File

src/iam/user/user.service.ts

Index

Properties
Methods

Constructor

constructor(prismaService: PrismaService, identityProvider: KeycloakProvider)
Parameters :
Name Type Optional
prismaService PrismaService No
identityProvider KeycloakProvider No

Methods

checkOrCreateUser
checkOrCreateUser(userId)

create entry for user in Turo database if doesnot exist

Parameters :
Name Optional Description
userId No

eg: test@me.com

Returns : Promise<User>

void

formatUser
formatUser(user: any)

Function to format user object comming from IDP

Parameters :
Name Type Optional
user any No
Returns : User
getTuroWidePermissions
getTuroWidePermissions(user)

check user permissions on header and retrun turowide permissions

Parameters :
Name Optional
user No

turo wide permissions

getUserDetails
getUserDetails(email: string)

Function to get user details using email ID directly from IDP provider

Parameters :
Name Type Optional
email string No
Returns : Promise<User>

user detais object

Async getUserPreferences
getUserPreferences(userId: string)

Function to get user preferences from userId

Parameters :
Name Type Optional Description
userId string No

: this is expected to be email always

Returns : Promise<UserPreference[]>

user preferences or throw error if not found

Async updateUserPreference
updateUserPreference(userId: string, preferenceKey: UserPreferenceKeys, preference: PreferenceValue)
Parameters :
Name Type Optional
userId string No
preferenceKey UserPreferenceKeys No
preference PreferenceValue No
Returns : Promise<UserPreference>
users
users(searchString: string)

Function to get user from configured identity provider based on search string - email specifically

Parameters :
Name Type Optional
searchString string No
Returns : Promise<User[]>

Properties

Private IDP_ALIAS
Type : string
Default value : "turo"

IDP_ALIAS used to fetch users only comming from identity provider and ignoring internal service account users

import { PrismaService } from "../../common/prisma/prisma.service";
import { Injectable } from "@nestjs/common";
import { User } from "./entity/user.entity";
import { KeycloakProvider } from "../../providers/keycloak/keycloak.provider";
import {
  UserPreference,
  UserPreferenceKeys,
} from "./entity/user.preference.entity";
import { PreferenceValue } from "./user.preference.type";
import { getNamesFromEmail } from "../../common/helper";

@Injectable()
export class UserService {
  /**
   * IDP_ALIAS used to fetch users only comming from identity provider
   * and ignoring internal service account users
   */
  private IDP_ALIAS = "turo";

  constructor(
    private readonly prismaService: PrismaService,
    private readonly identityProvider: KeycloakProvider,
  ) {}

  /**
   * create entry for user in Turo database if doesnot exist
   * @param userId eg: test@me.com
   * @returns void
   */
  checkOrCreateUser(userId): Promise<User> {
    const _userId = userId.toLowerCase();
    return this.prismaService.user.upsert({
      where: {
        id: _userId,
      },
      create: {
        id: _userId,
      },
      update: {},
    });
  }

  /**
   * Function to get user from configured identity provider
   * based on search string - email specifically
   * @param searchString
   * @returns
   */
  users(searchString: string): Promise<User[]> {
    return this.identityProvider
      .searchUser(searchString, this.IDP_ALIAS)
      .then((users) => {
        return users.map((user) => this.formatUser(user));
      });
  }

  /**
   * Function to get user details using email ID
   * directly from IDP provider
   * @param email
   * @returns user detais object
   */
  getUserDetails(email: string): Promise<User> {
    const _email = email.toLowerCase();
    return this.identityProvider
      .searchUser(_email, this.IDP_ALIAS)
      .then((users) => {
        if (users.length == 1) {
          return this.formatUser(users[0]);
        }
        // if user details not found
        const names = getNamesFromEmail(_email);
        return this.formatUser({
          email: _email,
          firstName: names.split(" ")[0].trim(),
          lastName: names.split(" ")[1] ? names.split(" ")[1].trim() : "",
        });
      });
  }

  /**
   * Function to format user object comming from IDP
   *
   * @param user
   * @returns
   */
  formatUser(user: any): User {
    return {
      id: user["email"],
      name: `${user["firstName"]} ${user["lastName"]}`,
      initials: `${user["firstName"].charAt(0).toUpperCase()}${user["lastName"].charAt(0).toUpperCase()}`,
      pictureURL: null,
      email: user["email"],
    };
  }

  /**
   * check user permissions on header and
   * retrun turowide permissions
   * @param user
   * @returns turo wide permissions
   */
  getTuroWidePermissions(user) {
    const permission = user.permission;
    let isTuroAdmin = false;
    let canCreateProject = false;
    if (permission["0"] && permission["0"]["*"] && permission["0"]["*"]["*"]) {
      isTuroAdmin = true;
    }

    if (
      permission["0"] &&
      permission["0"]["turo:project"] &&
      (permission["0"]["turo:project"]["project:CreateProject"] ||
        permission["0"]["turo:project"]["*"])
    ) {
      canCreateProject = true;
    }

    return {
      createProject: canCreateProject || isTuroAdmin,
    };
  }

  /**
   * Function to get user preferences from userId
   * @param userId : this is expected to be email always
   * @returns user preferences or throw error if not found
   */
  async getUserPreferences(userId: string): Promise<UserPreference[]> {
    const userPreferences = await this.prismaService.userPreference.findMany({
      where: {
        user: {
          id: userId,
        },
      },
    });

    return userPreferences.map(
      (userPreference) => new UserPreference(userPreference),
    );
  }

  async updateUserPreference(
    userId: string,
    preferenceKey: UserPreferenceKeys,
    preference: PreferenceValue,
  ): Promise<UserPreference> {
    const userPreference = await this.prismaService.userPreference.upsert({
      where: {
        userPreferenceIdentifier: {
          userId: userId,
          preferenceKey: preferenceKey,
        },
      },
      create: {
        preferenceKey: preferenceKey,
        preferenceValue: preference,
        user: {
          connect: {
            id: userId,
          },
        },
      },
      update: {
        preferenceValue: preference,
      },
    });

    return new UserPreference(userPreference);
  }
}

results matching ""

    No results matching ""