Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: zitadel server #63

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 24 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
# ZITADEL TypeScript with Turborepo and Changesets

This repository contains all TypeScript and JavaScript packages and applications you need to create your own ZITADEL Login UI.
The repo makes use of the [build system Turbo](https://turbo.build/repo) and the [Changesets CLI for versioning the packages](https://github.com/changesets/changesets).
This repository contains all TypeScript and JavaScript packages and applications you need to create your own ZITADEL
Login UI.
The repo makes use of the [build system Turbo](https://turbo.build/repo) and
the [Changesets CLI for versioning the packages](https://github.com/changesets/changesets).

**⚠️ This repo and packages are in alpha state and subject to change ⚠️**

The scope of functionality of this repo and packages is limited and under active development.
Once the package structure is set and all APIs are fully implemented we'll move this repo to beta state.
You can read the [contribution guide](/CONTRIBUTING.md) on how to contribute.
Questions can be raised in our [Discord channel](https://discord.gg/erh5Brh7jE) or as a [GitHub issue](https://github.com/zitadel/typescript/issues).
Questions can be raised in our [Discord channel](https://discord.gg/erh5Brh7jE) or as
a [GitHub issue](https://github.com/zitadel/typescript/issues).

## Developing Your Own ZITADEL Login UI

Expand All @@ -25,8 +28,8 @@ We think the easiest path of getting up and running, is the following:
## Included Apps And Packages

- `login`: The login UI used by ZITADEL Cloud, powered by Next.js
- `@zitadel/server`: core components for establishing node client connection, grpc stub
- `@zitadel/client`: core components for establishing web client connection, grpc stub
- `@zitadel/node`: core components for establishing node client connection, grpc stub
- `@zitadel/client`: shared client utilities
- `@zitadel/proto`: shared protobuf types
- `@zitadel/react`: shared React utilities and components built with tailwindcss
- `@zitadel/next`: shared Next.js utilities
Expand All @@ -38,9 +41,11 @@ Each package and app is 100% [TypeScript](https://www.typescriptlang.org/).
### Login

The login is currently in a work in progress state.
The goal is to implement a login UI, using the session API of ZITADEL, which also implements the OIDC Standard and is ready to use for everyone.
The goal is to implement a login UI, using the session API of ZITADEL, which also implements the OIDC Standard and is
ready to use for everyone.

In the first phase we want to have a MVP login ready with the OIDC Standard and a basic feature set. In a second step the features will be extended.
In the first phase we want to have a MVP login ready with the OIDC Standard and a basic feature set. In a second step
the features will be extended.

This list should show the current implementation state, and also what is missing.
You can already use the current state, and extend it with your needs.
Expand Down Expand Up @@ -105,11 +110,14 @@ You can already use the current state, and extend it with your needs.
## Versioning And Publishing Packages

Package publishing has been configured using [Changesets](https://github.com/changesets/changesets).
Here is their [documentation](https://github.com/changesets/changesets#documentation) for more information about the workflow.
Here is their [documentation](https://github.com/changesets/changesets#documentation) for more information about the
workflow.

The [GitHub Action](https://github.com/changesets/action) needs an `NPM_TOKEN` and `GITHUB_TOKEN` in the repository settings. The [Changesets bot](https://github.com/apps/changeset-bot) should also be installed on the GitHub repository.
The [GitHub Action](https://github.com/changesets/action) needs an `NPM_TOKEN` and `GITHUB_TOKEN` in the repository
settings. The [Changesets bot](https://github.com/apps/changeset-bot) should also be installed on the GitHub repository.

Read the [changesets documentation](https://github.com/changesets/changesets/blob/main/docs/automating-changesets.md) for more information about this automation
Read the [changesets documentation](https://github.com/changesets/changesets/blob/main/docs/automating-changesets.md)
for more information about this automation

### NPM

Expand All @@ -136,8 +144,10 @@ pnpm install
```

then setup the environment for the login application which needs a `.env.local` in `/apps/login`.
Go to your instance and create a service user for the application having the IAM_OWNER manager role.
This user is required to have access to create users on your primary organization and reading policy data so it can be restricted to your personal use case but we'll stick with IAM_OWNER for convenience. Create a PAT and copy the value to paste it under the `ZITADEL_SERVICE_USER_TOKEN` key.
Go to your instance and create a service user for the application having the `IAM_OWNER` manager role.
This user is required to have access to create users on your primary organization and reading policy data so it can be
restricted to your personal use case but we'll stick with `IAM_OWNER` for convenience. Create a PAT and copy the value to
paste it under the `ZITADEL_SERVICE_USER_TOKEN` key.
The file should look as follows:

```
Expand All @@ -164,7 +174,8 @@ Open the login application with your favorite browser at `localhost:3000`.

To deploy your own version on Vercel, navigate to your instance and create a service user.
Copy its id from the overview and set it as ZITADEL_SERVICE_USER_ID.
Then create a personal access token (PAT), copy and set it as ZITADEL_SERVICE_USER_TOKEN, then navigate to your instance settings and make sure it gets IAM_OWNER permissions.
Then create a personal access token (PAT), copy and set it as ZITADEL_SERVICE_USER_TOKEN, then navigate to your instance
settings and make sure it gets IAM_OWNER permissions.
Finally set your instance url as ZITADEL_API_URL. Make sure to set it without trailing slash.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fzitadel%2Ftypescript&env=ZITADEL_API_URL,ZITADEL_SERVICE_USER_ID,ZITADEL_SERVICE_USER_TOKEN&root-directory=apps/login&envDescription=Setup%20a%20service%20account%20with%20IAM_OWNER%20membership%20on%20your%20instance%20and%20provide%20its%20id%20and%20personal%20access%20token.&project-name=zitadel-login&repository-name=zitadel-login)
13 changes: 7 additions & 6 deletions apps/login/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,14 @@
"*": "prettier --write --ignore-unknown"
},
"dependencies": {
"@headlessui/react": "^1.7.14",
"@heroicons/react": "2.0.13",
"@tailwindcss/forms": "0.5.3",
"@vercel/analytics": "^1.0.0",
"@zitadel/client": "workspace:*",
"@headlessui/react": "^1.7.18",
"@heroicons/react": "2.1.3",
"@tailwindcss/forms": "0.5.7",
"@vercel/analytics": "^1.2.2",
"@zitadel/proto": "workspace:*",
"@zitadel/client2": "workspace:*",
"@zitadel/react": "workspace:*",
"@zitadel/server": "workspace:*",
"@zitadel/node": "workspace:*",
"clsx": "1.2.1",
"copy-to-clipboard": "^3.3.3",
"moment": "^2.29.4",
Expand Down
8 changes: 3 additions & 5 deletions apps/login/src/app/(login)/accounts/page.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { Session } from "@zitadel/server";
import { getBrandingSettings, listSessions, server } from "@/lib/zitadel";
import { getBrandingSettings, listSessions } from "@/lib/zitadel";
import { getAllSessionCookieIds } from "@/utils/cookies";
import { UserPlusIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
import SessionsList from "@/ui/SessionsList";
import DynamicTheme from "@/ui/DynamicTheme";

async function loadSessions(): Promise<Session[]> {
async function loadSessions() {
const ids = await getAllSessionCookieIds();

if (ids && ids.length) {
const response = await listSessions(
server,
ids.filter((id: string | undefined) => !!id),
);
return response?.sessions ?? [];
Expand All @@ -31,7 +29,7 @@ export default async function Page({

let sessions = await loadSessions();

const branding = await getBrandingSettings(server, organization);
const branding = await getBrandingSettings(organization);

return (
<DynamicTheme branding={branding}>
Expand Down
14 changes: 2 additions & 12 deletions apps/login/src/app/(login)/idp/[provider]/failure/page.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
import { ProviderSlug } from "@/lib/demos";
import { getBrandingSettings, server } from "@/lib/zitadel";
import Alert, { AlertType } from "@/ui/Alert";
import { getBrandingSettings } from "@/lib/zitadel";
import DynamicTheme from "@/ui/DynamicTheme";
import IdpSignin from "@/ui/IdpSignin";
import {
AddHumanUserRequest,
IDPInformation,
RetrieveIdentityProviderIntentResponse,
user,
IDPLink,
} from "@zitadel/server";
import { ClientError } from "nice-grpc";

const PROVIDER_NAME_MAPPING: {
[provider: string]: string;
Expand All @@ -29,7 +19,7 @@ export default async function Page({
const { id, token, authRequestId, organization } = searchParams;
const { provider } = params;

const branding = await getBrandingSettings(server, organization);
const branding = await getBrandingSettings(organization);

if (provider) {
return (
Expand Down
69 changes: 39 additions & 30 deletions apps/login/src/app/(login)/idp/[provider]/success/page.tsx
Original file line number Diff line number Diff line change
@@ -1,71 +1,81 @@
import { ProviderSlug } from "@/lib/demos";
import { getBrandingSettings, server } from "@/lib/zitadel";
import { getBrandingSettings, userService } from "@/lib/zitadel";
import Alert, { AlertType } from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import IdpSignin from "@/ui/IdpSignin";
import { AddHumanUserRequest } from "@zitadel/proto/zitadel/user/v2beta/user_service_pb";
import {
AddHumanUserRequest,
IDPInformation,
RetrieveIdentityProviderIntentResponse,
user,
IDPLink,
} from "@zitadel/server";
import { ClientError } from "nice-grpc";
} from "@zitadel/proto/zitadel/user/v2beta/idp_pb";
import { PartialMessage } from "@zitadel/client2";

const PROVIDER_MAPPING: {
[provider: string]: (rI: IDPInformation) => Partial<AddHumanUserRequest>;
[provider: string]: (
rI: IDPInformation,
) => PartialMessage<AddHumanUserRequest>;
} = {
[ProviderSlug.GOOGLE]: (idp: IDPInformation) => {
const idpLink: IDPLink = {
const rawInfo = idp.rawInformation?.toJson() as {
User: {
email: string;
name?: string;
given_name?: string;
family_name?: string;
};
};

const idpLink: PartialMessage<IDPLink> = {
idpId: idp.idpId,
userId: idp.userId,
userName: idp.userName,
};
const req: Partial<AddHumanUserRequest> = {

const req: PartialMessage<AddHumanUserRequest> = {
username: idp.userName,
email: {
email: idp.rawInformation?.User?.email,
isVerified: true,
email: rawInfo.User?.email,
verification: { case: "isVerified", value: true },
},
// organisation: Organisation | undefined;
profile: {
displayName: idp.rawInformation?.User?.name ?? "",
givenName: idp.rawInformation?.User?.given_name ?? "",
familyName: idp.rawInformation?.User?.family_name ?? "",
displayName: rawInfo.User?.name ?? "",
givenName: rawInfo.User?.given_name ?? "",
familyName: rawInfo.User?.family_name ?? "",
},
idpLinks: [idpLink],
};
return req;
},
[ProviderSlug.GITHUB]: (idp: IDPInformation) => {
const idpLink: IDPLink = {
const rawInfo = idp.rawInformation?.toJson() as {
email: string;
name: string;
};
const idpLink: PartialMessage<IDPLink> = {
idpId: idp.idpId,
userId: idp.userId,
userName: idp.userName,
};
const req: Partial<AddHumanUserRequest> = {
const req: PartialMessage<AddHumanUserRequest> = {
username: idp.userName,
email: {
email: idp.rawInformation?.email,
isVerified: true,
email: rawInfo?.email,
verification: { case: "isVerified", value: true },
},
// organisation: Organisation | undefined;
profile: {
displayName: idp.rawInformation?.name ?? "",
givenName: idp.rawInformation?.name ?? "",
familyName: idp.rawInformation?.name ?? "",
displayName: rawInfo?.name ?? "",
givenName: rawInfo?.name ?? "",
familyName: rawInfo?.name ?? "",
},
idpLinks: [idpLink],
};
return req;
},
};

function retrieveIDPIntent(
id: string,
token: string,
): Promise<RetrieveIdentityProviderIntentResponse> {
const userService = user.getUser(server);
function retrieveIDPIntent(id: string, token: string) {
return userService.retrieveIdentityProviderIntent(
{ idpIntentId: id, idpIntentToken: token },
{},
Expand All @@ -77,7 +87,6 @@ function createUser(
info: IDPInformation,
): Promise<string> {
const userData = PROVIDER_MAPPING[provider](info);
const userService = user.getUser(server);
return userService.addHumanUser(userData, {}).then((resp) => resp.userId);
}

Expand All @@ -91,7 +100,7 @@ export default async function Page({
const { id, token, authRequestId, organization } = searchParams;
const { provider } = params;

const branding = await getBrandingSettings(server, organization);
const branding = await getBrandingSettings(organization);

if (provider && id && token) {
return retrieveIDPIntent(id, token)
Expand Down Expand Up @@ -128,15 +137,15 @@ export default async function Page({
</DynamicTheme>
);
})
.catch((error: ClientError) => {
.catch((error) => {
return (
<DynamicTheme branding={branding}>
<div className="flex flex-col items-center space-y-4">
<h1>Register failed</h1>
<div className="w-full">
{
<Alert type={AlertType.ALERT}>
{JSON.stringify(error.details)}
{JSON.stringify(error.message)}
</Alert>
}
</div>
Expand Down
28 changes: 8 additions & 20 deletions apps/login/src/app/(login)/idp/page.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,16 @@
import {
getBrandingSettings,
getLegalAndSupportSettings,
server,
settingsService,
} from "@/lib/zitadel";
import DynamicTheme from "@/ui/DynamicTheme";
import { SignInWithIDP } from "@/ui/SignInWithIDP";
import {
GetActiveIdentityProvidersResponse,
IdentityProvider,
ZitadelServer,
settings,
} from "@zitadel/server";
import { makeReqCtx } from "@zitadel/client2/v2beta";

function getIdentityProviders(
server: ZitadelServer,
orgId?: string,
): Promise<IdentityProvider[] | undefined> {
const settingsService = settings.getSettings(server);
function getIdentityProviders(orgId?: string) {
return settingsService
.getActiveIdentityProviders(
orgId ? { ctx: { orgId } } : { ctx: { instance: true } },
{},
)
.then((resp: GetActiveIdentityProvidersResponse) => {
.getActiveIdentityProviders({ ctx: makeReqCtx(orgId) }, {})
.then((resp) => {
return resp.identityProviders;
});
}
Expand All @@ -35,15 +23,15 @@ export default async function Page({
const authRequestId = searchParams?.authRequestId;
const organization = searchParams?.organization;

const legal = await getLegalAndSupportSettings(server, organization);
const legal = await getLegalAndSupportSettings(organization);

const identityProviders = await getIdentityProviders(server, organization);
const identityProviders = await getIdentityProviders(organization);

const host = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";

const branding = await getBrandingSettings(server, organization);
const branding = await getBrandingSettings(organization);

return (
<DynamicTheme branding={branding}>
Expand Down