Migrated auth to Nitro
This commit is contained in:
1 parent
27feb1ce95
commit
eb4e9f0700
16 files changed
+517
-129
No files matched your search
@@ -0,0 +1,42 @@
|
||||
type AuthField = {
|
||||
name: string
|
||||
email?: boolean
|
||||
minimumLength?: number
|
||||
}
|
||||
|
||||
function receivedType(value: unknown) {
|
||||
if (value === null) return "null"
|
||||
if (Array.isArray(value)) return "array"
|
||||
return typeof value
|
||||
}
|
||||
|
||||
/** Match the first-issue messages returned by the legacy Zod validation hook. */
|
||||
export function getAuthValidationMessage(body: unknown, fields: AuthField[]) {
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
||||
return body === undefined ? "Required" : `Expected object, received ${receivedType(body)}`
|
||||
}
|
||||
|
||||
for (const field of fields) {
|
||||
const value = (body as Record<string, unknown>)[field.name]
|
||||
if (typeof value !== "string") {
|
||||
return value === undefined
|
||||
? "Required"
|
||||
: `Expected string, received ${receivedType(value)}`
|
||||
}
|
||||
|
||||
if (
|
||||
field.email &&
|
||||
!/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i.test(
|
||||
value,
|
||||
)
|
||||
) {
|
||||
return "Invalid email"
|
||||
}
|
||||
|
||||
if (field.minimumLength && value.length < field.minimumLength) {
|
||||
return `String must contain at least ${field.minimumLength} character(s)`
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { H3Event } from "h3"
|
||||
import { createError, getCookie } from "h3"
|
||||
import parseDuration from "parse-duration"
|
||||
import mongoose from "mongoose"
|
||||
import { getSessionModel } from "../models/session"
|
||||
import { getBackendRuntimeConfig } from "./backend-config"
|
||||
|
||||
export const SESSION_COOKIE = "musicSession"
|
||||
export const REFRESH_COOKIE = "refreshToken"
|
||||
|
||||
export function getSessionTtl(event?: H3Event) {
|
||||
const { tokenExpire } = getBackendRuntimeConfig(event)
|
||||
return parseDuration(tokenExpire) || 60 * 60 * 1000
|
||||
}
|
||||
|
||||
function getSessionTokens(event: H3Event) {
|
||||
const tokens: string[] = []
|
||||
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(cookieToken)
|
||||
if (bearerToken && bearerToken !== cookieToken) tokens.push(bearerToken)
|
||||
|
||||
return tokens
|
||||
}
|
||||
|
||||
export async function findSession(event: H3Event) {
|
||||
const Session = getSessionModel(getSessionTtl(event)) as mongoose.Model<any>
|
||||
|
||||
for (const token of getSessionTokens(event)) {
|
||||
const session = await Session.findOne({ token })
|
||||
.populate("userId", "+verified")
|
||||
.exec()
|
||||
|
||||
const user = session?.userId as unknown as
|
||||
| { _id: unknown; verified?: boolean; role?: string }
|
||||
| undefined
|
||||
|
||||
if (!session || !user) continue
|
||||
|
||||
return { session, user }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export async function findAuthenticatedSession(event: H3Event, adminOnly = false) {
|
||||
const auth = await findSession(event)
|
||||
if (!auth?.user.verified || (adminOnly && auth.user.role !== "admin")) return null
|
||||
return auth
|
||||
}
|
||||
|
||||
export async function requireAuthenticatedUser(event: H3Event, adminOnly = false) {
|
||||
const auth = await findAuthenticatedSession(event, adminOnly)
|
||||
if (!auth) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Unauthorized",
|
||||
data: { message: "Unauthorized" },
|
||||
})
|
||||
}
|
||||
|
||||
return auth.user
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { H3Event } from "h3"
|
||||
|
||||
/**
|
||||
* Read private backend settings at runtime. Nuxt's NUXT_* runtime overrides
|
||||
* take precedence, while existing standalone-backend variable names remain
|
||||
* usable during the migration.
|
||||
*/
|
||||
export function getBackendRuntimeConfig(event?: H3Event) {
|
||||
const config = useRuntimeConfig(event)
|
||||
|
||||
return {
|
||||
mongodbUri: config.mongodbUri || process.env.MONGODB_URI || "",
|
||||
uploadDir: config.uploadDir || process.env.UPLOAD_DIR || "",
|
||||
tokenExpire: config.tokenExpire || process.env.TOKEN_EXPIRE || "1h",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import mongoose from "mongoose"
|
||||
|
||||
let connectionPromise: Promise<typeof mongoose> | undefined
|
||||
|
||||
/**
|
||||
* Connect to the application's shared Mongoose instance.
|
||||
* Concurrent callers share the same connection attempt, and failed attempts
|
||||
* can be retried after the underlying cause has been corrected.
|
||||
*/
|
||||
export function connectToDatabase(uri: string): Promise<typeof mongoose> {
|
||||
if (!uri) {
|
||||
return Promise.reject(new Error("MongoDB runtime configuration is missing"))
|
||||
}
|
||||
|
||||
if (mongoose.connection.readyState === 1) {
|
||||
return Promise.resolve(mongoose)
|
||||
}
|
||||
|
||||
if (connectionPromise) {
|
||||
return connectionPromise
|
||||
}
|
||||
|
||||
if (mongoose.connection.readyState === 2) {
|
||||
connectionPromise = mongoose.connection
|
||||
.asPromise()
|
||||
.then(() => mongoose)
|
||||
.catch((error: unknown) => {
|
||||
throw error
|
||||
})
|
||||
.finally(() => {
|
||||
connectionPromise = undefined
|
||||
})
|
||||
|
||||
return connectionPromise
|
||||
}
|
||||
|
||||
connectionPromise = mongoose
|
||||
.connect(uri)
|
||||
.then(() => mongoose)
|
||||
.catch((error: unknown) => {
|
||||
throw new Error("MongoDB connection failed", { cause: error })
|
||||
})
|
||||
.finally(() => {
|
||||
connectionPromise = undefined
|
||||
})
|
||||
|
||||
return connectionPromise
|
||||
}
|
||||
Reference in new issue
Block a user