Files
zitadel/apps/login/src/lib/zitadel.ts

521 lines
12 KiB
TypeScript
Raw Normal View History

import {
createOIDCServiceClient,
createSessionServiceClient,
createSettingsServiceClient,
createUserServiceClient,
2024-08-21 11:11:00 +02:00
createIdpServiceClient,
makeReqCtx,
2024-08-06 09:34:45 +02:00
} from "@zitadel/client/v2";
2024-07-25 23:16:07 -04:00
import { createManagementServiceClient } from "@zitadel/client/v1";
import { createServerTransport } from "@zitadel/node";
2024-08-06 09:34:45 +02:00
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { RequestChallenges } from "@zitadel/proto/zitadel/session/v2/challenge_pb";
2023-04-20 14:39:51 +02:00
import {
2023-08-23 08:24:12 +02:00
RetrieveIdentityProviderIntentRequest,
2024-08-14 15:27:59 +02:00
VerifyPasskeyRegistrationRequest,
VerifyU2FRegistrationRequest,
2024-08-06 09:34:45 +02:00
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
2024-08-21 14:15:44 +02:00
import { IDPInformation } from "@zitadel/proto/zitadel/user/v2/idp_pb";
2024-08-06 09:34:45 +02:00
import { CreateCallbackRequest } from "@zitadel/proto/zitadel/oidc/v2/oidc_service_pb";
import { TextQueryMethod } from "@zitadel/proto/zitadel/object/v2/object_pb";
import type { RedirectURLs } from "@zitadel/proto/zitadel/user/v2/idp_pb";
2024-08-21 11:11:00 +02:00
import { PartialMessage, PlainMessage } from "@zitadel/client";
2024-08-21 12:13:24 +02:00
import { SearchQuery as UserSearchQuery } from "@zitadel/proto/zitadel/user/v2/query_pb";
2024-08-21 14:15:44 +02:00
import { IdentityProviderType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import { PROVIDER_MAPPING } from "./idp";
2023-04-20 12:55:39 +02:00
const SESSION_LIFETIME_S = 3000;
const transport = createServerTransport(
process.env.ZITADEL_SERVICE_USER_TOKEN!,
2024-06-11 09:55:03 -04:00
{
baseUrl: process.env.ZITADEL_API_URL!,
httpVersion: "2",
},
);
export const sessionService = createSessionServiceClient(transport);
export const managementService = createManagementServiceClient(transport);
export const userService = createUserServiceClient(transport);
export const oidcService = createOIDCServiceClient(transport);
2024-08-21 11:11:00 +02:00
export const idpService = createIdpServiceClient(transport);
2024-07-23 13:58:43 +02:00
export const settingsService = createSettingsServiceClient(transport);
2023-04-13 13:26:02 +02:00
export async function getBrandingSettings(organization?: string) {
2023-05-15 09:23:59 +02:00
return settingsService
.getBrandingSettings({ ctx: makeReqCtx(organization) }, {})
.then((resp) => resp.settings);
2023-04-21 13:49:15 +02:00
}
export async function getLoginSettings(orgId?: string) {
2023-06-28 11:29:56 +02:00
return settingsService
.getLoginSettings({ ctx: makeReqCtx(orgId) }, {})
.then((resp) => resp.settings);
2023-06-28 11:29:56 +02:00
}
export async function addOTPEmail(userId: string) {
2024-04-16 15:33:14 +02:00
return userService.addOTPEmail(
{
userId,
},
2024-05-13 16:17:12 -04:00
{},
2024-04-16 15:33:14 +02:00
);
}
2024-04-15 17:23:28 +02:00
export async function addOTPSMS(userId: string, token?: string) {
// TODO: Follow up here, I do not understand the branching
// let userService;
// if (token) {
// const authConfig: ZitadelServerOptions = {
// name: "zitadel login",
// apiUrl: process.env.ZITADEL_API_URL ?? "",
// token: token,
// };
// const sessionUser = initializeServer(authConfig);
// userService = user.getUser(sessionUser);
// } else {
// userService = user.getUser(server);
// }
2024-04-16 15:33:14 +02:00
return userService.addOTPSMS({ userId }, {});
}
2024-04-15 17:23:28 +02:00
export async function registerTOTP(userId: string, token?: string) {
// TODO: Follow up here, I do not understand the branching
// let userService;
// if (token) {
// const authConfig: ZitadelServerOptions = {
// name: "zitadel login",
// apiUrl: process.env.ZITADEL_API_URL ?? "",
// token: token,
// };
//
// const sessionUser = initializeServer(authConfig);
// userService = user.getUser(sessionUser);
// } else {
// userService = user.getUser(server);
// }
2024-04-16 15:33:14 +02:00
return userService.registerTOTP({ userId }, {});
2024-04-15 17:23:28 +02:00
}
export async function getGeneralSettings() {
return settingsService
2023-05-24 16:27:35 +02:00
.getGeneralSettings({}, {})
.then((resp) => resp.supportedLanguages);
}
export async function getLegalAndSupportSettings(organization?: string) {
2023-05-15 09:23:59 +02:00
return settingsService
.getLegalAndSupportSettings({ ctx: makeReqCtx(organization) }, {})
.then((resp) => {
2023-05-24 16:27:35 +02:00
return resp.settings;
});
2023-04-26 15:14:28 +02:00
}
export async function getPasswordComplexitySettings(organization?: string) {
2023-05-15 09:23:59 +02:00
return settingsService
.getPasswordComplexitySettings({ ctx: makeReqCtx(organization) })
.then((resp) => resp.settings);
2023-04-26 15:14:28 +02:00
}
2024-04-04 13:50:54 +02:00
export async function createSessionFromChecks(
checks: PlainMessage<Checks>,
challenges: PlainMessage<RequestChallenges> | undefined,
) {
2024-04-04 13:50:54 +02:00
return sessionService.createSession(
{
checks: checks,
challenges,
lifetime: {
seconds: BigInt(SESSION_LIFETIME_S),
2024-04-04 13:50:54 +02:00
nanos: 0,
},
},
2024-05-13 16:17:12 -04:00
{},
2024-04-04 13:50:54 +02:00
);
2024-03-25 13:39:23 +01:00
}
2024-03-15 17:21:21 +01:00
export async function createSessionForUserIdAndIdpIntent(
userId: string,
idpIntent: {
idpIntentId?: string | undefined;
idpIntentToken?: string | undefined;
2024-05-13 16:17:12 -04:00
},
) {
return sessionService.createSession({
checks: {
user: {
search: {
case: "userId",
value: userId,
},
},
idpIntent,
2024-03-15 17:21:21 +01:00
},
// lifetime: {
// seconds: 300,
// nanos: 0,
// },
});
2024-03-15 17:21:21 +01:00
}
export async function setSession(
sessionId: string,
sessionToken: string,
2024-04-16 09:27:58 +02:00
challenges: RequestChallenges | undefined,
checks?: PlainMessage<Checks>,
) {
return sessionService.setSession(
{
sessionId,
sessionToken,
challenges,
checks: checks ? checks : {},
metadata: {},
},
{},
);
}
export async function getSession(sessionId: string, sessionToken: string) {
return sessionService.getSession({ sessionId, sessionToken }, {});
}
export async function deleteSession(sessionId: string, sessionToken: string) {
2023-06-06 17:11:49 +02:00
return sessionService.deleteSession({ sessionId, sessionToken }, {});
}
export async function listSessions(ids: string[]) {
return sessionService.listSessions(
{
queries: [
{
query: {
case: "idsQuery",
value: { ids: ids },
},
},
],
},
{},
);
2023-05-17 15:25:25 +02:00
}
export type AddHumanUserData = {
2023-04-26 18:36:09 +02:00
firstName: string;
lastName: string;
email: string;
password: string | undefined;
organization: string | undefined;
};
2023-05-17 17:04:56 +02:00
export async function addHumanUser({
email,
firstName,
lastName,
password,
organization,
}: AddHumanUserData) {
return userService.addHumanUser({
2023-06-29 12:53:48 +02:00
email: { email },
username: email,
2023-08-23 08:24:12 +02:00
profile: { givenName: firstName, familyName: lastName },
organization: organization
? { org: { case: "orgId", value: organization } }
: undefined,
passwordType: password
? { case: "password", value: { password: password } }
: undefined,
});
}
2024-08-13 14:14:10 +02:00
export async function verifyTOTPRegistration(code: string, userId: string) {
return userService.verifyTOTPRegistration({ code, userId }, {});
}
export async function getUserByID(userId: string) {
2024-04-17 15:19:19 +02:00
return userService.getUserByID({ userId }, {});
}
2024-08-21 12:13:24 +02:00
export async function listUsers({
userName,
email,
organizationId,
}: {
userName?: string;
email?: string;
organizationId?: string;
}) {
const queries: PartialMessage<UserSearchQuery>[] = [];
if (userName) {
queries.push({
query: {
case: "userNameQuery",
value: {
userName,
method: TextQueryMethod.EQUALS,
},
},
});
}
if (organizationId) {
queries.push({
query: {
case: "organizationIdQuery",
value: {
organizationId,
},
},
});
}
if (email) {
queries.push({
query: {
case: "emailQuery",
value: {
emailAddress: email,
},
},
});
}
2024-03-12 11:35:19 +01:00
return userService.listUsers(
{
2024-08-21 12:13:24 +02:00
queries: queries,
2024-03-12 11:35:19 +01:00
},
2024-05-13 16:17:12 -04:00
{},
2024-03-12 11:35:19 +01:00
);
}
export async function getOrgByDomain(domain: string) {
return managementService.getOrgByDomainGlobal({ domain }, {});
2024-04-03 15:16:06 +02:00
}
export async function startIdentityProviderFlow({
idpId,
urls,
}: {
idpId: string;
urls: PlainMessage<RedirectURLs>;
}) {
2023-08-23 08:24:12 +02:00
return userService.startIdentityProviderIntent({
2023-07-27 11:05:42 +02:00
idpId,
content: {
case: "urls",
value: urls,
},
2023-07-27 11:05:42 +02:00
});
}
export async function retrieveIdentityProviderInformation({
idpIntentId,
idpIntentToken,
}: RetrieveIdentityProviderIntentRequest) {
2023-08-23 08:24:12 +02:00
return userService.retrieveIdentityProviderIntent({
idpIntentId,
idpIntentToken,
2023-07-28 15:23:17 +02:00
});
}
export async function getAuthRequest({
authRequestId,
}: {
authRequestId: string;
}) {
return oidcService.getAuthRequest({
authRequestId,
});
}
export async function createCallback(req: PlainMessage<CreateCallbackRequest>) {
return oidcService.createCallback(req);
}
export async function verifyEmail(userId: string, verificationCode: string) {
return userService.verifyEmail(
2023-05-17 17:04:56 +02:00
{
userId,
verificationCode,
},
2024-05-13 16:17:12 -04:00
{},
2023-05-17 17:04:56 +02:00
);
}
2023-05-22 11:48:18 +02:00
/**
*
* @param userId the id of the user where the email should be set
* @returns the newly set email
*/
2024-07-17 15:22:13 +02:00
export async function resendEmailCode(userId: string) {
return userService.resendEmailCode(
2023-05-22 11:48:18 +02:00
{
userId,
},
2024-05-13 16:17:12 -04:00
{},
2023-05-22 11:48:18 +02:00
);
}
export function retrieveIDPIntent(id: string, token: string) {
return userService.retrieveIdentityProviderIntent(
{ idpIntentId: id, idpIntentToken: token },
{},
);
}
2024-08-21 11:11:00 +02:00
export function getIDPByID(id: string) {
return idpService.getIDPByID({ id }, {}).then((resp) => resp.idp);
}
export function addIDPLink(
idp: {
id: string;
userId: string;
userName: string;
},
userId: string,
) {
return userService.addIDPLink(
{
idpLink: {
userId: idp.userId,
idpId: idp.id,
userName: idp.userName,
},
userId,
},
{},
);
}
2024-08-21 16:08:37 +02:00
export function createUser(provider: string, info: IDPInformation) {
const userData = PROVIDER_MAPPING[provider](info);
2024-08-21 16:08:37 +02:00
console.log("ud", userData);
return userService.addHumanUser(userData, {});
}
2024-07-15 17:20:38 +02:00
/**
*
* @param userId the id of the user where the email should be set
* @returns the newly set email
*/
2024-07-16 17:06:25 +02:00
export async function passwordReset(userId: string): Promise<any> {
return userService.passwordReset(
2024-07-15 17:20:38 +02:00
{
userId,
},
{},
);
}
/**
*
* @param server
* @param userId the id of the user where the email should be set
* @returns the newly set email
*/
export async function createPasskeyRegistrationLink(
userId: string,
2024-05-13 16:17:12 -04:00
token?: string,
) {
// let userService;
// if (token) {
// const authConfig: ZitadelServerOptions = {
// name: "zitadel login",
// apiUrl: process.env.ZITADEL_API_URL ?? "",
// token: token,
// };
//
// const sessionUser = initializeServer(authConfig);
// userService = user.getUser(sessionUser);
// } else {
// userService = user.getUser(server);
// }
2023-06-15 13:58:32 +02:00
return userService.createPasskeyRegistrationLink({
2023-06-15 13:58:32 +02:00
userId,
medium: {
case: "returnCode",
value: {},
},
2023-06-15 13:58:32 +02:00
});
}
/**
*
* @param userId the id of the user where the email should be set
* @param domain the domain on which the factor is registered
* @returns the newly set email
*/
export async function registerU2F(userId: string, domain: string) {
return userService.registerU2F({
userId,
domain,
});
}
/**
*
* @param userId the id of the user where the email should be set
* @param domain the domain on which the factor is registered
* @returns the newly set email
*/
export async function verifyU2FRegistration(
request: PlainMessage<VerifyU2FRegistrationRequest>,
) {
return userService.verifyU2FRegistration(request, {});
}
2024-07-30 14:37:11 +02:00
export async function getActiveIdentityProviders(orgId?: string) {
return settingsService.getActiveIdentityProviders(
{ ctx: makeReqCtx(orgId) },
{},
);
}
/**
*
* @param userId the id of the user where the email should be set
* @returns the newly set email
*/
export async function verifyPasskeyRegistration(
2024-08-14 15:27:59 +02:00
request: PartialMessage<VerifyPasskeyRegistrationRequest>,
) {
2024-08-14 15:51:51 +02:00
// TODO: find a better way to handle this
request = VerifyPasskeyRegistrationRequest.fromJson(request as any);
2024-08-14 15:27:59 +02:00
return userService.verifyPasskeyRegistration(request, {});
}
2023-06-12 10:38:28 +02:00
/**
*
* @param userId the id of the user where the email should be set
* @returns the newly set email
*/
export async function registerPasskey(
userId: string,
2023-06-27 18:08:22 +02:00
code: { id: string; code: string },
2024-05-13 16:17:12 -04:00
domain: string,
) {
return userService.registerPasskey({
2023-06-13 17:43:37 +02:00
userId,
code,
2023-06-27 18:08:22 +02:00
domain,
// authenticator:
2023-06-13 17:43:37 +02:00
});
2023-06-12 10:38:28 +02:00
}
2023-06-28 10:47:22 +02:00
/**
*
* @param userId the id of the user where the email should be set
* @returns the newly set email
*/
export async function listAuthenticationMethodTypes(userId: string) {
return userService.listAuthenticationMethodTypes({
2023-06-28 10:47:22 +02:00
userId,
});
}