File size: 2,959 Bytes
7b850b7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import { Injectable, Inject } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
import { Model } from 'mongoose';
import { CommonServices } from '../shared/common.service';
var qs = require('qs');
@Injectable()
export class AuthService extends CommonServices {
constructor(
private readonly userService: UserService,
private jwtService: JwtService,
) {
super();
}
async login(user: any, body: any = {}) {
const payload = {
userId: user._id,
name: user.name,
email: user.email,
roles: user.roles,
};
return {
access_token: this.jwtService.sign(payload, {
secret: 'secretKey',
expiresIn: '60d',
}),
user: {
_id: user._id,
name: user.name,
email: user.email,
roles: user.roles,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
},
};
}
async validateUser(identifier: string, password: string): Promise<any> {
console.log(`IDENTIFIER =>`, identifier);
console.log(`password =>`, password);
const user = await this.userService.userRepository
.findOne({
$or: [{ email: identifier }, { username: identifier }],
})
.select('+password');
if (user && bcrypt.compareSync(password, user.password)) {
return user;
} else {
const userInLowerCase = await this.userService.userRepository
.findOne({
$or: [
{ email: identifier.toLowerCase() },
{ username: identifier.toLowerCase() },
],
})
.select('+password');
if (
userInLowerCase &&
bcrypt.compareSync(password, userInLowerCase.password)
) {
return userInLowerCase;
}
}
return null;
}
async validateByEmail(identifier: string): Promise<any> {
const user = await this.userService.userRepository.findOne({
$or: [{ email: identifier }, { username: identifier }],
});
if (user) {
const rUser = {
userId: user._id,
name: user.name,
username: user.username,
email: user.email,
roles: user.roles,
// iat: user.iat,
// exp: user.exp
};
return rUser;
} else {
const userInLowerCase = await this.userService.userRepository.findOne({
$or: [
{ email: identifier.toLowerCase() },
{ username: identifier.toLowerCase() },
],
});
if (userInLowerCase) {
const rUser = {
userId: userInLowerCase._id,
name: userInLowerCase.name,
username: user.username,
email: userInLowerCase.email,
roles: userInLowerCase.roles,
};
return rUser;
}
}
return null;
}
}
|