Spaces:
Sleeping
Sleeping
File size: 4,997 Bytes
b0798af | 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 | 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');
}
}
|