All files / backend/src/auth local-file-provider.ts

84.84% Statements 56/66
77.27% Branches 17/22
89.47% Functions 17/19
86.2% Lines 50/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182                                                      1x           14x       28x 13x   15x 15x       16x       5x 5x   5x 1x     4x 4x 2x       2x 2x   2x                     2x 2x   2x       2x 2x 1x     1x 1x 1x       4x 4x   4x   4x               4x 4x       13x   13x 1x     12x 12x   12x                 12x 12x   12x       2x 2x   2x 1x     1x 1x       2x 2x                                                       2x      
/**
 * Local File Auth Provider
 *
 * Manages users in a JSON file with bcrypt-hashed passwords.
 * The users file lives in the config directory, not the sites directory.
 */
 
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { join } from 'path';
import { randomUUID } from 'crypto';
import bcrypt from 'bcryptjs';
import type { AuthProvider, AuthUser, AuthResult } from './types.js';
 
interface StoredUser {
  id: string;
  email: string;
  passwordHash: string;
  mustChangePassword: boolean;
  createdAt: string;
  lastLoginAt: string | null;
}
 
interface UsersFile {
  users: StoredUser[];
  meta: { version: number };
}
 
const BCRYPT_ROUNDS = 10;
 
export class LocalFileAuthProvider implements AuthProvider {
  private filePath: string;
 
  constructor(configDir: string, usersFile: string = 'users.json') {
    this.filePath = join(configDir, usersFile);
  }
 
  private readUsersFile(): UsersFile {
    if (!existsSync(this.filePath)) {
      return { users: [], meta: { version: 1 } };
    }
    const content = readFileSync(this.filePath, 'utf-8');
    return JSON.parse(content);
  }
 
  private writeUsersFile(data: UsersFile): void {
    writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8');
  }
 
  async authenticate(credentials: { email: string; password: string }): Promise<AuthResult> {
    const data = this.readUsersFile();
    const user = data.users.find(u => u.email === credentials.email);
 
    if (!user) {
      return { success: false, error: 'Invalid credentials' };
    }
 
    const valid = await bcrypt.compare(credentials.password, user.passwordHash);
    if (!valid) {
      return { success: false, error: 'Invalid credentials' };
    }
 
    // Update last login time
    user.lastLoginAt = new Date().toISOString();
    this.writeUsersFile(data);
 
    return {
      success: true,
      user: {
        id: user.id,
        email: user.email,
        mustChangePassword: user.mustChangePassword,
      },
    };
  }
 
  async changePassword(userId: string, oldPassword: string, newPassword: string): Promise<void> {
    const data = this.readUsersFile();
    const user = data.users.find(u => u.id === userId);
 
    Iif (!user) {
      throw new Error('User not found');
    }
 
    const valid = await bcrypt.compare(oldPassword, user.passwordHash);
    if (!valid) {
      throw new Error('Invalid current password');
    }
 
    user.passwordHash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS);
    user.mustChangePassword = false;
    this.writeUsersFile(data);
  }
 
  async getUserById(userId: string): Promise<AuthUser | null> {
    const data = this.readUsersFile();
    const user = data.users.find(u => u.id === userId);
 
    Iif (!user) return null;
 
    return {
      id: user.id,
      email: user.email,
      mustChangePassword: user.mustChangePassword,
    };
  }
 
  async needsPasswordChange(userId: string): Promise<boolean> {
    const user = await this.getUserById(userId);
    return user?.mustChangePassword ?? false;
  }
 
  async createUser(email: string, password: string, mustChangePassword: boolean = true): Promise<AuthUser> {
    const data = this.readUsersFile();
 
    if (data.users.some(u => u.email === email)) {
      throw new Error(`User with email '${email}' already exists`);
    }
 
    const id = randomUUID();
    const passwordHash = await bcrypt.hash(password, BCRYPT_ROUNDS);
 
    const storedUser: StoredUser = {
      id,
      email,
      passwordHash,
      mustChangePassword,
      createdAt: new Date().toISOString(),
      lastLoginAt: null,
    };
 
    data.users.push(storedUser);
    this.writeUsersFile(data);
 
    return { id, email, mustChangePassword };
  }
 
  async removeUser(email: string): Promise<void> {
    const data = this.readUsersFile();
    const index = data.users.findIndex(u => u.email === email);
 
    if (index === -1) {
      throw new Error(`User with email '${email}' not found`);
    }
 
    data.users.splice(index, 1);
    this.writeUsersFile(data);
  }
 
  async listUsers(): Promise<AuthUser[]> {
    const data = this.readUsersFile();
    return data.users.map(u => ({
      id: u.id,
      email: u.email,
      mustChangePassword: u.mustChangePassword,
    }));
  }
 
  /**
   * Reset a user's password (for CLI admin use).
   * Sets mustChangePassword to true.
   */
  async resetPassword(email: string, newPassword: string): Promise<void> {
    const data = this.readUsersFile();
    const user = data.users.find(u => u.email === email);
 
    if (!user) {
      throw new Error(`User with email '${email}' not found`);
    }
 
    user.passwordHash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS);
    user.mustChangePassword = true;
    this.writeUsersFile(data);
  }
 
  /**
   * Check if the users file exists (for first-run detection).
   */
  usersFileExists(): boolean {
    return existsSync(this.filePath);
  }
}