# CRM Server - Autentifikačný Systém Backend API server pre CRM systém s pokročilým autentifikačným systémom, role-based access control a kompletnou bezpečnostnou vrstvou. ## Technológie - **Node.js** + **Express.js** - Backend framework - **PostgreSQL** - Databáza - **Drizzle ORM** - Type-safe ORM - **JWT** - JSON Web Tokens pre autentifikáciu - **Bcrypt** - Password hashing - **Zod** - Validácia vstupov - **Helmet.js** - HTTP security headers - **Express Rate Limit** - Rate limiting - **JMAP** - Email posielanie (Truemail.sk) ## Funkcionality ### 3-Krokový Autentifikačný Flow 1. **Krok 1: Login s temporary password** - Používateľ dostane username a dočasné heslo - Prihlásenie vytvorí JWT tokens a session 2. **Krok 2: Nastavenie nového hesla** - Po prvom prihlásení musí užívateľ zmeniť heslo - Strong password policy (8+ znakov, uppercase, lowercase, čísla, špeciálne znaky) 3. **Krok 3: Email setup (voliteľný)** - Pripojenie emailu s verifikačným linkom - Možnosť preskočiť tento krok ### Role-Based Access Control (RBAC) - **Admin** - Plný prístup, môže vytvárať používateľov, meniť role - **Member** - Základný prístup (zatiaľ len vlastný profil) ### Bezpečnostné Vrstvy - ✅ **Helmet.js** - HTTP headers security (CSP, HSTS) - ✅ **CORS** - Whitelist configuration - ✅ **Rate limiting** - Login (5/15min), API (100/15min) - ✅ **Input validation** - Zod schemas - ✅ **SQL injection protection** - Drizzle ORM parametrized queries - ✅ **XSS protection** - Helmet + input sanitization - ✅ **Password security** - Bcrypt (12 rounds) - ✅ **JWT security** - HttpOnly cookies, short expiration - ✅ **Audit logging** - Všetky dôležité akcie logované - ✅ **Environment variables** - Citlivé dáta v .env ## Inštalácia ### 1. Klonovanie a Dependencies ```bash npm install ``` ### 2. Konfigurácia Environment Variables Skopírujte `.env.example` do `.env` a upravte hodnoty: ```bash cp .env.example .env ``` Dôležité premenné: - `JWT_SECRET` - Zmeňte v produkcii! - `JWT_REFRESH_SECRET` - Zmeňte v produkcii! - `BETTER_AUTH_SECRET` - Zmeňte v produkcii! - `DB_*` - Databázové credentials - `JMAP_*` - Email server credentials ### 3. Databáza Setup Spustite PostgreSQL (Docker): ```bash docker compose up -d postgres ``` Vygenerujte a aplikujte migrácie: ```bash npm run db:generate npm run db:migrate ``` ### 4. Seed Admin Account Vytvorte prvý admin účet: ```bash npm run db:seed ``` **DÔLEŽITÉ:** Uložte si vygenerované temporary password! ### 5. Spustenie Servera Development mode: ```bash npm run dev ``` Production mode: ```bash npm start ``` Server beží na `http://localhost:5000` ## API Endpointy ### Public Endpoints #### Login ```http POST /api/auth/login Content-Type: application/json { "username": "admin", "password": "temporary-password" } ``` **Response:** ```json { "success": true, "data": { "user": { ... }, "tokens": { "accessToken": "...", "refreshToken": "..." }, "needsPasswordChange": true, "needsEmailSetup": true } } ``` ### Protected Endpoints (vyžadujú JWT token) #### Set New Password (Krok 2) ```http POST /api/auth/set-password Authorization: Bearer Content-Type: application/json { "newPassword": "NewSecurePass123!", "confirmPassword": "NewSecurePass123!" } ``` #### Link Email (Krok 3) ```http POST /api/auth/link-email Authorization: Bearer Content-Type: application/json { "email": "user@example.com" } ``` #### Skip Email Setup ```http POST /api/auth/skip-email Authorization: Bearer ``` #### Get Current User ```http GET /api/auth/me Authorization: Bearer ``` #### Logout ```http POST /api/auth/logout Authorization: Bearer ``` ### Admin Endpoints (vyžadujú admin rolu) #### Create User ```http POST /api/admin/users Authorization: Bearer Content-Type: application/json { "username": "newuser", "tempPassword": "TempPass123!", "role": "member", "firstName": "John", "lastName": "Doe" } ``` #### Get All Users ```http GET /api/admin/users Authorization: Bearer ``` #### Get User by ID ```http GET /api/admin/users/:userId Authorization: Bearer ``` #### Change User Role ```http PATCH /api/admin/users/:userId/role Authorization: Bearer Content-Type: application/json { "role": "admin" } ``` #### Delete User ```http DELETE /api/admin/users/:userId Authorization: Bearer ``` ## Databázová Schéma ### Users Table ``` - id (UUID) - username (unique) - email (unique, nullable) - email_verified (boolean) - first_name - last_name - password (bcrypt hash) - temp_password (bcrypt hash) - changed_password (boolean) - role (enum: admin, member) - last_login - created_at - updated_at ``` ### Sessions Table ``` - id (text) - user_id (UUID, FK) - expires_at - ip_address - user_agent - created_at ``` ### Audit Logs Table ``` - id (UUID) - user_id (UUID, FK, nullable) - action - resource - resource_id - old_value (JSON) - new_value (JSON) - ip_address - user_agent - success (boolean) - error_message - created_at ``` ## Validačné Pravidlá ### Password Policy - Minimálne 8 znakov - Aspoň 1 veľké písmeno - Aspoň 1 malé písmeno - Aspoň 1 číslo - Aspoň 1 špeciálny znak ### Username Policy - 3-50 znakov - Iba písmená, čísla, pomlčky a podčiarkovníky ## Rate Limiting - **Login endpoint:** 5 pokusov / 15 minút - **API endpoints:** 100 requestov / 15 minút - **Citlivé operácie:** 3 pokusy / 15 minút ## Audit Logging Všetky dôležité akcie sú automaticky logované: - Login attempts (úspešné aj neúspešné) - Password changes - Email linking & verification - Role changes - User creation - A ďalšie... ## Security Best Practices 1. **HTTPS Only** - V produkcii vždy používajte HTTPS 2. **Strong Secrets** - Zmeňte všetky secret keys v `.env` 3. **Regular Updates** - Aktualizujte dependencies 4. **Monitor Logs** - Sledujte audit logs 5. **Backup Database** - Pravidelné zálohy PostgreSQL ## Database Commands ```bash # Generovanie migrácií npm run db:generate # Aplikovanie migrácií npm run db:migrate # Push schema (alternative to migrations) npm run db:push # Drizzle Studio (GUI) npm run db:studio # Seed admin account npm run db:seed ``` ## Testing Spustenie testov: ```bash npm test ``` ## Štruktúra Projektu ``` src/ ├── config/ # Database & auth config ├── db/ │ ├── schema.js # Drizzle schema │ ├── migrations/ # Auto-generated migrations │ └── seeds/ # Seed scripts ├── controllers/ # Request handlers ├── services/ # Business logic ├── middlewares/ │ ├── auth/ # Auth & role middleware │ ├── security/ # Rate limiting, validation │ └── global/ # Error handling ├── routes/ # API routes ├── validators/ # Zod schemas ├── utils/ # Helper functions ├── app.js # Express app └── index.js # Server entry point ``` ## Licencia MIT ## Autor Richard Tekula --- **POZNÁMKA:** Tento projekt je v aktívnom vývoji. Pre production nasadenie nezabudnite: 1. Zmeniť všetky secret keys v `.env` 2. Nastaviť HTTPS 3. Konfigurovať firewall 4. Nastaviť monitoring a alerting 5. Pravidelné security audity