feat: init auth service (#2180)

This commit is contained in:
Himself65
2023-04-27 22:49:44 -05:00
committed by GitHub
parent b4bb57b2a5
commit 3a5a66a5a3
11 changed files with 303 additions and 22 deletions

View File

@@ -4,6 +4,7 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { User } from '@prisma/client';
import { compare, hash } from 'bcrypt';
import jwt from 'jsonwebtoken';
import { Config } from '../../config';
@@ -16,30 +17,76 @@ export class AuthService {
constructor(private config: Config, private prisma: PrismaService) {}
sign(user: UserClaim) {
return jwt.sign(user, this.config.secret);
return jwt.sign(user, this.config.auth.privateKey, {
algorithm: 'ES256',
subject: user.id,
issuer: this.config.serverId,
expiresIn: this.config.auth.accessTokenExpiresIn,
});
}
refresh(user: UserClaim) {
return jwt.sign(user, this.config.auth.privateKey, {
algorithm: 'ES256',
subject: user.id,
issuer: this.config.serverId,
expiresIn: this.config.auth.refreshTokenExpiresIn,
});
}
verify(token: string) {
try {
const claims = jwt.verify(token, this.config.secret) as UserClaim;
return claims;
return jwt.verify(token, this.config.auth.publicKey, {
algorithms: ['ES256'],
}) as UserClaim;
} catch (e) {
throw new UnauthorizedException('Invalid token');
}
}
async signIn(email: string, password: string) {
async signIn(email: string, password: string): Promise<User> {
const user = await this.prisma.user.findFirst({
where: {
email,
password,
},
});
if (!user) {
throw new BadRequestException('Invalid email or password');
throw new BadRequestException('Invalid email');
}
if (!user.password) {
throw new BadRequestException('User has no password');
}
const equal = await compare(password, user.password);
if (!equal) {
throw new UnauthorizedException('Invalid password');
}
return user;
}
async register(name: string, email: string, password: string): Promise<User> {
const hashedPassword = await hash(password, this.config.auth.salt);
const user = await this.prisma.user.findFirst({
where: {
email,
},
});
if (user) {
throw new BadRequestException('Email already exists');
}
return this.prisma.user.create({
data: {
name,
email,
password: hashedPassword,
},
});
}
}