first commit
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const SECRET = 'life-circle-secret-key-2026';
|
||||
|
||||
export function auth(req, res, next) {
|
||||
const header = req.headers.authorization;
|
||||
if (!header) {
|
||||
return res.status(401).json({ message: '未登录' });
|
||||
}
|
||||
const token = header.split(' ')[1];
|
||||
try {
|
||||
const payload = jwt.verify(token, SECRET);
|
||||
req.user = payload;
|
||||
next();
|
||||
} catch (e) {
|
||||
return res.status(401).json({ message: '登录已过期,请重新登录' });
|
||||
}
|
||||
}
|
||||
|
||||
export function sign(user) {
|
||||
return jwt.sign(
|
||||
{ id: user.id, username: user.username, nickname: user.nickname, role: user.role },
|
||||
SECRET,
|
||||
{ expiresIn: '7d' }
|
||||
);
|
||||
}
|
||||
|
||||
export { SECRET };
|
||||
Reference in New Issue
Block a user