66 lines
1.9 KiB
TypeScript
66 lines
1.9 KiB
TypeScript
import { sign } from 'jsonwebtoken'
|
|
|
|
const SSO_BASE = process.env.SSO_URL ?? 'http://localhost:4001'
|
|
const JWT_SECRET = process.env.JWT_SECRET ?? 'dev-jwt-secret-change-in-production'
|
|
|
|
export interface SsoUser {
|
|
id: string
|
|
email: string
|
|
username: string
|
|
}
|
|
|
|
export interface AuthResult {
|
|
success: boolean
|
|
user?: SsoUser
|
|
sessionId?: string
|
|
error?: string
|
|
}
|
|
|
|
export function makeProfileJwt(userId: string, email: string): string {
|
|
return sign(
|
|
{ sub: userId, email, role: 'provider' },
|
|
JWT_SECRET,
|
|
{ expiresIn: '1h' },
|
|
)
|
|
}
|
|
|
|
export async function registerUser(data: {
|
|
email: string
|
|
username: string
|
|
password: string
|
|
registrationSelection?: string
|
|
}): Promise<AuthResult> {
|
|
try {
|
|
const res = await fetch(`${SSO_BASE}/auth/register`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(data),
|
|
})
|
|
const body = await res.json()
|
|
if (!res.ok) {
|
|
return { success: false, error: body.message ?? `HTTP ${res.status}` }
|
|
}
|
|
return { success: true, user: body.user, sessionId: body.sessionId }
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err)
|
|
return { success: false, error: `Registration failed: ${message}` }
|
|
}
|
|
}
|
|
|
|
export async function loginUser(email: string, password: string): Promise<AuthResult> {
|
|
try {
|
|
const res = await fetch(`${SSO_BASE}/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email, password }),
|
|
})
|
|
const body = await res.json()
|
|
if (!res.ok || !body.success) {
|
|
return { success: false, error: body.message ?? `HTTP ${res.status}` }
|
|
}
|
|
return { success: true, user: body.user, sessionId: body.sessionId }
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err)
|
|
return { success: false, error: `Login failed: ${message}` }
|
|
}
|
|
}
|