# Login Troubleshooting Guide

## ✅ Issue Fixed!

The login was failing due to **CORS configuration**. Your frontend is running on port **5174**, but CORS was only configured for ports 5173 and 3000.

## Changes Made

### 1. Updated CORS Configuration
**File:** `config/cors.php`
```php
'allowed_origins' => [
    'http://localhost:5173',
    'http://localhost:5174',  // ✅ ADDED
    'http://localhost:3000',
    'http://127.0.0.1:5173',
    'http://127.0.0.1:5174',  // ✅ ADDED
    'http://127.0.0.1:3000',
],
```

### 2. Updated Sanctum Configuration
**File:** `config/sanctum.php`
```php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,localhost:5173,localhost:5174,...',  // ✅ ADDED 5174
    ...
)))
```

### 3. Cleared Configuration Cache
```bash
php artisan config:clear
```

## Verified Credentials

✅ **User exists in database**
```
Username: sysadmin
Password: Admin@123
Email: sysadmin@repsis.com
Role: system_admin
Status: Active
```

✅ **Password hash verified** - Password is correct
✅ **Account is active** - state_type = 1

## Available Test Users

### 1. System Administrator
```
Username: sysadmin
Password: Admin@123
Role: system_admin
```

### 2. Finance Manager
```
Username: finance
Password: Finance@123
Role: finance
```

### 3. Regular User
```
Username: user
Password: User@123
Role: user
```

## How to Test Login

### From Frontend
1. Go to: `http://localhost:5174/login`
2. Enter credentials:
   - Username: `sysadmin`
   - Password: `Admin@123`
3. Click "Login"
4. Should see SweetAlert success message
5. Redirect to `/admin/dashboard`

### Test API Directly (PowerShell)
```powershell
$body = @{
    username = "sysadmin"
    password = "Admin@123"
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri "http://localhost:8000/api/auth/login" `
    -Method Post `
    -ContentType "application/json" `
    -Body $body

$response
```

### Expected Response
```json
{
  "user": {
    "id": 2,
    "username": "sysadmin",
    "email": "sysadmin@repsis.com",
    "role": "system_admin",
    "full_name": "System Administrator",
    ...
  },
  "token": "2|xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "menu_profile": 1,
  "message": "Login successful"
}
```

## Common Login Issues

### Issue 1: CORS Error
**Symptom:** Network error, CORS policy blocked
**Solution:** 
- Check port number in browser URL
- Ensure port is in `config/cors.php` allowed_origins
- Run `php artisan config:clear`

### Issue 2: 401 Unauthorized
**Symptom:** "Invalid credentials" message
**Solution:**
- Verify username/password (case-sensitive)
- Check user exists: `SELECT * FROM users WHERE username = 'sysadmin';`
- Verify password: Run test script

### Issue 3: 419 CSRF Token Mismatch
**Symptom:** "CSRF token mismatch" error
**Solution:**
- Check SANCTUM_STATEFUL_DOMAINS includes your frontend port
- Ensure `withCredentials: true` in axios config
- Clear cookies and try again

### Issue 4: Network Error
**Symptom:** Request doesn't reach server
**Solution:**
- Check backend server is running: `http://localhost:8000`
- Check frontend API URL in AuthContext.jsx
- Verify WAMP/MySQL is running

### Issue 5: SweetAlert Not Showing
**Symptom:** Login works but no alert
**Solution:**
- Check browser console for errors
- Verify SweetAlert2 is installed
- Check AuthContext.jsx login function

## Checking Server Status

### Laravel Server
```bash
# Check if running
curl http://localhost:8000/api/auth/me

# Start server if not running
php artisan serve
```

### Database Connection
```bash
php artisan db:show
```

### View All Users
```bash
php artisan tinker --execute="User::select('id','username','email','role')->get();"
```

## Debug Mode

### Enable Laravel Logging
**File:** `.env`
```env
APP_DEBUG=true
LOG_CHANNEL=single
```

### Check Logs
```bash
tail -f storage/logs/laravel.log
```

### Browser Console
1. Open DevTools (F12)
2. Go to Network tab
3. Try login
4. Check:
   - Request URL
   - Request Headers
   - Response
   - Console errors

## API Endpoints

### Authentication
```
POST /api/auth/login       - Login
POST /api/auth/logout      - Logout (requires auth)
GET  /api/auth/me          - Get current user (requires auth)
POST /api/auth/refresh     - Refresh token (requires auth)
```

### Test Endpoints
```bash
# Get CSRF cookie
curl -X GET http://localhost:8000/sanctum/csrf-cookie -v

# Login
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"sysadmin","password":"Admin@123"}'

# Get user (with token)
curl -X GET http://localhost:8000/api/auth/me \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
```

## Quick Fixes

### Reset Everything
```bash
# Clear all caches
php artisan config:clear
php artisan cache:clear
php artisan route:clear

# Restart server
# Ctrl+C to stop, then:
php artisan serve
```

### Re-seed Database
```bash
# Warning: This will delete all data!
php artisan migrate:fresh --seed
```

### Check Frontend Environment
**File:** `client/src/contexts/AuthContext.jsx`
```javascript
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000/api'
```

Make sure it points to: `http://localhost:8000/api`

## Still Not Working?

### Checklist
- [ ] Backend server running on port 8000
- [ ] Frontend running on port 5174
- [ ] WAMP/MySQL running
- [ ] CORS includes port 5174
- [ ] Sanctum stateful domains includes localhost:5174
- [ ] Config cache cleared
- [ ] Browser cache cleared
- [ ] Using correct credentials (sysadmin/Admin@123)
- [ ] Check browser console for errors
- [ ] Check Laravel logs

### Get Help
1. Check browser DevTools → Network tab
2. Check Laravel logs: `storage/logs/laravel.log`
3. Check database: `SELECT * FROM users;`
4. Test API directly with curl/Postman

---

**Last Updated:** December 3, 2025
**Status:** ✅ FIXED

