backend: Refactor AuthService and TokenService to use User object for authentication and token generation

This commit is contained in:
juancarmore 2025-03-21 00:54:16 +01:00
parent 5e1e418c13
commit a9274005ef
2 changed files with 27 additions and 11 deletions

View File

@ -1,17 +1,32 @@
import { MEET_ADMIN_SECRET, MEET_ADMIN_USER, MEET_PRIVATE_ACCESS, MEET_SECRET, MEET_USER } from '../environment.js';
import { injectable } from '../config/dependency-injector.config.js';
import { inject, injectable } from '../config/dependency-injector.config.js';
import { User } from '@typings-ce';
import { UserService } from './user.service.js';
@injectable()
export class AuthService {
authenticateAdmin(username: string, password: string): boolean {
constructor(@inject(UserService) protected userService: UserService) {}
authenticate(username: string, password: string): User | null {
const isAdmin = this.authenticateAdmin(username, password);
const isUser = this.authenticateUser(username, password);
if (isAdmin || isUser) {
return this.userService.getUser(username);
}
return null;
}
private authenticateAdmin(username: string, password: string): boolean {
return username === MEET_ADMIN_USER && password === MEET_ADMIN_SECRET;
}
authenticateUser(username: string, password: string): boolean {
private authenticateUser(username: string, password: string): boolean {
if (MEET_PRIVATE_ACCESS === 'true') {
return username === MEET_USER && password === MEET_SECRET;
}
return true;
return false;
}
}

View File

@ -6,23 +6,24 @@ import {
} from '../environment.js';
import { injectable } from '../config/dependency-injector.config.js';
import { AccessToken, AccessTokenOptions, ClaimGrants, TokenVerifier } from 'livekit-server-sdk';
import { User } from '@typings-ce';
@injectable()
export class TokenService {
async generateAccessToken(username: string): Promise<string> {
return await this.generateJwtToken(username, MEET_ACCESS_TOKEN_EXPIRATION);
async generateAccessToken(user: User): Promise<string> {
return await this.generateJwtToken(user, MEET_ACCESS_TOKEN_EXPIRATION);
}
async generateRefreshToken(username: string): Promise<string> {
return await this.generateJwtToken(username, MEET_REFRESH_TOKEN_EXPIRATION);
async generateRefreshToken(user: User): Promise<string> {
return await this.generateJwtToken(user, MEET_REFRESH_TOKEN_EXPIRATION);
}
private async generateJwtToken(username: string, expiration: string): Promise<string> {
private async generateJwtToken(user: User, expiration: string): Promise<string> {
const options: AccessTokenOptions = {
identity: username,
identity: user.username,
ttl: expiration,
metadata: JSON.stringify({
role: 'admin'
role: user.role
})
};
const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, options);