41 lines
1.1 KiB
TypeScript
41 lines
1.1 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';
|
|
import passport from '../passport';
|
|
import { sign } from '../utils/jwt';
|
|
|
|
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, next) => {
|
|
return passport.authenticate('local', (err, user) => {
|
|
if (user === false) {
|
|
ctx.body = { token: sign() };
|
|
ctx.throw(StatusCodes.UNAUTHORIZED);
|
|
}
|
|
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 };
|
|
});
|