# Brix Accounting API — Auth & Users

API reference for authentication, session management, role listing, and user administration.

---

## Base URL

All endpoints are prefixed with:

```
{BASE_URL}/api/v1
```

**Examples**

| Environment | Base URL |
|-------------|----------|
| Local (`php artisan serve`) | `http://127.0.0.1:8000/api/v1` |
| Production | Set per deployment (see `APP_URL` in `.env`) |

---

## Common headers

| Header | Value | Required |
|--------|-------|----------|
| `Accept` | `application/json` | Recommended on all requests |
| `Content-Type` | `application/json` | Required on `POST`, `PUT`, `PATCH` |
| `Authorization` | `Bearer {token}` | Required on protected endpoints |

All responses are JSON. Validation errors return `422` with a standard Laravel error body.

---

## Authentication model

- **Package:** Laravel Sanctum (personal access tokens)
- **Flow:** Login → receive `token` → send token on subsequent requests
- **Multi-tenancy:** Each user belongs to a `company_id`. Protected business routes require a valid company context.
- **User emails:** Login emails are **globally unique** across the system — one email maps to one user account and one company (or platform admin with `company_id` null).
- **Roles:** Fixed set — `ADMIN`, `MANAGER`, `CASHIER`, `ACCOUNTANT`. Assigned at user creation/update and enforced via Spatie Permission.

### Rate limiting

All `/api/*` routes are protected by a global API rate limiter. Login has an additional, stricter limit.

| Scope | Limit | Key |
|-------|-------|-----|
| `POST /login` | 5 requests / minute | IP + email (email normalized to lowercase) |
| All `/api/*` routes | 60 requests / minute | Authenticated user ID, or client IP when unauthenticated |

Limits are configurable via `LOGIN_RATE_LIMIT_PER_MINUTE` and `API_RATE_LIMIT_PER_MINUTE` in `.env`.

When a limit is exceeded, the API returns `429 Too Many Requests` with a `Retry-After` header (seconds until the bucket resets) and a JSON message body.

### Role permissions (auth module)

| Role | Login | `/me` | List roles | Manage users |
|------|-------|-------|------------|--------------|
| `ADMIN` | ✓ | ✓ | ✓ | ✓ |
| `MANAGER` | ✓ | ✓ | ✗ | ✗ |
| `CASHIER` | ✓ | ✓ | ✗ | ✗ |
| `ACCOUNTANT` | ✓ | ✓ | ✗ | ✗ |

User management endpoints require the `ADMIN` Spatie role.

---

## Seeded credentials (development)

After `php artisan migrate --seed`:

| Field | Value |
|-------|-------|
| Email | `admin@brixdemo.com` |
| Password | `password` |
| Role | `ADMIN` |

---

# Auth endpoints

## Login

Issue a Sanctum API token.

```
POST /login
```

**Authentication:** None

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `email` | string | Yes | Valid email |
| `password` | string | Yes | — |

### Example request

```http
POST /api/v1/login
Content-Type: application/json
Accept: application/json

{
  "email": "admin@brixdemo.com",
  "password": "password"
}
```

### Success response — `200 OK`

```json
{
  "token": "1|abcdefghijklmnopqrstuvwxyz",
  "user": {
    "id": 1,
    "name": "System Admin",
    "email": "admin@brixdemo.com",
    "role": "ADMIN",
    "active": true,
    "company": {
      "id": 1,
      "name": "Brix Demo Company",
      "email": "admin@brixdemo.com",
      "phone": null,
      "currency": "LKR",
      "tax_number": null,
      "active": true
    },
    "created_at": "2026-06-11T12:00:00.000000Z"
  }
}
```

### Error responses

| Status | Condition | Example |
|--------|-----------|---------|
| `422` | Invalid credentials | `{ "message": "...", "errors": { "email": ["The provided credentials are incorrect."] } }` |
| `422` | Deactivated account | `{ "errors": { "email": ["This account has been deactivated."] } }` |
| `422` | Validation failed | Missing or invalid `email` / `password` |
| `429` | Too many login attempts | Rate limit exceeded (5/min per IP + email). Response includes `Retry-After` header. |

---

## Logout

Revoke the current access token.

```
POST /logout
```

**Authentication:** Bearer token (`auth:sanctum`)

### Request body

None

### Example request

```http
POST /api/v1/logout
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "message": "Logged out successfully."
}
```

### Error responses

| Status | Condition |
|--------|-----------|
| `401` | Missing or invalid token |

---

## Current user profile

Return the authenticated user and their company.

```
GET /me
```

