File size: 2,238 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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';

@Injectable()
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 } });
  }
}