Refresh Token 구현 변경

This commit is contained in:
static
2024-12-28 15:44:30 +09:00
parent 796e4a7831
commit 1d0c309878
11 changed files with 233 additions and 79 deletions

View File

@@ -2,34 +2,31 @@ import { error } from "@sveltejs/kit";
import jwt from "jsonwebtoken";
import env from "$lib/server/loadenv";
interface TokenData {
type: "access" | "refresh";
userId: number;
clientId?: number;
}
type TokenPayload =
| {
type: "access";
userId: number;
clientId?: number;
}
| {
type: "refresh";
jti: string;
};
export enum TokenError {
EXPIRED,
INVALID,
}
export const issueToken = (type: "access" | "refresh", userId: number, clientId?: number) => {
return jwt.sign(
{
type,
userId,
clientId,
} satisfies TokenData,
env.jwt.secret,
{
expiresIn: type === "access" ? env.jwt.accessExp : env.jwt.refreshExp,
},
);
export const issueToken = (payload: TokenPayload) => {
return jwt.sign(payload, env.jwt.secret, {
expiresIn: payload.type === "access" ? env.jwt.accessExp : env.jwt.refreshExp,
});
};
export const verifyToken = (token: string) => {
try {
return jwt.verify(token, env.jwt.secret) as TokenData;
return jwt.verify(token, env.jwt.secret) as TokenPayload;
} catch (error) {
if (error instanceof jwt.TokenExpiredError) {
return TokenError.EXPIRED;
@@ -41,18 +38,18 @@ export const verifyToken = (token: string) => {
export const authenticate = (request: Request) => {
const accessToken = request.headers.get("Authorization");
if (!accessToken?.startsWith("Bearer ")) {
error(401, "Token required");
error(401, "Access token required");
}
const tokenData = verifyToken(accessToken.slice(7));
if (tokenData === TokenError.EXPIRED) {
error(401, "Token expired");
} else if (tokenData === TokenError.INVALID || tokenData.type !== "access") {
error(401, "Invalid token");
const tokenPayload = verifyToken(accessToken.slice(7));
if (tokenPayload === TokenError.EXPIRED) {
error(401, "Access token expired");
} else if (tokenPayload === TokenError.INVALID || tokenPayload.type !== "access") {
error(401, "Invalid access token");
}
return {
userId: tokenData.userId,
clientId: tokenData.clientId,
userId: tokenPayload.userId,
clientId: tokenPayload.clientId,
};
};