File

apps/recallassess/recallassess-api/src/config/auth-config.service.ts

Index

Methods

Constructor

constructor(authService: BNestAuthService, userService: BNestUserService, prisma: BNestPrismaService, dbUtilService: BNestDbUtilService)
Parameters :
Name Type Optional
authService BNestAuthService No
userService BNestUserService No
prisma BNestPrismaService No
dbUtilService BNestDbUtilService No

Methods

onModuleInit
onModuleInit()
Returns : void
import { BNestUserService } from "@bish-nest/core";
import { AuthCallbacks, BNestAuthService } from "@bish-nest/core/auth";
import { BNestDbUtilService, BNestPrismaService } from "@bish-nest/core/services";
import { Injectable, OnModuleInit } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import * as argon from "argon2";

@Injectable()
export class AuthConfigService implements OnModuleInit {
  constructor(
    private authService: BNestAuthService,
    private userService: BNestUserService,
    private prisma: BNestPrismaService,
    private dbUtilService: BNestDbUtilService,
  ) {}

  onModuleInit() {
    const callbacks: AuthCallbacks = {
      getUserByEmail: async (email: string) => {
        return await this.userService.findByEmail(email);
      },
      createUser: async (userData: Record<string, unknown>) => {
        const data = await this.dbUtilService.addCreatedBy(userData);
        // Remove password field as it's not in the Prisma schema (only hash is valid)
        const { password, ...dataWithoutPassword } = data as any;
        try {
          const createdUser = await this.prisma.client.user.create({
            data: dataWithoutPassword,
          });
          return createdUser;
        } catch (error) {
          if (error instanceof Prisma.PrismaClientKnownRequestError) {
            if (error.code === "P2002") {
              throw new Error("Credentials taken");
            }
          }
          throw error;
        }
      },
      validateUser: async (email: string, password: string) => {
        const user = await this.userService.findByEmail(email);
        if (user) {
          const pwMatches = await argon.verify((user as any).hash, password); // eslint-disable-line @typescript-eslint/no-explicit-any
          if (pwMatches) {
            return user;
          }
        }
        return null;
      },
      onSignInSuccess: async (user: Record<string, unknown>) => {
        // Add any custom logic here after successful sign in
        // For example: logging, analytics, etc.
        console.log(`User ${(user as any).email} signed in successfully`); // eslint-disable-line @typescript-eslint/no-explicit-any
        return user;
      },
    };

    this.authService.setCallbacks(callbacks);
  }
}

results matching ""

    No results matching ""