tianji/src/server/router/user.ts

90 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-09-02 14:53:57 +00:00
import { Router } from 'express';
import { header, body, validate } from '../middleware/validate';
import {
authUser,
authUserWithToken,
createAdminUser,
createUser,
getUserCount,
} from '../model/user';
2023-09-02 17:01:55 +00:00
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(user);
2023-09-02 17:01:55 +00:00
res.json({ info: user, token });
}
);
userRouter.post(
'/register',
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 userCount = await getUserCount();
if (userCount === 0) {
const user = await createAdminUser(username, password);
const token = jwtSign(user);
res.json({ info: user, token });
} else {
const user = await createUser(username, password);
const token = jwtSign(user);
res.json({ info: user, token });
}
}
);
userRouter.post(
'/loginWithToken',
validate(body('token').exists().withMessage('Token should be existed')),
async (req, res) => {
const { token } = req.body;
if (!token) {
throw new Error('Cannot get token');
}
const user = await authUserWithToken(token);
const newToken = jwtSign(user);
res.json({ info: user, token: newToken });
2023-09-02 17:01:55 +00:00
}
);
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 });
}
);