@wikiccu/nest-auth
Version:
A comprehensive authentication package for NestJS applications with Prisma and PostgreSQL
655 lines (488 loc) • 10.6 kB
Markdown
# WikiCCU Auth API Documentation
Complete API documentation for the WikiCCU NestJS Authentication Service.
## Table of Contents
- [Base URL](#base-url)
- [Authentication](#authentication)
- [Public Endpoints](#public-endpoints)
- [Authenticated Endpoints](#authenticated-endpoints)
- [Admin Endpoints](#admin-endpoints)
- [Error Responses](#error-responses)
- [Data Types](#data-types)
## Base URL
```
http://localhost:3000
```
## Authentication
The API uses JWT (JSON Web Tokens) for authentication. Most endpoints require a valid JWT token in the Authorization header.
### Token Types
- **Access Token**: Short-lived token (default: 15 minutes) for API requests
- **Refresh Token**: Long-lived token (default: 7 days) for getting new access tokens
### Authentication Header
```
Authorization: Bearer <access_token>
```
## Public Endpoints
These endpoints do not require authentication.
### Register User
**POST** `/auth/register`
Creates a new user account and sends email verification.
#### Request Body
```json
{
"email": "user@example.com",
"password": "password123",
"username": "johndoe",
"firstName": "John",
"lastName": "Doe"
}
```
#### Response (201 Created)
```json
{
"user": {
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"username": "johndoe",
"firstName": "John",
"lastName": "Doe",
"isEmailVerified": false,
"isActive": true,
"roles": ["user"],
"permissions": ["read:own"],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
},
"message": "User registered successfully. Please check your email for verification."
}
```
### Login User
**POST** `/auth/login`
Authenticates user and returns access and refresh tokens.
#### Request Body
```json
{
"email": "user@example.com",
"password": "password123",
"rememberMe": true
}
```
#### Response (200 OK)
```json
{
"user": {
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"username": "johndoe",
"firstName": "John",
"lastName": "Doe",
"isEmailVerified": true,
"isActive": true,
"roles": ["user"],
"permissions": ["read:own"]
},
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "refresh_token_here",
"expiresIn": 3600
}
```
### Refresh Token
**POST** `/auth/refresh`
Uses refresh token to get new access and refresh tokens.
#### Request Body
```json
{
"refreshToken": "refresh_token_here"
}
```
#### Response (200 OK)
```json
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "new_refresh_token_here",
"expiresIn": 3600
}
```
### Forgot Password
**POST** `/auth/forgot-password`
Sends password reset email if user exists.
#### Request Body
```json
{
"email": "user@example.com"
}
```
#### Response (200 OK)
```json
{
"message": "If an account with that email exists, a password reset email has been sent."
}
```
### Reset Password
**POST** `/auth/reset-password`
Resets password using token from email.
#### Request Body
```json
{
"token": "reset_token_from_email",
"newPassword": "newpassword123"
}
```
#### Response (200 OK)
```json
{
"message": "Password reset successfully"
}
```
### Verify Email
**POST** `/auth/verify-email`
Verifies email address using token from email.
#### Request Body
```json
{
"token": "email_verification_token"
}
```
#### Response (200 OK)
```json
{
"message": "Email verified successfully"
}
```
### Resend Email Verification
**POST** `/auth/resend-verification`
Resends email verification to user.
#### Request Body
```json
{
"email": "user@example.com"
}
```
#### Response (200 OK)
```json
{
"message": "Verification email sent successfully"
}
```
## Authenticated Endpoints
These endpoints require a valid JWT access token.
### Get User Profile
**GET** `/auth/profile`
Returns current user profile information.
#### Headers
```
Authorization: Bearer <access_token>
```
#### Response (200 OK)
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"username": "johndoe",
"firstName": "John",
"lastName": "Doe",
"isEmailVerified": true,
"isActive": true,
"roles": ["user"],
"permissions": ["read:own"],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
```
### Update User Profile
**PUT** `/auth/profile`
Updates current user profile information.
#### Headers
```
Authorization: Bearer <access_token>
Content-Type: application/json
```
#### Request Body
```json
{
"firstName": "Jane",
"lastName": "Smith",
"username": "janesmith"
}
```
#### Response (200 OK)
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"username": "janesmith",
"firstName": "Jane",
"lastName": "Smith",
"isEmailVerified": true,
"isActive": true,
"roles": ["user"],
"permissions": ["read:own"],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
```
### Change Password
**PUT** `/auth/change-password`
Changes current user password.
#### Headers
```
Authorization: Bearer <access_token>
Content-Type: application/json
```
#### Request Body
```json
{
"currentPassword": "oldpassword123",
"newPassword": "newpassword123"
}
```
#### Response (200 OK)
```json
{
"message": "Password changed successfully"
}
```
### Logout User
**POST** `/auth/logout`
Revokes the provided refresh token.
#### Headers
```
Authorization: Bearer <access_token>
Content-Type: application/json
```
#### Request Body
```json
{
"refreshToken": "refresh_token_here"
}
```
#### Response (200 OK)
```json
{
"message": "Logged out successfully"
}
```
## Admin Endpoints
These endpoints require admin role permissions.
### Get All Users
**GET** `/auth/users`
Returns paginated list of all users.
#### Headers
```
Authorization: Bearer <access_token>
```
#### Query Parameters
- `page` (optional): Page number (default: 1)
- `limit` (optional): Items per page (default: 10)
#### Example Request
```
GET /auth/users?page=1&limit=10
```
#### Response (200 OK)
```json
{
"users": [
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"username": "johndoe",
"firstName": "John",
"lastName": "Doe",
"isEmailVerified": true,
"isActive": true,
"roles": ["user"],
"permissions": ["read:own"],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
],
"total": 1,
"page": 1,
"limit": 10
}
```
### Create User (Admin)
**POST** `/auth/users`
Creates a new user account (pre-verified).
#### Headers
```
Authorization: Bearer <access_token>
Content-Type: application/json
```
#### Request Body
```json
{
"email": "admin@example.com",
"password": "adminpass123",
"username": "adminuser",
"firstName": "Admin",
"lastName": "User",
"roles": ["admin"]
}
```
#### Response (201 Created)
```json
{
"id": "456e7890-e89b-12d3-a456-426614174001",
"email": "admin@example.com",
"username": "adminuser",
"firstName": "Admin",
"lastName": "User",
"isEmailVerified": true,
"isActive": true,
"roles": ["admin"],
"permissions": ["read:all", "write:all"],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
```
### Update User (Admin)
**PUT** `/auth/users/{id}`
Updates user information including roles and active status.
#### Headers
```
Authorization: Bearer <access_token>
Content-Type: application/json
```
#### Path Parameters
- `id`: User ID
#### Request Body
```json
{
"firstName": "Updated",
"lastName": "Name",
"isActive": true,
"roles": ["user", "moderator"]
}
```
#### Response (200 OK)
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"username": "johndoe",
"firstName": "Updated",
"lastName": "Name",
"isEmailVerified": true,
"isActive": true,
"roles": ["user", "moderator"],
"permissions": ["read:own", "moderate:content"],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
```
### Delete User (Admin)
**DELETE** `/auth/users/{id}`
Permanently deletes a user account.
#### Headers
```
Authorization: Bearer <access_token>
```
#### Path Parameters
- `id`: User ID
#### Response (200 OK)
```json
{
"message": "User deleted successfully"
}
```
## Error Responses
### 400 Bad Request
```json
{
"statusCode": 400,
"message": ["Validation error message"],
"error": "Bad Request"
}
```
### 401 Unauthorized
```json
{
"statusCode": 401,
"message": "Unauthorized",
"error": "Unauthorized"
}
```
### 403 Forbidden
```json
{
"statusCode": 403,
"message": "Forbidden resource",
"error": "Forbidden"
}
```
### 409 Conflict
```json
{
"statusCode": 409,
"message": "User already exists",
"error": "Conflict"
}
```
### 500 Internal Server Error
```json
{
"statusCode": 500,
"message": "Internal server error",
"error": "Internal Server Error"
}
```
## Data Types
### User Object
```typescript
interface User {
id: string;
email: string;
username?: string;
firstName?: string;
lastName?: string;
isEmailVerified: boolean;
isActive: boolean;
roles: string[];
permissions: string[];
createdAt: string;
updatedAt: string;
}
```
### Login Response
```typescript
interface LoginResponse {
user: User;
accessToken: string;
refreshToken: string;
expiresIn: number;
}
```
### Register Response
```typescript
interface RegisterResponse {
user: User;
message: string;
}
```
### Paginated Response
```typescript
interface PaginatedResponse<T> {
users: T[];
total: number;
page: number;
limit: number;
}
```
## Authentication Flow
1. **Register**: Create a new user account
2. **Login**: Get access and refresh tokens
3. **Use Access Token**: Include in Authorization header for authenticated requests
4. **Refresh Token**: Get new tokens when access token expires
5. **Logout**: Revoke refresh token
## Rate Limiting
The API implements rate limiting on authentication endpoints:
- **Login**: 5 attempts per 15 minutes
- **Register**: 3 attempts per hour
- **Password Reset**: 3 attempts per hour
- **Email Verification**: 5 attempts per hour
## Security Notes
- Passwords must be at least 8 characters long
- JWT tokens are automatically rotated for security
- Failed login attempts result in temporary account lockout
- Email verification is required for full account access
- All sensitive operations require current password verification