**Authentication:** Bearer token (`auth:sanctum`)

### Example request

```http
GET /api/v1/me
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": {
    "id": 1,
    "name": "System Admin",
    "email": "admin@brixdemo.com",
    "role": "ADMIN",
    "active": true,
    "company": {
      "id": 1,
      "name": "Brix Demo Company",
      "email": "admin@brixdemo.com",
      "phone": null,
      "currency": "LKR",
      "tax_number": null,
      "active": true
    },
    "created_at": "2026-06-11T12:00:00.000000Z"
  }
}
```

> **Note:** Login returns `user` at the root. `/me` wraps the user in a `data` envelope (Laravel API Resource).

### Error responses

| Status | Condition |
|--------|-----------|
| `401` | Missing or invalid token |
| `403` | User has no `company_id` (on company-scoped routes only; `/me` does not use `company` middleware) |

---

# Roles endpoints

## List roles

Return assignable roles for user create/edit forms.

```
GET /roles
```

**Authentication:** Bearer token + company context + `ADMIN` role

**Middleware:** `auth:sanctum`, `company`, `role:ADMIN`

### Example request

```http
GET /api/v1/roles
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": [
    { "id": 1, "name": "ACCOUNTANT" },
    { "id": 2, "name": "ADMIN" },
    { "id": 3, "name": "CASHIER" },
    { "id": 4, "name": "MANAGER" }
  ]
}
```

Roles are ordered by `name` ascending.

### Error responses

| Status | Condition |
|--------|-----------|
| `401` | Unauthenticated |
| `403` | Not `ADMIN`, or no company context |

> **Note:** Roles are seeded at install time. There is no API to create new role types. The four names above are the only valid values for `users.role`.

---

# Users endpoints

All user endpoints are scoped to the authenticated admin's company (tenant isolation). Users in other companies are not visible or modifiable.

**Authentication:** Bearer token + company context + `ADMIN` role

---

## List users

```
GET /users
```

### Example request

```http
GET /api/v1/users
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": [
    {
      "id": 1,
      "name": "System Admin",
      "email": "admin@brixdemo.com",
      "role": "ADMIN",
      "active": true,
      "created_at": "2026-06-11T12:00:00.000000Z"
    },
    {
      "id": 2,
      "name": "Jane Accountant",
      "email": "jane@brixdemo.com",
      "role": "ACCOUNTANT",
      "active": true,
      "created_at": "2026-06-11T14:30:00.000000Z"
    }
  ]
}
```

`company` is omitted unless explicitly loaded. Results are ordered by `name`.

---

## Create user

```
POST /users
```

Creates a user in the admin's company and assigns the matching Spatie role.

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `name` | string | Yes | Max 150 characters |
| `email` | string | Yes | Valid email, max 150, globally unique |
| `password` | string | Yes | Laravel default password rules (min 8 characters) |
| `role` | string | Yes | One of: `ADMIN`, `MANAGER`, `CASHIER`, `ACCOUNTANT` |
| `active` | boolean | No | Defaults to `true` if omitted |

### Example request

```http
POST /api/v1/users
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Content-Type: application/json
Accept: application/json

{
  "name": "Jane Accountant",
  "email": "jane@brixdemo.com",
  "password": "secure-password",
  "role": "ACCOUNTANT",
  "active": true
}
```

### Success response — `201 Created`

```json
{
  "data": {
    "id": 2,
    "name": "Jane Accountant",
    "email": "jane@brixdemo.com",
    "role": "ACCOUNTANT",
    "active": true,
    "created_at": "2026-06-11T14:30:00.000000Z"
  }
}
```

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | Caller is not `ADMIN` |
| `422` | Validation failed (duplicate email, invalid role, weak password) |

---

## Get user

```
GET /users/{id}
```

### Example request

```http
GET /api/v1/users/2
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Accept: application/json
```

### Success response — `200 OK`

```json
{
  "data": {
    "id": 2,
    "name": "Jane Accountant",
    "email": "jane@brixdemo.com",
    "role": "ACCOUNTANT",
    "active": true,
    "created_at": "2026-06-11T14:30:00.000000Z"
  }
}
```

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | Not `ADMIN` |
| `404` | User not found or belongs to another company |

---

## Update user

```
PUT /users/{id}
PATCH /users/{id}
```

All body fields are optional (partial update supported).

### Request body

| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `name` | string | No | Max 150 characters |
| `email` | string | No | Valid email, max 150, globally unique |
| `password` | string | No | Laravel default password rules |
| `role` | string | No | One of: `ADMIN`, `MANAGER`, `CASHIER`, `ACCOUNTANT` |
| `active` | boolean | No | Set `false` to deactivate |

