This repository has been archived on 2023-05-17. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
auth/lib/server/controllers/auth.ts
mifi 42f091489e
Some checks failed
continuous-integration/drone/push Build is failing
Who knows what happens next...
2023-05-05 18:14:20 -04:00

55 lines
1.7 KiB
TypeScript

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 };