ToolJet/server/src/auth/auth.service.ts

38 lines
1,005 B
TypeScript
Raw Normal View History

2021-07-08 07:39:07 +00:00
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
2021-07-08 16:43:23 +00:00
import { User } from '../users/user.entity';
2021-07-08 07:39:07 +00:00
const bcrypt = require('bcrypt');
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService
) { }
async validateUser(email: string, password: string): Promise<User> {
const user = await this.usersService.findByEmail(email);
if(!user) return null;
const isVerified = await bcrypt.compare(password, user.password);
2021-07-08 07:39:07 +00:00
return isVerified ? user : null;
}
async login(params: any) {
const user = await this.validateUser(params.email, params.password);
if (user) {
const payload = { username: user.id, sub: user.email };
return {
access_token: this.jwtService.sign(payload),
};
} else {
throw new UnauthorizedException('Invalid credentials');
}
}
}