import Koa from 'koa'; import Router from 'koa-router'; import { StatusCodes } from 'http-status-codes'; import { ROUTE_PREFIX as prefix, RESET_ROUTE } from '../../constants/env'; import Auth from '../../db/model/auth'; import { sign } from '../../utils/jwt'; import passport from '../passport'; import { ErrorCodes, getErrorBody } from '../../constants/errors'; const routerOpts: Router.IRouterOptions = { prefix }; const router: Router = new Router(routerOpts); router.get('/info', (ctx) => { ctx.body = { service: process.env.SERVICE_NAME, }; }); router.post('/', async (ctx) => { const data = (await Auth.create(ctx.body)).save(); ctx.body = { success: true, data: { ...data, strategies: undefined } }; }); router.post('/login', async (ctx, next) => { return passport.authenticate('local', (err, user) => { if (user === false) { ctx.body = { token: null }; ctx.throw(StatusCodes.UNAUTHORIZED); } ctx.body = { token: sign(user) }; return ctx.login(user); })(ctx, next); }); router.post(process.env.RESET_ROUTE || RESET_ROUTE, async (ctx, next) => { const { token = null, password = null } = ctx.request.body as { token?: string; password?: string }; if (token && password) { const loginToken = await Auth.resetPassword(token, password).catch(); ctx.body({ token: loginToken }); next(); } ctx.body = { success: false, ...getErrorBody(ErrorCodes.RESET_REQUEST_DATA) }; }); router.patch('/:record', (ctx: Koa.Context) => { const data = Auth.findOneAndUpdate({ record: ctx.params.record }); if (!data) { ctx.throw(StatusCodes.NOT_FOUND); } ctx.body = { success: true, data }; }); export { router as authRouter };