tianji/src/server/router/user.ts

44 lines
1.0 KiB
TypeScript
Raw Normal View History

2023-09-02 14:53:57 +00:00
import { Router } from 'express';
import { body, validate } from '../middleware/validate';
2023-09-02 17:01:55 +00:00
import { authUser, createAdminUser } from '../model/user';
import { auth, jwtSign } from '../middleware/auth';
2023-09-02 14:53:57 +00:00
export const userRouter = Router();
2023-09-02 17:01:55 +00:00
userRouter.post(
'/login',
validate(
body('username').exists().withMessage('Username should be existed'),
body('password').exists().withMessage('Password should be existed')
),
async (req, res) => {
const { username, password } = req.body;
const user = await authUser(username, password);
const token = jwtSign({
id: user.id,
username: user.username,
role: user.role,
});
res.json({ token });
}
);
2023-09-02 14:53:57 +00:00
userRouter.post(
'/createAdmin',
2023-09-02 17:01:55 +00:00
auth(),
2023-09-02 14:53:57 +00:00
validate(
body('username').exists().withMessage('Username should be existed'),
body('password').exists().withMessage('Password should be existed')
),
async (req, res) => {
const { username, password } = req.body;
await createAdminUser(username, password);
res.json({ result: true });
}
);