Skip to content

Commit

Permalink
fix: lbac 1490: remplissage du granted by lors de la création (#1207)
Browse files Browse the repository at this point in the history
* fix: lbac 1490: review leo

* fix: enrichissement des grantedby

* fix: grantedBy lors de la creation

* fix: refactor user controller
  • Loading branch information
remy-auricoste authored Apr 25, 2024
1 parent d255bd0 commit 8005bf0
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 24 deletions.
18 changes: 9 additions & 9 deletions server/src/http/controllers/etablissementRecruteur.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,6 @@ import config from "@/config"
import { user2ToUserForToken } from "@/security/accessTokenService"
import { getUserFromRequest } from "@/security/authenticationService"
import { generateDepotSimplifieToken } from "@/services/appLinks.service"
import { getPublicUserRecruteurPropsOrError } from "@/services/roleManagement.service"
import { getUser2ByEmail, validateUser2Email } from "@/services/user2.service"

import { getAllDomainsFromEmailList, getEmailDomain, isEmailFromPrivateCompany, isUserMailExistInReferentiel } from "../../common/utils/mailUtils"
import { notifyToSlack } from "../../common/utils/slackUtils"
import { getNearEtablissementsFromRomes } from "../../services/catalogue.service"
import { CFA, ENTREPRISE } from "../../services/constant.service"
import {
entrepriseOnboardingWorkflow,
etablissementUnsubscribeDemandeDelegation,
Expand All @@ -26,7 +19,9 @@ import {
getOrganismeDeFormationDataFromSiret,
sendUserConfirmationEmail,
validateCreationEntrepriseFromCfa,
} from "../../services/etablissement.service"
} from "@/services/etablissement.service"
import { getPublicUserRecruteurPropsOrError } from "@/services/roleManagement.service"
import { getUser2ByEmail, validateUser2Email } from "@/services/user2.service"
import {
autoValidateUser,
createOrganizationUser,
Expand All @@ -36,7 +31,12 @@ import {
setUserHasToBeManuallyValidated,
updateLastConnectionDate,
updateUser2Fields,
} from "../../services/userRecruteur.service"
} from "@/services/userRecruteur.service"

import { getAllDomainsFromEmailList, getEmailDomain, isEmailFromPrivateCompany, isUserMailExistInReferentiel } from "../../common/utils/mailUtils"
import { notifyToSlack } from "../../common/utils/slackUtils"
import { getNearEtablissementsFromRomes } from "../../services/catalogue.service"
import { CFA, ENTREPRISE } from "../../services/constant.service"
import { Server } from "../server"

export default (server: Server) => {
Expand Down
14 changes: 10 additions & 4 deletions server/src/http/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,12 @@ export default (server: Server) => {
},
async (req, res) => {
const { origin, ...userFields } = req.body
const user = await createAdminUser(userFields, "création par l'interface admin", origin ?? "")
const userFromRequest = getUserFromRequest(req, zRoutes.post["/admin/users"]).value
const user = await createAdminUser(userFields, {
origin: origin ?? "",
reason: "création par l'interface admin",
grantedBy: userFromRequest._id.toString(),
})
return res.status(200).send({ _id: user._id })
}
)
Expand Down Expand Up @@ -271,10 +276,11 @@ export default (server: Server) => {
const user = await User2.findOne({ _id: userId }).lean()
if (!user) throw Boom.badRequest()

const mainRole = await RoleManagement.findOne({ user_id: userId }).lean()
if (!mainRole) {
throw Boom.internal(`inattendu : aucun role trouvé pour user id=${userId}`)
const roles = await RoleManagement.find({ user_id: userId }).lean()
if (roles.length !== 1) {
throw Boom.internal(`inattendu : attendu 1 role, ${roles.length} roles trouvés pour user id=${userId}`)
}
const [mainRole] = roles
const updatedRole = await modifyPermissionToUser(
{
user_id: userId,
Expand Down
1 change: 1 addition & 0 deletions server/src/jobs/lba_recruteur/formulaire/createUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export const createUserFromCLI = async (
type: Type,
is_email_checked: Email_valide,
},
"CLI",
{
reason: "created from CLI",
status: AccessStatus.GRANTED,
Expand Down
2 changes: 1 addition & 1 deletion server/src/services/etablissement.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ export const etablissementUnsubscribeDemandeDelegation = async (etablissementSir

export const autoValidateUserRoleOnCompany = async (userAndEntreprise: UserAndOrganization, origin: string) => {
const { isValid: validated, validator } = await isCompanyValid(userAndEntreprise)
const reason = `validation auto : ${validator}`
const reason = `demande de validation à : ${validator}`
if (validated) {
await authorizeUserOnEntreprise(userAndEntreprise, origin, reason)
} else {
Expand Down
14 changes: 12 additions & 2 deletions server/src/services/user2.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,41 @@ import { VALIDATION_UTILISATEUR } from "shared/constants/recruteur"
import { IUser2, IUserStatusEvent, UserEventType } from "shared/models/user2.model"

import { User2 } from "@/common/model"
import { ObjectId } from "@/common/mongodb"

import { isUserEmailChecked } from "./userRecruteur.service"

export const createUser2IfNotExist = async (userProps: Omit<IUser2, "_id" | "createdAt" | "updatedAt" | "status">, is_email_checked: boolean): Promise<IUser2> => {
export const createUser2IfNotExist = async (
userProps: Omit<IUser2, "_id" | "createdAt" | "updatedAt" | "status">,
is_email_checked: boolean,
grantedBy: string
): Promise<IUser2> => {
const { first_name, last_name, last_action_date, origin, phone } = userProps
const formatedEmail = userProps.email.toLocaleLowerCase()

let user = await User2.findOne({ email: formatedEmail }).lean()
if (!user) {
const id = new ObjectId()
grantedBy = grantedBy || id.toString()
const status: IUserStatusEvent[] = []
if (is_email_checked) {
status.push({
date: new Date(),
reason: "validation de l'email à la création",
status: UserEventType.VALIDATION_EMAIL,
validation_type: VALIDATION_UTILISATEUR.MANUAL,
granted_by: grantedBy,
})
}
status.push({
date: new Date(),
reason: "creation de l'utilisateur",
status: UserEventType.ACTIF,
validation_type: VALIDATION_UTILISATEUR.MANUAL,
granted_by: grantedBy,
})
const userFields: Omit<IUser2, "_id" | "createdAt" | "updatedAt"> = {
const userFields: Omit<IUser2, "createdAt" | "updatedAt"> = {
_id: id,
email: formatedEmail,
first_name,
last_name,
Expand Down
24 changes: 16 additions & 8 deletions server/src/services/userRecruteur.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ const getUserRecruteurByUser2Query = async (user2query: Partial<IUser2>): Promis
*/
export const createOrganizationUser = async (
userRecruteurProps: Omit<IUserRecruteur, "_id" | "createdAt" | "updatedAt" | "status" | "scope">,
grantedBy?: string,
statusEvent?: Pick<IRoleManagementEvent, "reason" | "validation_type" | "granted_by" | "status">
): Promise<UserAndOrganization> => {
const { type, origin, first_name, last_name, last_connection, email, is_email_checked, phone } = userRecruteurProps
Expand All @@ -173,7 +174,8 @@ export const createOrganizationUser = async (
phone: phone ?? "",
last_action_date: last_connection,
},
is_email_checked
is_email_checked,
grantedBy ?? ""
)
const organization = await createOrganizationIfNotExist(userRecruteurProps)
if (statusEvent) {
Expand All @@ -193,13 +195,14 @@ export const createOrganizationUser = async (
}
}

export const createOpcoUser = async (userProps: Pick<IUser2, "email" | "first_name" | "last_name" | "phone">, opco: OPCOS) => {
export const createOpcoUser = async (userProps: Pick<IUser2, "email" | "first_name" | "last_name" | "phone">, opco: OPCOS, grantedBy: string) => {
const user = await createUser2IfNotExist(
{
...userProps,
last_action_date: new Date(),
},
false
false,
grantedBy
)
await modifyPermissionToUser(
{
Expand All @@ -217,13 +220,17 @@ export const createOpcoUser = async (userProps: Pick<IUser2, "email" | "first_na
return user
}

export const createAdminUser = async (userProps: Pick<IUser2, "email" | "first_name" | "last_name" | "phone">, reason: string = "", origin: string = "") => {
export const createAdminUser = async (
userProps: Pick<IUser2, "email" | "first_name" | "last_name" | "phone">,
{ grantedBy, origin = "", reason = "" }: { reason?: string; origin?: string; grantedBy: string }
) => {
const user = await createUser2IfNotExist(
{
...userProps,
last_action_date: new Date(),
},
false
false,
grantedBy
)
await modifyPermissionToUser(
{
Expand All @@ -246,6 +253,7 @@ export const createAdminUser = async (userProps: Pick<IUser2, "email" | "first_n
*/
export const createUser = async (
userProps: Omit<IUserRecruteur, "_id" | "createdAt" | "updatedAt" | "status">,
grantedBy: string,
statusEvent?: Pick<IRoleManagementEvent, "reason" | "validation_type" | "granted_by" | "status">
): Promise<IUser2> => {
const { first_name, last_name, email, phone, type, opco } = userProps
Expand All @@ -257,13 +265,13 @@ export const createUser = async (
}

if (type === ENTREPRISE || type === CFA) {
const { user } = await createOrganizationUser(userProps, statusEvent)
const { user } = await createOrganizationUser(userProps, grantedBy, statusEvent)
return user
} else if (type === ADMIN) {
const user = await createAdminUser(userFields)
const user = await createAdminUser(userFields, { grantedBy })
return user
} else if (type === OPCO) {
const user = await createOpcoUser(userFields, parseEnumOrError(OPCOS, opco ?? null))
const user = await createOpcoUser(userFields, parseEnumOrError(OPCOS, opco ?? null), grantedBy)
return user
} else {
assertUnreachable(type)
Expand Down

0 comments on commit 8005bf0

Please sign in to comment.