also looking at this
chore: wip stx improvements
#1649
241 files
+19022
-1323
| @@ -0,0 +1,39 @@ | ||
| 1 | import type { Session, User } from './types' | |
| 2 | import { hashPassword, verifyPassword } from './password' | |
| 3 | import { createSession, destroySession, getSession } from './session' | |
| 4 | ||
| 5 | export async function login( | |
| 6 | email: string, | |
| 7 | password: string, | |
| 8 | findUser: (email: string) => Promise<(User & { password: string }) | null>, | |
| 9 | ): Promise<Session | null> { | |
| 10 | const user = await findUser(email) | |
| 11 | if (!user) | |
| 12 | return null | |
| 13 | ||
| 14 | const valid = await verifyPassword(password, user.password) | |
| 15 | if (!valid) | |
| 16 | return null | |
| 17 | ||
| 18 | return createSession(user.id, { email: user.email, name: user.name }) | |
| 19 | } | |
| 20 | ||
| 21 | export function logout(sessionId: string): void { | |
| 22 | destroySession(sessionId) | |
| 23 | } | |
| 24 | ||
| 25 | export async function register( | |
| 26 | data: { email: string, password: string, name?: string }, | |
| 27 | createUser: (userData: { email: string, password: string, name?: string }) => Promise<User>, | |
| 28 | ): Promise<User> { | |
| 29 | const hashed = await hashPassword(data.password) | |
| 30 | return createUser({ ...data, password: hashed }) | |
| 31 | } | |
| 32 | ||
| 33 | export function getUser(sessionId: string): { userId: string | number, data: Record<string, unknown> } | null { | |
| 34 | const session = getSession(sessionId) | |
| 35 | if (!session) | |
| 36 | return null | |
| 37 | ||
| 38 | return { userId: session.userId, data: session.data } | |
| 39 | } | |