# User Management System - Setup Complete

## Overview
A complete user management system has been implemented with admin-only user creation, forced password changes, and secure authentication.

## Features Implemented

### 1. **Default Administrator Account**
- **Username:** `admin`
- **Password:** `admin`
- **First Login:** User must change password immediately
- **Auto-created:** When database is initialized with no existing users

### 2. **Security Features**
- ✅ Public registration disabled (controlled by `DISABLE_SIGNUPS=true`)
- ✅ Admin-only user creation
- ✅ Forced password change on first login
- ✅ Password reset forces password change
- ✅ Account activation/deactivation
- ✅ Self-deletion prevention
- ✅ Last-admin deletion prevention
- ✅ Minimum 8-character password requirement

### 3. **User Management UI (Admin Only)**
- **Location:** Settings page → User Management section
- **Features:**
  - Create new users (username, email, password, role)
  - Edit user details (email, role, status)
  - Reset user passwords (forces password change)
  - Delete users (with confirmations)
  - Toggle account active/inactive status
  - View user information in table format

### 4. **Database Schema Updates**
New columns added to `users` table:
- `must_change_password` - Boolean flag for forced password change
- `is_active` - Boolean flag for account status
- `created_by` - Foreign key to track which admin created the user

### 5. **API Endpoints**

#### Authentication Endpoints (Updated)
- `POST /api/auth/login` - Returns `must_change_password` flag
- `POST /api/auth/register` - **DISABLED** (returns 403)
- `POST /api/auth/change-password` - Change password and clear flag
- `GET /api/auth/verify` - Verify token and return user data

#### User Management Endpoints (Admin Only)
- `GET /api/users` - List all users
- `GET /api/users/:id` - Get single user details
- `POST /api/users` - Create new user
- `PATCH /api/users/:id` - Update user (email, role, is_active)
- `POST /api/users/:id/reset-password` - Reset user password
- `DELETE /api/users/:id` - Delete user

### 6. **Frontend Components**

#### ChangePasswordDialog
- Non-dismissible modal dialog
- Shows when `must_change_password` is true
- Validates password (min 8 chars, match confirmation)
- Current password verification required
- Auto-redirects after successful change

#### UserManagement
- Admin-only component in Settings page
- User table with status indicators
- Create/Edit/Delete/Reset password dialogs
- Role management (User/Admin)
- Account activation toggle

### 7. **Translations Added**

#### English & Romanian
- User management section labels
- Dialog titles and messages
- Form field labels
- Error and success messages
- Password change dialog text
- Status indicators (Active/Inactive)
- Role labels (User/Administrator)

## First-Time Setup

### 1. Start the Application
```bash
cd /home/iulian/projects/tv
docker-compose up -d
```

### 2. First Login
1. Navigate to the login page
2. Enter credentials:
   - Username: `admin`
   - Password: `admin`
3. You will be prompted to change your password immediately
4. Set a secure new password (minimum 8 characters)

### 3. Create Additional Users (Admin Only)
1. Go to **Settings** → **User Management**
2. Click **Add User**
3. Fill in the form:
   - Username (required, unique)
   - Email (required, unique)
   - Password (min 8 chars)
   - Role (User or Admin)
4. New users will be required to change their password on first login

## User Workflows

### Admin Creates New User
1. Admin logs in
2. Goes to Settings → User Management
3. Clicks "Add User"
4. Fills in user details
5. New user receives credentials (via admin communication)
6. New user logs in and must change password

### User Password Reset (by Admin)
1. Admin goes to Settings → User Management
2. Clicks reset password icon for user
3. Confirms reset action
4. System sets temporary password
5. User must change password on next login

### Account Deactivation
1. Admin toggles "Active Account" switch for user
2. Inactive users cannot log in
3. Can be reactivated at any time

### User Deletion
1. Admin clicks delete icon for user
2. Confirms deletion (cannot be undone)
3. User and all associated data are removed
4. Cannot delete self or last admin

## Security Considerations

### Password Policy
- Minimum 8 characters
- Stored as bcrypt hash (10 rounds)
- Force change on first login
- Force change after admin reset

### Authorization
- JWT tokens with 7-day expiration
- Role-based access control (user/admin)
- Admin-only routes protected by middleware
- Inactive accounts cannot authenticate

### API Protection
- All user management endpoints require admin role
- Self-deletion prevented
- Last-admin deletion prevented
- Rate limiting on authentication endpoints

## File Changes Summary

### Backend Files
- `backend/database/db.js` - Database schema with migrations
- `backend/routes/auth.js` - Registration disabled, password change endpoint
- `backend/routes/users.js` - **NEW** User management API
- `backend/server.js` - Registered users route

### Frontend Files
- `frontend/src/components/ChangePasswordDialog.jsx` - **NEW** Password change UI
- `frontend/src/components/UserManagement.jsx` - **NEW** Admin user management
- `frontend/src/pages/Settings.jsx` - Added UserManagement section
- `frontend/src/pages/Login.jsx` - Added password change flow
- `frontend/src/store/authStore.js` - Added mustChangePassword state
- `frontend/src/locales/en.json` - Added 40+ translation keys
- `frontend/src/locales/ro.json` - Added 40+ translation keys

## Troubleshooting

### Cannot Login as Admin
- Ensure database exists at `/app/data/streamflow.db`
- Check that default admin was created (look for console message)
- Verify credentials: `admin` / `admin`

### Password Change Not Working
- Check browser console for errors
- Verify token is valid
- Ensure current password is correct
- Password must be at least 8 characters

### User Management Section Not Visible
- Only visible to admin role users
- Check user role in database
- Verify token includes role claim

### Cannot Create Users
- Only admin users can create users
- Check that username and email are unique
- Ensure password meets minimum requirements

## Next Steps (Optional Enhancements)

1. **Email Integration**
   - Send welcome emails with temporary credentials
   - Password reset email notifications
   - Account activation emails

2. **Password Complexity**
   - Require uppercase, lowercase, numbers, special chars
   - Implement password history
   - Add password strength meter

3. **Audit Logging**
   - Log user creation/deletion
   - Track password changes
   - Monitor failed login attempts

4. **Two-Factor Authentication**
   - TOTP-based 2FA
   - SMS/Email verification codes
   - Backup codes

5. **Session Management**
   - Active sessions list
   - Remote session termination
   - Session expiration settings

## Support
For issues or questions, check the logs:
```bash
docker-compose logs -f backend
```

## License
Part of StreamFlow IPTV application.
