# Admin Authentication System - Manual Testing Guide

This guide provides step-by-step instructions for manually testing the admin authentication and RBAC system.

## Prerequisites

1. Backend server is running (`npm run dev`)
2. Database is set up and seeded with admin accounts
3. API testing tool (Postman, curl, or similar)

## Test Scenarios

### 1. Admin Login

#### Test 1.1: Successful Login
```bash
curl -X POST http://localhost:3000/api/v1/admin/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "admin123"
  }'
```

**Expected Result:**
- Status: 200 OK
- Response contains `admin` object and `token`
- Admin object does NOT contain password field

#### Test 1.2: Invalid Username
```bash
curl -X POST http://localhost:3000/api/v1/admin/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "nonexistent",
    "password": "admin123"
  }'
```

**Expected Result:**
- Status: 401 Unauthorized
- Error code: `INVALID_CREDENTIALS`

#### Test 1.3: Invalid Password
```bash
curl -X POST http://localhost:3000/api/v1/admin/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "wrongpassword"
  }'
```

**Expected Result:**
- Status: 401 Unauthorized
- Error code: `INVALID_CREDENTIALS`

#### Test 1.4: Missing Credentials
```bash
curl -X POST http://localhost:3000/api/v1/admin/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin"
  }'
```

**Expected Result:**
- Status: 400 Bad Request
- Error code: `MISSING_CREDENTIALS`

### 2. Get Admin Profile

First, login and save the token:
```bash
TOKEN=$(curl -X POST http://localhost:3000/api/v1/admin/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}' \
  | jq -r '.data.token')
```

#### Test 2.1: Get Profile with Valid Token
```bash
curl -X GET http://localhost:3000/api/v1/admin/profile \
  -H "Authorization: Bearer $TOKEN"
```

**Expected Result:**
- Status: 200 OK
- Response contains admin profile
- Password field is NOT included

#### Test 2.2: Get Profile without Token
```bash
curl -X GET http://localhost:3000/api/v1/admin/profile
```

**Expected Result:**
- Status: 401 Unauthorized
- Error code: `MISSING_TOKEN`

#### Test 2.3: Get Profile with Invalid Token
```bash
curl -X GET http://localhost:3000/api/v1/admin/profile \
  -H "Authorization: Bearer invalid.token.here"
```

**Expected Result:**
- Status: 401 Unauthorized
- Error code: `INVALID_TOKEN`

### 3. Role-Based Access Control

To test RBAC, you'll need to create test endpoints or use existing admin endpoints with different role requirements.

#### Test 3.1: Super Admin Access
```bash
# Login as super admin
SUPER_TOKEN=$(curl -X POST http://localhost:3000/api/v1/admin/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}' \
  | jq -r '.data.token')

# Access super-admin-only endpoint (when implemented)
curl -X GET http://localhost:3000/api/v1/admin/system-settings \
  -H "Authorization: Bearer $SUPER_TOKEN"
```

**Expected Result:**
- Status: 200 OK (if endpoint exists)
- Super admin can access all endpoints

#### Test 3.2: Admin Role Restrictions
```bash
# Create an admin user first (requires super admin)
# Then login as that admin and test access
```

#### Test 3.3: Operator Role Restrictions
```bash
# Create an operator user first
# Then login as operator and test limited access
```

### 4. Login History Verification

After logging in, check the database to verify login history was recorded:

```sql
SELECT * FROM login_history 
WHERE user_type = 'admin' 
ORDER BY login_at DESC 
LIMIT 5;
```

**Expected Result:**
- New record created for each login
- Contains IP address, user agent, device info
- Timestamp matches login time

### 5. Operation Logging

Admin operations should be logged. Check the application logs after performing admin actions:

```bash
# Perform an admin action
curl -X GET http://localhost:3000/api/v1/admin/profile \
  -H "Authorization: Bearer $TOKEN"

# Check logs (location depends on your logger configuration)
tail -f logs/combined.log
```

**Expected Result:**
- Log entry contains admin ID, username, role
- Log entry contains request method, path, status code
- Sensitive data (passwords) is redacted

### 6. Token Expiration

#### Test 6.1: Expired Token
```bash
# Generate a token with short expiration (requires code modification)
# Wait for expiration
# Try to use expired token

curl -X GET http://localhost:3000/api/v1/admin/profile \
  -H "Authorization: Bearer <expired-token>"
```

**Expected Result:**
- Status: 401 Unauthorized
- Error message: "Token has expired"

### 7. Account Status

#### Test 7.1: Inactive Admin Account
```bash
# First, set an admin account to inactive in database
UPDATE admin SET status = 'inactive' WHERE username = 'testadmin';

# Try to login with inactive account
curl -X POST http://localhost:3000/api/v1/admin/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testadmin",
    "password": "password"
  }'
```

**Expected Result:**
- Status: 403 Forbidden
- Error code: `ACCOUNT_INACTIVE`

### 8. Cross-Token Type Validation

#### Test 8.1: User Token on Admin Endpoint
```bash
# Get a user token (from user login)
USER_TOKEN=$(curl -X POST http://localhost:3000/api/v1/auth/wechat-login \
  -H "Content-Type: application/json" \
  -d '{"code":"test-code"}' \
  | jq -r '.data.token')

# Try to use user token on admin endpoint
curl -X GET http://localhost:3000/api/v1/admin/profile \
  -H "Authorization: Bearer $USER_TOKEN"
```

**Expected Result:**
- Status: 401 Unauthorized
- Error code: `INVALID_TOKEN_TYPE`
- Message: "Admin token required"

## Verification Checklist

- [ ] Admin can login with valid credentials
- [ ] Invalid credentials are rejected
- [ ] JWT token is generated on successful login
- [ ] Token can be used to access protected endpoints
- [ ] Invalid/expired tokens are rejected
- [ ] Login history is recorded in database
- [ ] lastLoginAt is updated on each login
- [ ] Admin operations are logged
- [ ] Sensitive data is redacted from logs
- [ ] Inactive admin accounts cannot login
- [ ] User tokens cannot access admin endpoints
- [ ] Admin tokens cannot access user endpoints
- [ ] RBAC middleware correctly enforces role permissions
- [ ] Higher roles can access lower role endpoints
- [ ] Lower roles cannot access higher role endpoints

## Notes

- Replace `localhost:3000` with your actual server address
- Replace token values with actual tokens from login responses
- Some tests require database access to verify results
- Check application logs for operation logging verification
