tianji/src/server/middleware/auth.ts

81 lines
1.7 KiB
TypeScript
Raw Normal View History

import { findUser } from '../model/user';
2023-09-02 17:01:55 +00:00
import passport from 'passport';
import { Handler } from 'express';
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
import jwt from 'jsonwebtoken';
2023-09-05 07:43:29 +00:00
import { jwtSecret } from '../utils/common';
2023-09-02 17:01:55 +00:00
export const jwtIssuer = process.env.JWT_ISSUER || 'tianji.msgbyte.com';
export const jwtAudience = process.env.JWT_AUDIENCE || 'msgbyte.com';
2023-09-04 17:18:43 +00:00
export interface JWTPayload {
id: string;
username: string;
role: string;
}
2023-09-02 17:01:55 +00:00
passport.use(
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: jwtSecret,
issuer: jwtIssuer,
audience: jwtAudience,
},
function (jwt_payload, done) {
findUser(jwt_payload.id)
2023-09-02 17:01:55 +00:00
.then((user) => {
if (user) {
done(null, user);
} else {
done(null, false);
}
})
.catch((err) => {
done(err);
});
}
)
);
passport.serializeUser(function (user: any, cb) {
cb(null, { id: user.id, username: user.username });
});
passport.deserializeUser(function (user: any, cb) {
cb(null, user);
});
export function jwtSign(payload: JWTPayload): string {
const token = jwt.sign(
{
id: payload.id,
username: payload.username,
role: payload.role,
},
jwtSecret,
{
issuer: jwtIssuer,
audience: jwtAudience,
expiresIn: '30d',
}
);
return token;
}
export function jwtVerify(token: string): JWTPayload {
const payload = jwt.verify(token, jwtSecret, {
2023-09-02 17:01:55 +00:00
issuer: jwtIssuer,
audience: jwtAudience,
});
return payload as JWTPayload;
2023-09-02 17:01:55 +00:00
}
export function auth(): Handler {
return passport.authenticate('jwt', {
session: false,
});
}