50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
import Koa from 'koa';
|
|
import Router from 'koa-router';
|
|
import { StatusCodes } from 'http-status-codes';
|
|
import { API_PATH } from '../constants/defaults';
|
|
|
|
import Auth from '../model/auth';
|
|
|
|
const routerOpts: Router.IRouterOptions = {
|
|
prefix: process.env.API_PATH || API_PATH,
|
|
};
|
|
|
|
const router: Router = new Router(routerOpts);
|
|
|
|
router.post('/', async (ctx: Koa.Context) => {
|
|
const data = await Auth.create(ctx.body);
|
|
data.save();
|
|
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';
|
|
}
|
|
|
|
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);
|
|
});
|
|
|
|
|
|
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 };
|
|
}); |