Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions backend/src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,39 +79,38 @@ export class AuthService {
return result;
}

private hashToken(raw: string): string {
return crypto.createHash('sha256').update(raw).digest('hex');
}

async generateRefreshToken(userId: number): Promise<string> {
// Generate a random token
const token = crypto.randomBytes(32).toString('hex');
const raw = crypto.randomBytes(32).toString('hex');

// Calculate expiry (7 days from now)
const expiresAt = new Date();
expiresAt.setDate(expiresAt.getDate() + 7);

// Save to database
await this.refreshTokenRepository.save({
token,
token: this.hashToken(raw),
userId,
expiresAt,
revoked: false,
});

return token;
return raw;
}

async refreshAccessToken(
refreshToken: string,
): Promise<{ access_token: string; refresh_token: string }> {
// Find the refresh token
const storedToken = await this.refreshTokenRepository.findOne({
where: { token: refreshToken },
where: { token: this.hashToken(refreshToken) },
relations: ['user'],
});

if (!storedToken) {
throw new UnauthorizedException('Invalid refresh token');
}

// Check if token is expired or revoked
if (storedToken.revoked || new Date() > storedToken.expiresAt) {
throw new UnauthorizedException('Refresh token expired or revoked');
}
Expand All @@ -121,7 +120,6 @@ export class AuthService {
revoked: true,
});

// Generate new tokens
const payload = {
username: storedToken.user.username,
sub: storedToken.user.id,
Expand All @@ -138,7 +136,10 @@ export class AuthService {
}

async revokeRefreshToken(token: string): Promise<void> {
await this.refreshTokenRepository.update({ token }, { revoked: true });
await this.refreshTokenRepository.update(
{ token: this.hashToken(token) },
{ revoked: true },
);
}

async requestPasswordReset(email: string): Promise<{ message: string }> {
Expand Down
Loading