🔃 SSO users sync api (#60)

This commit is contained in:
Montassar Ghanmy
2023-05-26 10:58:29 +01:00
committed by GitHub
parent 42e0260296
commit 02ccb279f7
2 changed files with 59 additions and 0 deletions
@@ -8,6 +8,7 @@ import {
RealtimeBaseBusEvent,
} from "../../../../core/platform/services/realtime/types";
import { ResourceGetResponse } from "../../../../utils/types";
import { getInstance } from "../../../user/entities/user";
import {
ApplicationObject,
getApplicationObject,
@@ -163,6 +164,55 @@ export class ApplicationsApiController {
},
);
}
async syncUsers(
request: FastifyRequest<{
Body: {
email: string;
first_name: string;
last_name: string;
application_id: string;
company_id: string;
};
}>,
): Promise<any> {
const email = request.body.email.trim().toLocaleLowerCase();
const checkApplication = gr.services.applications.companyApps.get({
application_id: request.body.application_id,
company_id: request.body.company_id,
});
if (!checkApplication) {
throw new Error("Application is not allowed to sync users for this company.");
}
if (await gr.services.users.getByEmail(email)) {
throw new Error("This email is already used");
}
try {
const newUser = getInstance({
first_name: request.body.first_name,
last_name: request.body.last_name,
email_canonical: email,
username_canonical: (email.replace("@", ".") || "").toLocaleLowerCase(),
phone: "",
identity_provider: "console",
identity_provider_id: email,
mail_verified: true,
});
const user = await gr.services.users.create(newUser);
await gr.services.companies.setUserRole(request.body.company_id, user.entity.id, "admin");
await gr.services.users.save(user.entity, {
user: { id: user.entity.id, server_request: true },
});
} catch (err) {
throw new Error("An unknown error occured");
}
return {};
}
}
function getExecutionContext(request: FastifyRequest): ApplicationApiExecutionContext {
@@ -48,6 +48,15 @@ const routes: FastifyPluginCallback = (fastify: FastifyInstance, options, next)
handler: (request, reply) => controller.proxy.bind(controller)(request, reply, fastify),
});
// Sync SSO users
fastify.route({
method: "POST",
url: "/sync",
preValidation: [fastify.authenticate],
preHandler: [checkApplication],
handler: controller.syncUsers.bind(controller),
});
next();
};