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

Fixes #61: Added an option to create user on the dashboard's "User" section #73

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,24 +1,111 @@
"use client";

import React, { useState } from "react";
import * as yup from "yup";
import { useAdminApp } from "../use-admin-app";
import { PageLayout } from "../page-layout";
import { Alert } from "@/components/ui/alert";
import { StyledLink } from "@/components/link";
import { UserTable } from "@/components/data-table/user-table";
import { Button } from "@/components/ui/button";
import { SmartFormDialog } from "@/components/form-dialog";
import { ActionDialog } from "@/components/action-dialog";
import Typography from "@/components/ui/typography";


type CreateDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
setShowNotifyPasswordDialog: React.Dispatch<React.SetStateAction<boolean>>;
setcurrentUserPassword: React.Dispatch<React.SetStateAction<string>>;

};

export default function PageClient() {
const stackAdminApp = useAdminApp();
const allUsers = stackAdminApp.useServerUsers();
const [addUserOpen, setAddUserOpen] = React.useState(false);
const [showNotifyPasswordDialog, setShowNotifyPasswordDialog] = React.useState(false);
const [currentUserPassword, setcurrentUserPassword] = React.useState("");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setcurrent... -> setCurrent...



const handlePasswordNotificationClose = async () => {
setShowNotifyPasswordDialog(false);
};

return (
<PageLayout title="Users">
<PageLayout
title="Users"
actions={
<Button onClick={() => setAddUserOpen(true)}>Create users</Button>
}
>
{allUsers.length > 0 ? null : (
<Alert variant='success'>
Congratulations on starting your project! Check the <StyledLink href="https://docs.stack-auth.com">documentation</StyledLink> to add your first users.
<Alert variant="success">
Congratulations on starting your project! Check the{" "}
<StyledLink href="https://docs.stack-auth.com">
documentation
</StyledLink>{" "}
to add your first users.
</Alert>
)}
<UserTable users={allUsers} />
<CreateDialog
open={addUserOpen}
onOpenChange={setAddUserOpen}
setShowNotifyPasswordDialog={setShowNotifyPasswordDialog}
setcurrentUserPassword={setcurrentUserPassword}
/>
<ActionDialog
title="Password Change Required"
okButton={{
label: "Change Password Soon",
onClick: handlePasswordNotificationClose,
}}
open={showNotifyPasswordDialog}
onClose={handlePasswordNotificationClose}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eslint not passing: you should use runAsynchronouslyWithAlert, check out the other occurrence. Also please add the eslint plugin to vscode so the errors will be highlighted

>
<div className="flex flex-col gap-2">
<Typography className="mb-4">
Please change your password soon to ensure account security.
</Typography>
<Typography className="mb-4">
Your Current Password: {currentUserPassword}
</Typography>
</div>
</ActionDialog>
</PageLayout>
);
}

function CreateDialog({ open, onOpenChange, setShowNotifyPasswordDialog,setcurrentUserPassword }: CreateDialogProps) {
const stackAdminApp = useAdminApp();

const formSchema = yup.object({
email: yup.string().required().label("Email"),
});

const handleCreateUser = async (values: { email: string }) => {
const res= await stackAdminApp.createUserWithCredential({
email: values.email,
});
if (typeof res === 'string') {
setcurrentUserPassword(res);
setShowNotifyPasswordDialog(true);
} else {
console.error('Unexpected response:', res);
}

};

return (
<SmartFormDialog
open={open}
onOpenChange={onOpenChange}
title="Create a User"
formSchema={formSchema}
okButton={{ label: "Create User" }}
onSubmit={handleCreateUser}
cancelButton
/>
);
}
4 changes: 2 additions & 2 deletions packages/stack-shared/src/interface/clientInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -615,9 +615,9 @@ export class StackClientInterface {

async signUpWithCredential(
email: string,
password: string,
password: string | null,
emailVerificationRedirectUrl: string,
session: InternalSession,
session: InternalSession | null,
): Promise<KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"] | { accessToken: string, refreshToken: string }> {
const res = await this.sendClientRequestAndCatchKnownError(
"/auth/signup",
Expand Down
19 changes: 19 additions & 0 deletions packages/stack/src/lib/stack-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import * as cookie from "cookie";
import { InternalSession } from "@stackframe/stack-shared/dist/sessions";
import { useTrigger } from "@stackframe/stack-shared/dist/hooks/use-trigger";
import { mergeScopeStrings } from "@stackframe/stack-shared/dist/utils/strings";
import { generateSecureRandomString } from "@stackframe/stack-shared/dist/utils/crypto";


// NextNavigation.useRouter does not exist in react-server environments and some bundlers try to be helpful and throw a warning. Ignore the warning.
Expand Down Expand Up @@ -1019,6 +1020,23 @@ class _StackClientAppImpl<HasTokenStore extends boolean, ProjectId extends strin
return result;
}

async createUserWithCredential(options: {
email: string,
}): Promise<string | KnownErrors["UserEmailAlreadyExists"] | KnownErrors['PasswordRequirementsNotMet'] | undefined> {
const emailVerificationRedirectUrl = constructRedirectUrl(this.urls.emailVerification);
const password =generateSecureRandomString()
const errorCode = await this._interface.signUpWithCredential(
options.email,
password,
emailVerificationRedirectUrl,
null,
);
if (!errorCode) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a promise, you need to add await

return password
}
return errorCode;
}

async signUpWithCredential(options: {
email: string,
password: string,
Expand Down Expand Up @@ -2087,6 +2105,7 @@ export type StackClientApp<HasTokenStore extends boolean = boolean, ProjectId ex
signInWithOAuth(provider: string): Promise<void>,
signInWithCredential(options: { email: string, password: string }): Promise<KnownErrors["EmailPasswordMismatch"] | void>,
signUpWithCredential(options: { email: string, password: string }): Promise<KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"] | void>,
createUserWithCredential(options: { email: string }): Promise<string | KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"] | undefined>,
callOAuthCallback(): Promise<boolean>,
sendForgotPasswordEmail(email: string): Promise<KnownErrors["UserNotFound"] | void>,
sendMagicLinkEmail(email: string): Promise<KnownErrors["RedirectUrlNotWhitelisted"] | void>,
Expand Down