When `role` is provided, the Spatie role is synced to match.

### Example request

```http
PATCH /api/v1/users/2
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Content-Type: application/json
Accept: application/json

{
  "role": "MANAGER",
  "active": true
}
```

### Success response — `200 OK`

```json
{
  "data": {
    "id": 2,
    "name": "Jane Accountant",
    "email": "jane@brixdemo.com",
    "role": "MANAGER",
    "active": true,
    "created_at": "2026-06-11T14:30:00.000000Z"
  }
}
```

---

## Delete user

```
DELETE /users/{id}
```

Permanently deletes the user record. An admin **cannot** delete their own account.

### Example request

```http
DELETE /api/v1/users/2
Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz
Accept: application/json
```

### Success response — `204 No Content`

Empty body.

### Error responses

| Status | Condition |
|--------|-----------|
| `403` | Not `ADMIN`, or attempting to delete own account |
| `404` | User not found |

---

# Error reference

## Standard HTTP status codes

| Code | Meaning |
|------|---------|
| `200` | Success |
| `201` | Resource created |
| `204` | Success, no content |
| `401` | Unauthenticated — missing or invalid token |
| `403` | Forbidden — wrong role or no company context |
| `404` | Resource not found (or hidden by tenant scope) |
| `422` | Validation error |
| `429` | Too many requests — rate limit exceeded (`Retry-After` header present) |

## Validation error format — `422`

```json
{
  "message": "The email has already been taken. (and 1 more error)",
  "errors": {
    "email": ["The email has already been taken."],
    "role": ["The selected role is invalid."]
  }
}
```

## Forbidden — `403`

```json
{
  "message": "Forbidden."
}
```

## No company context — `403`

```json
{
  "message": "No company context."
}
```

---

# Frontend integration guide

## 1. Login and store token

```javascript
const response = await fetch(`${API_BASE}/login`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json',
  },
  body: JSON.stringify({ email, password }),
});

const { token, user } = await response.json();
localStorage.setItem('token', token);
```

## 2. Authenticated requests

```javascript
const headers = {
  Accept: 'application/json',
  Authorization: `Bearer ${localStorage.getItem('token')}`,
};
```

## 3. Admin user management flow

```
1. POST /login          (admin credentials)
2. GET  /roles          (populate role dropdown)
3. GET  /users          (list table)
4. POST /users          (create form submit)
5. PATCH /users/{id}    (edit form submit)
6. DELETE /users/{id}   (delete action)
```

## 4. Session refresh / profile

Use `GET /me` on app load to restore the current user without re-login (while token is valid).

## 5. Logout

```javascript
await fetch(`${API_BASE}/logout`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
});
localStorage.removeItem('token');
```

---

# Data models (reference)

## User object

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Primary key |
| `name` | string | Display name |
| `email` | string | Login email (globally unique) |
| `role` | string | `ADMIN` \| `MANAGER` \| `CASHIER` \| `ACCOUNTANT` |
| `active` | boolean | `false` blocks login |
| `company` | object | Present when loaded (login, `/me`) |
| `created_at` | ISO 8601 datetime | — |

## Company object (nested)

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Primary key |
| `name` | string | Company name |
| `email` | string \| null | Company contact email |
| `phone` | string \| null | — |
| `address` | string \| null | Mailing or registered address |
| `currency` | string | e.g. `LKR`, `USD` |
| `tax_number` | string \| null | — |
| `active` | boolean | — |

> For full company details including `address` and timestamps, use `GET /company`. See [company.md](./company.md).

## Role object

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Spatie role ID |
| `name` | string | Role name (use as `role` value on user forms) |

---

# Endpoint summary

| Method | Path | Auth | Description |
|--------|------|------|-------------|
| `POST` | `/login` | None | Obtain API token |
| `POST` | `/logout` | Token | Revoke current token |
| `GET` | `/me` | Token | Current user profile |
| `GET` | `/company` | Token | Current company profile |
| `PATCH` | `/company` | Token + ADMIN | Update company profile |
| `GET` | `/roles` | Token + ADMIN | List assignable roles |
| `GET` | `/users` | Token + ADMIN | List company users |
| `POST` | `/users` | Token + ADMIN | Create user |
| `GET` | `/users/{id}` | Token + ADMIN | Get user |
| `PUT`/`PATCH` | `/users/{id}` | Token + ADMIN | Update user |
| `DELETE` | `/users/{id}` | Token + ADMIN | Delete user |
