diff --git a/src/api/handlers/login.ts b/src/api/handlers/login.ts index d201abb..1edb0c2 100644 --- a/src/api/handlers/login.ts +++ b/src/api/handlers/login.ts @@ -7,6 +7,37 @@ import { ControllableError, AuthorizationError, NoSuchEntryError } from '../../m import Model from '../../model/model' import { SignatureError, verifyPubkeyReq } from '../pubkey' +export function login(model: Model): IMiddleware { + return async ctx => { + const session = ctx.state.oidcSession as InstanceType + const body: any = ctx.request.body + + if (!body || typeof body !== 'object') { + ctx.status = 400 + return + } + + const { username, password } = body + + try { + const userIdx = await model.pgDo(tr => model.users.authenticate(tr, username, password)) + session.loginAccount({ + accountId: String(userIdx), + }) + } catch (e) { + if (e instanceof ControllableError) { + ctx.status = 401 + } else { + ctx.status = 500 + } + return + } + + ctx.status = 200 + return + } +} + export function loginPAM(model: Model): IMiddleware { return async ctx => { const body: any = ctx.request.body diff --git a/src/api/router.ts b/src/api/router.ts index 7973306..eb571a2 100644 --- a/src/api/router.ts +++ b/src/api/router.ts @@ -2,7 +2,7 @@ import bodyParser from 'koa-bodyparser' import Router from 'koa-router' import Model from '../model/model' import Config from '../config' -import { loginPAM, logout, checkLogin, loginLegacy } from './handlers/login' +import { login, loginPAM, logout, checkLogin, loginLegacy } from './handlers/login' import { createUser, changePassword, sendChangePasswordEmail, getUserEmails, getUserInfo, checkChangePasswordEmailToken @@ -30,6 +30,13 @@ export function createRouter(model: Model, oidcProvider: OIDCProvider, config: C return next() }) + /** + * Login API route. + * @param username username. + * @param password password. + * 200 if success, 401 if not. + */ + router.post('/api/login', login(model)) /** * PAM Login API route. * @param username username.