This commit is contained in:
@@ -4,6 +4,8 @@ import { StatusCodes } from 'http-status-codes';
|
||||
import { API_PATH } from '../constants/defaults';
|
||||
|
||||
import Auth from '../model/auth';
|
||||
import passport from '../passport';
|
||||
import { sign } from '../utils/jwt';
|
||||
|
||||
const routerOpts: Router.IRouterOptions = {
|
||||
prefix: process.env.API_PATH || API_PATH,
|
||||
@@ -17,34 +19,22 @@ router.post('/', async (ctx: Koa.Context) => {
|
||||
ctx.body = { success: true, data };
|
||||
});
|
||||
|
||||
|
||||
router.post('/login', async (ctx: Koa.Context) => {
|
||||
const { body: { username = null, password = null } = {} } = ctx;
|
||||
|
||||
if (!username || !password) {
|
||||
let errors = {};
|
||||
|
||||
if (!username) {
|
||||
errors.username = 'is required';
|
||||
router.post('/login', async (ctx: Koa.Context, next) => {
|
||||
return passport.authenticate('local', (err, user) => {
|
||||
if (user === false) {
|
||||
ctx.body = { token: sign() };
|
||||
ctx.throw(StatusCodes.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if (!password) {
|
||||
errors.password = 'is required';
|
||||
}
|
||||
|
||||
ctx.status = StatusCodes.UNPROCESSABLE_ENTITY;
|
||||
ctx.throw(422, { errors });
|
||||
}
|
||||
|
||||
const callback = handlePassportResponse(req, res, next);
|
||||
return passport.authenticate('local', { session: false }, callback)(req, res, next);
|
||||
ctx.body = { token: sign(user) };
|
||||
return ctx.login(user);
|
||||
})(ctx, next);
|
||||
await next();
|
||||
});
|
||||
|
||||
|
||||
router.patch('/:customer_id', async (ctx: Koa.Context) => {
|
||||
const data = await Auth.findByIdAndUpdate(ctx.params.customer_id);
|
||||
if (!data) {
|
||||
ctx.throw(StatusCodes.NOT_FOUND);
|
||||
}
|
||||
ctx.body = { success: true, data };
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user