Много

This commit is contained in:
2024-09-12 00:39:01 +04:00
parent 6b07bd89b8
commit 8fb9214246
24 changed files with 643 additions and 194 deletions

View File

@@ -1,22 +1,24 @@
import {
ConflictException,
Injectable,
NotAcceptableException,
NotFoundException,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import {
SignInDto,
SignInResultDto,
SignUpDto,
SignUpResultDto,
SignInReqDto,
SignInResDto,
SignUpReqDto,
SignUpResDto,
UpdateTokenDto,
UpdateTokenResultDto,
} from "../dto/auth.dto";
import { UsersService } from "../users/users.service";
import { genSalt, hash } from "bcrypt";
import { Prisma } from "@prisma/client";
import { Prisma, UserRole } from "@prisma/client";
import { Types } from "mongoose";
import { UserDto, UserRoleDto } from "../dto/user.dto";
@Injectable()
export class AuthService {
@@ -25,16 +27,34 @@ export class AuthService {
private readonly jwtService: JwtService,
) {}
async signUp(signUpDto: SignUpDto): Promise<SignUpResultDto> {
if (await this.usersService.contains({ username: signUpDto.username }))
async decodeUserToken(token: string): Promise<UserDto | null> {
const jwtUser: { id: string } =
await this.jwtService.verifyAsync(token);
return this.usersService
.findUnique({ id: jwtUser.id })
.then((user) => user as UserDto | null);
}
async signUp(signUpDto: SignUpReqDto): Promise<SignUpResDto> {
if (
![UserRoleDto.STUDENT, UserRoleDto.TEACHER].includes(signUpDto.role)
) {
throw new NotAcceptableException("Передана неизвестная роль");
}
if (
await this.usersService.contains({ username: signUpDto.username })
) {
throw new ConflictException(
"Пользователь с таким именем уже существует!",
);
}
const salt = await genSalt(8);
const id = new Types.ObjectId().toString("hex");
const input: Prisma.userCreateInput = {
const input: Prisma.UserCreateInput = {
id: id,
username: signUpDto.username,
salt: salt,
@@ -42,6 +62,8 @@ export class AuthService {
accessToken: await this.jwtService.signAsync({
id: id,
}),
role: signUpDto.role as UserRole,
group: signUpDto.group,
};
return this.usersService.create(input).then((user) => {
@@ -52,7 +74,7 @@ export class AuthService {
});
}
async signIn(signInDto: SignInDto): Promise<SignInResultDto> {
async signIn(signInDto: SignInReqDto): Promise<SignInResDto> {
const user = await this.usersService.findUnique({
username: signInDto.username,
});