File size: 2,387 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { User } from "@prisma/client";
import { ErrorMessage, generateRandomName, processUsername } from "@reactive-resume/utils";
import { Profile, Strategy, StrategyOptions } from "passport-openidconnect";

import { UserService } from "@/server/user/user.service";

@Injectable()
export class OpenIDStrategy extends PassportStrategy(Strategy, "openid") {
  constructor(
    readonly authorizationURL: string,
    readonly callbackURL: string,
    readonly clientID: string,
    readonly clientSecret: string,
    readonly issuer: string,
    readonly scope: string,
    readonly tokenURL: string,
    readonly userInfoURL: string,
    private readonly userService: UserService,
  ) {
    super({
      authorizationURL,
      callbackURL,
      clientID,
      clientSecret,
      issuer,
      scope,
      tokenURL,
      userInfoURL,
    } as StrategyOptions);
  }

  async validate(
    _issuer: unknown,
    profile: Profile,
    done: (err?: string | Error | null, user?: Express.User, info?: unknown) => void,
  ) {
    const { displayName, emails, photos, username } = profile;

    const uniqueId = generateRandomName({ length: 2, style: "lowerCase", separator: "-" });
    const email = (emails?.[0].value ?? `${username ?? uniqueId}@openid.com`).toLocaleLowerCase();
    const picture = photos?.[0].value;

    let user: User | null = null;

    if (!email) throw new BadRequestException(ErrorMessage.InvalidCredentials);

    try {
      user =
        (await this.userService.findOneByIdentifier(email)) ??
        (username ? await this.userService.findOneByIdentifier(username) : null);

      if (!user) throw new BadRequestException(ErrorMessage.InvalidCredentials);

      done(null, user);
    } catch {
      try {
        user = await this.userService.create({
          email,
          picture,
          locale: "en-US",
          provider: "openid",
          name: displayName || uniqueId,
          emailVerified: true, // auto-verify emails
          username: processUsername(username ?? email.split("@")[0]),
          secrets: { create: {} },
        });

        done(null, user);
      } catch (error) {
        Logger.error(error);

        throw new BadRequestException(ErrorMessage.UserAlreadyExists);
      }
    }
  }
}