ReviewOS

also looking at this

loghqorg/loghq

Deploy: uniform auth session model (main → production)

#7
Merged glennmichael123 wants to merge main into production
282 files +3028 -64856
app/Actions/Auth/LoginAction.tsadded+95-0
Changes to app/Actions/Auth/LoginAction.ts
@@ -0,0 +1,95 @@
1import type { RequestInstance } from '@stacksjs/types'
2import { Action } from '@stacksjs/actions'
3import { Auth, createTwoFactorChallenge, getTwoFactorState } from '@stacksjs/auth'
4import { User } from '@stacksjs/orm'
5import { response } from '@stacksjs/router'
6import { schema } from '@stacksjs/validation'
7import { buildAuthCookie, sessionExpiryMinutes } from './authCookie'
8
9/**
10 * Email/password sign-in, registered at POST /api/auth/login (routes/auth.ts).
11 *
12 * Replaces the old login.stx page action. loghq is server-rendered stx with no
13 * client hydration, so on success the issued bearer is mirrored into the
14 * HttpOnly `auth-token` cookie (see authCookie.ts) — that cookie IS the session
15 * every server-rendered page and every same-origin dashboard fetch
16 * authenticates from. There is no localStorage token and no Authorization
17 * header anywhere in the client any more.
18 *
19 * `Auth.attempt` carries the rate limiting (RateLimiter, keyed by email) and
20 * verifies credentials WITHOUT minting a token, so a 2FA-enabled account never
21 * gets a token pack before its TOTP code is also checked.
22 */
23export default new Action({
24 name: 'LoginAction',
25 description: 'Login to the application',
26 method: 'POST',
27
28 validations: {
29 email: {
30 rule: schema.string().email(),
31 message: 'Email must be a valid email address.',
32 },
33 password: {
34 rule: schema.string().min(6).max(255),
35 message: 'Password must be between 6 and 255 characters.',
36 },
37 },
38
39 async handle(request: RequestInstance) {
40 const email = String(request.get('email') ?? '').trim()
41 const password = String(request.get('password') ?? '')
42
43 const isValid = await Auth.attempt({ email, password })
44 if (!isValid)
45 return response.unauthorized('Invalid email or password.')
46
47 const authedUser = await User.where('email', '=', email).first()
48 if (!authedUser)
49 return response.unauthorized('Invalid email or password.')
50
51 // 2FA is dormant in loghq (no enrolment UI), but wired so a 2FA-enabled
52 // account can never lock itself out. getTwoFactorState reads two_factor_*
53 // columns that may not exist on this database yet — treat any failure as
54 // "not enabled" so a normal login is never broken by their absence.
55 let twoFactorEnabled = false
56 try {
57 twoFactorEnabled = (await getTwoFactorState(authedUser.id as number)).enabled
58 }
59 catch {
60 twoFactorEnabled = false
61 }
62
63 if (twoFactorEnabled) {
64 const challengeToken = await createTwoFactorChallenge(authedUser.id as number)
65 return response.json({
66 requires_two_factor: true,
67 challenge_token: challengeToken,
68 })
69 }
70
71 // Session length is set once, here, from the "remember me" checkbox: a week
72 // by default, 30 days when checked. See sessionExpiryMinutes.
73 const expiresInMinutes = sessionExpiryMinutes(request.get('remember'))
74 const result = await Auth.loginUsingId(authedUser.id as number, { expiresInMinutes })
75 if (!result)
76 return response.unauthorized('Invalid email or password.')
77
78 const user = result.user
79
80 return response.json(
81 {
82 access_token: result.token,
83 token_type: 'Bearer',
84 expires_in: result.expiresIn,
85 token: result.token,
86 user: {
87 id: user?.id,
88 email: user?.email,
89 name: user?.name,
90 },
91 },
92 { status: 200, headers: { 'Set-Cookie': buildAuthCookie(result.token, result.expiresIn) } },
93 )
94 },
95})