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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 50x 2x 2x 2x 2x 2x 2x 2x 2x 2x 55x 55x 2x 2x 2x 2x 2x 54x 52x 52x 2x 52x 52x 52x 2x 52x 18x 18x 18x 18x 18x 18x 50x 18x 18x 18x 50x 18x 18x 18x 18x 18x 18x 18x 18x 18x 50x 18x 18x 18x 18x 18x 18x 18x 18x 18x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 18x 51x 49x 49x 1x 1x 1x 103x 2x 18x 18x 18x 103x 103x 17x 103x 17x 17x 2x 36x 36x 102x 36x 36x 36x 100x 100x 100x 35x 35x 2x 35x 35x 35x 35x 11x 2x 2x 2x 2x 13x 9x 9x 9x 9x 2x 2x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 9x 1x 9x 9x 1x 8x 1x 1x 2x 1x 1x 11x 1x 1x 2x 1x 1x 1x 2x 2x 2x 7x 7x 1x 2x 6x 4x 4x 1x 1x 4x 1x 4x 3x 3x 2x 2x 1x 1x 1x 4x 2x 1x 1x 2x 2x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 2x 1x 1x 2x 2x 2x 8x 8x 6x 3x 2x 3x 3x 1x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 3x 1x 1x 2x 2x 2x 2x 5x 4x 2x 2x 2x 2x 2x 2x 2x 50x | // src/services/authService.ts
import * as bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';
import { DatabaseError } from './processingErrors';
import type { Logger } from 'pino';
import { withTransaction, userRepo } from './db/index.db';
import { RepositoryError, ValidationError } from './db/errors.db';
import { logger } from './logger.server';
import { sendPasswordResetEmail } from './emailService.server';
import type { UserProfile } from '../types';
import { validatePasswordStrength } from '../utils/authUtils';
const JWT_SECRET = process.env.JWT_SECRET!;
class AuthService {
async registerUser(
email: string,
password: string,
fullName: string | undefined,
avatarUrl: string | undefined,
reqLog: Logger,
) {
const strength = validatePasswordStrength(password);
if (!strength.isValid) {
throw new ValidationError([], strength.feedback);
}
// Wrap user creation and activity logging in a transaction for atomicity.
// The `createUser` method is now designed to be composed within other transactions.
return withTransaction(async (client) => {
const transactionalUserRepo = new (await import('./db/user.db')).UserRepository(client);
const adminRepo = new (await import('./db/admin.db')).AdminRepository(client);
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
logger.info(`Hashing password for new user: ${email}`);
const newUser = await transactionalUserRepo.createUser(
email,
hashedPassword,
{ full_name: fullName, avatar_url: avatarUrl },
reqLog,
);
logger.info(
`Successfully created new user in DB: ${newUser.user.email} (ID: ${newUser.user.user_id})`,
);
await adminRepo.logActivity(
{
userId: newUser.user.user_id,
action: 'user_registered',
displayText: `${email} has registered.`,
icon: 'user-plus',
},
reqLog,
);
return newUser;
}).catch((error: unknown) => {
// Re-throw known repository errors (like UniqueConstraintError) to allow for specific handling upstream.
if (error instanceof RepositoryError) {
throw error;
}
// For unknown errors, log them and wrap them in a generic DatabaseError
// to standardize the error contract of the service layer.
const message =
error instanceof Error ? error.message : 'An unknown error occurred during registration.';
logger.error({ error, email }, `User registration failed with an unexpected error.`);
throw new DatabaseError(message);
});
}
async registerAndLoginUser(
email: string,
password: string,
fullName: string | undefined,
avatarUrl: string | undefined,
reqLog: Logger,
): Promise<{ newUserProfile: UserProfile; accessToken: string; refreshToken: string }> {
const newUserProfile = await this.registerUser(email, password, fullName, avatarUrl, reqLog);
const { accessToken, refreshToken } = await this.handleSuccessfulLogin(newUserProfile, reqLog);
return { newUserProfile, accessToken, refreshToken };
}
generateAuthTokens(userProfile: UserProfile) {
const payload = {
user_id: userProfile.user.user_id,
email: userProfile.user.email,
role: userProfile.role,
};
const accessToken = jwt.sign(payload, JWT_SECRET, { expiresIn: '15m' });
const refreshToken = crypto.randomBytes(64).toString('hex');
return { accessToken, refreshToken };
}
async saveRefreshToken(userId: string, refreshToken: string, reqLog: Logger) {
// The repository method `saveRefreshToken` already includes robust error handling
// and logging via `handleDbError`. No need for a redundant try/catch block here.
await userRepo.saveRefreshToken(userId, refreshToken, reqLog);
}
async handleSuccessfulLogin(userProfile: UserProfile, reqLog: Logger) {
const { accessToken, refreshToken } = this.generateAuthTokens(userProfile);
await this.saveRefreshToken(userProfile.user.user_id, refreshToken, reqLog);
return { accessToken, refreshToken };
}
async resetPassword(email: string, reqLog: Logger) {
try {
logger.debug(`[API /forgot-password] Received request for email: ${email}`);
const user = await userRepo.findUserByEmail(email, reqLog);
let token: string | undefined;
logger.debug(
{ user: user ? { user_id: user.user_id, email: user.email } : 'NOT FOUND' },
`[API /forgot-password] Database search result for ${email}:`,
);
if (user) {
token = crypto.randomBytes(32).toString('hex');
const saltRounds = 10;
const tokenHash = await bcrypt.hash(token, saltRounds);
const expiresAt = new Date(Date.now() + 3600000); // 1 hour
// Wrap the token creation in a transaction to ensure atomicity of the DELETE and INSERT operations.
await withTransaction(async (client) => {
const transactionalUserRepo = new (await import('./db/user.db')).UserRepository(client);
await transactionalUserRepo.createPasswordResetToken(
user.user_id,
tokenHash,
expiresAt,
reqLog,
client,
);
});
const resetLink = `${process.env.FRONTEND_URL}/reset-password/${token}`;
try {
await sendPasswordResetEmail(email, resetLink, reqLog);
} catch (emailError) {
logger.error({ emailError }, `Email send failure during password reset for user`);
}
} else {
logger.warn(`Password reset requested for non-existent email: ${email}`);
}
return token;
} catch (error) {
// Re-throw known repository errors to allow for specific handling upstream.
if (error instanceof RepositoryError) {
throw error;
}
// For unknown errors, log them and wrap them in a generic DatabaseError.
const message = error instanceof Error ? error.message : 'An unknown error occurred.';
logger.error(
{ error, email },
`An unexpected error occurred during password reset for email: ${email}`,
);
throw new DatabaseError(message);
}
}
async updatePassword(token: string, newPassword: string, reqLog: Logger) {
const strength = validatePasswordStrength(newPassword);
if (!strength.isValid) {
throw new ValidationError([], strength.feedback);
}
// Wrap all database operations in a transaction to ensure atomicity.
return withTransaction(async (client) => {
const transactionalUserRepo = new (await import('./db/user.db')).UserRepository(client);
const adminRepo = new (await import('./db/admin.db')).AdminRepository(client);
// This read can happen outside the transaction if we use the non-transactional repo.
const validTokens = await userRepo.getValidResetTokens(reqLog);
let tokenRecord;
for (const record of validTokens) {
const isMatch = await bcrypt.compare(token, record.token_hash);
if (isMatch) {
tokenRecord = record;
break;
}
}
if (!tokenRecord) {
return null; // Token is invalid or expired, not an error.
}
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(newPassword, saltRounds);
// These three writes are now atomic.
await transactionalUserRepo.updateUserPassword(tokenRecord.user_id, hashedPassword, reqLog);
await transactionalUserRepo.deleteResetToken(tokenRecord.token_hash, reqLog);
await adminRepo.logActivity(
{
userId: tokenRecord.user_id,
action: 'password_reset',
displayText: `User ID ${tokenRecord.user_id} has reset their password.`,
icon: 'key',
},
reqLog,
);
return true;
}).catch((error) => {
// Re-throw known repository errors to allow for specific handling upstream.
if (error instanceof RepositoryError) {
throw error;
}
// For unknown errors, log them and wrap them in a generic DatabaseError.
const message = error instanceof Error ? error.message : 'An unknown error occurred.';
logger.error({ error }, `An unexpected error occurred during password update.`);
throw new DatabaseError(message);
});
}
async getUserByRefreshToken(refreshToken: string, reqLog: Logger) {
try {
const basicUser = await userRepo.findUserByRefreshToken(refreshToken, reqLog);
if (!basicUser) {
return null;
}
const userProfile = await userRepo.findUserProfileById(basicUser.user_id, reqLog);
return userProfile;
} catch (error) {
// Re-throw known repository errors to allow for specific handling upstream.
if (error instanceof RepositoryError) {
throw error;
}
// For unknown errors, log them and wrap them in a generic DatabaseError.
const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred.';
logger.error(
{ error, refreshToken },
'An unexpected error occurred while fetching user by refresh token.',
);
throw new DatabaseError(errorMessage);
}
}
async logout(refreshToken: string, reqLog: Logger) {
// The repository method `deleteRefreshToken` now includes robust error handling
// and logging via `handleDbError`. No need for a redundant try/catch block here.
// The original implementation also swallowed errors, which is now fixed.
await userRepo.deleteRefreshToken(refreshToken, reqLog);
}
async refreshAccessToken(
refreshToken: string,
reqLog: Logger,
): Promise<{ accessToken: string } | null> {
const user = await this.getUserByRefreshToken(refreshToken, reqLog);
if (!user) {
return null;
}
const { accessToken } = this.generateAuthTokens(user);
return { accessToken };
}
}
export const authService = new AuthService();
|