This commit is contained in:
50
lib/server/controllers/auth.ts
Normal file
50
lib/server/controllers/auth.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import Koa from 'koa';
|
||||
import Router from 'koa-router';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
|
||||
import { ROUTE_PREFIX as prefix, RESET_ROUTE } from '../../constants/constants';
|
||||
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.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 };
|
||||
Reference in New Issue
Block a user