66 lines
1.5 KiB
JavaScript
66 lines
1.5 KiB
JavaScript
'use strict';
|
||
|
||
const express = require('express');
|
||
const auth = require('./auth');
|
||
const { ok, asyncHandler } = require('../common/http');
|
||
const { ApiError, API_CODES } = require('../common/api-codes');
|
||
|
||
const router = express.Router();
|
||
|
||
function meta(req) {
|
||
return { ip: req.ip, userAgent: req.headers['user-agent'] };
|
||
}
|
||
|
||
function requireFields(body, fields) {
|
||
for (const f of fields) {
|
||
if (body == null || body[f] == null || body[f] === '') {
|
||
throw new ApiError(API_CODES.BAD_PARAMS, `缺少参数:${f}`, 400);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 公共端点(无需 JWT)
|
||
router.post(
|
||
'/login',
|
||
asyncHandler(async (req, res) => {
|
||
requireFields(req.body, ['username', 'password']);
|
||
ok(res, await auth.login(req.body.username, req.body.password, meta(req)));
|
||
}),
|
||
);
|
||
|
||
router.post(
|
||
'/refresh',
|
||
asyncHandler(async (req, res) => {
|
||
requireFields(req.body, ['refreshToken']);
|
||
ok(res, await auth.refresh(req.body.refreshToken));
|
||
}),
|
||
);
|
||
|
||
// 需认证端点
|
||
router.post(
|
||
'/logout',
|
||
auth.requireAuth,
|
||
asyncHandler(async (req, res) => {
|
||
ok(res, await auth.logout(req.user, req.body && req.body.refreshToken, meta(req)));
|
||
}),
|
||
);
|
||
|
||
router.post(
|
||
'/change-password',
|
||
auth.requireAuth,
|
||
asyncHandler(async (req, res) => {
|
||
requireFields(req.body, ['oldPassword', 'newPassword']);
|
||
ok(res, await auth.changePassword(req.user, req.body.oldPassword, req.body.newPassword, meta(req)));
|
||
}),
|
||
);
|
||
|
||
router.get(
|
||
'/profile',
|
||
auth.requireAuth,
|
||
asyncHandler(async (req, res) => {
|
||
ok(res, await auth.profile(req.user));
|
||
}),
|
||
);
|
||
|
||
module.exports = router;
|