Merge pull request #107 from zitadel/qa

Promote qa to prod
This commit is contained in:
Max Peintner
2024-08-13 11:45:20 +02:00
committed by GitHub
59 changed files with 4654 additions and 5854 deletions

View File

@@ -1 +1,2 @@
ZITADEL_API_URL=http://localhost:22222
ZITADEL_API_URL=http://localhost:22222
DEBUG=true

View File

@@ -33,9 +33,6 @@ const secureHeaders = [
const nextConfig = {
reactStrictMode: true, // Recommended for the `pages` directory, default in `app`.
swcMinify: true,
experimental: {
serverActions: true,
},
images: {
remotePatterns: [
{

View File

@@ -40,6 +40,7 @@
"@zitadel/node": "workspace:*",
"@zitadel/proto": "workspace:*",
"@zitadel/react": "workspace:*",
"@zitadel/next": "workspace:*",
"clsx": "1.2.1",
"copy-to-clipboard": "^3.3.3",
"moment": "^2.29.4",

View File

@@ -1,5 +1,5 @@
import { getBrandingSettings, listSessions } from "@/lib/zitadel";
import { getAllSessionCookieIds } from "@/utils/cookies";
import { getAllSessionCookieIds } from "@zitadel/next";
import { UserPlusIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
import SessionsList from "@/ui/SessionsList";

View File

@@ -44,6 +44,36 @@ const PROVIDER_MAPPING: {
};
return req;
},
[ProviderSlug.AZURE]: (idp: IDPInformation) => {
const rawInfo = idp.rawInformation?.toJson() as {
mail: string;
displayName?: string;
givenName?: string;
surname?: string;
};
const idpLink: PartialMessage<IDPLink> = {
idpId: idp.idpId,
userId: idp.userId,
userName: idp.userName,
};
const req: PartialMessage<AddHumanUserRequest> = {
username: idp.userName,
email: {
email: rawInfo?.mail,
verification: { case: "isVerified", value: true },
},
// organisation: Organisation | undefined;
profile: {
displayName: rawInfo?.displayName ?? "",
givenName: rawInfo?.givenName ?? "",
familyName: rawInfo?.surname ?? "",
},
idpLinks: [idpLink],
};
return req;
},
[ProviderSlug.GITHUB]: (idp: IDPInformation) => {
const rawInfo = idp.rawInformation?.toJson() as {
email: string;

View File

@@ -51,16 +51,16 @@ export default async function Page({
organization={organization}
submit={submit}
allowRegister={!!loginSettings?.allowRegister}
/>
{legal && identityProviders && process.env.ZITADEL_API_URL && (
<SignInWithIDP
host={host}
identityProviders={identityProviders}
authRequestId={authRequestId}
organization={organization}
></SignInWithIDP>
)}
>
{legal && identityProviders && process.env.ZITADEL_API_URL && (
<SignInWithIDP
host={host}
identityProviders={identityProviders}
authRequestId={authRequestId}
organization={organization}
></SignInWithIDP>
)}
</UsernameForm>
</div>
</DynamicTheme>
);

View File

@@ -11,7 +11,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
export default async function Page({
searchParams,
@@ -29,10 +29,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
return listAuthenticationMethodTypes(
@@ -48,7 +48,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
return listAuthenticationMethodTypes(

View File

@@ -13,7 +13,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
export default async function Page({
searchParams,
@@ -31,10 +31,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
const userId = response.session.factors.user.id;
@@ -58,7 +58,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session && response.session.factors?.user?.id) {
const userId = response.session.factors.user.id;

View File

@@ -1,13 +1,9 @@
import {
getBrandingSettings,
getLoginSettings,
getSession,
} from "@/lib/zitadel";
import { getBrandingSettings, sessionService } from "@/lib/zitadel";
import Alert from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import LoginOTP from "@/ui/LoginOTP";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -21,21 +17,13 @@ export default async function Page({
const { method } = params;
const { session, token } = await loadSession(loginName, organization);
const session = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
const branding = await getBrandingSettings(organization);
async function loadSession(loginName?: string, organization?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
return { session: response?.session, token: recent.token };
});
}
return (
<DynamicTheme branding={branding}>
<div className="flex flex-col items-center space-y-4">

View File

@@ -2,19 +2,18 @@ import {
addOTPEmail,
addOTPSMS,
getBrandingSettings,
getSession,
registerTOTP,
sessionService,
} from "@/lib/zitadel";
import Alert from "@/ui/Alert";
import BackButton from "@/ui/BackButton";
import { Button, ButtonVariants } from "@/ui/Button";
import DynamicTheme from "@/ui/DynamicTheme";
import { Spinner } from "@/ui/Spinner";
import TOTPRegister from "@/ui/TOTPRegister";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import Link from "next/link";
import { RegisterTOTPResponse } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -28,7 +27,10 @@ export default async function Page({
const { method } = params;
const branding = await getBrandingSettings(organization);
const { session, token } = await loadSession(loginName, organization);
const session = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
let totpResponse: RegisterTOTPResponse | undefined,
totpError: Error | undefined;
@@ -56,17 +58,6 @@ export default async function Page({
throw new Error("No session found");
}
async function loadSession(loginName?: string, organization?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
return { session: response?.session, token: recent.token };
});
}
const paramsToContinue = new URLSearchParams({});
let urlToContinue = "/accounts";

View File

@@ -0,0 +1,45 @@
import { demos } from "@/lib/demos";
import Link from "next/link";
export default function Page() {
return (
<div className="rounded-lg bg-vc-border-gradient dark:bg-dark-vc-border-gradient p-px shadow-lg shadow-black/5 dark:shadow-black/20 mb-10">
<div className="rounded-lg bg-background-light-400 dark:bg-background-dark-500 px-8 py-12">
<div className="space-y-8">
<h1 className="text-xl font-medium">Pages</h1>
<div className="space-y-10">
{demos.map((section) => {
return (
<div key={section.name} className="space-y-5">
<div className="text-xs font-semibold uppercase tracking-wider text-gray-500">
{section.name}
</div>
<div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
{section.items.map((item) => {
return (
<Link
href={`/${item.slug}`}
key={item.name}
className="bg-background-light-400 dark:bg-background-dark-400 group block space-y-1.5 rounded-md px-5 py-3 hover:shadow-lg hover:dark:bg-white/10 border border-divider-light dark:border-divider-dark transition-all "
>
<div className="font-medium">{item.name}</div>
{item.description ? (
<div className="line-clamp-3 text-sm text-text-light-secondary-500 dark:text-text-dark-secondary-500">
{item.description}
</div>
) : null}
</Link>
);
})}
</div>
</div>
);
})}
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,9 +1,9 @@
import { getBrandingSettings, getSession } from "@/lib/zitadel";
import { getBrandingSettings, getSession, sessionService } from "@/lib/zitadel";
import Alert, { AlertType } from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import RegisterPasskey from "@/ui/RegisterPasskey";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -13,19 +13,11 @@ export default async function Page({
const { loginName, promptPasswordless, organization, authRequestId } =
searchParams;
const sessionFactors = await loadSession(loginName);
const sessionFactors = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
async function loadSession(loginName?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
}
});
}
const title = !!promptPasswordless
? "Authenticate with a passkey"
: "Use your passkey to confirm it's really you";

View File

@@ -6,7 +6,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
const title = "Authenticate with a passkey";
const description =
@@ -28,10 +28,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
@@ -40,7 +40,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;

View File

@@ -2,12 +2,13 @@ import {
getBrandingSettings,
getLoginSettings,
getSession,
sessionService,
} from "@/lib/zitadel";
import Alert from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import PasswordForm from "@/ui/PasswordForm";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -16,20 +17,11 @@ export default async function Page({
}) {
const { loginName, organization, promptPasswordless, authRequestId, alt } =
searchParams;
const sessionFactors = await loadSession(loginName, organization);
async function loadSession(loginName?: string, organization?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
}
});
}
const sessionFactors = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
const branding = await getBrandingSettings(organization);
const loginSettings = await getLoginSettings(organization);

View File

@@ -1,11 +1,11 @@
import { createCallback, getBrandingSettings, getSession } from "@/lib/zitadel";
import DynamicTheme from "@/ui/DynamicTheme";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { getMostRecentCookieWithLoginname } from "@zitadel/next";
import { redirect } from "next/navigation";
async function loadSession(loginName: string, authRequestId?: string) {
const recent = await getMostRecentCookieWithLoginname(`${loginName}`);
const recent = await getMostRecentCookieWithLoginname({ loginName });
if (authRequestId) {
return createCallback({

View File

@@ -10,7 +10,7 @@ import UserAvatar from "@/ui/UserAvatar";
import {
getMostRecentCookieWithLoginname,
getSessionCookieById,
} from "@/utils/cookies";
} from "@zitadel/next";
export default async function Page({
searchParams,
@@ -31,10 +31,10 @@ export default async function Page({
loginName?: string,
organization?: string,
) {
const recent = await getMostRecentCookieWithLoginname(
const recent = await getMostRecentCookieWithLoginname({
loginName,
organization,
);
});
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
@@ -43,7 +43,7 @@ export default async function Page({
}
async function loadSessionById(sessionId: string, organization?: string) {
const recent = await getSessionCookieById(sessionId, organization);
const recent = await getSessionCookieById({ sessionId, organization });
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;

View File

@@ -1,10 +1,11 @@
import { getBrandingSettings, getSession } from "@/lib/zitadel";
import { getBrandingSettings, getSession, sessionService } from "@/lib/zitadel";
import Alert, { AlertType } from "@/ui/Alert";
import DynamicTheme from "@/ui/DynamicTheme";
import RegisterPasskey from "@/ui/RegisterPasskey";
import RegisterU2F from "@/ui/RegisterU2F";
import UserAvatar from "@/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { getMostRecentCookieWithLoginname } from "@zitadel/next";
import { loadMostRecentSession } from "@zitadel/next";
export default async function Page({
searchParams,
@@ -13,19 +14,11 @@ export default async function Page({
}) {
const { loginName, organization, authRequestId } = searchParams;
const sessionFactors = await loadSession(loginName);
const sessionFactors = await loadMostRecentSession(sessionService, {
loginName,
organization,
});
async function loadSession(loginName?: string) {
const recent = await getMostRecentCookieWithLoginname(
loginName,
organization,
);
return getSession(recent.id, recent.token).then((response) => {
if (response?.session) {
return response.session;
}
});
}
const title = "Use your passkey to confirm it's really you";
const description =
"Your device will ask for your fingerprint, face, or screen lock";

View File

@@ -4,7 +4,6 @@ import {
getLoginSettings,
listAuthenticationMethodTypes,
listUsers,
PROVIDER_NAME_MAPPING,
startIdentityProviderFlow,
} from "@/lib/zitadel";
import { createSessionForUserIdAndUpdateCookie } from "@/utils/session";

View File

@@ -1,9 +1,8 @@
import {
SessionCookie,
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
} from "@/utils/cookies";
} from "@zitadel/next";
import { setSessionAndUpdateCookie } from "@/utils/session";
import { NextRequest, NextResponse, userAgent } from "next/server";
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
@@ -16,12 +15,12 @@ export async function POST(request: NextRequest) {
const { loginName, sessionId, organization, authRequestId, code, method } =
body;
const recentPromise: Promise<SessionCookie> = sessionId
? getSessionCookieById(sessionId).catch((error) => {
const recentPromise = sessionId
? getSessionCookieById({ sessionId }).catch((error) => {
return Promise.reject(error);
})
: loginName
? getSessionCookieByLoginName(loginName, organization).catch(
? getSessionCookieByLoginName({ loginName, organization }).catch(
(error) => {
return Promise.reject(error);
},

View File

@@ -3,7 +3,7 @@ import {
getSession,
registerPasskey,
} from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
@@ -11,7 +11,7 @@ export async function POST(request: NextRequest) {
if (body) {
const { sessionId } = body;
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -1,5 +1,5 @@
import { getSession, verifyPasskeyRegistration } from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse, userAgent } from "next/server";
export async function POST(request: NextRequest) {
@@ -13,7 +13,7 @@ export async function POST(request: NextRequest) {
device.vendor || device.model ? ", " : ""
}${os.name}${os.name ? ", " : ""}${browser.name}`;
}
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -5,12 +5,11 @@ import {
listAuthenticationMethodTypes,
} from "@/lib/zitadel";
import {
SessionCookie,
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
removeSessionFromCookie,
} from "@/utils/cookies";
} from "@zitadel/next";
import {
createSessionAndUpdateCookie,
createSessionForIdpAndUpdateCookie,
@@ -76,12 +75,12 @@ export async function PUT(request: NextRequest) {
challenges,
} = body;
const recentPromise: Promise<SessionCookie> = sessionId
const recentPromise = sessionId
? getSessionCookieById(sessionId).catch((error) => {
return Promise.reject(error);
})
: loginName
? getSessionCookieByLoginName(loginName, organization).catch(
? getSessionCookieByLoginName({ loginName, organization }).catch(
(error) => {
return Promise.reject(error);
},
@@ -166,9 +165,9 @@ export async function PUT(request: NextRequest) {
*/
export async function DELETE(request: NextRequest) {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
if (id) {
const session = await getSessionCookieById(id);
const sessionId = searchParams.get("id");
if (sessionId) {
const session = await getSessionCookieById({ sessionId });
return deleteSession(session.id, session.token)
.then(() => {

View File

@@ -4,7 +4,7 @@ import {
registerPasskey,
registerU2F,
} from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
@@ -12,7 +12,7 @@ export async function POST(request: NextRequest) {
if (body) {
const { sessionId } = body;
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -1,5 +1,5 @@
import { getSession, verifyU2FRegistration } from "@/lib/zitadel";
import { getSessionCookieById } from "@/utils/cookies";
import { getSessionCookieById } from "@zitadel/next";
import { NextRequest, NextResponse, userAgent } from "next/server";
import { VerifyU2FRegistrationRequest } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { PlainMessage } from "@zitadel/client";
@@ -15,7 +15,7 @@ export async function POST(request: NextRequest) {
device.vendor || device.model ? ", " : ""
}${os.name}${os.name ? ", " : ""}${browser.name}`;
}
const sessionCookie = await getSessionCookieById(sessionId);
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession(sessionCookie.id, sessionCookie.token);

View File

@@ -6,7 +6,7 @@ import {
listSessions,
startIdentityProviderFlow,
} from "@/lib/zitadel";
import { SessionCookie, getAllSessions } from "@/utils/cookies";
import { getAllSessions } from "@zitadel/next";
import { NextRequest, NextResponse } from "next/server";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import {
@@ -52,7 +52,7 @@ export async function GET(request: NextRequest) {
const authRequestId = searchParams.get("authRequest");
const sessionId = searchParams.get("sessionId");
const sessionCookies: SessionCookie[] = await getAllSessions();
const sessionCookies = await getAllSessions();
const ids = sessionCookies.map((s) => s.id);
let sessions: Session[] = [];
if (ids && ids.length) {

View File

@@ -1,54 +1,8 @@
import { demos } from "@/lib/demos";
import Link from "next/link";
import { redirect } from "next/navigation";
export default function Page() {
return (
<div className="rounded-lg bg-vc-border-gradient dark:bg-dark-vc-border-gradient p-px shadow-lg shadow-black/5 dark:shadow-black/20 mb-10">
<div className="rounded-lg bg-background-light-400 dark:bg-background-dark-500 px-8 py-12">
<div className="space-y-8">
<h1 className="text-xl font-medium">Pages</h1>
<div className="space-y-10">
{demos.map((section) => {
return (
<div key={section.name} className="space-y-5">
<div className="text-xs font-semibold uppercase tracking-wider text-gray-500">
{section.name}
</div>
<div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
{section.items.map((item) => {
return (
<Link
href={`/${item.slug}`}
key={item.name}
className="bg-background-light-400 dark:bg-background-dark-400 group block space-y-1.5 rounded-md px-5 py-3 hover:shadow-lg hover:dark:bg-white/10 border border-divider-light dark:border-divider-dark transition-all "
>
<div className="font-medium">{item.name}</div>
{item.description ? (
<div className="line-clamp-3 text-sm text-text-light-secondary-500 dark:text-text-dark-secondary-500">
{item.description}
</div>
) : null}
</Link>
);
})}
</div>
</div>
);
})}
</div>
<div className="flex flex-col">
<div className="mb-5 text-xs font-semibold uppercase tracking-wider text-gray-500">
Deploy your own on Vercel
</div>
<a href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fzitadel%2Ftypescript&root-directory=apps/login&env=ZITADEL_API_URL,ZITADEL_SERVICE_USER_ID,ZITADEL_SERVICE_USER_TOKEN&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">
<img src="https://vercel.com/button" alt="Deploy with Vercel" />
</a>
</div>
</div>
</div>
</div>
);
// automatically redirect to loginname
if (process.env.DEBUG !== "true") {
redirect("/loginname");
}
}

View File

@@ -1,5 +1,5 @@
import { listSessions } from "@/lib/zitadel";
import { SessionCookie, getAllSessions } from "@/utils/cookies";
import { getAllSessions } from "@zitadel/next";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { NextRequest, NextResponse } from "next/server";
@@ -12,7 +12,7 @@ async function loadSessions(ids: string[]): Promise<Session[]> {
}
export async function GET(request: NextRequest) {
const sessionCookies: SessionCookie[] = await getAllSessions();
const sessionCookies = await getAllSessions();
const ids = sessionCookies.map((s) => s.id);
let sessions: Session[] = [];
if (ids && ids.length) {

View File

@@ -7,6 +7,7 @@ export type Item = {
export enum ProviderSlug {
GOOGLE = "google",
GITHUB = "github",
AZURE = "microsoft",
}
export const demos: { name: string; items: Item[] }[] = [

View File

@@ -1,6 +1,6 @@
"use server";
import { getMostRecentCookieWithLoginname } from "@/utils/cookies";
import { getMostRecentCookieWithLoginname } from "@zitadel/next";
import { getSession, verifyTOTPRegistration } from "./zitadel";
export async function verifyTOTP(
@@ -8,7 +8,7 @@ export async function verifyTOTP(
loginName?: string,
organization?: string,
) {
return getMostRecentCookieWithLoginname(loginName, organization)
return getMostRecentCookieWithLoginname({ loginName, organization })
.then((recent) => {
return getSession(recent.id, recent.token).then((response) => {
return { session: response?.session, token: recent.token };

View File

@@ -298,6 +298,7 @@ export const PROVIDER_NAME_MAPPING: {
} = {
[ProviderSlug.GOOGLE]: "Google",
[ProviderSlug.GITHUB]: "GitHub",
[ProviderSlug.AZURE]: "Microft",
};
export async function startIdentityProviderFlow({

View File

@@ -19,6 +19,10 @@ export function middleware(request: NextRequest) {
// this is a workaround for the next.js server not forwarding the host header
requestHeaders.set("x-zitadel-forwarded", `host="${request.nextUrl.host}"`);
// requestHeaders.set("x-zitadel-public-host", `${request.nextUrl.host}`);
// this is a workaround for the next.js server not forwarding the host header
// requestHeaders.set("x-zitadel-instance-host", `${INSTANCE}`);
const responseHeaders = new Headers();
responseHeaders.set("Access-Control-Allow-Origin", "*");

View File

@@ -2,6 +2,7 @@
import { ColorShade, getColorHash } from "@/utils/colors";
import { useTheme } from "next-themes";
import Image from "next/image";
interface AvatarProps {
name: string | null | undefined;
@@ -71,14 +72,17 @@ export function Avatar({
: size === "base"
? "w-[38px] h-[38px] font-bold"
: size === "small"
? "w-[32px] h-[32px] font-bold text-[13px]"
: ""
? "!w-[32px] !h-[32px] font-bold text-[13px]"
: "w-12 h-12"
}`}
style={resolvedTheme === "light" ? avatarStyleLight : avatarStyleDark}
>
{imageUrl ? (
<img
className="border border-divider-light dark:border-divider-dark rounded-full w-12 h-12"
<Image
height={48}
width={48}
alt="avatar"
className="w-full h-full border border-divider-light dark:border-divider-dark rounded-full"
src={imageUrl}
/>
) : (

View File

@@ -1,4 +1,5 @@
"use client";
import { ZitadelReactProvider } from "@zitadel/react";
import { useTheme } from "next-themes";

View File

@@ -55,32 +55,38 @@ export default function SessionItem({
return (
<Link
href={
validUser
validUser && authRequestId
? `/login?` +
new URLSearchParams(
authRequestId
? {
// loginName: session.factors?.user?.loginName as string,
sessionId: session.id,
authRequest: authRequestId,
}
: {
loginName: session.factors?.user?.loginName as string,
},
)
: `/loginname?` +
new URLSearchParams(
authRequestId
? {
loginName: session.factors?.user?.loginName as string,
submit: "true",
authRequestId,
}
: {
loginName: session.factors?.user?.loginName as string,
submit: "true",
},
)
new URLSearchParams({
// loginName: session.factors?.user?.loginName as string,
sessionId: session.id,
authRequest: authRequestId,
})
: !validUser
? `/loginname?` +
new URLSearchParams(
authRequestId
? {
loginName: session.factors?.user?.loginName as string,
submit: "true",
authRequestId,
}
: {
loginName: session.factors?.user?.loginName as string,
submit: "true",
},
)
: "/signedin?" +
new URLSearchParams(
authRequestId
? {
loginName: session.factors?.user?.loginName as string,
authRequestId,
}
: {
loginName: session.factors?.user?.loginName as string,
},
)
}
className="group flex flex-row items-center bg-background-light-400 dark:bg-background-dark-400 border border-divider-light hover:shadow-lg dark:hover:bg-white/10 py-2 px-4 rounded-md transition-all"
>

View File

@@ -102,7 +102,13 @@ export function SignInWithIDP({
return (
<SignInWithAzureAD
key={`idp-${i}`}
onClick={() => alert("TODO: unimplemented")}
onClick={() =>
startFlow(idp.id, ProviderSlug.AZURE).then(
({ authUrl }) => {
router.push(authUrl);
},
)
}
></SignInWithAzureAD>
);
case 10: // IdentityProviderType.IDENTITY_PROVIDER_TYPE_GOOGLE:
@@ -143,10 +149,6 @@ export function SignInWithIDP({
<Alert>{error}</Alert>
</div>
)}
<div className="mt-8 flex w-full flex-row items-center pt-4">
<BackButton />
<span className="flex-grow"></span>
</div>
</div>
);
}

View File

@@ -11,6 +11,7 @@ import {
LoginSettings,
PasskeysType,
} from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import BackButton from "./BackButton";
type Inputs = {
loginName: string;
@@ -23,6 +24,7 @@ type Props = {
organization?: string;
submit: boolean;
allowRegister: boolean;
children?: React.ReactNode;
};
export default function UsernameForm({
@@ -32,6 +34,7 @@ export default function UsernameForm({
organization,
submit,
allowRegister,
children,
}: Props) {
const { register, handleSubmit, formState } = useForm<Inputs>({
mode: "onBlur",
@@ -220,6 +223,16 @@ export default function UsernameForm({
{...register("loginName", { required: "This field is required" })}
label="Loginname"
/>
{allowRegister && (
<button
className="transition-all text-sm hover:text-primary-light-500 dark:hover:text-primary-dark-500"
onClick={() => router.push("/register")}
type="button"
disabled={loading}
>
Register new user
</button>
)}
</div>
{error && (
@@ -228,17 +241,10 @@ export default function UsernameForm({
</div>
)}
<div className="mt-8 flex w-full flex-row items-center">
{allowRegister && (
<Button
type="button"
className="self-end"
variant={ButtonVariants.Secondary}
onClick={() => router.push("/register")}
>
register
</Button>
)}
<div className="pt-6 pb-4">{children}</div>
<div className="mt-4 flex w-full flex-row items-center">
<BackButton />
<span className="flex-grow"></span>
<Button
type="submit"

View File

@@ -6,11 +6,7 @@ import {
getSession,
setSession,
} from "@/lib/zitadel";
import {
SessionCookie,
addSessionToCookie,
updateSessionCookie,
} from "./cookies";
import { addSessionToCookie, updateSessionCookie } from "@zitadel/next";
import {
Challenges,
RequestChallenges,
@@ -19,6 +15,17 @@ import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { PlainMessage } from "@zitadel/client";
type CustomCookieData = {
id: string;
token: string;
loginName: string;
organization?: string;
creationDate: string;
expirationDate: string;
changeDate: string;
authRequestId?: string; // if its linked to an OIDC flow
};
export async function createSessionAndUpdateCookie(
loginName: string,
password: string | undefined,
@@ -43,7 +50,7 @@ export async function createSessionAndUpdateCookie(
createdSession.sessionToken,
).then((response) => {
if (response?.session && response.session?.factors?.user?.loginName) {
const sessionCookie: SessionCookie = {
const sessionCookie: any = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationDate: `${response.session.creationDate?.toDate().getTime() ?? ""}`,
@@ -61,7 +68,7 @@ export async function createSessionAndUpdateCookie(
sessionCookie.organization = organization;
}
return addSessionToCookie(sessionCookie).then(() => {
return addSessionToCookie<CustomCookieData>(sessionCookie).then(() => {
return response.session as Session;
});
} else {
@@ -96,7 +103,7 @@ export async function createSessionForUserIdAndUpdateCookie(
createdSession.sessionToken,
).then((response) => {
if (response?.session && response.session?.factors?.user?.loginName) {
const sessionCookie: SessionCookie = {
const sessionCookie: any = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationDate: `${response.session.creationDate?.toDate().getTime() ?? ""}`,
@@ -146,7 +153,7 @@ export async function createSessionForIdpAndUpdateCookie(
createdSession.sessionToken,
).then((response) => {
if (response?.session && response.session?.factors?.user?.loginName) {
const sessionCookie: SessionCookie = {
const sessionCookie: any = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationDate: `${response.session.creationDate?.toDate().getTime() ?? ""}`,
@@ -181,7 +188,7 @@ export type SessionWithChallenges = Session & {
};
export async function setSessionAndUpdateCookie(
recentCookie: SessionCookie,
recentCookie: CustomCookieData,
checks: PlainMessage<Checks>,
challenges: RequestChallenges | undefined,
authRequestId: string | undefined,
@@ -193,7 +200,7 @@ export async function setSessionAndUpdateCookie(
checks,
).then((updatedSession) => {
if (updatedSession) {
const sessionCookie: SessionCookie = {
const sessionCookie: CustomCookieData = {
id: recentCookie.id,
token: updatedSession.sessionToken,
creationDate: recentCookie.creationDate,
@@ -211,7 +218,7 @@ export async function setSessionAndUpdateCookie(
(response) => {
if (response?.session && response.session.factors?.user?.loginName) {
const { session } = response;
const newCookie: SessionCookie = {
const newCookie: CustomCookieData = {
id: sessionCookie.id,
token: updatedSession.sessionToken,
creationDate: sessionCookie.creationDate,

View File

@@ -1,4 +1,4 @@
const sharedConfig = require("zitadel-tailwind-config/tailwind.config.js");
const sharedConfig = require("zitadel-tailwind-config/tailwind.config.mjs");
let colors = {
background: { light: { contrast: {} }, dark: { contrast: {} } },

View File

@@ -9,28 +9,32 @@
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
},
"test:integration": {
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
},
"test:unit": {
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
},
"test:watch": {
"dependsOn": [
"@zitadel/node#build",
"@zitadel/client#build",
"@zitadel/react#build"
"@zitadel/react#build",
"@zitadel/next#build"
]
}
}

View File

@@ -26,7 +26,7 @@
"devDependencies": {
"@changesets/cli": "^2.22.0",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.0",
"eslint": "8.57.0",
"eslint-config-zitadel": "workspace:*",
"prettier": "^3.2.5",
"prettier-plugin-organize-imports": "^4.0.0",

View File

@@ -6,6 +6,7 @@
"types": "./dist/index.d.ts",
"sideEffects": false,
"license": "MIT",
"type": "module",
"files": [
"dist/**"
],
@@ -25,6 +26,8 @@
"peerDependencies": {
"@zitadel/node": "workspace:*",
"@zitadel/react": "workspace:*",
"@zitadel/client": "workspace:*",
"@zitadel/proto": "workspace:*",
"next": "^14.2.3",
"react": "18.2.0"
},

View File

@@ -1,6 +1,5 @@
import "./styles.css";
// import "./styles.css";
export {
ZitadelNextProvider,
type ZitadelNextProps,
} from "./components/ZitadelNextProvider";
export { ZitadelNextProvider, type ZitadelNextProps } from "./components/ZitadelNextProvider";
export * from "./utils/cookies";
export { loadMostRecentSession } from "./utils/session";

View File

@@ -2,7 +2,7 @@
import { cookies } from "next/headers";
export type SessionCookie = {
export type Cookie = {
id: string;
token: string;
loginName: string;
@@ -13,7 +13,9 @@ export type SessionCookie = {
authRequestId?: string; // if its linked to an OIDC flow
};
function setSessionHttpOnlyCookie(sessions: SessionCookie[]) {
type SessionCookie<T> = Cookie & T;
function setSessionHttpOnlyCookie<T>(sessions: SessionCookie<T>[]) {
const cookiesList = cookies();
// @ts-ignore
return cookiesList.set({
@@ -24,20 +26,13 @@ function setSessionHttpOnlyCookie(sessions: SessionCookie[]) {
});
}
export async function addSessionToCookie(
session: SessionCookie,
cleanup: boolean = false,
): Promise<any> {
export async function addSessionToCookie<T>(session: SessionCookie<T>, cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
let currentSessions: SessionCookie[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [];
let currentSessions: SessionCookie<T>[] = stringifiedCookie?.value ? JSON.parse(stringifiedCookie?.value) : [];
const index = currentSessions.findIndex(
(s) => s.loginName === session.loginName,
);
const index = currentSessions.findIndex((s) => s.loginName === session.loginName);
if (index > -1) {
currentSessions[index] = session;
@@ -56,17 +51,11 @@ export async function addSessionToCookie(
}
}
export async function updateSessionCookie(
id: string,
session: SessionCookie,
cleanup: boolean = false,
): Promise<any> {
export async function updateSessionCookie<T>(id: string, session: SessionCookie<T>, cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
const sessions: SessionCookie[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [session];
const sessions: SessionCookie<T>[] = stringifiedCookie?.value ? JSON.parse(stringifiedCookie?.value) : [session];
const foundIndex = sessions.findIndex((session) => session.id === id);
@@ -82,20 +71,15 @@ export async function updateSessionCookie(
return setSessionHttpOnlyCookie(sessions);
}
} else {
throw "updateSessionCookie: session id now found";
throw "updateSessionCookie<T>: session id now found";
}
}
export async function removeSessionFromCookie(
session: SessionCookie,
cleanup: boolean = false,
): Promise<any> {
export async function removeSessionFromCookie<T>(session: SessionCookie<T>, cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
const sessions: SessionCookie[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [session];
const sessions: SessionCookie<T>[] = stringifiedCookie?.value ? JSON.parse(stringifiedCookie?.value) : [session];
const reducedSessions = sessions.filter((s) => s.id !== session.id);
if (cleanup) {
@@ -109,18 +93,15 @@ export async function removeSessionFromCookie(
}
}
export async function getMostRecentSessionCookie(): Promise<any> {
export async function getMostRecentSessionCookie<T>(): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const latest = sessions.reduce((prev, current) => {
return new Date(prev.changeDate).getTime() >
new Date(current.changeDate).getTime()
? prev
: current;
return new Date(prev.changeDate).getTime() > new Date(current.changeDate).getTime() ? prev : current;
});
return latest;
@@ -129,20 +110,21 @@ export async function getMostRecentSessionCookie(): Promise<any> {
}
}
export async function getSessionCookieById(
id: string,
organization?: string,
): Promise<SessionCookie> {
export async function getSessionCookieById<T>({
sessionId,
organization,
}: {
sessionId: string;
organization?: string;
}): Promise<SessionCookie<T>> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const found = sessions.find((s) =>
organization
? s.organization === organization && s.id === id
: s.id === id,
organization ? s.organization === organization && s.id === sessionId : s.id === sessionId,
);
if (found) {
return found;
@@ -154,19 +136,20 @@ export async function getSessionCookieById(
}
}
export async function getSessionCookieByLoginName(
loginName: string,
organization?: string,
): Promise<SessionCookie> {
export async function getSessionCookieByLoginName<T>({
loginName,
organization,
}: {
loginName?: string;
organization?: string;
}): Promise<SessionCookie<T>> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const found = sessions.find((s) =>
organization
? s.organization === organization && s.loginName === loginName
: s.loginName === loginName,
organization ? s.organization === organization && s.loginName === loginName : s.loginName === loginName,
);
if (found) {
return found;
@@ -183,23 +166,17 @@ export async function getSessionCookieByLoginName(
* @param cleanup when true, removes all expired sessions, default true
* @returns Session Cookies
*/
export async function getAllSessionCookieIds(
cleanup: boolean = false,
): Promise<any> {
export async function getAllSessionCookieIds<T>(cleanup: boolean = false): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
if (cleanup) {
const now = new Date();
return sessions
.filter((session) =>
session.expirationDate
? new Date(session.expirationDate) > now
: true,
)
.filter((session) => (session.expirationDate ? new Date(session.expirationDate) > now : true))
.map((session) => session.id);
} else {
return sessions.map((session) => session.id);
@@ -214,20 +191,16 @@ export async function getAllSessionCookieIds(
* @param cleanup when true, removes all expired sessions, default true
* @returns Session Cookies
*/
export async function getAllSessions(
cleanup: boolean = false,
): Promise<SessionCookie[]> {
export async function getAllSessions<T>(cleanup: boolean = false): Promise<SessionCookie<T>[]> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
if (cleanup) {
const now = new Date();
return sessions.filter((session) =>
session.expirationDate ? new Date(session.expirationDate) > now : true,
);
return sessions.filter((session) => (session.expirationDate ? new Date(session.expirationDate) > now : true));
} else {
return sessions;
}
@@ -238,18 +211,22 @@ export async function getAllSessions(
/**
* Returns most recent session filtered by optinal loginName
* @param loginName
* @param loginName optional loginName to filter cookies, if non provided, returns most recent session
* @param organization optional organization to filter cookies
* @returns most recent session
*/
export async function getMostRecentCookieWithLoginname(
loginName?: string,
organization?: string,
): Promise<any> {
export async function getMostRecentCookieWithLoginname<T>({
loginName,
organization,
}: {
loginName?: string;
organization?: string;
}): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
let filtered = sessions.filter((cookie) => {
return !!loginName ? cookie.loginName === loginName : true;
});
@@ -263,10 +240,7 @@ export async function getMostRecentCookieWithLoginname(
const latest =
filtered && filtered.length
? filtered.reduce((prev, current) => {
return new Date(prev.changeDate).getTime() >
new Date(current.changeDate).getTime()
? prev
: current;
return new Date(prev.changeDate).getTime() > new Date(current.changeDate).getTime() ? prev : current;
})
: undefined;
@@ -280,5 +254,3 @@ export async function getMostRecentCookieWithLoginname(
return Promise.reject("Could not read session cookie");
}
}
export async function clearSessions() {}

View File

@@ -0,0 +1,16 @@
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { GetSessionResponse } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { getMostRecentCookieWithLoginname } from "./cookies";
export async function loadMostRecentSession(
sessionService: any, // TODO: SessionServiceClient,
sessionParams: { loginName?: string; organization?: string },
): Promise<Session | undefined> {
const recent = await getMostRecentCookieWithLoginname({
loginName: sessionParams.loginName,
organization: sessionParams.organization,
});
return sessionService
.getSession({ sessionId: recent.id, sessionToken: recent.token }, {})
.then((resp: GetSessionResponse) => resp.session);
}

View File

@@ -1,4 +1,4 @@
const sharedConfig = require("zitadel-tailwind-config/tailwind.config.js");
const sharedConfig = require("zitadel-tailwind-config/tailwind.config.mjs");
/** @type {import('tailwindcss').Config} */
module.exports = {

View File

@@ -1,20 +1,9 @@
{
"extends": [
"//"
],
"extends": ["//"],
"tasks": {
"dev": {
"dependsOn": [
"@zitadel/react#build"
]
},
"build": {
"outputs": [
"dist/**"
],
"dependsOn": [
"@zitadel/react#build"
]
"outputs": ["dist/**"],
"dependsOn": ["@zitadel/client#build", "@zitadel/react#build"]
}
}
}

View File

@@ -3,7 +3,7 @@
"tasks": {
"generate": {
"outputs": ["zitadel/**"],
"cache": false
"cache": true
}
}
}

View File

@@ -1,4 +1,4 @@
const sharedConfig = require("zitadel-tailwind-config/tailwind.config.js");
const sharedConfig = require("zitadel-tailwind-config/tailwind.config.mjs");
/** @type {import('tailwindcss').Config} */
module.exports = {

9810
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,7 @@
{
"$schema": "https://turbo.build/schema.json",
"ui": "tui",
"globalDependencies": [
"**/.env.*local"
],
"globalDependencies": ["**/.env.*local"],
"globalEnv": [
"DEBUG",
"ZITADEL_API_URL",