Spaces:
Paused
Paused
Download apps/prevision-api/src/users/users.service.ts from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/prevision-api/src/users/users.service.ts
- Command line
-
hf download hf://spaces/modventures/prevision/apps/prevision-api/src/users/users.service.ts
-
curl -L -o users.service.ts https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/prevision-api/src/users/users.service.ts
2.24 kB
| import { Injectable } from '@nestjs/common'; | |
| import { ClerkService } from '../clerk/clerk.service.js'; | |
| import { AppException } from '../common/exceptions/app.exception.js'; | |
| import { Prisma, type User, type UserRole } from '../generated/prisma/client.js'; | |
| import { PrismaService } from '../prisma/prisma.service.js'; | |
| () | |
| export class UsersService { | |
| constructor( | |
| private readonly prisma: PrismaService, | |
| private readonly clerk: ClerkService, | |
| ) {} | |
| /** | |
| * The account behind a Clerk user, created on first sign-in. Matched by Clerk id, | |
| * then by verified email, so a recreated Clerk account keeps its account and usage. | |
| */ | |
| async findOrCreateFromClerk(clerkUserId: string): Promise<User> { | |
| const existing = await this.prisma.db.user.findUnique({ where: { clerkUserId } }); | |
| if (existing) return existing; | |
| const { email, name } = await this.clerk.getVerifiedProfile(clerkUserId); | |
| try { | |
| return await this.prisma.db.$transaction(async (tx) => { | |
| const byEmail = await tx.user.findUnique({ where: { email } }); | |
| if (byEmail) return tx.user.update({ where: { id: byEmail.id }, data: { clerkUserId, name: byEmail.name ?? name } }); | |
| if (await tx.user.count({ where: { email, deletedAt: { not: null } } })) { | |
| throw new AppException(403, 'ACCOUNT_DISABLED', 'This account has been closed. Please contact us.'); | |
| } | |
| return tx.user.create({ data: { clerkUserId, email, name } }); | |
| }); | |
| } catch (error) { | |
| const raced = error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002'; | |
| const winner = raced ? await this.prisma.db.user.findUnique({ where: { clerkUserId } }) : null; | |
| if (winner) return winner; | |
| throw error; | |
| } | |
| } | |
| /** Accounts are created by signing in; this only changes the role of an existing one. */ | |
| async setRole(email: string, role: UserRole): Promise<User> { | |
| const user = await this.prisma.db.user.findUnique({ where: { email: email.trim().toLowerCase() } }); | |
| if (!user) throw new AppException(404, 'USER_NOT_FOUND', `No account for ${email}. Sign in to Prevision once first.`); | |
| return this.prisma.db.user.update({ where: { id: user.id }, data: { role } }); | |
| } | |
| } | |