typing server action responses

This commit is contained in:
peintnermax
2024-09-16 15:57:42 +02:00
parent 4077353048
commit 604c56758b
9 changed files with 65 additions and 26 deletions

View File

@@ -18,7 +18,7 @@ export async function resetPassword(command: ResetPasswordCommand) {
users.details.totalResult !== BigInt(1) || users.details.totalResult !== BigInt(1) ||
!users.result[0].userId !users.result[0].userId
) { ) {
throw Error("Could not find user"); return { error: "Could not find user" };
} }
const userId = users.result[0].userId; const userId = users.result[0].userId;

View File

@@ -2,6 +2,7 @@
import { addHumanUser } from "@/lib/zitadel"; import { addHumanUser } from "@/lib/zitadel";
import { createSessionForUserIdAndUpdateCookie } from "@/utils/session"; import { createSessionForUserIdAndUpdateCookie } from "@/utils/session";
import { Factors } from "@zitadel/proto/zitadel/session/v2/session_pb";
type RegisterUserCommand = { type RegisterUserCommand = {
email: string; email: string;
@@ -11,6 +12,13 @@ type RegisterUserCommand = {
organization?: string; organization?: string;
authRequestId?: string; authRequestId?: string;
}; };
export type RegisterUserResponse = {
userId: string;
sessionId: string;
factors: Factors | undefined;
};
export async function registerUser(command: RegisterUserCommand) { export async function registerUser(command: RegisterUserCommand) {
const human = await addHumanUser({ const human = await addHumanUser({
email: command.email, email: command.email,
@@ -19,8 +27,9 @@ export async function registerUser(command: RegisterUserCommand) {
password: command.password ? command.password : undefined, password: command.password ? command.password : undefined,
organization: command.organization, organization: command.organization,
}); });
if (!human) { if (!human) {
throw Error("Could not create user"); return { error: "Could not create user" };
} }
return createSessionForUserIdAndUpdateCookie( return createSessionForUserIdAndUpdateCookie(

View File

@@ -23,6 +23,10 @@ export async function addU2F(command: RegisterU2FCommand) {
sessionId: command.sessionId, sessionId: command.sessionId,
}); });
if (!sessionCookie) {
return { error: "Could not get session" };
}
const session = await getSession({ const session = await getSession({
sessionId: sessionCookie.id, sessionId: sessionCookie.id,
sessionToken: sessionCookie.token, sessionToken: sessionCookie.token,
@@ -31,14 +35,15 @@ export async function addU2F(command: RegisterU2FCommand) {
const domain = headers().get("host"); const domain = headers().get("host");
if (!domain) { if (!domain) {
throw Error("Could not get domain"); return { error: "Could not get domain" };
} }
const userId = session?.session?.factors?.user?.id; const userId = session?.session?.factors?.user?.id;
if (!userId) { if (!session || !userId) {
throw Error("Could not get session"); return { error: "Could not get session" };
} }
return registerU2F(userId, domain); return registerU2F(userId, domain);
} }
@@ -65,7 +70,7 @@ export async function verifyU2F(command: VerifyU2FCommand) {
const userId = session?.session?.factors?.user?.id; const userId = session?.session?.factors?.user?.id;
if (!userId) { if (!userId) {
throw new Error("Could not get session"); return { error: "Could not get session" };
} }
const req = create(VerifyU2FRegistrationRequestSchema, { const req = create(VerifyU2FRegistrationRequestSchema, {

View File

@@ -451,7 +451,7 @@ export function createUser(
* @param userId the id of the user where the email should be set * @param userId the id of the user where the email should be set
* @returns the newly set email * @returns the newly set email
*/ */
export async function passwordReset(userId: string): Promise<any> { export async function passwordReset(userId: string) {
return userService.passwordReset( return userService.passwordReset(
{ {
userId, userId,

View File

@@ -77,10 +77,15 @@ export default function PasswordForm({
loginName, loginName,
organization, organization,
}).catch((error: Error) => { }).catch((error: Error) => {
console.error(error);
setLoading(false); setLoading(false);
setError(error.message ?? "Could not reset password"); setError("Could not reset password");
}); });
if (response && "error" in response) {
setError(response.error);
}
setLoading(false); setLoading(false);
if (response) { if (response) {

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { registerUser } from "@/lib/server/register"; import { registerUser, RegisterUserResponse } from "@/lib/server/register";
import { LegalAndSupportSettings } from "@zitadel/proto/zitadel/settings/v2/legal_settings_pb"; import { LegalAndSupportSettings } from "@zitadel/proto/zitadel/settings/v2/legal_settings_pb";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
@@ -63,10 +63,15 @@ export default function RegisterFormWithoutPassword({
lastName: values.lastname, lastName: values.lastname,
organization: organization, organization: organization,
}).catch((error) => { }).catch((error) => {
setError(error.message ?? "Could not register user"); console.error(error);
setError("Could not register user");
setLoading(false); setLoading(false);
}); });
if (response && "error" in response) {
setError(response.error);
}
setLoading(false); setLoading(false);
return response; return response;
@@ -89,7 +94,7 @@ export default function RegisterFormWithoutPassword({
if (withPassword) { if (withPassword) {
return router.push(`/register?` + new URLSearchParams(registerParams)); return router.push(`/register?` + new URLSearchParams(registerParams));
} else { } else {
const session = await submitAndRegister(value); const session = (await submitAndRegister(value)) as RegisterUserResponse;
const params = new URLSearchParams({}); const params = new URLSearchParams({});
if (session?.factors?.user?.loginName) { if (session?.factors?.user?.loginName) {

View File

@@ -2,6 +2,7 @@
import { addU2F, verifyU2F } from "@/lib/server/u2f"; import { addU2F, verifyU2F } from "@/lib/server/u2f";
import { coerceToArrayBuffer, coerceToBase64Url } from "@/utils/base64"; import { coerceToArrayBuffer, coerceToBase64Url } from "@/utils/base64";
import { RegisterU2FResponse } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import Alert from "./Alert"; import Alert from "./Alert";
@@ -9,8 +10,6 @@ import BackButton from "./BackButton";
import { Button, ButtonVariants } from "./Button"; import { Button, ButtonVariants } from "./Button";
import { Spinner } from "./Spinner"; import { Spinner } from "./Spinner";
type Inputs = {};
type Props = { type Props = {
sessionId: string; sessionId: string;
authRequestId?: string; authRequestId?: string;
@@ -41,8 +40,9 @@ export default function RegisterU2F({
publicKeyCredential, publicKeyCredential,
sessionId, sessionId,
}).catch((error: Error) => { }).catch((error: Error) => {
console.error(error);
setLoading(false); setLoading(false);
setError(error.message); setError("An error on verifying passkey occurred");
}); });
setLoading(false); setLoading(false);
@@ -55,20 +55,27 @@ export default function RegisterU2F({
setLoading(true); setLoading(true);
const response = await addU2F({ const response = await addU2F({
sessionId, sessionId,
}).catch((error) => { }).catch((error: Error) => {
console.error(error);
setLoading(false); setLoading(false);
setError(error.message); setError("An error on registering passkey");
}); });
if (!response) { if (response && "error" in response && response?.error) {
setError(response?.error);
}
if (!response || "u2fId" in response) {
setLoading(false); setLoading(false);
setError("An error on registering passkey"); setError("An error on registering passkey");
return; return;
} }
const u2fId = response?.u2fId; const u2fResponse = response as unknown as RegisterU2FResponse;
const u2fId = u2fResponse.u2fId;
const options: CredentialCreationOptions = const options: CredentialCreationOptions =
(response?.publicKeyCredentialCreationOptions as CredentialCreationOptions) ?? (u2fResponse?.publicKeyCredentialCreationOptions as CredentialCreationOptions) ??
{}; {};
if (options.publicKey) { if (options.publicKey) {

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { registerUser } from "@/lib/server/register"; import { registerUser, RegisterUserResponse } from "@/lib/server/register";
import { import {
lowerCaseValidator, lowerCaseValidator,
numberValidator, numberValidator,
@@ -66,9 +66,14 @@ export default function SetPasswordForm({
authRequestId: authRequestId, authRequestId: authRequestId,
password: values.password, password: values.password,
}).catch((error: Error) => { }).catch((error: Error) => {
setError(error.message ?? "Could not register user"); console.error(error);
setError("Could not register user");
}); });
if (response && "error" in response) {
setError(response.error);
}
setLoading(false); setLoading(false);
if (!response) { if (!response) {
@@ -76,10 +81,12 @@ export default function SetPasswordForm({
return; return;
} }
const params = new URLSearchParams({ userId: response.userId }); const userReponse = response as RegisterUserResponse;
if (response.factors?.user?.loginName) { const params = new URLSearchParams({ userId: userReponse.userId });
params.append("loginName", response.factors.user.loginName);
if (userReponse.factors?.user?.loginName) {
params.append("loginName", userReponse.factors.user.loginName);
} }
if (authRequestId) { if (authRequestId) {
params.append("authRequestId", authRequestId); params.append("authRequestId", authRequestId);
@@ -87,8 +94,8 @@ export default function SetPasswordForm({
if (organization) { if (organization) {
params.append("organization", organization); params.append("organization", organization);
} }
if (response && response.sessionId) { if (userReponse && userReponse.sessionId) {
params.append("sessionId", response.sessionId); params.append("sessionId", userReponse.sessionId);
} }
return router.push(`/verify?` + params); return router.push(`/verify?` + params);

View File

@@ -51,6 +51,7 @@ export default function UsernameForm({
organization, organization,
authRequestId, authRequestId,
}).catch((error: Error) => { }).catch((error: Error) => {
console.error(error);
setError("An internal error occurred"); setError("An internal error occurred");
}); });