File size: 15,894 Bytes
8059bf0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | # Authentication Views Usage Examples
This document provides practical examples of how to use the authentication views in the Sub2API frontend.
## Quick Start
### 1. Login Flow
**Scenario:** User wants to log into their existing account
```typescript
// Route: /login
// Component: LoginView.vue
// User interactions:
// 1. Navigate to /login
// 2. Enter username: "john_doe"
// 3. Enter password: "MySecurePass123"
// 4. Optionally check "Remember me"
// 5. Click "Sign In"
// What happens:
// - Form validation runs (client-side)
// - If valid, authStore.login() is called
// - API request to POST /api/auth/login
// - On success:
// - Token stored in localStorage
// - User data stored in state
// - Success toast: "Login successful! Welcome back."
// - Redirect to /dashboard (or intended route)
// - On error:
// - Error message displayed inline
// - Error toast shown
// - User can retry
```
### 2. Registration Flow
**Scenario:** New user wants to create an account
```typescript
// Route: /register
// Component: RegisterView.vue
// User interactions:
// 1. Navigate to /register
// 2. Enter username: "jane_smith"
// 3. Enter email: "jane@example.com"
// 4. Enter password: "SecurePass123"
// 5. Enter confirm password: "SecurePass123"
// 6. Click "Create Account"
// What happens:
// - Form validation runs (client-side)
// - Username: 3-50 chars, alphanumeric + _ -
// - Email: Valid format
// - Password: 8+ chars, letters + numbers
// - Passwords match
// - If valid, authStore.register() is called
// - API request to POST /api/auth/register
// - On success:
// - Token stored in localStorage
// - User data stored in state
// - Success toast: "Account created successfully! Welcome to Sub2API."
// - Redirect to /dashboard
// - On error:
// - Error message displayed inline
// - Error toast shown
// - User can retry
```
## Code Examples
### Importing the Views
```typescript
// Method 1: Direct import
import LoginView from '@/views/auth/LoginView.vue'
import RegisterView from '@/views/auth/RegisterView.vue'
// Method 2: Named exports from index
import { LoginView, RegisterView } from '@/views/auth'
// Method 3: Lazy loading (recommended for routes)
const LoginView = () => import('@/views/auth/LoginView.vue')
const RegisterView = () => import('@/views/auth/RegisterView.vue')
```
### Using in Router
```typescript
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/login',
name: 'Login',
component: () => import('@/views/auth/LoginView.vue'),
meta: { requiresAuth: false }
},
{
path: '/register',
name: 'Register',
component: () => import('@/views/auth/RegisterView.vue'),
meta: { requiresAuth: false }
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
### Navigation to Auth Views
```typescript
// From template
<router-link to="/login">Login</router-link>
<router-link to="/register">Sign Up</router-link>
// From script
import { useRouter } from 'vue-router';
const router = useRouter();
// Navigate to login
router.push('/login');
// Navigate to register
router.push('/register');
// Navigate with redirect query
router.push({
path: '/login',
query: { redirect: '/dashboard' }
});
```
### Programmatic Auth Flow
```typescript
import { useAuthStore } from '@/stores'
import { useAppStore } from '@/stores'
import { useRouter } from 'vue-router'
const authStore = useAuthStore()
const appStore = useAppStore()
const router = useRouter()
// Login
async function login() {
try {
await authStore.login({
username: 'john_doe',
password: 'MySecurePass123'
})
appStore.showSuccess('Login successful!')
router.push('/dashboard')
} catch (error) {
appStore.showError('Login failed. Please check your credentials.')
}
}
// Register
async function register() {
try {
await authStore.register({
username: 'jane_smith',
email: 'jane@example.com',
password: 'SecurePass123'
})
appStore.showSuccess('Account created successfully!')
router.push('/dashboard')
} catch (error) {
appStore.showError('Registration failed. Please try again.')
}
}
```
## Validation Examples
### Login Validation
```typescript
// Valid inputs
β
Username: "john_doe" (3+ chars)
β
Password: "SecurePass123" (6+ chars)
// Invalid inputs
β Username: "jo" β Error: "Username must be at least 3 characters"
β Password: "12345" β Error: "Password must be at least 6 characters"
β Username: "" β Error: "Username is required"
β Password: "" β Error: "Password is required"
```
### Registration Validation
```typescript
// Valid inputs
β
Username: "jane_smith" (3-50 chars, alphanumeric + _ -)
β
Email: "jane@example.com" (valid format)
β
Password: "SecurePass123" (8+ chars, letters + numbers)
β
Confirm: "SecurePass123" (matches password)
// Invalid inputs
β Username: "ja" β Error: "Username must be at least 3 characters"
β Username: "jane@smith" β Error: "Username can only contain letters, numbers, underscores, and hyphens"
β Email: "invalid-email" β Error: "Please enter a valid email address"
β Password: "short" β Error: "Password must be at least 8 characters with letters and numbers"
β Password: "12345678" β Error: "Password must be at least 8 characters with letters and numbers" (no letters)
β Password: "password" β Error: "Password must be at least 8 characters with letters and numbers" (no numbers)
β Confirm: "DifferentPass" β Error: "Passwords do not match"
```
## Error Handling Examples
### Backend Errors
```typescript
// Example 1: Username already exists
{
response: {
data: {
detail: "Username 'john_doe' is already taken"
}
}
}
// Displayed: "Username 'john_doe' is already taken"
// Example 2: Invalid credentials
{
response: {
data: {
detail: 'Invalid username or password'
}
}
}
// Displayed: "Invalid username or password"
// Example 3: Network error
{
message: 'Network Error'
}
// Displayed: "Network Error" + Error toast
// Example 4: Unknown error
{
}
// Displayed: "Login failed. Please check your credentials and try again." (default)
```
### Client-side Validation Errors
```typescript
// Multiple validation errors displayed simultaneously
errors = {
username: 'Username must be at least 3 characters',
email: 'Please enter a valid email address',
password: 'Password must be at least 8 characters with letters and numbers',
confirmPassword: 'Passwords do not match'
}
// Each error appears below its respective input field with red styling
```
## Testing Examples
### Unit Test: Login View
```typescript
import { describe, it, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia } from 'pinia'
import LoginView from '@/views/auth/LoginView.vue'
describe('LoginView', () => {
it('validates required fields', async () => {
const wrapper = mount(LoginView, {
global: {
plugins: [createPinia()]
}
})
// Submit empty form
await wrapper.find('form').trigger('submit')
// Check for validation errors
expect(wrapper.text()).toContain('Username is required')
expect(wrapper.text()).toContain('Password is required')
})
it('calls authStore.login on valid submission', async () => {
const wrapper = mount(LoginView, {
global: {
plugins: [createPinia()]
}
})
// Fill in form
await wrapper.find('#username').setValue('john_doe')
await wrapper.find('#password').setValue('SecurePass123')
// Submit form
await wrapper.find('form').trigger('submit')
// Verify authStore.login was called
// (mock implementation needed)
})
})
```
### E2E Test: Registration Flow
```typescript
import { test, expect } from '@playwright/test'
test('user can register successfully', async ({ page }) => {
// Navigate to register page
await page.goto('/register')
// Fill in registration form
await page.fill('#username', 'new_user')
await page.fill('#email', 'new_user@example.com')
await page.fill('#password', 'SecurePass123')
await page.fill('#confirmPassword', 'SecurePass123')
// Submit form
await page.click('button[type="submit"]')
// Wait for redirect to dashboard
await page.waitForURL('/dashboard')
// Verify success toast appears
await expect(page.locator('.toast-success')).toBeVisible()
await expect(page.locator('.toast-success')).toContainText('Account created successfully')
})
test('shows validation errors for invalid inputs', async ({ page }) => {
await page.goto('/register')
// Enter mismatched passwords
await page.fill('#password', 'SecurePass123')
await page.fill('#confirmPassword', 'DifferentPass')
// Submit form
await page.click('button[type="submit"]')
// Verify error message
await expect(page.locator('text=Passwords do not match')).toBeVisible()
})
```
## Integration with Navigation Guards
### Router Guard Example
```typescript
import { useAuthStore } from '@/stores'
router.beforeEach((to, from, next) => {
const authStore = useAuthStore()
// Redirect authenticated users away from auth pages
if (authStore.isAuthenticated && (to.path === '/login' || to.path === '/register')) {
next('/dashboard')
return
}
// Redirect unauthenticated users to login
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
return
}
next()
})
```
## Customization Examples
### Custom Success Redirect
```typescript
// In LoginView.vue
async function handleLogin(): Promise<void> {
try {
await authStore.login({
username: formData.username,
password: formData.password
})
appStore.showSuccess('Login successful!')
// Custom redirect logic
const isAdmin = authStore.isAdmin
const redirectTo = isAdmin ? '/admin/dashboard' : '/dashboard'
await router.push(redirectTo)
} catch (error) {
// Error handling...
}
}
```
### Custom Validation Rules
```typescript
// Custom password strength validation
function validatePasswordStrength(password: string): boolean {
const hasMinLength = password.length >= 12
const hasUpperCase = /[A-Z]/.test(password)
const hasLowerCase = /[a-z]/.test(password)
const hasNumber = /[0-9]/.test(password)
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password)
return hasMinLength && hasUpperCase && hasLowerCase && hasNumber && hasSpecialChar
}
// Use in validation
if (!validatePasswordStrength(formData.password)) {
errors.password =
'Password must be at least 12 characters with uppercase, lowercase, numbers, and special characters'
isValid = false
}
```
### Custom Error Handling
```typescript
// In RegisterView.vue
async function handleRegister(): Promise<void> {
try {
await authStore.register({
username: formData.username,
email: formData.email,
password: formData.password
})
appStore.showSuccess('Account created successfully!')
await router.push('/dashboard')
} catch (error: unknown) {
const err = error as { response?: { status?: number; data?: { detail?: string } } }
// Custom error handling based on status code
if (err.response?.status === 409) {
errorMessage.value =
'This username or email is already registered. Please use a different one.'
} else if (err.response?.status === 422) {
errorMessage.value = 'Invalid input. Please check your information and try again.'
} else if (err.response?.status === 500) {
errorMessage.value = 'Server error. Please try again later.'
} else {
errorMessage.value = err.response?.data?.detail || 'Registration failed. Please try again.'
}
appStore.showError(errorMessage.value)
}
}
```
## Accessibility Examples
### Keyboard Navigation
```typescript
// Tab order:
// 1. Username input
// 2. Password input
// 3. Remember me checkbox (login) / Confirm password (register)
// 4. Submit button
// 5. Footer link (register/login)
// Enter key submits form
// Escape key can be used to clear focus
```
### Screen Reader Support
```html
<!-- Proper labels for screen readers -->
<label for="username" class="mb-1 block text-sm font-medium text-gray-700"> Username </label>
<input
id="username"
type="text"
aria-label="Username"
aria-required="true"
aria-invalid="false"
aria-describedby="username-error"
/>
<p id="username-error" role="alert" class="text-sm text-red-600">
<!-- Error message here -->
</p>
<!-- Loading state announced -->
<button type="submit" aria-busy="true" aria-label="Signing in...">
<span class="sr-only">Signing in...</span>
<!-- Visual content -->
</button>
```
## Performance Considerations
### Lazy Loading
```typescript
// Router configuration with lazy loading
{
path: '/login',
component: () => import('@/views/auth/LoginView.vue'), // β
Lazy loaded
}
// Direct import (not recommended for routes)
import LoginView from '@/views/auth/LoginView.vue'; // β Eager loaded
```
### Optimization Tips
1. Use `v-once` for static content
2. Debounce expensive validation operations
3. Minimize reactive dependencies
4. Use `shallowRef` for complex objects when possible
5. Avoid unnecessary watchers
## Security Best Practices
1. Never log passwords or tokens
2. Use HTTPS in production
3. Implement rate limiting on backend
4. Validate all inputs server-side
5. Use secure password hashing (bcrypt, argon2)
6. Implement CSRF protection
7. Set secure cookie flags
8. Use Content Security Policy headers
9. Sanitize all user inputs
10. Implement account lockout after failed attempts
## Common Issues and Solutions
### Issue: Token not persisting after refresh
```typescript
// Solution: Initialize auth state on app mount
// In main.ts or App.vue
import { useAuthStore } from '@/stores'
const authStore = useAuthStore()
authStore.checkAuth() // Restore auth from localStorage
```
### Issue: Redirect loop after login
```typescript
// Solution: Check router guard logic
router.beforeEach((to, from, next) => {
const authStore = useAuthStore()
// β
Correct: Check specific routes
if (authStore.isAuthenticated && (to.path === '/login' || to.path === '/register')) {
next('/dashboard')
return
}
// β Wrong: Blanket redirect
// if (authStore.isAuthenticated) {
// next('/dashboard'); // This causes loops!
// }
next()
})
```
### Issue: Form not clearing after successful submission
```typescript
// Solution: Reset form data
async function handleLogin(): Promise<void> {
try {
await authStore.login({...});
// Reset form
formData.username = '';
formData.password = '';
formData.remember = false;
// Clear errors
errors.username = '';
errors.password = '';
await router.push('/dashboard');
} catch (error) {
// Error handling...
}
}
```
## Additional Resources
- [Vue 3 Documentation](https://vuejs.org/)
- [Vue Router Documentation](https://router.vuejs.org/)
- [Pinia Documentation](https://pinia.vuejs.org/)
- [TailwindCSS Documentation](https://tailwindcss.com/)
- [TypeScript Handbook](https://www.typescriptlang.org/docs/)
|