49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
private prisma: PrismaService,
|
|
private jwtService: JwtService,
|
|
) {}
|
|
|
|
async createAnonymousUser(name?: string) {
|
|
const user = await this.prisma.user.create({
|
|
data: { name: name || 'Гость' },
|
|
});
|
|
|
|
const token = this.jwtService.sign({ sub: user.id, type: 'anonymous' });
|
|
return { user, token };
|
|
}
|
|
|
|
async register(email: string, password: string, name: string) {
|
|
const user = await this.prisma.user.create({
|
|
data: {
|
|
email,
|
|
name,
|
|
},
|
|
});
|
|
|
|
const token = this.jwtService.sign({ sub: user.id, type: 'registered' });
|
|
return { user, token };
|
|
}
|
|
|
|
async login(email: string, password: string) {
|
|
const user = await this.prisma.user.findUnique({
|
|
where: { email },
|
|
});
|
|
|
|
if (!user) {
|
|
throw new Error('User not found');
|
|
}
|
|
|
|
const token = this.jwtService.sign({ sub: user.id, type: 'registered' });
|
|
return { user, token };
|
|
}
|
|
|
|
async validateUser(userId: string) {
|
|
return this.prisma.user.findUnique({ where: { id: userId } });
|
|
}
|
|
}
|