Files
Picsur/backend/src/routes/api/auth/auth.service.ts

55 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-02-21 14:53:21 +01:00
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
2022-02-25 12:22:00 +01:00
import { JwtDataDto } from 'imagur-shared/dist/dto/auth.dto';
import { EUser } from 'imagur-shared/dist/entities/user.entity';
2022-02-24 22:56:27 +01:00
import { AsyncFailable, HasFailed, Fail } from 'imagur-shared/dist/types';
import { UsersService } from '../../../collections/userdb/userdb.service';
2022-02-21 14:53:21 +01:00
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}
async createUser(username: string, password: string): AsyncFailable<EUser> {
2022-02-21 14:53:21 +01:00
const hashedPassword = await bcrypt.hash(password, 12);
2022-02-23 11:10:25 +01:00
return this.usersService.create(username, hashedPassword);
2022-02-21 14:53:21 +01:00
}
async deleteUser(user: string | EUser): AsyncFailable<EUser> {
2022-02-23 11:10:25 +01:00
return this.usersService.delete(user);
2022-02-21 14:53:21 +01:00
}
async listUsers(): AsyncFailable<EUser[]> {
return this.usersService.findAll();
2022-02-21 14:53:21 +01:00
}
async authenticate(username: string, password: string): AsyncFailable<EUser> {
const user = await this.usersService.findOne(username, true);
2022-02-21 22:17:44 +01:00
if (HasFailed(user)) return user;
2022-02-21 14:53:21 +01:00
2022-02-21 22:17:44 +01:00
if (!(await bcrypt.compare(password, user.password)))
return Fail('Wrong password');
2022-02-21 14:53:21 +01:00
return await this.usersService.findOne(username);
2022-02-21 14:53:21 +01:00
}
async createToken(user: EUser): Promise<string> {
2022-02-21 14:53:21 +01:00
const jwtData: JwtDataDto = {
user,
2022-02-21 14:53:21 +01:00
};
return this.jwtService.signAsync(jwtData);
}
async makeAdmin(user: string | EUser): AsyncFailable<true> {
2022-02-21 14:53:21 +01:00
return this.usersService.modifyAdmin(user, true);
}
async revokeAdmin(user: string | EUser): AsyncFailable<true> {
2022-02-21 14:53:21 +01:00
return this.usersService.modifyAdmin(user, false);
}
}