mirror of
https://github.com/kmc7468/arkvault.git
synced 2025-12-15 06:18:48 +00:00
Access Token 저장 방식 변경
This commit is contained in:
@@ -1,48 +1,15 @@
|
|||||||
import { get } from "svelte/store";
|
|
||||||
import { accessTokenStore } from "$lib/stores";
|
|
||||||
|
|
||||||
const refreshToken = async () => {
|
const refreshToken = async () => {
|
||||||
const res = await fetch("/api/auth/refreshToken", {
|
return await fetch("/api/auth/refreshToken", { method: "POST" });
|
||||||
method: "POST",
|
|
||||||
credentials: "same-origin",
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
accessTokenStore.set(null);
|
|
||||||
throw new Error("Failed to refresh token");
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await res.json();
|
|
||||||
const token = data.accessToken as string;
|
|
||||||
|
|
||||||
accessTokenStore.set(token);
|
|
||||||
return token;
|
|
||||||
};
|
|
||||||
|
|
||||||
const callAPIInternal = async (
|
|
||||||
input: RequestInfo,
|
|
||||||
init: RequestInit | undefined,
|
|
||||||
token: string | null,
|
|
||||||
retryIfUnauthorized = true,
|
|
||||||
): Promise<Response> => {
|
|
||||||
if (!token) {
|
|
||||||
token = await refreshToken();
|
|
||||||
retryIfUnauthorized = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const res = await fetch(input, {
|
|
||||||
...init,
|
|
||||||
headers: {
|
|
||||||
...init?.headers,
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (res.status === 401 && retryIfUnauthorized) {
|
|
||||||
return await callAPIInternal(input, init, null, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
return res;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const callAPI = async (input: RequestInfo, init?: RequestInit) => {
|
export const callAPI = async (input: RequestInfo, init?: RequestInit) => {
|
||||||
return await callAPIInternal(input, init, get(accessTokenStore));
|
let res = await fetch(input, init);
|
||||||
|
if (res.status === 401) {
|
||||||
|
res = await refreshToken();
|
||||||
|
if (!res.ok) {
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
res = await fetch(input, init);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { error } from "@sveltejs/kit";
|
import { error, type Cookies } from "@sveltejs/kit";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import env from "$lib/server/loadenv";
|
import env from "$lib/server/loadenv";
|
||||||
|
|
||||||
@@ -35,13 +35,13 @@ export const verifyToken = (token: string) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const authenticate = (request: Request) => {
|
export const authenticate = (cookies: Cookies) => {
|
||||||
const accessToken = request.headers.get("Authorization");
|
const accessToken = cookies.get("accessToken");
|
||||||
if (!accessToken?.startsWith("Bearer ")) {
|
if (!accessToken) {
|
||||||
error(401, "Access token required");
|
error(401, "Access token not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokenPayload = verifyToken(accessToken.slice(7));
|
const tokenPayload = verifyToken(accessToken);
|
||||||
if (tokenPayload === TokenError.EXPIRED) {
|
if (tokenPayload === TokenError.EXPIRED) {
|
||||||
error(401, "Access token expired");
|
error(401, "Access token expired");
|
||||||
} else if (tokenPayload === TokenError.INVALID || tokenPayload.type !== "access") {
|
} else if (tokenPayload === TokenError.INVALID || tokenPayload.type !== "access") {
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ export const logout = async (refreshToken: string) => {
|
|||||||
await revokeRefreshToken(jti);
|
await revokeRefreshToken(jti);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const refreshToken = async (refreshToken: string) => {
|
export const refreshTokens = async (refreshToken: string) => {
|
||||||
const { jti: oldJti, userId, clientId } = await verifyRefreshToken(refreshToken);
|
const { jti: oldJti, userId, clientId } = await verifyRefreshToken(refreshToken);
|
||||||
const newJti = uuidv4();
|
const newJti = uuidv4();
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
import { writable } from "svelte/store";
|
|
||||||
|
|
||||||
export const accessTokenStore = writable<string | null>(null);
|
|
||||||
@@ -1,2 +1 @@
|
|||||||
export * from "./auth";
|
|
||||||
export * from "./key";
|
export * from "./key";
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import { accessTokenStore } from "$lib/stores";
|
|
||||||
|
|
||||||
export const requestLogin = async (email: string, password: string) => {
|
export const requestLogin = async (email: string, password: string) => {
|
||||||
const res = await fetch("/api/auth/login", {
|
const res = await fetch("/api/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -8,13 +6,5 @@ export const requestLogin = async (email: string, password: string) => {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({ email, password }),
|
body: JSON.stringify({ email, password }),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return res.ok;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await res.json();
|
|
||||||
const token = data.accessToken as string;
|
|
||||||
|
|
||||||
accessTokenStore.set(token);
|
|
||||||
return true;
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { error, json } from "@sveltejs/kit";
|
import { error, text } from "@sveltejs/kit";
|
||||||
import ms from "ms";
|
import ms from "ms";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import env from "$lib/server/loadenv";
|
import env from "$lib/server/loadenv";
|
||||||
@@ -10,7 +10,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
|||||||
.object({
|
.object({
|
||||||
email: z.string().email().nonempty(),
|
email: z.string().email().nonempty(),
|
||||||
password: z.string().nonempty(),
|
password: z.string().nonempty(),
|
||||||
pubKey: z.string().nonempty().optional(),
|
pubKey: z.string().base64().nonempty().optional(),
|
||||||
})
|
})
|
||||||
.safeParse(await request.json());
|
.safeParse(await request.json());
|
||||||
if (!zodRes.success) error(400, "Invalid request body");
|
if (!zodRes.success) error(400, "Invalid request body");
|
||||||
@@ -18,12 +18,15 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
|||||||
const { email, password, pubKey } = zodRes.data;
|
const { email, password, pubKey } = zodRes.data;
|
||||||
const { accessToken, refreshToken } = await login(email.trim(), password.trim(), pubKey?.trim());
|
const { accessToken, refreshToken } = await login(email.trim(), password.trim(), pubKey?.trim());
|
||||||
|
|
||||||
|
cookies.set("accessToken", accessToken, {
|
||||||
|
path: "/",
|
||||||
|
maxAge: Math.floor(ms(env.jwt.accessExp) / 1000),
|
||||||
|
sameSite: "strict",
|
||||||
|
});
|
||||||
cookies.set("refreshToken", refreshToken, {
|
cookies.set("refreshToken", refreshToken, {
|
||||||
path: "/api/auth",
|
path: "/api/auth",
|
||||||
maxAge: Math.floor(ms(env.jwt.refreshExp) / 1000),
|
maxAge: Math.floor(ms(env.jwt.refreshExp) / 1000),
|
||||||
httpOnly: true,
|
|
||||||
secure: true,
|
|
||||||
sameSite: "strict",
|
sameSite: "strict",
|
||||||
});
|
});
|
||||||
return json({ accessToken });
|
return text("Logged in", { headers: { "Content-Type": "text/plain" } });
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,8 +4,11 @@ import type { RequestHandler } from "./$types";
|
|||||||
|
|
||||||
export const POST: RequestHandler = async ({ cookies }) => {
|
export const POST: RequestHandler = async ({ cookies }) => {
|
||||||
const token = cookies.get("refreshToken");
|
const token = cookies.get("refreshToken");
|
||||||
if (!token) error(401, "Token not found");
|
if (!token) error(401, "Refresh token not found");
|
||||||
|
|
||||||
await logout(token.trim());
|
await logout(token.trim());
|
||||||
return text("Logged out");
|
|
||||||
|
cookies.delete("accessToken", { path: "/" });
|
||||||
|
cookies.delete("refreshToken", { path: "/api/auth" });
|
||||||
|
return text("Logged out", { headers: { "Content-Type": "text/plain" } });
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
import { error, json } from "@sveltejs/kit";
|
import { error, text } from "@sveltejs/kit";
|
||||||
import { refreshToken } from "$lib/server/services/auth";
|
import { refreshTokens } from "$lib/server/services/auth";
|
||||||
import type { RequestHandler } from "./$types";
|
import type { RequestHandler } from "./$types";
|
||||||
|
|
||||||
export const POST: RequestHandler = async ({ cookies }) => {
|
export const POST: RequestHandler = async ({ cookies }) => {
|
||||||
const token = cookies.get("refreshToken");
|
const token = cookies.get("refreshToken");
|
||||||
if (!token) error(401, "Token not found");
|
if (!token) error(401, "Refresh token not found");
|
||||||
|
|
||||||
const { accessToken, refreshToken: newToken } = await refreshToken(token.trim());
|
const { accessToken, refreshToken } = await refreshTokens(token.trim());
|
||||||
|
|
||||||
cookies.set("refreshToken", newToken, {
|
cookies.set("accessToken", accessToken, {
|
||||||
path: "/api/auth",
|
path: "/",
|
||||||
httpOnly: true,
|
|
||||||
secure: true,
|
|
||||||
sameSite: "strict",
|
sameSite: "strict",
|
||||||
});
|
});
|
||||||
return json({ accessToken });
|
cookies.set("refreshToken", refreshToken, {
|
||||||
|
path: "/api/auth",
|
||||||
|
sameSite: "strict",
|
||||||
|
});
|
||||||
|
return text("Token refreshed", { headers: { "Content-Type": "text/plain" } });
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { authenticate } from "$lib/server/modules/auth";
|
|||||||
import { registerPubKey } from "$lib/server/services/key";
|
import { registerPubKey } from "$lib/server/services/key";
|
||||||
import type { RequestHandler } from "./$types";
|
import type { RequestHandler } from "./$types";
|
||||||
|
|
||||||
export const POST: RequestHandler = async ({ request }) => {
|
export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||||
const zodRes = z
|
const zodRes = z
|
||||||
.object({
|
.object({
|
||||||
pubKey: z.string().base64().nonempty(),
|
pubKey: z.string().base64().nonempty(),
|
||||||
@@ -12,7 +12,7 @@ export const POST: RequestHandler = async ({ request }) => {
|
|||||||
.safeParse(await request.json());
|
.safeParse(await request.json());
|
||||||
if (!zodRes.success) error(400, "Invalid request body");
|
if (!zodRes.success) error(400, "Invalid request body");
|
||||||
|
|
||||||
const { userId, clientId } = authenticate(request);
|
const { userId, clientId } = authenticate(cookies);
|
||||||
if (clientId) {
|
if (clientId) {
|
||||||
error(403, "Forbidden");
|
error(403, "Forbidden");
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user