Use musicSession cookie for auth

This commit is contained in:
lucast committed 2026-10-02 00:20:38 +02:00
1 parent e2c47e6d0f
commit e89463591c
8 files changed
+80 -104

No files matched your search

+2 -4
View File
@@ -10,9 +10,7 @@ import {
export default defineEventHandler(async (event) => {
const activeSession = await findAuthenticatedSession(event)
if (activeSession) {
return { authenticated: true, sessionToken: activeSession.session.token }
}
if (activeSession) return { authenticated: true }
const refreshToken = getCookie(event, REFRESH_COOKIE)
if (!refreshToken) return { authenticated: false }
@@ -31,5 +29,5 @@ export default defineEventHandler(async (event) => {
maxAge: Math.floor(ttl / 1000),
})
return { authenticated: true, sessionToken: session.token }
return { authenticated: true }
})
+1 -3
View File
@@ -49,7 +49,5 @@ export default defineAuthenticatedEventHandler(async (event) => {
})
setResponseStatus(event, 201)
// The response token remains for unmigrated frontend calls that still send
// Authorization: Bearer. The HttpOnly cookie serves migrated Nitro routes.
return { sessionToken: session.token, expireAt }
return { expireAt }
})
+10 -39
View File
@@ -79,46 +79,19 @@ export function getSessionTtl(event?: H3Event) {
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) {
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: credential.token })
.populate("userId", "+verified")
.exec()
const session = await Session.findOne({ token })
.populate("userId", "+verified")
.exec()
const user = session?.userId as unknown as
| { _id: unknown; verified?: boolean; role?: string }
| undefined
const user = session?.userId as unknown as
| { _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
return session && user ? { session, user } : null
}
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 isUnsafeMethod = !["GET", "HEAD", "OPTIONS"].includes(method)
if (isUnsafeMethod && auth.source === "cookie") {
assertCookieRequestOrigin(event)
}
if (isUnsafeMethod) assertCookieRequestOrigin(event)
return auth.user
}
+5 -6
View File
@@ -17,8 +17,8 @@ const operations: ApiOperation[] = [
{ 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/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: "get", path: "/auth/session", tag: "Auth", summary: "Get or renew the current session", response: "SessionStatus" },
{ 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: "Check the current session", response: "SessionStatus" },
{ 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/{id}", tag: "Artist", summary: "Get an artist", auth: true, response: "ArtistOrNull" },
@@ -140,7 +140,7 @@ function operationSpec(operation: ApiOperation) {
return {
tags: [operation.tag],
summary: operation.summary,
...(operation.auth || operation.admin ? { security: [{ Bearer: [] }, { SessionCookie: [] }] } : {}),
...(operation.auth || operation.admin ? { security: [{ SessionCookie: [] }] } : {}),
...(parameters.length ? { parameters } : {}),
...(operation.body
? {
@@ -174,7 +174,6 @@ export const openApiDocument = {
paths,
components: {
securitySchemes: {
Bearer: { type: "http", scheme: "bearer" },
SessionCookie: { type: "apiKey", in: "cookie", name: "musicSession" },
},
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" } } } },
Session: { type: "object", properties: { sessionToken: { type: "string" }, expireAt: { type: "string", format: "date-time" } } },
SessionStatus: { type: "object", properties: { authenticated: { type: "boolean" }, sessionToken: { type: "string" } } },
Session: { type: "object", properties: { expireAt: { type: "string", format: "date-time" } } },
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") } } },
ArtistList: { type: "array", items: ref("Artist") },
GenreList: { type: "array", items: ref("Genre") },