Blame · Line-by-line history
auth.tsx
Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.
| 06d5ffe | 1 | /** |
| 2 | * Auth routes — register, login, logout (web + API). | |
| 3 | */ | |
| 4 | ||
| 5 | import { Hono } from "hono"; | |
| 7298a17 | 6 | import { setCookie, deleteCookie, getCookie } from "hono/cookie"; |
| a4f3e24 | 7 | import { and, eq, isNull, sql } from "drizzle-orm"; |
| 06d5ffe | 8 | import { db } from "../db"; |
| 7298a17 | 9 | import { |
| 10 | users, | |
| 11 | sessions, | |
| 12 | organizations, | |
| 13 | userTotp, | |
| 14 | userRecoveryCodes, | |
| 15 | } from "../db/schema"; | |
| 06d5ffe | 16 | import { |
| 17 | hashPassword, | |
| 18 | verifyPassword, | |
| 19 | generateSessionToken, | |
| 20 | sessionCookieOptions, | |
| 21 | sessionExpiry, | |
| 22 | } from "../lib/auth"; | |
| 7298a17 | 23 | import { verifyTotpCode, hashRecoveryCode } from "../lib/totp"; |
| edf7c36 | 24 | import { getSsoConfig } from "../lib/sso"; |
| 06d5ffe | 25 | import { Layout } from "../views/layout"; |
| bb0f894 | 26 | import { |
| 27 | Form, | |
| 28 | FormGroup, | |
| 29 | Input, | |
| 30 | Button, | |
| 09be7bf | 31 | LinkButton, |
| bb0f894 | 32 | Alert, |
| 33 | Text, | |
| 34 | } from "../views/ui"; | |
| 06d5ffe | 35 | import type { AuthEnv } from "../middleware/auth"; |
| 36 | ||
| 37 | const auth = new Hono<AuthEnv>(); | |
| 38 | ||
| 39 | // --- Web UI --- | |
| 40 | ||
| 41 | auth.get("/register", (c) => { | |
| 42 | const error = c.req.query("error"); | |
| 134750b | 43 | const csrf = c.get("csrfToken") as string | undefined; |
| 06d5ffe | 44 | return c.html( |
| 45 | <Layout title="Register"> | |
| 46 | <div class="auth-container"> | |
| 47 | <h2>Create account</h2> | |
| 48 | {error && <div class="auth-error">{decodeURIComponent(error)}</div>} | |
| 134750b | 49 | <Form method="post" action="/register" csrfToken={csrf}> |
| 0316dbb | 50 | <FormGroup label="Username" htmlFor="username"> |
| 51 | <Input | |
| 52 | id="username" | |
| 06d5ffe | 53 | type="text" |
| 54 | name="username" | |
| 55 | required | |
| 56 | pattern="^[a-zA-Z0-9_-]+$" | |
| 57 | minLength={2} | |
| 58 | maxLength={39} | |
| 59 | placeholder="your-username" | |
| 60 | autocomplete="username" | |
| 61 | /> | |
| bb0f894 | 62 | </FormGroup> |
| 63 | <FormGroup label="Email" htmlFor="email"> | |
| 64 | <Input | |
| 06d5ffe | 65 | type="email" |
| 66 | name="email" | |
| 67 | required | |
| 68 | placeholder="you@example.com" | |
| 69 | autocomplete="email" | |
| 2c3ba6e | 70 | aria-label="Email" |
| 06d5ffe | 71 | /> |
| bb0f894 | 72 | </FormGroup> |
| 73 | <FormGroup label="Password" htmlFor="password"> | |
| 74 | <Input | |
| 06d5ffe | 75 | type="password" |
| 76 | name="password" | |
| 77 | required | |
| 78 | minLength={8} | |
| 79 | placeholder="Min 8 characters" | |
| 80 | autocomplete="new-password" | |
| 2c3ba6e | 81 | aria-label="Password" |
| 06d5ffe | 82 | /> |
| bb0f894 | 83 | </FormGroup> |
| 84 | <Button type="submit" variant="primary"> | |
| 06d5ffe | 85 | Create account |
| bb0f894 | 86 | </Button> |
| 87 | </Form> | |
| 06d5ffe | 88 | <p class="auth-switch"> |
| bb0f894 | 89 | <Text>Already have an account? <a href="/login">Sign in</a></Text> |
| 06d5ffe | 90 | </p> |
| 91 | </div> | |
| 92 | </Layout> | |
| 93 | ); | |
| 94 | }); | |
| 95 | ||
| 96 | auth.post("/register", async (c) => { | |
| 97 | const body = await c.req.parseBody(); | |
| 98 | const username = String(body.username || "").trim(); | |
| 99 | const email = String(body.email || "").trim(); | |
| 100 | const password = String(body.password || ""); | |
| 101 | ||
| 102 | if (!username || !email || !password) { | |
| 103 | return c.redirect("/register?error=All+fields+are+required"); | |
| 104 | } | |
| 105 | ||
| 106 | if (!/^[a-zA-Z0-9_-]+$/.test(username)) { | |
| 107 | return c.redirect( | |
| 108 | "/register?error=Username+may+only+contain+letters%2C+numbers%2C+hyphens+and+underscores" | |
| 109 | ); | |
| 110 | } | |
| 111 | ||
| 112 | if (password.length < 8) { | |
| 113 | return c.redirect("/register?error=Password+must+be+at+least+8+characters"); | |
| 114 | } | |
| 115 | ||
| 116 | // Check existing | |
| 117 | const [existingUser] = await db | |
| 118 | .select() | |
| 119 | .from(users) | |
| 120 | .where(eq(users.username, username)) | |
| 121 | .limit(1); | |
| 122 | if (existingUser) { | |
| 123 | return c.redirect("/register?error=Username+already+taken"); | |
| 124 | } | |
| 125 | ||
| 7437605 | 126 | // B2: usernames share the URL namespace with org slugs; refuse collisions. |
| 127 | const [existingOrg] = await db | |
| 128 | .select({ id: organizations.id }) | |
| 129 | .from(organizations) | |
| 130 | .where(eq(organizations.slug, username.toLowerCase())) | |
| 131 | .limit(1); | |
| 132 | if (existingOrg) { | |
| 133 | return c.redirect("/register?error=Username+already+taken"); | |
| 134 | } | |
| 135 | ||
| 06d5ffe | 136 | const [existingEmail] = await db |
| 137 | .select() | |
| 138 | .from(users) | |
| 139 | .where(eq(users.email, email)) | |
| 140 | .limit(1); | |
| 141 | if (existingEmail) { | |
| 142 | return c.redirect("/register?error=Email+already+registered"); | |
| 143 | } | |
| 144 | ||
| 145 | const passwordHash = await hashPassword(password); | |
| 146 | ||
| a4f3e24 | 147 | // First user ever registered becomes admin automatically |
| 148 | const [userCount] = await db | |
| 149 | .select({ count: sql`count(*)::int` }) | |
| 150 | .from(users); | |
| 151 | const isFirstUser = (userCount?.count as number) === 0; | |
| 152 | ||
| 06d5ffe | 153 | const [user] = await db |
| 154 | .insert(users) | |
| a4f3e24 | 155 | .values({ username, email, passwordHash, isAdmin: isFirstUser }) |
| 06d5ffe | 156 | .returning(); |
| 157 | ||
| 2d985e5 | 158 | // If username matches SITE_ADMIN_USERNAME env, grant site admin instantly |
| 159 | // so the operator doesn't have to wait for the next boot's bootstrap pass. | |
| 160 | await import("../lib/admin-bootstrap").then((m) => | |
| 161 | m.ensureEnvAdminOnRegister({ userId: user.id, username }) | |
| 162 | ).catch(() => {}); | |
| 163 | ||
| 06d5ffe | 164 | // Create session |
| 165 | const token = generateSessionToken(); | |
| 166 | await db.insert(sessions).values({ | |
| 167 | userId: user.id, | |
| 168 | token, | |
| 169 | expiresAt: sessionExpiry(), | |
| 170 | }); | |
| 171 | ||
| 172 | setCookie(c, "session", token, sessionCookieOptions()); | |
| 173 | ||
| 174 | const redirect = c.req.query("redirect") || "/"; | |
| 175 | return c.redirect(redirect); | |
| 176 | }); | |
| 177 | ||
| edf7c36 | 178 | auth.get("/login", async (c) => { |
| 06d5ffe | 179 | const error = c.req.query("error"); |
| 180 | const redirect = c.req.query("redirect") || ""; | |
| edf7c36 | 181 | const ssoCfg = await getSsoConfig(); |
| 182 | const ssoEnabled = | |
| 183 | !!ssoCfg?.enabled && | |
| 184 | !!ssoCfg.authorizationEndpoint && | |
| 185 | !!ssoCfg.tokenEndpoint && | |
| 186 | !!ssoCfg.userinfoEndpoint && | |
| 187 | !!ssoCfg.clientId && | |
| 188 | !!ssoCfg.clientSecret; | |
| 189 | const ssoLabel = ssoCfg?.providerName || "SSO"; | |
| 134750b | 190 | const csrf = c.get("csrfToken") as string | undefined; |
| 06d5ffe | 191 | return c.html( |
| 192 | <Layout title="Sign in"> | |
| 193 | <div class="auth-container"> | |
| 194 | <h2>Sign in</h2> | |
| 195 | {error && <div class="auth-error">{decodeURIComponent(error)}</div>} | |
| 0316dbb | 196 | <Form |
| b9968e3 | 197 | method="post" |
| 06d5ffe | 198 | action={`/login${redirect ? `?redirect=${encodeURIComponent(redirect)}` : ""}`} |
| 134750b | 199 | csrfToken={csrf} |
| 06d5ffe | 200 | > |
| bb0f894 | 201 | <FormGroup label="Username or email" htmlFor="username"> |
| 202 | <Input | |
| 06d5ffe | 203 | type="text" |
| 204 | name="username" | |
| 205 | required | |
| 206 | placeholder="username or email" | |
| 207 | autocomplete="username" | |
| 2c3ba6e | 208 | aria-label="Username or email" |
| 06d5ffe | 209 | /> |
| bb0f894 | 210 | </FormGroup> |
| 211 | <FormGroup label="Password" htmlFor="password"> | |
| 212 | <Input | |
| 06d5ffe | 213 | type="password" |
| 214 | name="password" | |
| 215 | required | |
| 216 | placeholder="Password" | |
| 217 | autocomplete="current-password" | |
| 2c3ba6e | 218 | aria-label="Password" |
| 06d5ffe | 219 | /> |
| bb0f894 | 220 | </FormGroup> |
| 221 | <Button type="submit" variant="primary"> | |
| 06d5ffe | 222 | Sign in |
| bb0f894 | 223 | </Button> |
| 224 | </Form> | |
| 09be7bf | 225 | {ssoEnabled && ( |
| 226 | <div class="auth-sso"> | |
| 227 | <div class="auth-divider">or</div> | |
| 228 | <LinkButton href="/login/sso">Sign in with {ssoLabel}</LinkButton> | |
| 229 | </div> | |
| 230 | )} | |
| 06d5ffe | 231 | <p class="auth-switch"> |
| bb0f894 | 232 | <Text>New to gluecron? <a href="/register">Create an account</a></Text> |
| 06d5ffe | 233 | </p> |
| 2df1f8c | 234 | <script |
| 235 | dangerouslySetInnerHTML={{ | |
| 236 | __html: /* js */ ` | |
| 237 | (function () { | |
| 238 | const btn = document.getElementById('pk-signin-btn'); | |
| 239 | const status = document.getElementById('pk-signin-status'); | |
| 240 | const userInput = document.getElementById('username'); | |
| 241 | const redirect = ${JSON.stringify(redirect || "/")}; | |
| 242 | if (!btn) return; | |
| 243 | function b64uToBuf(s) { | |
| 244 | s = s.replace(/-/g,'+').replace(/_/g,'/'); | |
| 245 | while (s.length % 4) s += '='; | |
| 246 | const bin = atob(s); | |
| 247 | const buf = new Uint8Array(bin.length); | |
| 248 | for (let i=0;i<bin.length;i++) buf[i] = bin.charCodeAt(i); | |
| 249 | return buf.buffer; | |
| 250 | } | |
| 251 | function bufToB64u(buf) { | |
| 252 | const bytes = new Uint8Array(buf); | |
| 253 | let bin = ''; | |
| 254 | for (let i=0;i<bytes.length;i++) bin += String.fromCharCode(bytes[i]); | |
| 255 | return btoa(bin).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,''); | |
| 256 | } | |
| 257 | btn.addEventListener('click', async function () { | |
| 258 | if (!window.PublicKeyCredential) { | |
| 259 | status.textContent = 'Passkeys not supported in this browser.'; | |
| 260 | return; | |
| 261 | } | |
| 262 | status.textContent = 'Preparing…'; | |
| 263 | try { | |
| 264 | const username = (userInput && userInput.value || '').trim(); | |
| 265 | const optsRes = await fetch('/api/passkeys/auth/options', { | |
| 266 | method: 'POST', | |
| 267 | headers: { 'content-type': 'application/json' }, | |
| 268 | body: JSON.stringify(username ? { username: username } : {}) | |
| 269 | }); | |
| 270 | if (!optsRes.ok) throw new Error('options failed'); | |
| 271 | const { options, sessionKey } = await optsRes.json(); | |
| 272 | options.challenge = b64uToBuf(options.challenge); | |
| 273 | if (options.allowCredentials) { | |
| 274 | options.allowCredentials = options.allowCredentials.map(function (c) { | |
| 275 | return Object.assign({}, c, { id: b64uToBuf(c.id) }); | |
| 276 | }); | |
| 277 | } | |
| 278 | status.textContent = 'Touch your authenticator…'; | |
| 279 | const cred = await navigator.credentials.get({ publicKey: options }); | |
| 280 | const resp = { | |
| 281 | id: cred.id, | |
| 282 | rawId: bufToB64u(cred.rawId), | |
| 283 | type: cred.type, | |
| 284 | response: { | |
| 285 | clientDataJSON: bufToB64u(cred.response.clientDataJSON), | |
| 286 | authenticatorData: bufToB64u(cred.response.authenticatorData), | |
| 287 | signature: bufToB64u(cred.response.signature), | |
| 288 | userHandle: cred.response.userHandle ? bufToB64u(cred.response.userHandle) : null | |
| 289 | }, | |
| 290 | clientExtensionResults: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {} | |
| 291 | }; | |
| 292 | const verifyRes = await fetch('/api/passkeys/auth/verify', { | |
| 293 | method: 'POST', | |
| 294 | headers: { 'content-type': 'application/json' }, | |
| 295 | body: JSON.stringify({ sessionKey: sessionKey, response: resp }) | |
| 296 | }); | |
| 297 | if (!verifyRes.ok) { | |
| 298 | const j = await verifyRes.json().catch(function () { return {}; }); | |
| 299 | throw new Error(j.error || 'verify failed'); | |
| 300 | } | |
| 301 | status.textContent = 'Signed in. Redirecting…'; | |
| 302 | window.location.href = redirect; | |
| 303 | } catch (e) { | |
| 304 | status.textContent = 'Error: ' + (e && e.message ? e.message : e); | |
| 305 | } | |
| 306 | }); | |
| 307 | })(); | |
| 308 | `, | |
| 309 | }} | |
| 310 | /> | |
| 06d5ffe | 311 | </div> |
| 312 | </Layout> | |
| 313 | ); | |
| 314 | }); | |
| 315 | ||
| 316 | auth.post("/login", async (c) => { | |
| 317 | const body = await c.req.parseBody(); | |
| 318 | const identifier = String(body.username || "").trim(); | |
| 319 | const password = String(body.password || ""); | |
| 320 | const redirect = c.req.query("redirect") || "/"; | |
| 321 | ||
| 322 | if (!identifier || !password) { | |
| 323 | return c.redirect("/login?error=All+fields+are+required"); | |
| 324 | } | |
| 325 | ||
| 326 | // Find user by username or email | |
| 327 | const isEmail = identifier.includes("@"); | |
| 328 | const [user] = await db | |
| 329 | .select() | |
| 330 | .from(users) | |
| 331 | .where( | |
| 332 | isEmail | |
| 333 | ? eq(users.email, identifier) | |
| 334 | : eq(users.username, identifier) | |
| 335 | ) | |
| 336 | .limit(1); | |
| 337 | ||
| 338 | if (!user) { | |
| 339 | return c.redirect("/login?error=Invalid+credentials"); | |
| 340 | } | |
| 341 | ||
| 342 | const valid = await verifyPassword(password, user.passwordHash); | |
| 343 | if (!valid) { | |
| 344 | return c.redirect("/login?error=Invalid+credentials"); | |
| 345 | } | |
| 346 | ||
| 7298a17 | 347 | // B4: if the user has TOTP enabled, issue a pending-2fa session and |
| 348 | // redirect to the code prompt. | |
| 349 | const [totp] = await db | |
| 350 | .select({ enabledAt: userTotp.enabledAt }) | |
| 351 | .from(userTotp) | |
| 352 | .where(eq(userTotp.userId, user.id)) | |
| 353 | .limit(1); | |
| 354 | const needs2fa = !!(totp && totp.enabledAt); | |
| 355 | ||
| 06d5ffe | 356 | const token = generateSessionToken(); |
| 357 | await db.insert(sessions).values({ | |
| 358 | userId: user.id, | |
| 359 | token, | |
| 360 | expiresAt: sessionExpiry(), | |
| 7298a17 | 361 | requires2fa: needs2fa, |
| 06d5ffe | 362 | }); |
| 363 | ||
| 364 | setCookie(c, "session", token, sessionCookieOptions()); | |
| 7298a17 | 365 | if (needs2fa) { |
| 366 | return c.redirect( | |
| 367 | `/login/2fa?redirect=${encodeURIComponent(redirect)}` | |
| 368 | ); | |
| 369 | } | |
| 06d5ffe | 370 | return c.redirect(redirect); |
| 371 | }); | |
| 372 | ||
| 7298a17 | 373 | // --- 2FA verify (B4) --- |
| 374 | auth.get("/login/2fa", async (c) => { | |
| 375 | const token = getCookie(c, "session"); | |
| 376 | if (!token) return c.redirect("/login"); | |
| 377 | const error = c.req.query("error"); | |
| 378 | const redirect = c.req.query("redirect") || "/"; | |
| 379 | return c.html( | |
| 380 | <Layout title="Two-factor authentication"> | |
| 381 | <div class="auth-container"> | |
| 382 | <h2>Enter your code</h2> | |
| 383 | <p | |
| 384 | class="auth-switch" | |
| 385 | style="margin-bottom: 16px; margin-top: 0" | |
| 386 | > | |
| 387 | Open your authenticator app and enter the 6-digit code. Lost your | |
| 388 | device? Paste a recovery code instead. | |
| 389 | </p> | |
| 390 | {error && <div class="auth-error">{decodeURIComponent(error)}</div>} | |
| 391 | <form | |
| b9968e3 | 392 | method="post" |
| 7298a17 | 393 | action={`/login/2fa?redirect=${encodeURIComponent(redirect)}`} |
| 394 | > | |
| 134750b | 395 | <input type="hidden" name="_csrf" value={(c.get("csrfToken") as string | undefined) || ""} /> |
| 7298a17 | 396 | <div class="form-group"> |
| 397 | <label for="code">Code</label> | |
| 398 | <input | |
| 399 | type="text" | |
| 400 | id="code" | |
| 401 | name="code" | |
| 402 | required | |
| 403 | autocomplete="one-time-code" | |
| 404 | inputmode="numeric" | |
| 405 | maxLength={24} | |
| 406 | placeholder="123456 or xxxx-xxxx-xxxx" | |
| 407 | /> | |
| 408 | </div> | |
| 409 | <button type="submit" class="btn btn-primary"> | |
| 410 | Verify | |
| 411 | </button> | |
| 412 | </form> | |
| 413 | <p class="auth-switch"> | |
| 414 | <a href="/logout">Cancel</a> | |
| 415 | </p> | |
| 416 | </div> | |
| 417 | </Layout> | |
| 418 | ); | |
| 419 | }); | |
| 420 | ||
| 421 | auth.post("/login/2fa", async (c) => { | |
| 422 | const token = getCookie(c, "session"); | |
| 423 | if (!token) return c.redirect("/login"); | |
| 424 | const body = await c.req.parseBody(); | |
| 425 | const code = String(body.code || "").trim(); | |
| 426 | const redirect = c.req.query("redirect") || "/"; | |
| 427 | ||
| 428 | if (!code) { | |
| 429 | return c.redirect( | |
| 430 | `/login/2fa?error=Code+is+required&redirect=${encodeURIComponent(redirect)}` | |
| 431 | ); | |
| 432 | } | |
| 433 | ||
| 434 | try { | |
| 435 | const [session] = await db | |
| 436 | .select() | |
| 437 | .from(sessions) | |
| 438 | .where(eq(sessions.token, token)) | |
| 439 | .limit(1); | |
| 440 | if ( | |
| 441 | !session || | |
| 442 | new Date(session.expiresAt) < new Date() || | |
| 443 | !session.requires2fa | |
| 444 | ) { | |
| 445 | return c.redirect("/login"); | |
| 446 | } | |
| 447 | ||
| 448 | const [totp] = await db | |
| 449 | .select() | |
| 450 | .from(userTotp) | |
| 451 | .where(eq(userTotp.userId, session.userId)) | |
| 452 | .limit(1); | |
| 453 | if (!totp || !totp.enabledAt) { | |
| 454 | // User doesn't have 2FA actually enabled — clear the flag and let | |
| 455 | // them in. This can only happen if 2FA was disabled in another | |
| 456 | // session between password check and code prompt. | |
| 457 | await db | |
| 458 | .update(sessions) | |
| 459 | .set({ requires2fa: false }) | |
| 460 | .where(eq(sessions.token, token)); | |
| 461 | return c.redirect(redirect); | |
| 462 | } | |
| 463 | ||
| 464 | // Try TOTP code first. | |
| 465 | const isSix = /^\d{6}$/.test(code); | |
| 466 | let ok = false; | |
| 467 | if (isSix) { | |
| 468 | ok = await verifyTotpCode(totp.secret, code); | |
| 469 | } | |
| 470 | // Fall through to recovery code. | |
| 471 | if (!ok) { | |
| 472 | const hash = await hashRecoveryCode(code); | |
| 473 | const [rec] = await db | |
| 474 | .select() | |
| 475 | .from(userRecoveryCodes) | |
| 476 | .where( | |
| 477 | and( | |
| 478 | eq(userRecoveryCodes.userId, session.userId), | |
| 479 | eq(userRecoveryCodes.codeHash, hash), | |
| 480 | isNull(userRecoveryCodes.usedAt) | |
| 481 | ) | |
| 482 | ) | |
| 483 | .limit(1); | |
| 484 | if (rec) { | |
| 485 | await db | |
| 486 | .update(userRecoveryCodes) | |
| 487 | .set({ usedAt: new Date() }) | |
| 488 | .where(eq(userRecoveryCodes.id, rec.id)); | |
| 489 | ok = true; | |
| 490 | } | |
| 491 | } | |
| 492 | ||
| 493 | if (!ok) { | |
| 494 | return c.redirect( | |
| 495 | `/login/2fa?error=Invalid+code&redirect=${encodeURIComponent(redirect)}` | |
| 496 | ); | |
| 497 | } | |
| 498 | ||
| 499 | await db | |
| 500 | .update(sessions) | |
| 501 | .set({ requires2fa: false }) | |
| 502 | .where(eq(sessions.token, token)); | |
| 503 | await db | |
| 504 | .update(userTotp) | |
| 505 | .set({ lastUsedAt: new Date() }) | |
| 506 | .where(eq(userTotp.userId, session.userId)); | |
| 507 | ||
| 508 | return c.redirect(redirect); | |
| 509 | } catch (err) { | |
| 510 | console.error("[auth] 2fa verify:", err); | |
| 511 | return c.redirect( | |
| 512 | `/login/2fa?error=Service+unavailable&redirect=${encodeURIComponent(redirect)}` | |
| 513 | ); | |
| 514 | } | |
| 515 | }); | |
| 516 | ||
| 06d5ffe | 517 | auth.get("/logout", async (c) => { |
| 518 | deleteCookie(c, "session", { path: "/" }); | |
| 519 | return c.redirect("/"); | |
| 520 | }); | |
| 521 | ||
| 522 | // --- API --- | |
| 523 | ||
| 524 | auth.post("/api/auth/register", async (c) => { | |
| 525 | const body = await c.req.json<{ | |
| 526 | username: string; | |
| 527 | email: string; | |
| 528 | password: string; | |
| 529 | }>(); | |
| 530 | ||
| 531 | if (!body.username || !body.email || !body.password) { | |
| 532 | return c.json({ error: "username, email, and password are required" }, 400); | |
| 533 | } | |
| 534 | ||
| 535 | if (!/^[a-zA-Z0-9_-]+$/.test(body.username)) { | |
| 536 | return c.json({ error: "Invalid username" }, 400); | |
| 537 | } | |
| 538 | ||
| 539 | if (body.password.length < 8) { | |
| 540 | return c.json({ error: "Password must be at least 8 characters" }, 400); | |
| 541 | } | |
| 542 | ||
| 543 | const [existing] = await db | |
| 544 | .select() | |
| 545 | .from(users) | |
| 546 | .where(eq(users.username, body.username)) | |
| 547 | .limit(1); | |
| 548 | if (existing) { | |
| 549 | return c.json({ error: "Username already taken" }, 409); | |
| 550 | } | |
| 551 | ||
| 552 | const passwordHash = await hashPassword(body.password); | |
| 553 | const [user] = await db | |
| 554 | .insert(users) | |
| 555 | .values({ | |
| 556 | username: body.username, | |
| 557 | email: body.email, | |
| 558 | passwordHash, | |
| 559 | }) | |
| 560 | .returning(); | |
| 561 | ||
| 562 | const token = generateSessionToken(); | |
| 563 | await db.insert(sessions).values({ | |
| 564 | userId: user.id, | |
| 565 | token, | |
| 566 | expiresAt: sessionExpiry(), | |
| 567 | }); | |
| 568 | ||
| 569 | return c.json( | |
| 570 | { | |
| 571 | user: { id: user.id, username: user.username, email: user.email }, | |
| 572 | token, | |
| 573 | }, | |
| 574 | 201 | |
| 575 | ); | |
| 576 | }); | |
| 577 | ||
| 578 | auth.post("/api/auth/login", async (c) => { | |
| 579 | const body = await c.req.json<{ username: string; password: string }>(); | |
| 580 | ||
| 581 | if (!body.username || !body.password) { | |
| 582 | return c.json({ error: "username and password are required" }, 400); | |
| 583 | } | |
| 584 | ||
| 585 | const isEmail = body.username.includes("@"); | |
| 586 | const [user] = await db | |
| 587 | .select() | |
| 588 | .from(users) | |
| 589 | .where( | |
| 590 | isEmail | |
| 591 | ? eq(users.email, body.username) | |
| 592 | : eq(users.username, body.username) | |
| 593 | ) | |
| 594 | .limit(1); | |
| 595 | ||
| 596 | if (!user) return c.json({ error: "Invalid credentials" }, 401); | |
| 597 | ||
| 598 | const valid = await verifyPassword(body.password, user.passwordHash); | |
| 599 | if (!valid) return c.json({ error: "Invalid credentials" }, 401); | |
| 600 | ||
| 601 | const token = generateSessionToken(); | |
| 602 | await db.insert(sessions).values({ | |
| 603 | userId: user.id, | |
| 604 | token, | |
| 605 | expiresAt: sessionExpiry(), | |
| 606 | }); | |
| 607 | ||
| 608 | return c.json({ | |
| 609 | user: { id: user.id, username: user.username, email: user.email }, | |
| 610 | token, | |
| 611 | }); | |
| 612 | }); | |
| 613 | ||
| 614 | export default auth; |