# Authentication

The Monetarie NPC Backoffice uses a session-based authentication system with localStorage persistence. This guide covers the authentication flow, components, and security considerations.

## Overview

The authentication system consists of:

1. **Auth Store** (`src/stores/auth.ts`) - Pinia store managing authentication state
2. **Login View** (`src/features/auth/views/LoginView.vue`) - Login form component
3. **Router Guards** (`src/router/index.ts`) - Route protection middleware
4. **Mock Users** (`src/mocks/users.ts`) - Demo credential validation

## Authentication Flow

```
┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│   User      │────>│  LoginView   │────>│  AuthStore  │
│  submits    │     │  validates   │     │   login()   │
│  form       │     │  form        │     │             │
└─────────────┘     └──────────────┘     └──────┬──────┘
                                                 │
                    ┌──────────────┐              │
                    │  LocalStorage│<────────────┘
                    │   saves      │
                    │   user       │
                    └──────┬───────┘
                           │
                    ┌──────┴──────┐
                    │   Router    │
                    │  redirects  │
                    │  to /       │
                    └─────────────┘
```

## Auth Store

The `useAuthStore` manages the complete authentication lifecycle:

### State

```typescript
interface User {
  id: number
  name: string
  email: string
  role: string
  avatar?: string
}

// Store state
const user = ref<User | null>(null)
const isAuthenticated = computed(() => user.value !== null)
```

### Actions

#### `login(email: string, password: string): boolean`

Authenticates the user against mock credentials.

```typescript
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const success = authStore.login('admin@monetarie_npc.com.br', 'admin123')
if (success) {
  // User is now authenticated
  router.push('/')
} else {
  // Show error message
}
```

#### `logout()`

Clears the user session and removes from localStorage.

```typescript
authStore.logout()
router.push('/login')
```

#### `updateAvatar(avatar: string)`

Updates the user's avatar URL.

```typescript
authStore.updateAvatar('https://example.com/new-avatar.jpg')
```

### Initialization

The store automatically initializes on creation by checking localStorage:

```typescript
function init() {
  const savedUser = localStorage.getItem('user')
  if (savedUser) {
    user.value = JSON.parse(savedUser)
  }
}

init()
```

## Login View

The login page (`src/features/auth/views/LoginView.vue`) provides:

### Features

- Email and password validation
- Password visibility toggle
- Language selector
- Error message display
- Loading state during authentication

### Form Validation

```typescript
const rules = {
  required: (v: string) => !!v || 'Required',
  email: (v: string) => /.+@.+\..+/.test(v) || 'Invalid email'
}
```

### Login Handler

```vue
<script setup lang="ts">
async function handleLogin() {
  const { valid } = await formRef.value.validate()
  if (!valid) return

  loading.value = true
  error.value = false

  // Simulate network delay
  await new Promise(resolve => setTimeout(resolve, 500))

  const success = authStore.login(email.value, password.value)

  if (success) {
    router.push('/')
  } else {
    error.value = true
  }

  loading.value = false
}
</script>
```

### Language Selection

The login page includes a language toggle:

```vue
<v-btn-toggle v-model="selectedLocale" mandatory>
  <v-btn
    v-for="loc in availableLocales"
    :key="loc.code"
    :value="loc.code"
  >
    {{ loc.flag }} {{ loc.code.split('-')[0].toUpperCase() }}
  </v-btn>
</v-btn-toggle>
```

## Route Protection

### Navigation Guards

The router uses `beforeEach` guards to protect routes:

```typescript
// src/router/index.ts
router.beforeEach((to, _from, next) => {
  const authStore = useAuthStore()

  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    // Redirect to login if not authenticated
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    // Redirect to dashboard if already authenticated
    next('/')
  } else {
    next()
  }
})
```

### Route Meta

Routes are configured with authentication requirements:

```typescript
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/features/auth/views/LoginView.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'dashboard',
    component: () => import('@/features/dashboard/views/DashboardView.vue'),
    meta: { requiresAuth: true }
  },
  // ... other protected routes
]
```

## Mock Credentials

For demo purposes, the application uses hardcoded credentials:

| Field | Value |
|-------|-------|
| Email | `admin@monetarie_npc.com.br` |
| Password | `admin123` |
| Name | Administrador |
| Role | admin |

::: warning Production Note
In a production environment, replace the mock authentication with:
- API-based authentication
- JWT token management
- Secure password hashing
- Session refresh mechanisms
:::

## Session Persistence

User sessions are persisted in localStorage:

```typescript
// On login
localStorage.setItem('user', JSON.stringify(userWithoutPassword))

// On logout
localStorage.removeItem('user')

// On init
const savedUser = localStorage.getItem('user')
```

::: tip Security Consideration
For production, consider using:
- HttpOnly cookies for tokens
- Short-lived access tokens with refresh tokens
- Secure storage mechanisms
:::

## Using Authentication in Components

### Check Authentication Status

```vue
<script setup lang="ts">
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// Reactive authentication check
const isLoggedIn = computed(() => authStore.isAuthenticated)
</script>

<template>
  <div v-if="isLoggedIn">
    Welcome, {{ authStore.user?.name }}
  </div>
</template>
```

### Logout Button

```vue
<script setup lang="ts">
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

const authStore = useAuthStore()
const router = useRouter()

function handleLogout() {
  authStore.logout()
  router.push('/login')
}
</script>

<template>
  <v-btn @click="handleLogout">
    Logout
  </v-btn>
</template>
```

## Related Documentation

- [Pinia Stores](/api/stores) - Complete store documentation
- [Dashboard](/guide/dashboard) - Protected dashboard features
- [i18n Setup](/api/i18n) - Multi-language support
