75 lines
2.1 KiB
TypeScript
75 lines
2.1 KiB
TypeScript
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { UsersService } from '../users/users.service';
|
|
import * as bcrypt from 'bcryptjs';
|
|
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
private readonly usersService: UsersService,
|
|
private readonly jwtService: JwtService,
|
|
) {}
|
|
|
|
async register(username: string, password: string, name: string, email: string, roleId: string) {
|
|
// 检查用户名是否已存在
|
|
const existingUser = await this.usersService.findByUsername(username);
|
|
if (existingUser) {
|
|
throw new Error('Username already exists');
|
|
}
|
|
|
|
// 检查邮箱是否已存在
|
|
const existingEmail = await this.usersService.findByEmail(email);
|
|
if (existingEmail) {
|
|
throw new Error('Email already exists');
|
|
}
|
|
|
|
// 哈希密码
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
|
|
// 创建用户
|
|
const user = await this.usersService.create({
|
|
username,
|
|
password: hashedPassword,
|
|
name,
|
|
email,
|
|
roleId,
|
|
});
|
|
|
|
return user;
|
|
}
|
|
|
|
async login(username: string, password: string) {
|
|
// 查找用户
|
|
console.log('Login attempt for user:', username);
|
|
const user = await this.usersService.findByUsername(username);
|
|
console.log('Found user:', user);
|
|
if (!user) {
|
|
throw new UnauthorizedException('Invalid credentials');
|
|
}
|
|
|
|
// 验证密码
|
|
const isPasswordValid = await bcrypt.compare(password, user.password);
|
|
console.log('Password valid:', isPasswordValid);
|
|
if (!isPasswordValid) {
|
|
throw new UnauthorizedException('Invalid credentials');
|
|
}
|
|
|
|
// 生成JWT token
|
|
const payload = { sub: user.id, username: user.username, role: user.role.name };
|
|
const token = this.jwtService.sign(payload);
|
|
|
|
const response = {
|
|
access_token: token,
|
|
user: {
|
|
id: user.id,
|
|
username: user.username,
|
|
name: user.name,
|
|
email: user.email,
|
|
role: user.role.name,
|
|
},
|
|
};
|
|
console.log('Login response:', response);
|
|
return response;
|
|
}
|
|
}
|