Use musicSession cookie for auth
This commit is contained in:
1 parent
e2c47e6d0f
commit
e89463591c
8 files changed
+80
-104
No files matched your search
@@ -6,7 +6,7 @@ export function useApiFetch<DataT = any, ErrorT = any>(
|
|||||||
options?: UseFetchOptions<DataT, ErrorT>,
|
options?: UseFetchOptions<DataT, ErrorT>,
|
||||||
authorize: boolean = true,
|
authorize: boolean = true,
|
||||||
): ReturnType<typeof useFetch<DataT, ErrorT>> {
|
): ReturnType<typeof useFetch<DataT, ErrorT>> {
|
||||||
const { sessionToken, refreshSessionToken } = useAuth()
|
const { refreshSession } = useAuth()
|
||||||
|
|
||||||
const defaults: UseFetchOptions<DataT, ErrorT> = {
|
const defaults: UseFetchOptions<DataT, ErrorT> = {
|
||||||
// The migrated API lives in this Nuxt app under server/api.
|
// The migrated API lives in this Nuxt app under server/api.
|
||||||
@@ -16,19 +16,23 @@ export function useApiFetch<DataT = any, ErrorT = any>(
|
|||||||
retryDelay: 0,
|
retryDelay: 0,
|
||||||
retryStatusCodes: [401],
|
retryStatusCodes: [401],
|
||||||
|
|
||||||
headers:
|
headers: {},
|
||||||
authorize && sessionToken.value
|
|
||||||
? { Authorization: `Bearer ${sessionToken.value}` }
|
|
||||||
: {},
|
|
||||||
onResponseError: async ({ request, response, options }) => {
|
onResponseError: async ({ request, response, options }) => {
|
||||||
if (response.status == 401 && authorize) {
|
if (response.status == 401 && authorize) {
|
||||||
const newToken = await refreshSessionToken()
|
const refreshed = await refreshSession()
|
||||||
|
|
||||||
if (!newToken) return
|
if (!refreshed.ok) return
|
||||||
|
|
||||||
const headers = new Headers(options.headers as HeadersInit)
|
if (import.meta.server && refreshed.sessionCookie) {
|
||||||
headers.set("Authorization", `Bearer ${newToken}`)
|
const headers = new Headers(options.headers as HeadersInit)
|
||||||
options.headers = headers
|
const cookies = (headers.get("cookie") ?? "")
|
||||||
|
.split(";")
|
||||||
|
.map((cookie) => cookie.trim())
|
||||||
|
.filter((cookie) => cookie && !cookie.startsWith("musicSession="))
|
||||||
|
cookies.push(refreshed.sessionCookie)
|
||||||
|
headers.set("cookie", cookies.join("; "))
|
||||||
|
options.headers = headers
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-28
@@ -1,17 +1,11 @@
|
|||||||
import { appendResponseHeader } from "h3"
|
import { appendResponseHeader } from "h3"
|
||||||
|
|
||||||
type SessionResponse = {
|
type SessionRefresh = { ok: boolean; sessionCookie?: string }
|
||||||
sessionToken: string
|
const refreshPromises = new WeakMap<object, Promise<SessionRefresh>>()
|
||||||
expireAt: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export const useAuth = () => {
|
export const useAuth = () => {
|
||||||
const sessionToken = useCookie<string | null>("sessionToken", {
|
const nuxtApp = useNuxtApp()
|
||||||
sameSite: "lax",
|
const authenticated = useState("auth:authenticated", () => false)
|
||||||
maxAge: 60 * 60,
|
|
||||||
})
|
|
||||||
|
|
||||||
let refreshPromise: Promise<string | null> | null = null
|
|
||||||
|
|
||||||
const signin = async (email: string, password: string, remember = false) => {
|
const signin = async (email: string, password: string, remember = false) => {
|
||||||
try {
|
try {
|
||||||
@@ -20,7 +14,7 @@ export const useAuth = () => {
|
|||||||
body: { email, password, remember: Boolean(remember) },
|
body: { email, password, remember: Boolean(remember) },
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!(await refreshSessionToken())) throw new Error("Unable to create session")
|
if (!(await refreshSession()).ok) throw new Error("Unable to create session")
|
||||||
await navigateTo("/")
|
await navigateTo("/")
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
throw new Error(error?.data?.message || error?.statusMessage || "Failed to sign in")
|
throw new Error(error?.data?.message || error?.statusMessage || "Failed to sign in")
|
||||||
@@ -34,7 +28,7 @@ export const useAuth = () => {
|
|||||||
body: { name, email, password },
|
body: { name, email, password },
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!(await refreshSessionToken())) throw new Error("Unable to create session")
|
if (!(await refreshSession()).ok) throw new Error("Unable to create session")
|
||||||
await navigateTo("/")
|
await navigateTo("/")
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
throw new Error(error?.data?.message || error?.statusMessage || "Failed to sign up")
|
throw new Error(error?.data?.message || error?.statusMessage || "Failed to sign up")
|
||||||
@@ -45,55 +39,64 @@ export const useAuth = () => {
|
|||||||
try {
|
try {
|
||||||
await $fetch("/api/auth/signout", { method: "POST" })
|
await $fetch("/api/auth/signout", { method: "POST" })
|
||||||
} finally {
|
} finally {
|
||||||
sessionToken.value = null
|
authenticated.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const refreshSessionToken = async (): Promise<string | null> => {
|
const refreshSession = async (): Promise<SessionRefresh> => {
|
||||||
if (refreshPromise) return refreshPromise
|
const inFlight = refreshPromises.get(nuxtApp)
|
||||||
|
if (inFlight) return inFlight
|
||||||
|
|
||||||
refreshPromise = (async () => {
|
const refreshPromise = (async () => {
|
||||||
const response = await $fetch.raw<SessionResponse>(
|
const response = await $fetch.raw<{ expireAt: string }>(
|
||||||
"/api/auth/session",
|
"/api/auth/session",
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: import.meta.server
|
headers: import.meta.server
|
||||||
? useRequestHeaders(["cookie", "authorization"])
|
? useRequestHeaders(["cookie"])
|
||||||
: undefined,
|
: undefined,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
let sessionCookie: string | undefined
|
||||||
|
const setCookies = import.meta.server ? response.headers.getSetCookie() : []
|
||||||
|
for (const cookie of setCookies) {
|
||||||
|
if (!cookie.startsWith("musicSession=")) continue
|
||||||
|
sessionCookie = cookie.split(";", 1)[0]
|
||||||
|
}
|
||||||
|
|
||||||
if (import.meta.server) {
|
if (import.meta.server) {
|
||||||
const event = useRequestEvent()
|
const event = useRequestEvent()
|
||||||
if (event) {
|
if (event) {
|
||||||
for (const cookie of response.headers.getSetCookie()) {
|
for (const cookie of setCookies) {
|
||||||
appendResponseHeader(event, "set-cookie", cookie)
|
appendResponseHeader(event, "set-cookie", cookie)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return response._data!
|
return { ok: true, sessionCookie }
|
||||||
})()
|
})()
|
||||||
.then((response) => {
|
.then((result) => {
|
||||||
sessionToken.value = response.sessionToken
|
authenticated.value = true
|
||||||
return response.sessionToken
|
return result
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
sessionToken.value = null
|
authenticated.value = false
|
||||||
return null
|
return { ok: false }
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
refreshPromise = null
|
refreshPromises.delete(nuxtApp)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
refreshPromises.set(nuxtApp, refreshPromise)
|
||||||
return refreshPromise
|
return refreshPromise
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
sessionToken,
|
authenticated,
|
||||||
signin,
|
signin,
|
||||||
signup,
|
signup,
|
||||||
signout,
|
signout,
|
||||||
refreshSessionToken,
|
refreshSession,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,8 @@ export default defineNuxtRouteMiddleware(async (to) => {
|
|||||||
if (to.path.startsWith("/auth")) return
|
if (to.path.startsWith("/auth")) return
|
||||||
|
|
||||||
const auth = useAuth()
|
const auth = useAuth()
|
||||||
|
if (import.meta.client && auth.authenticated.value) return
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Forward the incoming SSR credentials to this endpoint; the browser sends
|
// Forward the incoming SSR credentials to this endpoint; the browser sends
|
||||||
// same-origin cookies automatically during client navigation.
|
// same-origin cookies automatically during client navigation.
|
||||||
@@ -12,7 +14,6 @@ export default defineNuxtRouteMiddleware(async (to) => {
|
|||||||
: undefined
|
: undefined
|
||||||
const response = await $fetch.raw<{
|
const response = await $fetch.raw<{
|
||||||
authenticated: boolean
|
authenticated: boolean
|
||||||
sessionToken?: string
|
|
||||||
}>("/api/auth/session", { headers: requestHeaders })
|
}>("/api/auth/session", { headers: requestHeaders })
|
||||||
const session = response._data
|
const session = response._data
|
||||||
|
|
||||||
@@ -27,8 +28,10 @@ export default defineNuxtRouteMiddleware(async (to) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session?.sessionToken) auth.sessionToken.value = session.sessionToken
|
if (session?.authenticated) {
|
||||||
if (session?.authenticated) return
|
auth.authenticated.value = true
|
||||||
|
return
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Treat unavailable auth state as unauthenticated.
|
// Treat unavailable auth state as unauthenticated.
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-11
@@ -60,23 +60,23 @@ export const cfetch = async <DataT = any>(
|
|||||||
headers.delete("Content-Type")
|
headers.delete("Content-Type")
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authorize) {
|
|
||||||
const { sessionToken, refreshSessionToken } = useAuth()
|
|
||||||
let token = sessionToken.value
|
|
||||||
|
|
||||||
if (!token) token = await refreshSessionToken()
|
|
||||||
if (token) headers.set("Authorization", `Bearer ${token}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return (await $fetch(toApiUrl(url), requestOptions as any)) as DataT
|
return (await $fetch(toApiUrl(url), requestOptions as any)) as DataT
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
if (!authorize || error?.response?.status !== 401) throw error
|
if (!authorize || error?.response?.status !== 401) throw error
|
||||||
|
|
||||||
const token = await useAuth().refreshSessionToken()
|
const refreshed = await useAuth().refreshSession()
|
||||||
if (!token) throw error
|
if (!refreshed.ok) throw error
|
||||||
|
|
||||||
|
if (import.meta.server && refreshed.sessionCookie) {
|
||||||
|
const cookies = (headers.get("cookie") ?? "")
|
||||||
|
.split(";")
|
||||||
|
.map((cookie) => cookie.trim())
|
||||||
|
.filter((cookie) => cookie && !cookie.startsWith("musicSession="))
|
||||||
|
cookies.push(refreshed.sessionCookie)
|
||||||
|
headers.set("cookie", cookies.join("; "))
|
||||||
|
}
|
||||||
|
|
||||||
headers.set("Authorization", `Bearer ${token}`)
|
|
||||||
return (await $fetch(toApiUrl(url), requestOptions as any)) as DataT
|
return (await $fetch(toApiUrl(url), requestOptions as any)) as DataT
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,9 +10,7 @@ import {
|
|||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
const activeSession = await findAuthenticatedSession(event)
|
const activeSession = await findAuthenticatedSession(event)
|
||||||
if (activeSession) {
|
if (activeSession) return { authenticated: true }
|
||||||
return { authenticated: true, sessionToken: activeSession.session.token }
|
|
||||||
}
|
|
||||||
|
|
||||||
const refreshToken = getCookie(event, REFRESH_COOKIE)
|
const refreshToken = getCookie(event, REFRESH_COOKIE)
|
||||||
if (!refreshToken) return { authenticated: false }
|
if (!refreshToken) return { authenticated: false }
|
||||||
@@ -31,5 +29,5 @@ export default defineEventHandler(async (event) => {
|
|||||||
maxAge: Math.floor(ttl / 1000),
|
maxAge: Math.floor(ttl / 1000),
|
||||||
})
|
})
|
||||||
|
|
||||||
return { authenticated: true, sessionToken: session.token }
|
return { authenticated: true }
|
||||||
})
|
})
|
||||||
@@ -49,7 +49,5 @@ export default defineAuthenticatedEventHandler(async (event) => {
|
|||||||
})
|
})
|
||||||
setResponseStatus(event, 201)
|
setResponseStatus(event, 201)
|
||||||
|
|
||||||
// The response token remains for unmigrated frontend calls that still send
|
return { expireAt }
|
||||||
// Authorization: Bearer. The HttpOnly cookie serves migrated Nitro routes.
|
|
||||||
return { sessionToken: session.token, expireAt }
|
|
||||||
})
|
})
|
||||||
+10
-39
@@ -79,46 +79,19 @@ export function getSessionTtl(event?: H3Event) {
|
|||||||
return parseDuration(tokenExpire) || 60 * 60 * 1000
|
return parseDuration(tokenExpire) || 60 * 60 * 1000
|
||||||
}
|
}
|
||||||
|
|
||||||
function getSessionTokens(event: H3Event) {
|
|
||||||
const tokens: { token: string; source: "cookie" | "bearer" }[] = []
|
|
||||||
const cookieToken = getCookie(event, SESSION_COOKIE)
|
|
||||||
const authorization = event.node.req.headers.authorization
|
|
||||||
const bearerToken = authorization?.startsWith("Bearer ")
|
|
||||||
? authorization.slice("Bearer ".length)
|
|
||||||
: undefined
|
|
||||||
|
|
||||||
if (cookieToken) tokens.push({ token: cookieToken, source: "cookie" })
|
|
||||||
if (bearerToken && bearerToken !== cookieToken) {
|
|
||||||
tokens.push({ token: bearerToken, source: "bearer" })
|
|
||||||
}
|
|
||||||
|
|
||||||
return tokens
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function findSession(event: H3Event) {
|
export async function findSession(event: H3Event) {
|
||||||
const Session = getSessionModel(getSessionTtl(event)) as mongoose.Model<any>
|
const Session = getSessionModel(getSessionTtl(event)) as mongoose.Model<any>
|
||||||
|
const token = getCookie(event, SESSION_COOKIE)
|
||||||
|
if (!token) return null
|
||||||
|
|
||||||
for (const credential of getSessionTokens(event)) {
|
const session = await Session.findOne({ token })
|
||||||
const session = await Session.findOne({ token: credential.token })
|
.populate("userId", "+verified")
|
||||||
.populate("userId", "+verified")
|
.exec()
|
||||||
.exec()
|
const user = session?.userId as unknown as
|
||||||
|
| { _id: unknown; verified?: boolean; role?: string }
|
||||||
|
| undefined
|
||||||
|
|
||||||
const user = session?.userId as unknown as
|
return session && user ? { session, user } : null
|
||||||
| { _id: unknown; verified?: boolean; role?: string }
|
|
||||||
| undefined
|
|
||||||
|
|
||||||
if (!session || !user) continue
|
|
||||||
|
|
||||||
const bearerToken = event.node.req.headers.authorization?.startsWith("Bearer ")
|
|
||||||
? event.node.req.headers.authorization.slice("Bearer ".length)
|
|
||||||
: undefined
|
|
||||||
// If the cookie and bearer header carry the same valid token, the request
|
|
||||||
// is independently authenticated by the explicit bearer credential.
|
|
||||||
const source = bearerToken === credential.token ? "bearer" : credential.source
|
|
||||||
return { session, user, source }
|
|
||||||
}
|
|
||||||
|
|
||||||
return null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function findAuthenticatedSession(event: H3Event, adminOnly = false) {
|
export async function findAuthenticatedSession(event: H3Event, adminOnly = false) {
|
||||||
@@ -139,9 +112,7 @@ export async function requireAuthenticatedUser(event: H3Event, adminOnly = false
|
|||||||
|
|
||||||
const method = event.node.req.method?.toUpperCase() || "GET"
|
const method = event.node.req.method?.toUpperCase() || "GET"
|
||||||
const isUnsafeMethod = !["GET", "HEAD", "OPTIONS"].includes(method)
|
const isUnsafeMethod = !["GET", "HEAD", "OPTIONS"].includes(method)
|
||||||
if (isUnsafeMethod && auth.source === "cookie") {
|
if (isUnsafeMethod) assertCookieRequestOrigin(event)
|
||||||
assertCookieRequestOrigin(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
return auth.user
|
return auth.user
|
||||||
}
|
}
|
||||||
@@ -17,8 +17,8 @@ const operations: ApiOperation[] = [
|
|||||||
{ method: "get", path: "/health", tag: "Health", summary: "Health check", response: "Health" },
|
{ method: "get", path: "/health", tag: "Health", summary: "Health check", response: "Health" },
|
||||||
{ method: "post", path: "/auth/register", tag: "Auth", summary: "Register a user", body: "json", response: "EmptyObject", status: 201 },
|
{ method: "post", path: "/auth/register", tag: "Auth", summary: "Register a user", body: "json", response: "EmptyObject", status: 201 },
|
||||||
{ method: "post", path: "/auth/signin", tag: "Auth", summary: "Sign in", body: "json", response: "EmptyObject" },
|
{ method: "post", path: "/auth/signin", tag: "Auth", summary: "Sign in", body: "json", response: "EmptyObject" },
|
||||||
{ method: "post", path: "/auth/session", tag: "Auth", summary: "Create a session", body: "json", response: "Session", status: 201 },
|
{ method: "post", path: "/auth/session", tag: "Auth", summary: "Renew the current session", body: "json", response: "Session", status: 201 },
|
||||||
{ method: "get", path: "/auth/session", tag: "Auth", summary: "Get or renew the current session", response: "SessionStatus" },
|
{ method: "get", path: "/auth/session", tag: "Auth", summary: "Check the current session", response: "SessionStatus" },
|
||||||
{ method: "post", path: "/auth/signout", tag: "Auth", summary: "Sign out", response: "Signout" },
|
{ method: "post", path: "/auth/signout", tag: "Auth", summary: "Sign out", response: "Signout" },
|
||||||
{ method: "get", path: "/artists", tag: "Artist", summary: "Get artists by ID", auth: true, query: ["ids"], response: "ArtistList" },
|
{ method: "get", path: "/artists", tag: "Artist", summary: "Get artists by ID", auth: true, query: ["ids"], response: "ArtistList" },
|
||||||
{ method: "get", path: "/artists/{id}", tag: "Artist", summary: "Get an artist", auth: true, response: "ArtistOrNull" },
|
{ method: "get", path: "/artists/{id}", tag: "Artist", summary: "Get an artist", auth: true, response: "ArtistOrNull" },
|
||||||
@@ -140,7 +140,7 @@ function operationSpec(operation: ApiOperation) {
|
|||||||
return {
|
return {
|
||||||
tags: [operation.tag],
|
tags: [operation.tag],
|
||||||
summary: operation.summary,
|
summary: operation.summary,
|
||||||
...(operation.auth || operation.admin ? { security: [{ Bearer: [] }, { SessionCookie: [] }] } : {}),
|
...(operation.auth || operation.admin ? { security: [{ SessionCookie: [] }] } : {}),
|
||||||
...(parameters.length ? { parameters } : {}),
|
...(parameters.length ? { parameters } : {}),
|
||||||
...(operation.body
|
...(operation.body
|
||||||
? {
|
? {
|
||||||
@@ -174,7 +174,6 @@ export const openApiDocument = {
|
|||||||
paths,
|
paths,
|
||||||
components: {
|
components: {
|
||||||
securitySchemes: {
|
securitySchemes: {
|
||||||
Bearer: { type: "http", scheme: "bearer" },
|
|
||||||
SessionCookie: { type: "apiKey", in: "cookie", name: "musicSession" },
|
SessionCookie: { type: "apiKey", in: "cookie", name: "musicSession" },
|
||||||
},
|
},
|
||||||
schemas: {
|
schemas: {
|
||||||
@@ -232,8 +231,8 @@ export const openApiDocument = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
User: { type: "object", properties: { _id: { type: "string" }, name: { type: "string" }, email: { type: "string", format: "email" }, role: { type: "string" }, verified: { type: "boolean" }, savedTracks: { type: "array", items: { type: "string", description: "MongoDB ObjectId" } } } },
|
User: { type: "object", properties: { _id: { type: "string" }, name: { type: "string" }, email: { type: "string", format: "email" }, role: { type: "string" }, verified: { type: "boolean" }, savedTracks: { type: "array", items: { type: "string", description: "MongoDB ObjectId" } } } },
|
||||||
Session: { type: "object", properties: { sessionToken: { type: "string" }, expireAt: { type: "string", format: "date-time" } } },
|
Session: { type: "object", properties: { expireAt: { type: "string", format: "date-time" } } },
|
||||||
SessionStatus: { type: "object", properties: { authenticated: { type: "boolean" }, sessionToken: { type: "string" } } },
|
SessionStatus: { type: "object", properties: { authenticated: { type: "boolean" } } },
|
||||||
SearchResults: { type: "object", properties: { tracks: { type: "array", items: ref("Track") }, albums: { type: "array", items: ref("Album") }, artists: { type: "array", items: ref("Artist") } } },
|
SearchResults: { type: "object", properties: { tracks: { type: "array", items: ref("Track") }, albums: { type: "array", items: ref("Album") }, artists: { type: "array", items: ref("Artist") } } },
|
||||||
ArtistList: { type: "array", items: ref("Artist") },
|
ArtistList: { type: "array", items: ref("Artist") },
|
||||||
GenreList: { type: "array", items: ref("Genre") },
|
GenreList: { type: "array", items: ref("Genre") },
|
||||||
|
|||||||
Reference in new issue
Block a user