Chat / backend /src /modules /auth /auth.service.ts
kishankrish19's picture
Deploy Stillwave fullstack clean
b0798af
Raw History Blame Contribute Delete
5 kB
import {
Injectable,
ConflictException,
UnauthorizedException,
NotFoundException,
ServiceUnavailableException,
BadRequestException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { randomUUID, createHash } from 'node:crypto';
import * as bcrypt from 'bcrypt';
import { Store } from '../../core/store';
export interface UserAccount {
id: string;
email: string;
username: string;
display_name: string;
account_type: 'listener' | 'admin';
password_hash: string;
created_at: string;
bio?: string;
country?: string;
avatar_url?: string;
}
const digest = (value: string) =>
createHash('sha256').update(value).digest('hex');
@Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,
private readonly store: Store,
) {}
publicUser(user: UserAccount) {
const { password_hash, ...profile } = user;
return profile;
}
async signup(dto: {
email: string;
password: string;
username: string;
display_name: string;
}) {
const email = dto.email.trim().toLowerCase(),
username = dto.username.trim().toLowerCase();
if (!/^[a-z0-9_.-]{3,30}$/.test(username) || !dto.display_name.trim())
throw new BadRequestException(
'Use a name and a username with 3–30 letters, numbers, dots, underscores or hyphens',
);
if (Buffer.byteLength(dto.password, 'utf8') > 72)
throw new BadRequestException('Password must fit within 72 UTF-8 bytes');
const password_hash = await bcrypt.hash(dto.password, 12);
const user = this.store.transaction(() => {
const users = this.store.list<UserAccount>('users');
if (users.some((u) => u.email === email || u.username === username))
throw new ConflictException('Email or username is already registered');
return this.store.put<UserAccount>('users', {
id: randomUUID(),
email,
username,
display_name: dto.display_name.trim(),
password_hash,
account_type:
users.length === 0 &&
(process.env.NODE_ENV !== 'production' ||
process.env.FIRST_USER_ADMIN !== 'false')
? 'admin'
: 'listener',
created_at: new Date().toISOString(),
});
});
return { user: this.publicUser(user), ...this.createSession(user) };
}
async login(dto: { email: string; password: string }) {
const user = this.store
.list<UserAccount>('users')
.find((u) => u.email === dto.email.trim().toLowerCase());
if (!user || !(await bcrypt.compare(dto.password, user.password_hash)))
throw new UnauthorizedException('Email or password is incorrect');
return { user: this.publicUser(user), ...this.createSession(user) };
}
private createSession(user: UserAccount, sessionId = randomUUID()) {
const payload = { sub: user.id, sid: sessionId };
const access_token = this.jwtService.sign(
{ ...payload, type: 'access' },
{ expiresIn: '15m' },
);
const refresh_token = this.jwtService.sign(
{ ...payload, type: 'refresh', jti: randomUUID() },
{ expiresIn: '7d' },
);
this.store.put(
'sessions',
{
id: sessionId,
user_id: user.id,
hash: digest(refresh_token),
expires: Date.now() + 7 * 86400000,
},
user.id,
);
return {
access_token,
refresh_token,
token_type: 'Bearer',
expires_in: 900,
};
}
async refreshToken(token: string) {
try {
const payload = this.jwtService.verify(token);
const session = this.store.get('sessions', payload.sid);
const user = this.store.get<UserAccount>('users', payload.sub);
if (
payload.type !== 'refresh' ||
!session ||
!user ||
session.hash !== digest(token) ||
session.expires < Date.now()
)
throw new Error();
return this.createSession(user, session.id);
} catch {
throw new UnauthorizedException(
'Your session has expired. Please sign in again.',
);
}
}
async logout(userId: string, sessionId?: string) {
if (sessionId) this.store.remove('sessions', sessionId);
else
this.store
.list('sessions', userId)
.forEach((s) => this.store.remove('sessions', s.id));
return { success: true };
}
async getMe(userId: string) {
const user = this.store.get<UserAccount>('users', userId);
if (!user) throw new NotFoundException('Account not found');
return this.publicUser(user);
}
async forgotPassword(_email: string) {
throw new ServiceUnavailableException(
'Email recovery is not configured. Contact the server administrator.',
);
}
async resetPassword(_token: string, _password: string) {
throw new ServiceUnavailableException('Email recovery is not configured');
}
async getOAuthUrl(_provider: string) {
throw new ServiceUnavailableException('Social sign-in is not configured');
}
}