also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,883 +0,0 @@ | ||
| 1 | # Authentication How-To | |
| 2 | ||
| 3 | This guide covers implementing authentication in your Stacks application, including user registration, login, token management, and protected routes. | |
| 4 | ||
| 5 | ## Setting Up Authentication | |
| 6 | ||
| 7 | ### Configuration | |
| 8 | ||
| 9 | Configure authentication in `config/auth.ts`: | |
| 10 | ||
| 11 | ```typescript | |
| 12 | // config/auth.ts | |
| 13 | import type { AuthConfig } from '@stacksjs/types' | |
| 14 | ||
| 15 | export default { | |
| 16 | // Default authentication guard | |
| 17 | default: 'api', | |
| 18 | ||
| 19 | // Available guards | |
| 20 | guards: { | |
| 21 | api: { | |
| 22 | driver: 'token', | |
| 23 | provider: 'users', | |
| 24 | }, | |
| 25 | }, | |
| 26 | ||
| 27 | // User providers | |
| 28 | providers: { | |
| 29 | users: { | |
| 30 | driver: 'database', | |
| 31 | table: 'users', | |
| 32 | }, | |
| 33 | }, | |
| 34 | ||
| 35 | // Field names | |
| 36 | username: 'email', | |
| 37 | password: 'password', | |
| 38 | ||
| 39 | // Token settings | |
| 40 | tokenExpiry: 30 * 24 * 60 * 60 * 1000, // 30 days | |
| 41 | tokenRotation: 24, // hours | |
| 42 | defaultAbilities: ['*'], | |
| 43 | defaultTokenName: 'auth-token', | |
| 44 | ||
| 45 | // Password reset | |
| 46 | passwordReset: { | |
| 47 | expire: 60, // minutes | |
| 48 | throttle: 60, // seconds | |
| 49 | }, | |
| 50 | } satisfies AuthConfig | |
| 51 | ``` | |
| 52 | ||
| 53 | ### Database Setup | |
| 54 | ||
| 55 | Ensure your users table has the required fields: | |
| 56 | ||
| 57 | ```sql | |
| 58 | -- database/migrations/create-users-table.sql | |
| 59 | CREATE TABLE users ( | |
| 60 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 61 | email TEXT NOT NULL UNIQUE, | |
| 62 | password TEXT NOT NULL, | |
| 63 | name TEXT, | |
| 64 | email*verified*at DATETIME, | |
| 65 | created*at DATETIME DEFAULT CURRENT*TIMESTAMP, | |
| 66 | updated*at DATETIME DEFAULT CURRENT*TIMESTAMP | |
| 67 | ); | |
| 68 | ||
| 69 | -- Tokens table for API authentication | |
| 70 | CREATE TABLE personal*access*tokens ( | |
| 71 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 72 | user*id INTEGER NOT NULL, | |
| 73 | name TEXT NOT NULL, | |
| 74 | token TEXT NOT NULL UNIQUE, | |
| 75 | abilities TEXT, | |
| 76 | last*used*at DATETIME, | |
| 77 | expires*at DATETIME, | |
| 78 | created*at DATETIME DEFAULT CURRENT*TIMESTAMP, | |
| 79 | FOREIGN KEY (user*id) REFERENCES users(id) ON DELETE CASCADE | |
| 80 | ); | |
| 81 | ``` | |
| 82 | ||
| 83 | Run migrations: | |
| 84 | ||
| 85 | ```bash | |
| 86 | buddy migrate | |
| 87 | ``` | |
| 88 | ||
| 89 | ## User Registration | |
| 90 | ||
| 91 | ### Registration Action | |
| 92 | ||
| 93 | ```typescript | |
| 94 | // app/Actions/Auth/RegisterAction.ts | |
| 95 | import type { RequestInstance } from '@stacksjs/types' | |
| 96 | import { Action } from '@stacksjs/actions' | |
| 97 | import { register } from '@stacksjs/auth' | |
| 98 | import { response } from '@stacksjs/router' | |
| 99 | import { schema } from '@stacksjs/validation' | |
| 100 | ||
| 101 | export default new Action({ | |
| 102 | name: 'RegisterAction', | |
| 103 | description: 'Register a new user', | |
| 104 | method: 'POST', | |
| 105 | ||
| 106 | validations: { | |
| 107 | email: { | |
| 108 | rule: schema.string().email(), | |
| 109 | message: 'Please provide a valid email address.', | |
| 110 | }, | |
| 111 | password: { | |
| 112 | rule: schema.string().min(8).max(255), | |
| 113 | message: 'Password must be at least 8 characters.', | |
| 114 | }, | |
| 115 | password*confirmation: { | |
| 116 | rule: schema.string(), | |
| 117 | message: 'Password confirmation is required.', | |
| 118 | }, | |
| 119 | name: { | |
| 120 | rule: schema.string().min(2).max(100), | |
| 121 | message: 'Name must be between 2 and 100 characters.', | |
| 122 | }, | |
| 123 | }, | |
| 124 | ||
| 125 | async handle(request: RequestInstance) { | |
| 126 | const email = request.get('email') | |
| 127 | const password = request.get('password') | |
| 128 | const passwordConfirmation = request.get('password*confirmation') | |
| 129 | const name = request.get('name') | |
| 130 | ||
| 131 | // Verify password confirmation | |
| 132 | if (password !== passwordConfirmation) { | |
| 133 | return response.badRequest('Passwords do not match.') | |
| 134 | } | |
| 135 | ||
| 136 | // Check if email already exists | |
| 137 | const existingUser = await User.where('email', email).first() | |
| 138 | if (existingUser) { | |
| 139 | return response.badRequest('Email already registered.') | |
| 140 | } | |
| 141 | ||
| 142 | // Register the user | |
| 143 | const result = await register({ email, password, name }) | |
| 144 | ||
| 145 | if (result) { | |
| 146 | return response.json({ | |
| 147 | message: 'Registration successful', | |
| 148 | token: result.token, | |
| 149 | user: { | |
| 150 | id: result.user.id, | |
| 151 | email: result.user.email, | |
| 152 | name: result.user.name, | |
| 153 | }, | |
| 154 | }, 201) | |
| 155 | } | |
| 156 | ||
| 157 | return response.error('Registration failed') | |
| 158 | }, | |
| 159 | }) | |
| 160 | ``` | |
| 161 | ||
| 162 | ### Registration Route | |
| 163 | ||
| 164 | ```typescript | |
| 165 | // routes/api.ts | |
| 166 | route.post('/register', 'Actions/Auth/RegisterAction') | |
| 167 | ``` | |
| 168 | ||
| 169 | ### Registration Form (Frontend) | |
| 170 | ||
| 171 | ```html | |
| 172 | <!-- resources/components/RegisterForm.stx --> | |
| 173 | <script server> | |
| 174 | import { ref } from '@stacksjs/reactivity' | |
| 175 | ||
| 176 | const form = ref({ | |
| 177 | name: '', | |
| 178 | email: '', | |
| 179 | password: '', | |
| 180 | password*confirmation: '', | |
| 181 | }) | |
| 182 | const error = ref('') | |
| 183 | const loading = ref(false) | |
| 184 | ||
| 185 | async function handleRegister() { | |
| 186 | error.value = '' | |
| 187 | loading.value = true | |
| 188 | ||
| 189 | try { | |
| 190 | const res = await fetch('/api/register', { | |
| 191 | method: 'POST', | |
| 192 | headers: { 'Content-Type': 'application/json' }, | |
| 193 | body: JSON.stringify(form.value), | |
| 194 | }) | |
| 195 | ||
| 196 | const data = await res.json() | |
| 197 | ||
| 198 | if (!res.ok) { | |
| 199 | error.value = data.message || 'Registration failed' | |
| 200 | return | |
| 201 | } | |
| 202 | ||
| 203 | // Store token and redirect | |
| 204 | localStorage.setItem('token', data.token) | |
| 205 | window.location.href = '/dashboard' | |
| 206 | } catch (e) { | |
| 207 | error.value = 'An error occurred. Please try again.' | |
| 208 | } finally { | |
| 209 | loading.value = false | |
| 210 | } | |
| 211 | } | |
| 212 | </script> | |
| 213 | ||
| 214 | <form onsubmit="event.preventDefault(); handleRegister()" class="mx-auto space-y-4 max-w-md"> | |
| 215 | <h2 class="font-bold text-2xl">Create Account</h2> | |
| 216 | ||
| 217 | @if(error.value) | |
| 218 | <div class="p-3 text-red-700 bg-red-100 rounded"> | |
| 219 | {{ error.value }} | |
| 220 | </div> | |
| 221 | @endif | |
| 222 | ||
| 223 | <div> | |
| 224 | <label class="block mb-1 font-medium text-sm">Name</label> | |
| 225 | <input | |
| 226 | type="text" | |
| 227 | value="{{ form.value.name }}" | |
| 228 | oninput="form.value.name = event.target.value" | |
| 229 | class="px-3 py-2 w-full border rounded-lg" | |
| 230 | required | |
| 231 | /> | |
| 232 | </div> | |
| 233 | ||
| 234 | <div> | |
| 235 | <label class="block mb-1 font-medium text-sm">Email</label> | |
| 236 | <input | |
| 237 | type="email" | |
| 238 | value="{{ form.value.email }}" | |
| 239 | oninput="form.value.email = event.target.value" | |
| 240 | class="px-3 py-2 w-full border rounded-lg" | |
| 241 | required | |
| 242 | /> | |
| 243 | </div> | |
| 244 | ||
| 245 | <div> | |
| 246 | <label class="block mb-1 font-medium text-sm">Password</label> | |
| 247 | <input | |
| 248 | type="password" | |
| 249 | value="{{ form.value.password }}" | |
| 250 | oninput="form.value.password = event.target.value" | |
| 251 | class="px-3 py-2 w-full border rounded-lg" | |
| 252 | required | |
| 253 | /> | |
| 254 | </div> | |
| 255 | ||
| 256 | <div> | |
| 257 | <label class="block mb-1 font-medium text-sm">Confirm Password</label> | |
| 258 | <input | |
| 259 | type="password" | |
| 260 | value="{{ form.value.password*confirmation }}" | |
| 261 | oninput="form.value.password*confirmation = event.target.value" | |
| 262 | class="px-3 py-2 w-full border rounded-lg" | |
| 263 | required | |
| 264 | /> | |
| 265 | </div> | |
| 266 | ||
| 267 | <button | |
| 268 | type="submit" | |
| 269 | disabled="{{ loading.value }}" | |
| 270 | class="py-2 w-full text-white bg-blue-500 hover:bg-blue-600 rounded-lg disabled:opacity-50" | |
| 271 | > | |
| 272 | {{ loading.value ? 'Creating account...' : 'Register' }} | |
| 273 | </button> | |
| 274 | ||
| 275 | <p class="text-center text-gray-600 text-sm"> | |
| 276 | Already have an account? | |
| 277 | <a href="/login" class="text-blue-500 hover:underline">Login</a> | |
| 278 | </p> | |
| 279 | </form> | |
| 280 | ``` | |
| 281 | ||
| 282 | ## User Login | |
| 283 | ||
| 284 | ### Login Action | |
| 285 | ||
| 286 | ```typescript | |
| 287 | // app/Actions/Auth/LoginAction.ts | |
| 288 | import type { RequestInstance } from '@stacksjs/types' | |
| 289 | import { Action } from '@stacksjs/actions' | |
| 290 | import { Auth } from '@stacksjs/auth' | |
| 291 | import { response } from '@stacksjs/router' | |
| 292 | import { schema } from '@stacksjs/validation' | |
| 293 | ||
| 294 | export default new Action({ | |
| 295 | name: 'LoginAction', | |
| 296 | description: 'Login to the application', | |
| 297 | method: 'POST', | |
| 298 | ||
| 299 | validations: { | |
| 300 | email: { | |
| 301 | rule: schema.string().email(), | |
| 302 | message: 'Email must be a valid email address.', | |
| 303 | }, | |
| 304 | password: { | |
| 305 | rule: schema.string().min(1), | |
| 306 | message: 'Password is required.', | |
| 307 | }, | |
| 308 | }, | |
| 309 | ||
| 310 | async handle(request: RequestInstance) { | |
| 311 | const email = request.get('email') | |
| 312 | const password = request.get('password') | |
| 313 | const remember = request.get('remember', false) | |
| 314 | ||
| 315 | const result = await Auth.login({ email, password }) | |
| 316 | ||
| 317 | if (result) { | |
| 318 | return response.json({ | |
| 319 | token: result.token, | |
| 320 | user: { | |
| 321 | id: result.user?.id, | |
| 322 | email: result.user?.email, | |
| 323 | name: result.user?.name, | |
| 324 | }, | |
| 325 | // Extend token expiry if "remember me" | |
| 326 | expiresIn: remember ? 30 * 24 * 60 * 60 : 24 * 60 * 60, | |
| 327 | }) | |
| 328 | } | |
| 329 | ||
| 330 | return response.unauthorized('Invalid email or password') | |
| 331 | }, | |
| 332 | }) | |
| 333 | ``` | |
| 334 | ||
| 335 | ### Login Route | |
| 336 | ||
| 337 | ```typescript | |
| 338 | // routes/api.ts | |
| 339 | route.post('/login', 'Actions/Auth/LoginAction') | |
| 340 | ``` | |
| 341 | ||
| 342 | ### Login Form (Frontend) | |
| 343 | ||
| 344 | ```html | |
| 345 | <!-- resources/components/LoginForm.stx --> | |
| 346 | <script server> | |
| 347 | import { ref } from '@stacksjs/reactivity' | |
| 348 | ||
| 349 | const form = ref({ | |
| 350 | email: '', | |
| 351 | password: '', | |
| 352 | remember: false, | |
| 353 | }) | |
| 354 | const error = ref('') | |
| 355 | const loading = ref(false) | |
| 356 | ||
| 357 | async function handleLogin() { | |
| 358 | error.value = '' | |
| 359 | loading.value = true | |
| 360 | ||
| 361 | try { | |
| 362 | const res = await fetch('/api/login', { | |
| 363 | method: 'POST', | |
| 364 | headers: { 'Content-Type': 'application/json' }, | |
| 365 | body: JSON.stringify(form.value), | |
| 366 | }) | |
| 367 | ||
| 368 | const data = await res.json() | |
| 369 | ||
| 370 | if (!res.ok) { | |
| 371 | error.value = data.message || 'Login failed' | |
| 372 | return | |
| 373 | } | |
| 374 | ||
| 375 | // Store token | |
| 376 | localStorage.setItem('token', data.token) | |
| 377 | ||
| 378 | // Redirect to dashboard | |
| 379 | window.location.href = '/dashboard' | |
| 380 | } catch (e) { | |
| 381 | error.value = 'An error occurred. Please try again.' | |
| 382 | } finally { | |
| 383 | loading.value = false | |
| 384 | } | |
| 385 | } | |
| 386 | </script> | |
| 387 | ||
| 388 | <form onsubmit="event.preventDefault(); handleLogin()" class="mx-auto space-y-4 max-w-md"> | |
| 389 | <h2 class="font-bold text-2xl">Login</h2> | |
| 390 | ||
| 391 | @if(error.value) | |
| 392 | <div class="p-3 text-red-700 bg-red-100 rounded"> | |
| 393 | {{ error.value }} | |
| 394 | </div> | |
| 395 | @endif | |
| 396 | ||
| 397 | <div> | |
| 398 | <label class="block mb-1 font-medium text-sm">Email</label> | |
| 399 | <input | |
| 400 | type="email" | |
| 401 | value="{{ form.value.email }}" | |
| 402 | oninput="form.value.email = event.target.value" | |
| 403 | class="px-3 py-2 w-full border rounded-lg" | |
| 404 | required | |
| 405 | /> | |
| 406 | </div> | |
| 407 | ||
| 408 | <div> | |
| 409 | <label class="block mb-1 font-medium text-sm">Password</label> | |
| 410 | <input | |
| 411 | type="password" | |
| 412 | value="{{ form.value.password }}" | |
| 413 | oninput="form.value.password = event.target.value" | |
| 414 | class="px-3 py-2 w-full border rounded-lg" | |
| 415 | required | |
| 416 | /> | |
| 417 | </div> | |
| 418 | ||
| 419 | <div class="flex gap-2 items-center"> | |
| 420 | <input | |
| 421 | type="checkbox" | |
| 422 | id="remember" | |
| 423 | checked="{{ form.value.remember }}" | |
| 424 | onchange="form.value.remember = event.target.checked" | |
| 425 | /> | |
| 426 | <label for="remember" class="text-sm">Remember me</label> | |
| 427 | </div> | |
| 428 | ||
| 429 | <button | |
| 430 | type="submit" | |
| 431 | disabled="{{ loading.value }}" | |
| 432 | class="py-2 w-full text-white bg-blue-500 hover:bg-blue-600 rounded-lg disabled:opacity-50" | |
| 433 | > | |
| 434 | {{ loading.value ? 'Logging in...' : 'Login' }} | |
| 435 | </button> | |
| 436 | ||
| 437 | <div class="flex justify-between text-sm"> | |
| 438 | <a href="/forgot-password" class="text-blue-500 hover:underline"> | |
| 439 | Forgot password? | |
| 440 | </a> | |
| 441 | <a href="/register" class="text-blue-500 hover:underline"> | |
| 442 | Create account | |
| 443 | </a> | |
| 444 | </div> | |
| 445 | </form> | |
| 446 | ``` | |
| 447 | ||
| 448 | ## Token Management | |
| 449 | ||
| 450 | ### Creating API Tokens | |
| 451 | ||
| 452 | ```typescript | |
| 453 | // app/Actions/Auth/CreateTokenAction.ts | |
| 454 | import type { RequestInstance } from '@stacksjs/types' | |
| 455 | import { Action } from '@stacksjs/actions' | |
| 456 | import { response } from '@stacksjs/router' | |
| 457 | import { schema } from '@stacksjs/validation' | |
| 458 | ||
| 459 | export default new Action({ | |
| 460 | name: 'CreateTokenAction', | |
| 461 | description: 'Create a new API token', | |
| 462 | method: 'POST', | |
| 463 | ||
| 464 | validations: { | |
| 465 | name: { | |
| 466 | rule: schema.string().min(1).max(100), | |
| 467 | message: 'Token name is required.', | |
| 468 | }, | |
| 469 | abilities: { | |
| 470 | rule: schema.array().optional(), | |
| 471 | message: 'Abilities must be an array.', | |
| 472 | }, | |
| 473 | }, | |
| 474 | ||
| 475 | async handle(request: RequestInstance) { | |
| 476 | const user = request.user() | |
| 477 | const name = request.get('name') | |
| 478 | const abilities = request.get('abilities', ['*']) | |
| 479 | ||
| 480 | const token = await user.createToken(name, abilities) | |
| 481 | ||
| 482 | return response.json({ | |
| 483 | token: token.plainTextToken, | |
| 484 | name: token.name, | |
| 485 | abilities: token.abilities, | |
| 486 | }, 201) | |
| 487 | }, | |
| 488 | }) | |
| 489 | ``` | |
| 490 | ||
| 491 | ### Listing Tokens | |
| 492 | ||
| 493 | ```typescript | |
| 494 | // app/Actions/Auth/ListTokensAction.ts | |
| 495 | import type { RequestInstance } from '@stacksjs/types' | |
| 496 | import { Action } from '@stacksjs/actions' | |
| 497 | import { response } from '@stacksjs/router' | |
| 498 | ||
| 499 | export default new Action({ | |
| 500 | name: 'ListTokensAction', | |
| 501 | description: 'List user tokens', | |
| 502 | method: 'GET', | |
| 503 | ||
| 504 | async handle(request: RequestInstance) { | |
| 505 | const user = request.user() | |
| 506 | const tokens = await user.tokens() | |
| 507 | ||
| 508 | return response.json({ | |
| 509 | tokens: tokens.map(token => ({ | |
| 510 | id: token.id, | |
| 511 | name: token.name, | |
| 512 | abilities: token.abilities, | |
| 513 | lastUsedAt: token.last*used*at, | |
| 514 | createdAt: token.created*at, | |
| 515 | })), | |
| 516 | }) | |
| 517 | }, | |
| 518 | }) | |
| 519 | ``` | |
| 520 | ||
| 521 | ### Revoking Tokens | |
| 522 | ||
| 523 | ```typescript | |
| 524 | // app/Actions/Auth/RevokeTokenAction.ts | |
| 525 | import type { RequestInstance } from '@stacksjs/types' | |
| 526 | import { Action } from '@stacksjs/actions' | |
| 527 | import { response } from '@stacksjs/router' | |
| 528 | ||
| 529 | export default new Action({ | |
| 530 | name: 'RevokeTokenAction', | |
| 531 | description: 'Revoke an API token', | |
| 532 | method: 'DELETE', | |
| 533 | ||
| 534 | async handle(request: RequestInstance) { | |
| 535 | const user = request.user() | |
| 536 | const tokenId = request.param('id') | |
| 537 | ||
| 538 | const token = await PersonalAccessToken.where('id', tokenId) | |
| 539 | .where('user*id', user.id) | |
| 540 | .first() | |
| 541 | ||
| 542 | if (!token) { | |
| 543 | return response.notFound('Token not found') | |
| 544 | } | |
| 545 | ||
| 546 | await token.delete() | |
| 547 | ||
| 548 | return response.json({ message: 'Token revoked' }) | |
| 549 | }, | |
| 550 | }) | |
| 551 | ``` | |
| 552 | ||
| 553 | ### Refreshing Tokens | |
| 554 | ||
| 555 | ```typescript | |
| 556 | // app/Actions/Auth/RefreshTokenAction.ts | |
| 557 | import type { RequestInstance } from '@stacksjs/types' | |
| 558 | import { Action } from '@stacksjs/actions' | |
| 559 | import { Auth } from '@stacksjs/auth' | |
| 560 | import { response } from '@stacksjs/router' | |
| 561 | ||
| 562 | export default new Action({ | |
| 563 | name: 'RefreshTokenAction', | |
| 564 | description: 'Refresh authentication token', | |
| 565 | method: 'POST', | |
| 566 | ||
| 567 | async handle(request: RequestInstance) { | |
| 568 | const currentToken = request.bearerToken() | |
| 569 | ||
| 570 | if (!currentToken) { | |
| 571 | return response.unauthorized('No token provided') | |
| 572 | } | |
| 573 | ||
| 574 | const result = await Auth.refreshToken(currentToken) | |
| 575 | ||
| 576 | if (result) { | |
| 577 | return response.json({ | |
| 578 | token: result.token, | |
| 579 | expiresIn: result.expiresIn, | |
| 580 | }) | |
| 581 | } | |
| 582 | ||
| 583 | return response.unauthorized('Invalid or expired token') | |
| 584 | }, | |
| 585 | }) | |
| 586 | ``` | |
| 587 | ||
| 588 | ## Protected Routes | |
| 589 | ||
| 590 | ### Using Auth Middleware | |
| 591 | ||
| 592 | ```typescript | |
| 593 | // routes/api.ts | |
| 594 | import { route } from '@stacksjs/router' | |
| 595 | ||
| 596 | // Public routes | |
| 597 | route.post('/login', 'Actions/Auth/LoginAction') | |
| 598 | route.post('/register', 'Actions/Auth/RegisterAction') | |
| 599 | route.post('/auth/refresh', 'Actions/Auth/RefreshTokenAction') | |
| 600 | ||
| 601 | // Protected routes - require authentication | |
| 602 | route.group({ middleware: 'auth' }, () => { | |
| 603 | route.get('/me', 'Actions/Auth/AuthUserAction') | |
| 604 | route.post('/logout', 'Actions/Auth/LogoutAction') | |
| 605 | ||
| 606 | // Token management | |
| 607 | route.get('/tokens', 'Actions/Auth/ListTokensAction') | |
| 608 | route.post('/token', 'Actions/Auth/CreateTokenAction') | |
| 609 | route.delete('/tokens/{id}', 'Actions/Auth/RevokeTokenAction') | |
| 610 | ||
| 611 | // User profile | |
| 612 | route.put('/profile', 'Actions/User/UpdateProfileAction') | |
| 613 | route.put('/password', 'Actions/User/ChangePasswordAction') | |
| 614 | }) | |
| 615 | ``` | |
| 616 | ||
| 617 | ### Get Authenticated User | |
| 618 | ||
| 619 | ```typescript | |
| 620 | // app/Actions/Auth/AuthUserAction.ts | |
| 621 | import type { RequestInstance } from '@stacksjs/types' | |
| 622 | import { Action } from '@stacksjs/actions' | |
| 623 | import { response } from '@stacksjs/router' | |
| 624 | ||
| 625 | export default new Action({ | |
| 626 | name: 'AuthUserAction', | |
| 627 | description: 'Get authenticated user', | |
| 628 | method: 'GET', | |
| 629 | ||
| 630 | async handle(request: RequestInstance) { | |
| 631 | const user = request.user() | |
| 632 | ||
| 633 | return response.json({ | |
| 634 | id: user.id, | |
| 635 | email: user.email, | |
| 636 | name: user.name, | |
| 637 | emailVerifiedAt: user.email*verified*at, | |
| 638 | createdAt: user.created*at, | |
| 639 | }) | |
| 640 | }, | |
| 641 | }) | |
| 642 | ``` | |
| 643 | ||
| 644 | ### Logout Action | |
| 645 | ||
| 646 | ```typescript | |
| 647 | // app/Actions/Auth/LogoutAction.ts | |
| 648 | import type { RequestInstance } from '@stacksjs/types' | |
| 649 | import { Action } from '@stacksjs/actions' | |
| 650 | import { Auth } from '@stacksjs/auth' | |
| 651 | import { response } from '@stacksjs/router' | |
| 652 | ||
| 653 | export default new Action({ | |
| 654 | name: 'LogoutAction', | |
| 655 | description: 'Logout the user', | |
| 656 | method: 'POST', | |
| 657 | ||
| 658 | async handle(request: RequestInstance) { | |
| 659 | const token = request.bearerToken() | |
| 660 | ||
| 661 | if (token) { | |
| 662 | await Auth.revokeToken(token) | |
| 663 | } | |
| 664 | ||
| 665 | return response.json({ message: 'Logged out successfully' }) | |
| 666 | }, | |
| 667 | }) | |
| 668 | ``` | |
| 669 | ||
| 670 | ## Frontend Authentication Helper | |
| 671 | ||
| 672 | Create a reusable auth service: | |
| 673 | ||
| 674 | ```typescript | |
| 675 | // resources/functions/auth.ts | |
| 676 | import { reactive } from '@stacksjs/reactivity' | |
| 677 | ||
| 678 | interface User { | |
| 679 | id: number | |
| 680 | email: string | |
| 681 | name: string | |
| 682 | } | |
| 683 | ||
| 684 | export const auth = reactive({ | |
| 685 | user: null as User | null, | |
| 686 | token: localStorage.getItem('token'), | |
| 687 | isAuthenticated: !!localStorage.getItem('token'), | |
| 688 | }) | |
| 689 | ||
| 690 | export async function login(email: string, password: string) { | |
| 691 | const res = await fetch('/api/login', { | |
| 692 | method: 'POST', | |
| 693 | headers: { 'Content-Type': 'application/json' }, | |
| 694 | body: JSON.stringify({ email, password }), | |
| 695 | }) | |
| 696 | ||
| 697 | if (!res.ok) { | |
| 698 | const error = await res.json() | |
| 699 | throw new Error(error.message || 'Login failed') | |
| 700 | } | |
| 701 | ||
| 702 | const data = await res.json() | |
| 703 | auth.token = data.token | |
| 704 | auth.user = data.user | |
| 705 | auth.isAuthenticated = true | |
| 706 | localStorage.setItem('token', data.token) | |
| 707 | ||
| 708 | return data | |
| 709 | } | |
| 710 | ||
| 711 | export async function logout() { | |
| 712 | if (auth.token) { | |
| 713 | await fetch('/api/logout', { | |
| 714 | method: 'POST', | |
| 715 | headers: { | |
| 716 | 'Authorization': `Bearer ${auth.token}`, | |
| 717 | }, | |
| 718 | }) | |
| 719 | } | |
| 720 | ||
| 721 | auth.token = null | |
| 722 | auth.user = null | |
| 723 | auth.isAuthenticated = false | |
| 724 | localStorage.removeItem('token') | |
| 725 | } | |
| 726 | ||
| 727 | export async function fetchUser() { | |
| 728 | if (!auth.token) return null | |
| 729 | ||
| 730 | const res = await fetch('/api/me', { | |
| 731 | headers: { | |
| 732 | 'Authorization': `Bearer ${auth.token}`, | |
| 733 | }, | |
| 734 | }) | |
| 735 | ||
| 736 | if (res.ok) { | |
| 737 | auth.user = await res.json() | |
| 738 | return auth.user | |
| 739 | } | |
| 740 | ||
| 741 | // Token invalid, clear auth state | |
| 742 | await logout() | |
| 743 | return null | |
| 744 | } | |
| 745 | ||
| 746 | export function getAuthHeaders() { | |
| 747 | return auth.token | |
| 748 | ? { 'Authorization': `Bearer ${auth.token}` } | |
| 749 | : {} | |
| 750 | } | |
| 751 | ``` | |
| 752 | ||
| 753 | ## Password Reset | |
| 754 | ||
| 755 | ### Request Password Reset | |
| 756 | ||
| 757 | ```typescript | |
| 758 | // app/Actions/Password/SendPasswordResetEmailAction.ts | |
| 759 | import type { RequestInstance } from '@stacksjs/types' | |
| 760 | import { Action } from '@stacksjs/actions' | |
| 761 | import { response } from '@stacksjs/router' | |
| 762 | import { schema } from '@stacksjs/validation' | |
| 763 | ||
| 764 | export default new Action({ | |
| 765 | name: 'SendPasswordResetEmailAction', | |
| 766 | description: 'Send password reset email', | |
| 767 | method: 'POST', | |
| 768 | ||
| 769 | validations: { | |
| 770 | email: { | |
| 771 | rule: schema.string().email(), | |
| 772 | message: 'Valid email is required.', | |
| 773 | }, | |
| 774 | }, | |
| 775 | ||
| 776 | async handle(request: RequestInstance) { | |
| 777 | const email = request.get('email') | |
| 778 | ||
| 779 | // Always return success to prevent email enumeration | |
| 780 | const user = await User.where('email', email).first() | |
| 781 | ||
| 782 | if (user) { | |
| 783 | // Generate reset token | |
| 784 | const token = await user.createPasswordResetToken() | |
| 785 | ||
| 786 | // Send email (using your email service) | |
| 787 | await sendEmail({ | |
| 788 | to: email, | |
| 789 | subject: 'Reset Your Password', | |
| 790 | template: 'password-reset', | |
| 791 | data: { | |
| 792 | resetUrl: `${APP*URL}/reset-password?token=${token}`, | |
| 793 | }, | |
| 794 | }) | |
| 795 | } | |
| 796 | ||
| 797 | return response.json({ | |
| 798 | message: 'If an account exists, a reset link has been sent.', | |
| 799 | }) | |
| 800 | }, | |
| 801 | }) | |
| 802 | ``` | |
| 803 | ||
| 804 | ### Reset Password | |
| 805 | ||
| 806 | ```typescript | |
| 807 | // app/Actions/Password/PasswordResetAction.ts | |
| 808 | import type { RequestInstance } from '@stacksjs/types' | |
| 809 | import { Action } from '@stacksjs/actions' | |
| 810 | import { hash } from '@stacksjs/auth' | |
| 811 | import { response } from '@stacksjs/router' | |
| 812 | import { schema } from '@stacksjs/validation' | |
| 813 | ||
| 814 | export default new Action({ | |
| 815 | name: 'PasswordResetAction', | |
| 816 | description: 'Reset user password', | |
| 817 | method: 'POST', | |
| 818 | ||
| 819 | validations: { | |
| 820 | token: { | |
| 821 | rule: schema.string(), | |
| 822 | message: 'Reset token is required.', | |
| 823 | }, | |
| 824 | password: { | |
| 825 | rule: schema.string().min(8), | |
| 826 | message: 'Password must be at least 8 characters.', | |
| 827 | }, | |
| 828 | password*confirmation: { | |
| 829 | rule: schema.string(), | |
| 830 | message: 'Password confirmation is required.', | |
| 831 | }, | |
| 832 | }, | |
| 833 | ||
| 834 | async handle(request: RequestInstance) { | |
| 835 | const token = request.get('token') | |
| 836 | const password = request.get('password') | |
| 837 | const passwordConfirmation = request.get('password*confirmation') | |
| 838 | ||
| 839 | if (password !== passwordConfirmation) { | |
| 840 | return response.badRequest('Passwords do not match.') | |
| 841 | } | |
| 842 | ||
| 843 | // Verify token and get user | |
| 844 | const resetRecord = await PasswordReset.where('token', token) | |
| 845 | .where('expires*at', '>', new Date()) | |
| 846 | .first() | |
| 847 | ||
| 848 | if (!resetRecord) { | |
| 849 | return response.badRequest('Invalid or expired reset token.') | |
| 850 | } | |
| 851 | ||
| 852 | const user = await User.find(resetRecord.user*id) | |
| 853 | ||
| 854 | if (!user) { | |
| 855 | return response.badRequest('User not found.') | |
| 856 | } | |
| 857 | ||
| 858 | // Update password | |
| 859 | await user.update({ | |
| 860 | password: await hash(password), | |
| 861 | }) | |
| 862 | ||
| 863 | // Delete used token | |
| 864 | await resetRecord.delete() | |
| 865 | ||
| 866 | return response.json({ | |
| 867 | message: 'Password reset successfully.', | |
| 868 | }) | |
| 869 | }, | |
| 870 | }) | |
| 871 | ``` | |
| 872 | ||
| 873 | ## Next Steps | |
| 874 | ||
| 875 | - [Build an API](/bootcamp/api) - Create API endpoints | |
| 876 | - [Testing How-To](/bootcamp/how-to/testing) - Test your authentication | |
| 877 | - [Deployment How-To](/bootcamp/how-to/deploy) - Deploy with authentication | |
| 878 | ||
| 879 | ## Related Documentation | |
| 880 | ||
| 881 | - [Authentication Guide](/guide/auth) | |
| 882 | - [Auth Package](/packages/auth) | |
| 883 | - [Middleware Guide](/basics/middleware) | |