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 #64

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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,108 @@
"use client";

import React 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("");


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>
)}
<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}
>
<div className="flex flex-col gap-2">
<Typography className="mb-4">
Please change your password soon to ensure account security.
N2D4 marked this conversation as resolved.
Show resolved Hide resolved
</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,
});
console.log(res)
if(res){

setcurrentUserPassword(res)
setShowNotifyPasswordDialog(true);
}

};

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

async signUpWithCredential(
email: string,
password: string,
password: string | null,
emailVerificationRedirectUrl: string,
tokenStore: TokenStore,
tokenStore: TokenStore | null,
): Promise<KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"] | undefined> {
const requestBody = {
email,
password,
emailVerificationRedirectUrl,
};

const headers = {
"Content-Type": "application/json",
};

const requestOptions = {
headers,
method: "POST",
body: JSON.stringify(requestBody),
};

const res = await this.sendClientRequestAndCatchKnownError(
"/auth/signup",
{
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify({
email,
password,
emailVerificationRedirectUrl,
}),
},
requestOptions,
tokenStore,
[KnownErrors.UserEmailAlreadyExists, KnownErrors.PasswordRequirementsNotMet]
);

if (res.status === "error") {
return res.error;
}

const result = await res.data.json();
tokenStore.set({
accessToken: result.accessToken,
refreshToken: result.refreshToken,
});

if (tokenStore) {
const result = await res.data.json();
tokenStore.set({
accessToken: result.accessToken,
refreshToken: result.refreshToken,
});
}
}

async signInWithMagicLink(code: string, tokenStore: TokenStore): Promise<KnownErrors["MagicLinkError"] | { newUser: boolean }> {
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 @@ -21,6 +21,7 @@ import { EmailTemplateType, ServerPermissionDefinitionCustomizableJson, ServerPe
import { EmailTemplateCrud, ListEmailTemplatesCrud } from "@stackframe/stack-shared/dist/interface/crud/email-templates";
import { scrambleDuringCompileTime } from "@stackframe/stack-shared/dist/utils/compile-time";
import { isReactServer } from "@stackframe/stack-sc";
import { generateSecureRandomString } from "@stackframe/stack-shared/dist/utils/crypto";
import * as cookie from "cookie";

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

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) {
return password
}
return errorCode;
}

async signUpWithCredential(options: {
email: string,
Expand Down Expand Up @@ -1759,6 +1777,7 @@ export type StackClientApp<HasTokenStore extends boolean = boolean, ProjectId ex

signInWithOAuth(provider: string): Promise<void>,
signInWithCredential(options: { email: string, password: string }): Promise<KnownErrors["EmailPasswordMismatch"] | undefined>,
createUserWithCredential(options: { email: string }): Promise<string | KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"] | undefined>,
signUpWithCredential(options: { email: string, password: string }): Promise<KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"] | undefined>,
callOAuthCallback(): Promise<boolean>,
sendForgotPasswordEmail(email: string): Promise<KnownErrors["UserNotFound"] | undefined>,
Expand Down