chore: updated sign in workflow (#2939)

* chore: new sign in workflow

* chore: request new code button added

* chore: create new password form added

* fix: build errors

* chore: remove unused components

* chore: update submitting state texts

* fix: oauth sign in process
This commit is contained in:
Aaryan Khandelwal 2023-11-29 19:07:33 +05:30 committed by GitHub
parent 804c03bd15
commit 6d97dd814a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 1452 additions and 1090 deletions

View File

@ -49,9 +49,9 @@ export const buttonStyling: IButtonStyling = {
disabled: `cursor-not-allowed !text-custom-primary-60`,
},
"outline-primary": {
default: `text-custom-primary-100 bg-custom-background-100 border border-custom-primary-100`,
hover: `hover:border-custom-primary-80 hover:bg-custom-primary-10`,
pressed: `focus:text-custom-primary-80 focus:bg-custom-primary-10 focus:border-custom-primary-80`,
default: `text-custom-primary-100 bg-transparent border border-custom-primary-100`,
hover: `hover:bg-custom-primary-100/20`,
pressed: `focus:text-custom-primary-100 focus:bg-custom-primary-100/30`,
disabled: `cursor-not-allowed !text-custom-primary-60 !border-custom-primary-60 `,
},
"neutral-primary": {
@ -80,7 +80,7 @@ export const buttonStyling: IButtonStyling = {
disabled: `cursor-not-allowed !text-red-300`,
},
"outline-danger": {
default: `text-red-500 bg-custom-background-100 border border-red-500`,
default: `text-red-500 bg-transparent border border-red-500`,
hover: `hover:text-red-400 hover:border-red-400`,
pressed: `focus:text-red-400 focus:border-red-400`,
disabled: `cursor-not-allowed !text-red-300 !border-red-300`,

View File

@ -1,314 +0,0 @@
import React, { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { XCircle } from "lucide-react";
// ui
import { Button, Input } from "@plane/ui";
// components
import { AuthType } from "components/page-views";
// services
import { AuthService } from "services/auth.service";
// hooks
import useToast from "hooks/use-toast";
import useTimer from "hooks/use-timer";
type EmailCodeFormValues = {
email: string;
key?: string;
token?: string;
};
const authService = new AuthService();
type Props = {
handleSignIn: any;
authType: AuthType;
};
export const EmailCodeForm: React.FC<Props> = (Props) => {
const { handleSignIn, authType } = Props;
// states
const [codeSent, setCodeSent] = useState(false);
const [codeResent, setCodeResent] = useState(false);
const [isCodeResending, setIsCodeResending] = useState(false);
const [errorResendingCode, setErrorResendingCode] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [sentEmail, setSentEmail] = useState<string>("");
const { setToastAlert } = useToast();
const { timer: resendCodeTimer, setTimer: setResendCodeTimer } = useTimer();
const {
handleSubmit,
control,
setError,
setValue,
getValues,
formState: { errors, isSubmitting, isValid, isDirty },
} = useForm<EmailCodeFormValues>({
defaultValues: {
email: "",
key: "",
token: "",
},
mode: "onChange",
reValidateMode: "onChange",
});
const isResendDisabled = resendCodeTimer > 0 || isCodeResending || isSubmitting;
const onSubmit = async ({ email }: EmailCodeFormValues) => {
setErrorResendingCode(false);
await authService
.emailCode({ email })
.then((res) => {
setSentEmail(email);
setValue("key", res.key);
setCodeSent(true);
})
.catch((err) => {
setErrorResendingCode(true);
setToastAlert({
title: "Oops!",
type: "error",
message: err?.error,
});
});
};
const handleSignin = async (formData: EmailCodeFormValues) => {
setIsLoading(true);
await authService
.magicSignIn(formData)
.then((response) => {
handleSignIn(response);
})
.catch((error) => {
setIsLoading(false);
setToastAlert({
title: "Oops!",
type: "error",
message: error?.response?.data?.error ?? "Enter the correct code to sign in",
});
setError("token" as keyof EmailCodeFormValues, {
type: "manual",
message: error?.error,
});
});
};
const emailOld = getValues("email");
useEffect(() => {
const submitForm = (e: KeyboardEvent) => {
if (!codeSent && e.key === "Enter") {
e.preventDefault();
handleSubmit(onSubmit)().then(() => {
setResendCodeTimer(30);
});
} else if (
codeSent &&
sentEmail != getValues("email") &&
getValues("email").length > 0 &&
(e.key === "Enter" || e.key === "Tab")
) {
e.preventDefault();
console.log("resend");
onSubmit({ email: getValues("email") }).then(() => {
setCodeResent(true);
});
}
};
window.addEventListener("keydown", submitForm);
return () => {
window.removeEventListener("keydown", submitForm);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [handleSubmit, codeSent, sentEmail]);
return (
<>
{codeSent || codeResent ? (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-custom-text-100">
Moving to the runway
</h1>
<div className="text-center text-sm text-onboarding-text-200 mt-3">
<p>Paste the code you got at </p>
<span className="text-center text-sm text-custom-primary-80 mt-1 font-semibold ">{sentEmail} </span>
<span className="text-onboarding-text-200">below.</span>
</div>
</>
) : (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">
{authType === "sign-in" ? "Get on your flight deck!" : "Lets get you prepped!"}
</h1>
{authType == "sign-up" ? (
<div>
<p className="text-center text-sm text-onboarding-text-200 mt-3">
This whole thing will take less than two minutes.
</p>
<p className="text-center text-sm text-onboarding-text-200 mt-1">Promise!</p>
</div>
) : (
<p className="text-center text-sm text-onboarding-text-200 px-10 sm:px-20 mt-3">
Sign in with the email you used to sign up for Plane
</p>
)}
</>
)}
<form className="mt-5 sm:w-96 mx-auto">
<div className="space-y-1">
<Controller
control={control}
name="email"
rules={{
required: "Email address is required",
validate: (value) =>
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
value
) || "Email address is not valid",
}}
render={({ field: { value, onChange, ref } }) => (
<div className={`flex items-center relative rounded-md bg-onboarding-background-200`}>
<Input
id="email"
name="email"
type="email"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className={`w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12`}
/>
{value.length > 0 && (
<XCircle
className="h-5 w-5 absolute stroke-custom-text-400 hover:cursor-pointer right-3"
onClick={() => setValue("email", "")}
/>
)}
</div>
)}
/>
</div>
{codeSent && (
<>
<div>
{codeResent && sentEmail === getValues("email") ? (
<div className="text-sm my-2.5 text-onboarding-text-300 m-0">
You got a new code at <span className="font-semibold text-custom-primary-80">{sentEmail}</span>.
</div>
) : sentEmail != getValues("email") && getValues("email").length > 0 ? (
<div className="text-sm my-2.5 text-onboarding-text-300 m-0">
Hit enter
<span> </span>or <span className="italic">Tab</span> to get a new code
</div>
) : (
<div className="my-4" />
)}
</div>
<div className={`flex items-center relative rounded-md bg-onboarding-background-200`}>
<Controller
control={control}
name="token"
rules={{
required: "Code is required",
}}
render={({ field: { value, onChange, ref } }) => (
<Input
id="token"
name="token"
type="token"
value={value ?? ""}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.token)}
placeholder="gets-sets-flys"
className="border-onboarding-border-100 h-[46px] w-full"
/>
)}
/>
{resendCodeTimer <= 0 && !isResendDisabled && (
<button
type="button"
className={`flex absolute w-fit right-3.5 justify-end text-xs outline-none cursor-pointer text-custom-primary-100`}
onClick={() => {
setIsCodeResending(true);
onSubmit({ email: getValues("email") }).then(() => {
setCodeResent(true);
setIsCodeResending(false);
setResendCodeTimer(30);
});
}}
disabled={isResendDisabled}
>
<span className="font-medium">Resend</span>
</button>
)}
</div>
<div
className={`flex w-full justify-end text-xs outline-none ${
isResendDisabled ? "cursor-default text-custom-text-200" : "cursor-pointer text-custom-primary-100"
} `}
>
{resendCodeTimer > 0 ? (
<span className="text-right">Request new code in {resendCodeTimer}s</span>
) : isCodeResending ? (
"Sending new code..."
) : null}
</div>
</>
)}
{codeSent ? (
<div className="my-4">
{" "}
<Button
variant="primary"
type="submit"
className="w-full"
size="xl"
onClick={handleSubmit(handleSignin)}
disabled={!isValid && isDirty}
loading={isLoading}
>
{isLoading ? "Signing in..." : "Next step"}
</Button>
<div className="w-3/4 my-4 mx-auto">
<p className="text-xs text-center text-onboarding-text-300">
When you click the button above, you agree with our{" "}
<a
href="https://plane.so/terms-and-conditions"
target="_blank"
rel="noopener noreferrer"
className="font-medium underline"
>
terms and conditions of service.
</a>{" "}
</p>
</div>
</div>
) : (
<Button
variant="primary"
className="w-full mt-4"
size="xl"
onClick={() => {
handleSubmit(onSubmit)().then(() => {
setResendCodeTimer(30);
});
}}
disabled={!isValid && isDirty}
loading={isSubmitting}
>
{isSubmitting ? "Sending code..." : "Send unique code"}
</Button>
)}
</form>
</>
);
};

View File

@ -1,69 +0,0 @@
import { FC } from "react";
import { useRouter } from "next/router";
import { useForm, Controller } from "react-hook-form";
// ui
import { Input, Button } from "@plane/ui";
export interface EmailForgotPasswordFormValues {
email: string;
}
export interface IEmailForgotPasswordForm {
onSubmit: (formValues: any) => Promise<void>;
}
export const EmailForgotPasswordForm: FC<IEmailForgotPasswordForm> = (props) => {
const { onSubmit } = props;
// router
const router = useRouter();
// form data
const {
control,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<EmailForgotPasswordFormValues>({
defaultValues: {
email: "",
},
mode: "onChange",
reValidateMode: "onChange",
});
return (
<form className="space-y-4 mt-10 w-full sm:w-[360px] mx-auto" onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-1">
<Controller
control={control}
name="email"
rules={{
required: "Email address is required",
validate: (value) =>
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
value
) || "Email address is not valid",
}}
render={({ field: { value, onChange } }) => (
<Input
id="email"
type="email"
name="email"
value={value}
onChange={onChange}
hasError={Boolean(errors.email)}
placeholder="Enter registered email address.."
className="border-custom-border-300 h-[46px] w-full"
/>
)}
/>
</div>
<div className="mt-5 flex flex-col-reverse sm:flex-row items-center gap-2">
<Button className="w-full text-center h-[46px]" onClick={() => router.push("/")}>
Go Back
</Button>
<Button type="submit" className="w-full text-center h-[46px]" loading={isSubmitting}>
{isSubmitting ? "Sending link..." : "Send reset link"}
</Button>
</div>
</form>
);
};

View File

@ -1,118 +0,0 @@
import React from "react";
import { useForm, Controller } from "react-hook-form";
import { useRouter } from "next/router";
// ui
import { Input, Button } from "@plane/ui";
export interface EmailPasswordFormValues {
email: string;
password?: string;
medium?: string;
}
export interface IEmailPasswordForm {
onSubmit: (formData: EmailPasswordFormValues) => Promise<void>;
}
export const EmailPasswordForm: React.FC<IEmailPasswordForm> = (props) => {
const { onSubmit } = props;
// router
const router = useRouter();
// form info
const {
control,
handleSubmit,
formState: { errors, isSubmitting, isValid, isDirty },
} = useForm<EmailPasswordFormValues>({
defaultValues: {
email: "",
password: "",
medium: "email",
},
mode: "onChange",
reValidateMode: "onChange",
});
return (
<>
<form className="space-y-4 mt-10 w-full sm:w-[360px] mx-auto" onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-1">
<Controller
control={control}
name="email"
rules={{
required: "Email address is required",
validate: (value) =>
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
value
) || "Email address is not valid",
}}
render={({ field: { value, onChange } }) => (
<Input
id="email"
type="email"
name="email"
value={value}
onChange={onChange}
hasError={Boolean(errors.email)}
placeholder="Enter your email address..."
className="border-custom-border-300 h-[46px] w-full"
/>
)}
/>
</div>
<div className="space-y-1">
<Controller
control={control}
name="password"
rules={{
required: "Password is required",
}}
render={({ field: { value, onChange } }) => (
<Input
id="password"
type="password"
name="password"
value={value}
onChange={onChange}
hasError={Boolean(errors.password)}
placeholder="Enter your password..."
className="border-custom-border-300 h-[46px] w-full"
/>
)}
/>
</div>
<div className="text-right text-xs">
<button
type="button"
onClick={() => router.push("/accounts/forgot-password")}
className="text-custom-text-200 hover:text-custom-primary-100"
>
Forgot your password?
</button>
</div>
<div>
<Button
variant="primary"
type="submit"
className="w-full"
size="xl"
disabled={!isValid && isDirty}
loading={isSubmitting}
>
{isSubmitting ? "Signing in..." : "Sign in"}
</Button>
</div>
<div className="text-xs">
<button
type="button"
onClick={() => router.push("/accounts/sign-up")}
className="text-custom-text-200 hover:text-custom-primary-100"
>
{"Don't have an account? Sign Up"}
</button>
</div>
</form>
</>
);
};

View File

@ -8,16 +8,14 @@ import { useTheme } from "next-themes";
// images
import githubLightModeImage from "/public/logos/github-black.png";
import githubDarkModeImage from "/public/logos/github-dark.svg";
import { AuthType } from "components/page-views";
export interface GithubLoginButtonProps {
handleSignIn: React.Dispatch<string>;
clientId: string;
authType: AuthType;
}
export const GithubLoginButton: FC<GithubLoginButtonProps> = (props) => {
const { handleSignIn, clientId, authType } = props;
const { handleSignIn, clientId } = props;
// states
const [loginCallBackURL, setLoginCallBackURL] = useState(undefined);
const [gitCode, setGitCode] = useState<null | string>(null);
@ -55,7 +53,7 @@ export const GithubLoginButton: FC<GithubLoginButtonProps> = (props) => {
width={20}
alt="GitHub Logo"
/>
<span className="text-onboarding-text-200">{authType == "sign-in" ? "Sign-in" : "Sign-up"} with GitHub</span>
<span className="text-onboarding-text-200">Sign-in with GitHub</span>
</button>
</Link>
</div>

View File

@ -1,7 +1,5 @@
export * from "./sign-in-forms";
export * from "./deactivate-account-modal";
export * from "./email-code-form";
export * from "./email-password-form";
export * from "./email-forgot-password-form";
export * from "./github-login-button";
export * from "./google-login";
export * from "./email-signup-form";

View File

@ -0,0 +1,133 @@
import React from "react";
import { Controller, useForm } from "react-hook-form";
// services
import { AuthService } from "services/auth.service";
// hooks
import useToast from "hooks/use-toast";
// ui
import { Button, Input } from "@plane/ui";
// helpers
import { checkEmailValidity } from "helpers/string.helper";
// constants
import { ESignInSteps } from "components/account";
type Props = {
email: string;
handleStepChange: (step: ESignInSteps) => void;
handleSignInRedirection: () => Promise<void>;
};
type TCreatePasswordFormValues = {
email: string;
password: string;
};
const defaultValues: TCreatePasswordFormValues = {
email: "",
password: "",
};
// services
const authService = new AuthService();
export const CreatePasswordForm: React.FC<Props> = (props) => {
const { email, handleSignInRedirection } = props;
// toast alert
const { setToastAlert } = useToast();
// form info
const {
control,
formState: { errors, isSubmitting, isValid },
handleSubmit,
} = useForm<TCreatePasswordFormValues>({
defaultValues: {
...defaultValues,
email,
},
mode: "onChange",
reValidateMode: "onChange",
});
const handleCreatePassword = async (formData: TCreatePasswordFormValues) => {
const payload = {
password: formData.password,
};
await authService
.setPassword(payload)
.then(async () => {
setToastAlert({
type: "success",
title: "Success!",
message: "Password created successfully.",
});
await handleSignInRedirection();
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
);
};
return (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">
Let{"'"}s get a new password
</h1>
<form onSubmit={handleSubmit(handleCreatePassword)} className="mt-11 sm:w-96 mx-auto space-y-4">
<Controller
control={control}
name="email"
rules={{
required: "Email is required",
validate: (value) => checkEmailValidity(value) || "Email is invalid",
}}
render={({ field: { value, onChange, ref } }) => (
<Input
id="email"
name="email"
type="email"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className="w-full h-[46px] text-onboarding-text-400 border border-onboarding-border-100 pr-12"
disabled
/>
)}
/>
<div>
<Controller
control={control}
name="password"
rules={{
required: "Password is required",
}}
render={({ field: { value, onChange, ref } }) => (
<Input
type="password"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.password)}
placeholder="Create password"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
)}
/>
<p className="text-xs text-onboarding-text-200 mt-3">
Whatever you choose now will be your account{"'"}s password until you change it.
</p>
</div>
<Button type="submit" variant="primary" className="w-full" size="xl" disabled={!isValid} loading={isSubmitting}>
{isSubmitting ? "Submitting..." : "Go to workspace"}
</Button>
</form>
</>
);
};

View File

@ -0,0 +1,152 @@
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { XCircle } from "lucide-react";
// services
import { AuthService } from "services/auth.service";
// hooks
import useToast from "hooks/use-toast";
// ui
import { Button, Input } from "@plane/ui";
// helpers
import { checkEmailValidity } from "helpers/string.helper";
// types
import { IEmailCheckData, TEmailCheckTypes } from "types/auth";
// constants
import { ESignInSteps } from "components/account";
type Props = {
handleStepChange: (step: ESignInSteps) => void;
updateEmail: (email: string) => void;
};
type TEmailCodeFormValues = {
email: string;
};
const authService = new AuthService();
export const EmailForm: React.FC<Props> = (props) => {
const { handleStepChange, updateEmail } = props;
// states
const [isCheckingEmail, setIsCheckingEmail] = useState<TEmailCheckTypes | null>(null);
const { setToastAlert } = useToast();
const {
control,
formState: { errors, isValid },
handleSubmit,
watch,
} = useForm<TEmailCodeFormValues>({
defaultValues: {
email: "",
},
mode: "onChange",
reValidateMode: "onChange",
});
const handleEmailCheck = async (type: TEmailCheckTypes) => {
setIsCheckingEmail(type);
const email = watch("email");
const payload: IEmailCheckData = {
email,
type,
};
// update the global email state
updateEmail(email);
await authService
.emailCheck(payload)
.then((res) => {
// if type is magic_code, send the user to magic sign in
if (type === "magic_code") handleStepChange(ESignInSteps.UNIQUE_CODE);
// if type is password, check if the user has a password set
if (type === "password") {
// if password is autoset, send them to set new password link
if (res.is_password_autoset) handleStepChange(ESignInSteps.SET_PASSWORD_LINK);
// if password is not autoset, send them to password form
else handleStepChange(ESignInSteps.PASSWORD);
}
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
)
.finally(() => setIsCheckingEmail(null));
};
return (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">
Get on your flight deck!
</h1>
<p className="text-center text-sm text-onboarding-text-200 px-20 mt-3">
Sign in with the email you used to sign up for Plane
</p>
<form onSubmit={handleSubmit(() => {})} className="mt-5 sm:w-96 mx-auto">
<div className="space-y-1">
<Controller
control={control}
name="email"
rules={{
required: "Email is required",
validate: (value) => checkEmailValidity(value) || "Email is invalid",
}}
render={({ field: { value, onChange, ref } }) => (
<div className="flex items-center relative rounded-md bg-onboarding-background-200">
<Input
id="email"
name="email"
type="email"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
{value.length > 0 && (
<XCircle
className="h-5 w-5 absolute stroke-custom-text-400 hover:cursor-pointer right-3"
onClick={() => onChange("")}
/>
)}
</div>
)}
/>
</div>
<div className="grid grid-cols-2 gap-2.5 mt-4">
<Button
type="button"
variant="primary"
className="w-full"
size="xl"
onClick={() => handleEmailCheck("magic_code")}
disabled={!isValid}
loading={Boolean(isCheckingEmail)}
>
{isCheckingEmail === "magic_code" ? "Sending code..." : "Send unique code"}
</Button>
<Button
type="button"
variant="outline-primary"
className="w-full"
size="xl"
onClick={() => handleEmailCheck("password")}
disabled={!isValid}
loading={Boolean(isCheckingEmail)}
>
{isCheckingEmail === "password" ? "Loading..." : "Use password"}
</Button>
</div>
</form>
</>
);
};

View File

@ -0,0 +1,8 @@
export * from "./create-password";
export * from "./email-form";
export * from "./o-auth-options";
export * from "./optional-set-password";
export * from "./unique-code";
export * from "./password";
export * from "./root";
export * from "./set-password-link";

View File

@ -0,0 +1,104 @@
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// services
import { AuthService } from "services/auth.service";
import { UserService } from "services/user.service";
// hooks
import useToast from "hooks/use-toast";
// components
import { ESignInSteps, GithubLoginButton, GoogleLoginButton } from "components/account";
type Props = {
updateEmail: (email: string) => void;
handleStepChange: (step: ESignInSteps) => void;
handleSignInRedirection: () => Promise<void>;
};
// services
const authService = new AuthService();
const userService = new UserService();
export const OAuthOptions: React.FC<Props> = observer((props) => {
const { updateEmail, handleStepChange, handleSignInRedirection } = props;
// toast alert
const { setToastAlert } = useToast();
// mobx store
const {
appConfig: { envConfig },
} = useMobxStore();
const handleGoogleSignIn = async ({ clientId, credential }: any) => {
try {
if (clientId && credential) {
const socialAuthPayload = {
medium: "google",
credential,
clientId,
};
const response = await authService.socialAuth(socialAuthPayload);
if (response) {
const currentUser = await userService.currentUser();
updateEmail(currentUser.email);
if (currentUser.is_password_autoset) handleStepChange(ESignInSteps.OPTIONAL_SET_PASSWORD);
else handleSignInRedirection();
}
} else throw Error("Cant find credentials");
} catch (err: any) {
setToastAlert({
title: "Error signing in!",
type: "error",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
});
}
};
const handleGitHubSignIn = async (credential: string) => {
try {
if (envConfig && envConfig.github_client_id && credential) {
const socialAuthPayload = {
medium: "github",
credential,
clientId: envConfig.github_client_id,
};
const response = await authService.socialAuth(socialAuthPayload);
if (response) {
const currentUser = await userService.currentUser();
updateEmail(currentUser.email);
if (currentUser.is_password_autoset) handleStepChange(ESignInSteps.OPTIONAL_SET_PASSWORD);
else handleSignInRedirection();
}
} else throw Error("Cant find credentials");
} catch (err: any) {
setToastAlert({
title: "Error signing in!",
type: "error",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
});
}
};
return (
<>
<div className="flex sm:w-96 items-center mt-4 mx-auto">
<hr className={`border-onboarding-border-100 w-full`} />
<p className="text-center text-sm text-onboarding-text-400 mx-3 flex-shrink-0">Or continue with</p>
<hr className={`border-onboarding-border-100 w-full`} />
</div>
<div className="flex flex-col items-center justify-center gap-4 pt-7 sm:flex-row sm:w-96 mx-auto overflow-hidden">
{envConfig?.google_client_id && (
<GoogleLoginButton clientId={envConfig?.google_client_id} handleSignIn={handleGoogleSignIn} />
)}
{envConfig?.github_client_id && (
<GithubLoginButton clientId={envConfig?.github_client_id} handleSignIn={handleGitHubSignIn} />
)}
</div>
</>
);
});

View File

@ -0,0 +1,94 @@
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
// ui
import { Button, Input } from "@plane/ui";
// helpers
import { checkEmailValidity } from "helpers/string.helper";
// constants
import { ESignInSteps } from "components/account";
type Props = {
email: string;
handleStepChange: (step: ESignInSteps) => void;
handleSignInRedirection: () => Promise<void>;
};
export const OptionalSetPasswordForm: React.FC<Props> = (props) => {
const { email, handleStepChange, handleSignInRedirection } = props;
// states
const [isGoingToWorkspace, setIsGoingToWorkspace] = useState(false);
const {
control,
formState: { errors, isValid },
} = useForm({
defaultValues: {
email,
},
mode: "onChange",
reValidateMode: "onChange",
});
const handleGoToWorkspace = async () => {
setIsGoingToWorkspace(true);
await handleSignInRedirection().finally(() => setIsGoingToWorkspace(false));
};
return (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">Set a password</h1>
<p className="text-center text-sm text-onboarding-text-200 px-20 mt-3">
If you{"'"}d to do away with codes, set a password here.
</p>
<form className="mt-5 sm:w-96 mx-auto">
<Controller
control={control}
name="email"
rules={{
required: "Email is required",
validate: (value) => checkEmailValidity(value) || "Email is invalid",
}}
render={({ field: { value, onChange, ref } }) => (
<Input
id="email"
name="email"
type="email"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className="w-full h-[46px] text-onboarding-text-400 border border-onboarding-border-100 pr-12"
disabled
/>
)}
/>
<div className="grid grid-cols-2 gap-2.5 mt-4">
<Button
type="button"
variant="primary"
onClick={() => handleStepChange(ESignInSteps.CREATE_PASSWORD)}
className="w-full"
size="xl"
disabled={!isValid}
>
Create password
</Button>
<Button
type="button"
variant="outline-primary"
className="w-full"
size="xl"
onClick={handleGoToWorkspace}
disabled={!isValid}
loading={isGoingToWorkspace}
>
{isGoingToWorkspace ? "Going to app..." : "Go to workspace"}
</Button>
</div>
</form>
</>
);
};

View File

@ -0,0 +1,201 @@
import React from "react";
import { Controller, useForm } from "react-hook-form";
import { XCircle } from "lucide-react";
// services
import { AuthService } from "services/auth.service";
// hooks
import useToast from "hooks/use-toast";
// ui
import { Button, Input } from "@plane/ui";
// helpers
import { checkEmailValidity } from "helpers/string.helper";
// types
import { IEmailCheckData, IPasswordSignInData } from "types/auth";
// constants
import { ESignInSteps } from "components/account";
type Props = {
email: string;
updateEmail: (email: string) => void;
handleStepChange: (step: ESignInSteps) => void;
handleSignInRedirection: () => Promise<void>;
};
type TPasswordFormValues = {
email: string;
password: string;
};
const defaultValues: TPasswordFormValues = {
email: "",
password: "",
};
const authService = new AuthService();
export const PasswordForm: React.FC<Props> = (props) => {
const { email, updateEmail, handleStepChange, handleSignInRedirection } = props;
// toast alert
const { setToastAlert } = useToast();
// form info
const {
control,
formState: { dirtyFields, errors, isSubmitting, isValid },
getValues,
handleSubmit,
reset,
setError,
} = useForm<TPasswordFormValues>({
defaultValues: {
...defaultValues,
email,
},
mode: "onChange",
reValidateMode: "onChange",
});
const handlePasswordSignIn = async (formData: TPasswordFormValues) => {
const payload: IPasswordSignInData = {
email: formData.email,
password: formData.password,
};
await authService
.passwordSignIn(payload)
.then(async () => await handleSignInRedirection())
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
);
};
const handleEmailCheck = async (formData: TPasswordFormValues) => {
const payload: IEmailCheckData = {
email: formData.email,
type: "password",
};
await authService
.emailCheck(payload)
.then((res) => {
if (res.is_password_autoset) handleStepChange(ESignInSteps.SET_PASSWORD_LINK);
else
reset({
email: formData.email,
password: "",
});
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
);
};
const handleFormSubmit = async (formData: TPasswordFormValues) => {
if (dirtyFields.email) await handleEmailCheck(formData);
else await handlePasswordSignIn(formData);
};
const handleForgotPassword = async () => {
const emailFormValue = getValues("email");
const isEmailValid = checkEmailValidity(emailFormValue);
if (!isEmailValid) {
setError("email", { message: "Email is invalid" });
return;
}
authService
.sendResetPasswordLink({ email: emailFormValue })
.then(() => handleStepChange(ESignInSteps.SET_PASSWORD_LINK))
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
);
};
return (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">
Get on your flight deck
</h1>
<form onSubmit={handleSubmit(handleFormSubmit)} className="mt-11 sm:w-96 mx-auto space-y-4">
<div>
<Controller
control={control}
name="email"
rules={{
required: "Email is required",
validate: (value) => checkEmailValidity(value) || "Email is invalid",
}}
render={({ field: { value, onChange } }) => (
<div className="flex items-center relative rounded-md bg-onboarding-background-200">
<Input
id="email"
name="email"
type="email"
value={value}
onChange={(e) => {
updateEmail(e.target.value);
onChange(e.target.value);
}}
onBlur={() => {
if (dirtyFields.email) handleEmailCheck(getValues());
}}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
{value.length > 0 && (
<XCircle
className="h-5 w-5 absolute stroke-custom-text-400 hover:cursor-pointer right-3"
onClick={() => onChange("")}
/>
)}
</div>
)}
/>
</div>
<div>
<Controller
control={control}
name="password"
rules={{
required: dirtyFields.email ? false : "Password is required",
}}
render={({ field: { value, onChange } }) => (
<Input
type="password"
value={value}
onChange={onChange}
hasError={Boolean(errors.password)}
placeholder="Enter password"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
)}
/>
<button
type="button"
onClick={handleForgotPassword}
className="text-xs font-medium text-right w-full text-custom-primary-100"
>
Forgot your password?
</button>
</div>
<Button type="submit" variant="primary" className="w-full" size="xl" disabled={!isValid} loading={isSubmitting}>
{isSubmitting ? "Signing in..." : "Go to workspace"}
</Button>
</form>
</>
);
};

View File

@ -0,0 +1,84 @@
import React, { useState } from "react";
// components
import {
EmailForm,
UniqueCodeForm,
PasswordForm,
SetPasswordLink,
OAuthOptions,
OptionalSetPasswordForm,
CreatePasswordForm,
} from "components/account";
export enum ESignInSteps {
EMAIL = "EMAIL",
PASSWORD = "PASSWORD",
SET_PASSWORD_LINK = "SET_PASSWORD_LINK",
UNIQUE_CODE = "UNIQUE_CODE",
OPTIONAL_SET_PASSWORD = "OPTIONAL_SET_PASSWORD",
CREATE_PASSWORD = "CREATE_PASSWORD",
}
type Props = {
handleSignInRedirection: () => Promise<void>;
};
export const SignInRoot: React.FC<Props> = (props) => {
const { handleSignInRedirection } = props;
// states
const [signInStep, setSignInStep] = useState<ESignInSteps>(ESignInSteps.EMAIL);
const [email, setEmail] = useState("");
return (
<>
<div className="mx-auto flex flex-col divide-y divide-custom-border-200">
{signInStep === ESignInSteps.EMAIL && (
<EmailForm
handleStepChange={(step: ESignInSteps) => setSignInStep(step)}
updateEmail={(newEmail) => setEmail(newEmail)}
/>
)}
{signInStep === ESignInSteps.PASSWORD && (
<PasswordForm
email={email}
updateEmail={(newEmail) => setEmail(newEmail)}
handleStepChange={(step: ESignInSteps) => setSignInStep(step)}
handleSignInRedirection={handleSignInRedirection}
/>
)}
{signInStep === ESignInSteps.SET_PASSWORD_LINK && (
<SetPasswordLink email={email} updateEmail={(newEmail) => setEmail(newEmail)} />
)}
{signInStep === ESignInSteps.UNIQUE_CODE && (
<UniqueCodeForm
email={email}
updateEmail={(newEmail) => setEmail(newEmail)}
handleStepChange={(step: ESignInSteps) => setSignInStep(step)}
handleSignInRedirection={handleSignInRedirection}
/>
)}
{signInStep === ESignInSteps.OPTIONAL_SET_PASSWORD && (
<OptionalSetPasswordForm
email={email}
handleStepChange={(step: ESignInSteps) => setSignInStep(step)}
handleSignInRedirection={handleSignInRedirection}
/>
)}
{signInStep === ESignInSteps.CREATE_PASSWORD && (
<CreatePasswordForm
email={email}
handleStepChange={(step: ESignInSteps) => setSignInStep(step)}
handleSignInRedirection={handleSignInRedirection}
/>
)}
</div>
{signInStep !== ESignInSteps.OPTIONAL_SET_PASSWORD && (
<OAuthOptions
updateEmail={(newEmail) => setEmail(newEmail)}
handleStepChange={(step: ESignInSteps) => setSignInStep(step)}
handleSignInRedirection={handleSignInRedirection}
/>
)}
</>
);
};

View File

@ -0,0 +1,122 @@
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { XCircle } from "lucide-react";
// services
import { AuthService } from "services/auth.service";
// hooks
import useToast from "hooks/use-toast";
// ui
import { Button, Input } from "@plane/ui";
// helpers
import { checkEmailValidity } from "helpers/string.helper";
// types
import { IEmailCheckData } from "types/auth";
type Props = {
email: string;
updateEmail: (email: string) => void;
};
const authService = new AuthService();
export const SetPasswordLink: React.FC<Props> = (props) => {
const { email, updateEmail } = props;
// states
const [isSendingNewLink, setIsSendingNewLink] = useState(false);
const { setToastAlert } = useToast();
const {
control,
formState: { errors, isValid },
watch,
} = useForm({
defaultValues: {
email,
},
mode: "onChange",
reValidateMode: "onChange",
});
const handleSendNewLink = async () => {
setIsSendingNewLink(true);
const payload: IEmailCheckData = {
email: watch("email"),
type: "password",
};
await authService
.emailCheck(payload)
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
)
.finally(() => setIsSendingNewLink(false));
};
return (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">
Get on your flight deck!
</h1>
<p className="text-center text-sm text-onboarding-text-200 px-20 mt-3">
We have sent a link to <span className="font-medium text-custom-primary-100">{email},</span> so you can set a
password
</p>
<form className="mt-5 sm:w-96 mx-auto">
<div className="space-y-1">
<Controller
control={control}
name="email"
rules={{
required: "Email is required",
validate: (value) => checkEmailValidity(value) || "Email is invalid",
}}
render={({ field: { value, onChange, ref } }) => (
<div className="flex items-center relative rounded-md bg-onboarding-background-200">
<Input
id="email"
name="email"
type="email"
value={value}
onChange={(e) => {
updateEmail(e.target.value);
onChange(e.target.value);
}}
ref={ref}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
{value.length > 0 && (
<XCircle
className="h-5 w-5 absolute stroke-custom-text-400 hover:cursor-pointer right-3"
onClick={() => onChange("")}
/>
)}
</div>
)}
/>
</div>
<div className="mt-4">
<Button
type="button"
variant="primary"
className="w-full"
size="xl"
onClick={handleSendNewLink}
disabled={!isValid}
loading={isSendingNewLink}
>
{isSendingNewLink ? "Sending new link..." : "Get link again"}
</Button>
</div>
</form>
</>
);
};

View File

@ -0,0 +1,232 @@
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { CornerDownLeft, XCircle } from "lucide-react";
// services
import { AuthService } from "services/auth.service";
import { UserService } from "services/user.service";
// hooks
import useToast from "hooks/use-toast";
import useTimer from "hooks/use-timer";
// ui
import { Button, Input } from "@plane/ui";
// helpers
import { checkEmailValidity } from "helpers/string.helper";
// types
import { IEmailCheckData, IMagicSignInData } from "types/auth";
// constants
import { ESignInSteps } from "components/account";
type Props = {
email: string;
updateEmail: (email: string) => void;
handleStepChange: (step: ESignInSteps) => void;
handleSignInRedirection: () => Promise<void>;
};
type TUniqueCodeFormValues = {
email: string;
token: string;
};
const defaultValues: TUniqueCodeFormValues = {
email: "",
token: "",
};
// services
const authService = new AuthService();
const userService = new UserService();
export const UniqueCodeForm: React.FC<Props> = (props) => {
const { email, updateEmail, handleStepChange, handleSignInRedirection } = props;
// states
const [isRequestingNewCode, setIsRequestingNewCode] = useState(false);
// toast alert
const { setToastAlert } = useToast();
// timer
const { timer: resendTimerCode, setTimer: setResendCodeTimer } = useTimer();
// form info
const {
control,
formState: { dirtyFields, errors, isSubmitting, isValid },
getValues,
handleSubmit,
reset,
} = useForm<TUniqueCodeFormValues>({
defaultValues: {
...defaultValues,
email,
},
mode: "onChange",
reValidateMode: "onChange",
});
const handleUniqueCodeSignIn = async (formData: TUniqueCodeFormValues) => {
const payload: IMagicSignInData = {
email: formData.email,
key: `magic_${formData.email}`,
token: formData.token,
};
await authService
.magicSignIn(payload)
.then(async () => {
const currentUser = await userService.currentUser();
if (currentUser.is_password_autoset) handleStepChange(ESignInSteps.OPTIONAL_SET_PASSWORD);
else await handleSignInRedirection();
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
);
};
const handleSendNewLink = async (formData: TUniqueCodeFormValues) => {
const payload: IEmailCheckData = {
email: formData.email,
type: "magic_code",
};
await authService
.emailCheck(payload)
.then(() => {
setToastAlert({
type: "success",
title: "Success!",
message: "A new unique code has been sent to your email.",
});
reset({
email: formData.email,
token: "",
});
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
);
};
const handleFormSubmit = async (formData: TUniqueCodeFormValues) => {
if (dirtyFields.email) await handleSendNewLink(formData);
else await handleUniqueCodeSignIn(formData);
};
const handleRequestNewCode = async () => {
setIsRequestingNewCode(true);
await handleSendNewLink(getValues())
.then(() => setResendCodeTimer(30))
.finally(() => setIsRequestingNewCode(false));
};
const isRequestNewCodeDisabled = isRequestingNewCode || resendTimerCode > 0;
return (
<>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">
Moving to the runway
</h1>
<p className="text-center text-sm text-onboarding-text-200 px-20 mt-3">
Paste the code you got at <span className="font-medium text-custom-primary-100">{email}</span> below.
</p>
<form onSubmit={handleSubmit(handleFormSubmit)} className="mt-5 sm:w-96 mx-auto space-y-4">
<div>
<Controller
control={control}
name="email"
rules={{
required: "Email is required",
validate: (value) => checkEmailValidity(value) || "Email is invalid",
}}
render={({ field: { value, onChange, ref } }) => (
<div className="flex items-center relative rounded-md bg-onboarding-background-200">
<Input
id="email"
name="email"
type="email"
value={value}
onChange={(e) => {
updateEmail(e.target.value);
onChange(e.target.value);
}}
onBlur={() => {
if (dirtyFields.email) handleSendNewLink(getValues());
}}
ref={ref}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
{value.length > 0 && (
<XCircle
className="h-5 w-5 absolute stroke-custom-text-400 hover:cursor-pointer right-3"
onClick={() => onChange("")}
/>
)}
</div>
)}
/>
{dirtyFields.email && (
<button
type="submit"
className="text-xs text-onboarding-text-300 mt-1.5 flex items-center gap-1 outline-none bg-transparent border-none"
>
Hit <CornerDownLeft className="h-2.5 w-2.5" /> or <span className="italic">Tab</span> to get a new code
</button>
)}
</div>
<div>
<Controller
control={control}
name="token"
rules={{
required: dirtyFields.email ? false : "Code is required",
}}
render={({ field: { value, onChange } }) => (
<Input
value={value}
onChange={onChange}
hasError={Boolean(errors.token)}
placeholder="gets-sets-fays"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
)}
/>
<button
type="button"
onClick={handleRequestNewCode}
className={`text-xs text-right w-full text-onboarding-text-200 ${
isRequestNewCodeDisabled ? "" : "hover:text-custom-primary-100"
}`}
disabled={isRequestNewCodeDisabled}
>
{resendTimerCode > 0
? `Request new code in ${resendTimerCode}s`
: isRequestingNewCode
? "Requesting new code..."
: "Request new code"}
</button>
</div>
<Button
type="submit"
variant="primary"
className="w-full"
size="xl"
disabled={!isValid || dirtyFields.email}
loading={isSubmitting}
>
{isSubmitting ? "Signing in..." : "Confirm"}
</Button>
</form>
</>
);
};

View File

@ -1,22 +1,14 @@
import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { observer } from "mobx-react-lite";
import Image from "next/image";
import { useTheme } from "next-themes";
import { useRouter } from "next/router";
import { Lightbulb } from "lucide-react";
// hooks
import useToast from "hooks/use-toast";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// services
import { AuthService } from "services/auth.service";
// components
import {
GoogleLoginButton,
GithubLoginButton,
EmailCodeForm,
EmailPasswordForm,
EmailPasswordFormValues,
} from "components/account";
import { SignInRoot } from "components/account";
// ui
import { Loader, Spinner } from "@plane/ui";
// images
@ -27,8 +19,6 @@ import { IUser, IUserSettings } from "types";
export type AuthType = "sign-in" | "sign-up";
const authService = new AuthService();
export const SignInView = observer(() => {
// store
const {
@ -37,27 +27,14 @@ export const SignInView = observer(() => {
} = useMobxStore();
// router
const router = useRouter();
const { next: next_url } = router.query as { next: string };
const { next: next_url } = router.query;
// states
const [isLoading, setLoading] = useState(false);
const [authType, setAuthType] = useState<AuthType>("sign-in");
// toast
const { setToastAlert } = useToast();
// next-themes
const { resolvedTheme } = useTheme();
// computed.
const enableEmailPassword =
envConfig &&
(envConfig?.email_password_login ||
!(
envConfig?.email_password_login ||
envConfig?.magic_login ||
envConfig?.google_client_id ||
envConfig?.github_client_id
));
const handleLoginRedirection = useCallback(
(user: IUser) => {
const handleSignInRedirection = useCallback(
async (user: IUser) => {
// if the user is not onboarded, redirect them to the onboarding page
if (!user.is_onboarded) {
router.push("/onboarding");
@ -65,122 +42,33 @@ export const SignInView = observer(() => {
}
// if next_url is provided, redirect the user to that url
if (next_url) {
router.push(next_url);
router.push(next_url.toString());
return;
}
// if the user is onboarded, fetch their last workspace details
fetchCurrentUserSettings()
await fetchCurrentUserSettings()
.then((userSettings: IUserSettings) => {
const workspaceSlug =
userSettings?.workspace?.last_workspace_slug || userSettings?.workspace?.fallback_workspace_slug;
if (workspaceSlug) router.push(`/${workspaceSlug}`);
else router.push("/profile");
})
.catch(() => {
setLoading(false);
});
.catch(() => setLoading(false));
},
[fetchCurrentUserSettings, router, next_url]
);
const mutateUserInfo = useCallback(() => {
fetchCurrentUser().then((user) => {
handleLoginRedirection(user);
const mutateUserInfo = useCallback(async () => {
await fetchCurrentUser().then(async (user) => {
await handleSignInRedirection(user);
});
}, [fetchCurrentUser, handleLoginRedirection]);
}, [fetchCurrentUser, handleSignInRedirection]);
useEffect(() => {
mutateUserInfo();
}, [mutateUserInfo]);
const handleGoogleSignIn = async ({ clientId, credential }: any) => {
try {
setLoading(true);
if (clientId && credential) {
const socialAuthPayload = {
medium: "google",
credential,
clientId,
};
const response = await authService.socialAuth(socialAuthPayload);
if (response) {
mutateUserInfo();
}
} else {
setLoading(false);
throw Error("Cant find credentials");
}
} catch (err: any) {
setLoading(false);
setToastAlert({
title: "Error signing in!",
type: "error",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
});
}
};
const handleGitHubSignIn = async (credential: string) => {
try {
setLoading(true);
if (envConfig && envConfig.github_client_id && credential) {
const socialAuthPayload = {
medium: "github",
credential,
clientId: envConfig.github_client_id,
};
const response = await authService.socialAuth(socialAuthPayload);
if (response) {
mutateUserInfo();
}
} else {
setLoading(false);
throw Error("Cant find credentials");
}
} catch (err: any) {
setLoading(false);
setToastAlert({
title: "Error signing in!",
type: "error",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
});
}
};
const handlePasswordSignIn = (formData: EmailPasswordFormValues) => {
setLoading(true);
return authService
.emailLogin(formData)
.then(() => {
mutateUserInfo();
})
.catch((err) => {
setLoading(false);
setToastAlert({
type: "error",
title: "Error!",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
});
});
};
const handleEmailCodeSignIn = async (response: any) => {
try {
setLoading(true);
if (response) {
mutateUserInfo();
}
} catch (err: any) {
setLoading(false);
setToastAlert({
type: "error",
title: "Error!",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
});
}
};
return (
<>
{isLoading ? (
@ -194,26 +82,10 @@ export const SignInView = observer(() => {
<Image src={BluePlaneLogoWithoutText} height={30} width={30} alt="Plane Logo" className="mr-2" />
<span className="font-semibold text-2xl sm:text-3xl">Plane</span>
</div>
{/* <div className="">
{authType === "sign-in" && (
<div className="mx-auto text-right text-onboarding-text-300 text-sm">
New to Plane?{" "}
<p
className="text-custom-primary-100 hover text-base font-medium hover:cursor-pointer"
onClick={() => {
setAuthType("sign-up");
}}
>
Create a new account
</p>
</div>
)}
</div> */}
</div>
<div className="h-full bg-onboarding-gradient-100 md:w-2/3 sm:w-4/5 px-4 pt-4 rounded-t-md mx-auto shadow-sm border-x border-t border-custom-border-200 ">
<div className={`px-7 sm:px-0 bg-onboarding-gradient-200 h-full pt-24 pb-56 rounded-t-md overflow-auto`}>
<div className="px-7 sm:px-0 bg-onboarding-gradient-200 h-full pt-24 pb-56 rounded-t-md overflow-auto">
{!envConfig ? (
<div className="pt-10 mx-auto flex justify-center">
<div>
@ -230,57 +102,21 @@ export const SignInView = observer(() => {
</div>
) : (
<>
<>
{enableEmailPassword && <EmailPasswordForm onSubmit={handlePasswordSignIn} />}
{envConfig?.magic_login && (
<div className="sm:w-96 mx-auto flex flex-col divide-y divide-custom-border-200">
<div className="pb-2">
<EmailCodeForm authType={authType} handleSignIn={handleEmailCodeSignIn} />
</div>
</div>
)}
<div className="flex sm:w-96 items-center mt-4 mx-auto">
<hr className={`border-onboarding-border-100 w-full`} />
<p className="text-center text-sm text-onboarding-text-400 mx-3 flex-shrink-0">
Or continue with
</p>
<hr className={`border-onboarding-border-100 w-full`} />
</div>
<div className="flex flex-col items-center justify-center gap-4 pt-7 sm:flex-row sm:w-96 mx-auto overflow-hidden">
{envConfig?.google_client_id && (
<GoogleLoginButton clientId={envConfig?.google_client_id} handleSignIn={handleGoogleSignIn} />
)}
{envConfig?.github_client_id && (
<GithubLoginButton
authType={authType}
clientId={envConfig?.github_client_id}
handleSignIn={handleGitHubSignIn}
/>
)}
</div>
{/* {authType === "sign-up" && (
<div className="sm:w-96 text-center mx-auto mt-6 text-onboarding-text-400 text-sm">
Already using Plane?{" "}
<span
className="text-custom-primary-80 hover text-sm font-medium underline hover:cursor-pointer"
onClick={() => {
setAuthType("sign-in");
}}
>
Sign in
</span>
</div>
)} */}
</>
<div
className={`flex py-2 bg-onboarding-background-100 border border-onboarding-border-200 mx-auto rounded-[3.5px] sm:w-96 mt-16`}
>
<SignInRoot handleSignInRedirection={mutateUserInfo} />
<div className="flex py-2 bg-onboarding-background-100 border border-onboarding-border-200 mx-auto rounded-[3.5px] sm:w-96 mt-16">
<Lightbulb className="h-7 w-7 mr-2 mx-3" />
<p className={`text-sm text-left text-onboarding-text-100`}>
Try the latest features, like Tiptap editor, to write compelling responses.{" "}
<span className="font-medium text-sm underline hover:cursor-pointer" onClick={() => {}}>
See new features
</span>
<p className="text-sm text-left text-onboarding-text-100">
Pages gets a facelift! Write anything and use Galileo to help you start.{" "}
<Link href="https://plane.so/changelog">
<a
target="_blank"
rel="noopener noreferrer"
className="font-medium text-sm underline hover:cursor-pointer"
>
Learn more
</a>
</Link>
</p>
</div>
<div className="flex justify-center border border-onboarding-border-200 sm:w-96 sm:h-52 object-cover mt-8 mx-auto rounded-md bg-onboarding-background-100 ">

View File

@ -206,3 +206,21 @@ export const substringMatch = (text: string, searchQuery: string): boolean => {
return false;
}
};
/**
* @returns {boolean} true if email is valid, false otherwise
* @description Returns true if email is valid, false otherwise
* @param {string} email string to check if it is a valid email
* @example checkEmailIsValid("hello world") => false
* @example checkEmailIsValid("example@plane.so") => true
*/
export const checkEmailValidity = (email: string): boolean => {
if (!email) return false;
const isEmailValid =
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
email
);
return isEmailValid;
};

View File

@ -1,75 +0,0 @@
import { ReactElement } from "react";
import Image from "next/image";
// components
import { EmailForgotPasswordForm, EmailForgotPasswordFormValues } from "components/account";
// layouts
import DefaultLayout from "layouts/default-layout";
// services
import { UserService } from "services/user.service";
// hooks
import useToast from "hooks/use-toast";
// images
import BluePlaneLogoWithoutText from "public/plane-logos/blue-without-text.png";
// types
import { NextPageWithLayout } from "types/app";
const userService = new UserService();
const ForgotPasswordPage: NextPageWithLayout = () => {
// toast
const { setToastAlert } = useToast();
const handleForgotPassword = (formData: EmailForgotPasswordFormValues) => {
const payload = {
email: formData.email,
};
return userService
.forgotPassword(payload)
.then(() =>
setToastAlert({
type: "success",
title: "Success!",
message: "Password reset link has been sent to your email address.",
})
)
.catch((err) => {
if (err.status === 400)
setToastAlert({
type: "error",
title: "Error!",
message: "Please check the Email ID entered.",
});
else
setToastAlert({
type: "error",
title: "Error!",
message: "Something went wrong. Please try again.",
});
});
};
return (
<>
<div className="hidden sm:block sm:fixed border-r-[0.5px] border-custom-border-200 h-screen w-[0.5px] top-0 left-20 lg:left-32" />
<div className="fixed grid place-items-center bg-custom-background-100 sm:py-5 top-11 sm:top-12 left-7 sm:left-16 lg:left-28">
<div className="grid place-items-center bg-custom-background-100">
<div className="h-[30px] w-[30px]">
<Image src={BluePlaneLogoWithoutText} alt="Plane Logo" />
</div>
</div>
</div>
<div className="grid place-items-center h-full overflow-y-auto py-6 px-7">
<div>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-custom-text-100">Forgot Password</h1>
<EmailForgotPasswordForm onSubmit={handleForgotPassword} />
</div>
</div>
</>
);
};
ForgotPasswordPage.getLayout = function getLayout(page: ReactElement) {
return <DefaultLayout>{page}</DefaultLayout>;
};
export default ForgotPasswordPage;

View File

@ -1,105 +0,0 @@
import { useState, useEffect, ReactElement } from "react";
import { useRouter } from "next/router";
import { useTheme } from "next-themes";
// layouts
import DefaultLayout from "layouts/default-layout";
// services
import { AuthService } from "services/auth.service";
// hooks
import useUserAuth from "hooks/use-user-auth";
import useToast from "hooks/use-toast";
// types
import { NextPageWithLayout } from "types/app";
const authService = new AuthService();
const MagicSignInPage: NextPageWithLayout = () => {
const router = useRouter();
const { password, key } = router.query;
const { setToastAlert } = useToast();
const { setTheme } = useTheme();
const { mutateUser } = useUserAuth("sign-in");
const [isSigningIn, setIsSigningIn] = useState(false);
const [errorSigningIn, setErrorSignIn] = useState<string | undefined>();
useEffect(() => {
setTheme("system");
}, [setTheme]);
useEffect(() => {
setIsSigningIn(() => false);
setErrorSignIn(() => undefined);
if (!password || !key) {
setErrorSignIn("URL is invalid");
return;
} else {
setIsSigningIn(() => true);
authService
.magicSignIn({ token: password, key })
.then(async () => {
setIsSigningIn(false);
await mutateUser();
})
.catch((err) => {
setErrorSignIn(err.response.data.error);
setIsSigningIn(false);
});
}
}, [password, key, mutateUser, router]);
return (
<div className="h-screen w-full overflow-auto bg-custom-background-90">
{isSigningIn ? (
<div className="flex h-full w-full flex-col items-center justify-center gap-3">
<h2 className="text-4xl font-medium">Signing you in...</h2>
<p className="text-sm font-medium text-custom-text-200">Please wait while we are preparing your take off.</p>
</div>
) : errorSigningIn ? (
<div className="flex h-full w-full flex-col items-center justify-center gap-3">
<h2 className="text-4xl font-medium">Error</h2>
<div className="text-sm font-medium text-custom-text-200 flex gap-2">
<div>{errorSigningIn}.</div>
<span
className="cursor-pointer underline"
onClick={() => {
authService
.emailCode({ email: (key as string).split("_")[1] })
.then(() => {
setToastAlert({
type: "success",
title: "Email sent",
message: "A new link/code has been send to you.",
});
})
.catch(() => {
setToastAlert({
type: "error",
title: "Error",
message: "Unable to send email.",
});
});
}}
>
Send link again?
</span>
</div>
</div>
) : (
<div className="flex h-full w-full flex-col items-center justify-center gap-y-2">
<h2 className="text-4xl font-medium">Success</h2>
<p className="text-sm font-medium text-custom-text-200">Redirecting you to the app...</p>
</div>
)}
</div>
);
};
MagicSignInPage.getLayout = function getLayout(page: ReactElement) {
return <DefaultLayout>{page}</DefaultLayout>;
};
export default MagicSignInPage;

View File

@ -0,0 +1,185 @@
import { ReactElement } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/router";
import { useTheme } from "next-themes";
import { Lightbulb } from "lucide-react";
import { Controller, useForm } from "react-hook-form";
// services
import { AuthService } from "services/auth.service";
// hooks
import useToast from "hooks/use-toast";
// layouts
import DefaultLayout from "layouts/default-layout";
// ui
import { Button, Input } from "@plane/ui";
// images
import BluePlaneLogoWithoutText from "public/plane-logos/blue-without-text.png";
import signInIssues from "public/onboarding/onboarding-issues.svg";
// helpers
import { checkEmailValidity } from "helpers/string.helper";
// type
import { NextPageWithLayout } from "types/app";
type TResetPasswordFormValues = {
email: string;
password: string;
};
const defaultValues: TResetPasswordFormValues = {
email: "",
password: "",
};
// services
const authService = new AuthService();
const HomePage: NextPageWithLayout = () => {
// router
const router = useRouter();
const { uidb64, token, email } = router.query;
// next-themes
const { resolvedTheme } = useTheme();
// toast
const { setToastAlert } = useToast();
// form info
const {
control,
formState: { errors, isSubmitting, isValid },
handleSubmit,
} = useForm<TResetPasswordFormValues>({
defaultValues: {
...defaultValues,
email: email?.toString() ?? "",
},
});
const handleResetPassword = async (formData: TResetPasswordFormValues) => {
if (!uidb64 || !token || !email) return;
const payload = {
new_password: formData.password,
};
await authService.resetPassword(uidb64.toString(), token.toString(), payload).catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
);
};
return (
<div className="bg-onboarding-gradient-100 h-full w-full">
<div className="flex items-center justify-between sm:py-5 px-8 pb-4 sm:px-16 lg:px-28 ">
<div className="flex gap-x-2 py-10 items-center">
<Image src={BluePlaneLogoWithoutText} height={30} width={30} alt="Plane Logo" className="mr-2" />
<span className="font-semibold text-2xl sm:text-3xl">Plane</span>
</div>
</div>
<div className="h-full bg-onboarding-gradient-100 md:w-2/3 sm:w-4/5 px-4 pt-4 rounded-t-md mx-auto shadow-sm border-x border-t border-custom-border-200 ">
<div className="px-7 sm:px-0 bg-onboarding-gradient-200 h-full pt-24 pb-56 rounded-t-md overflow-auto">
<div className="sm:w-96 mx-auto flex flex-col divide-y divide-custom-border-200">
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-onboarding-text-100">
Let{"'"}s get a new password
</h1>
<form onSubmit={handleSubmit(handleResetPassword)} className="mt-11 sm:w-96 mx-auto space-y-4">
<Controller
control={control}
name="email"
rules={{
required: "Email is required",
validate: (value) => checkEmailValidity(value) || "Email is invalid",
}}
render={({ field: { value, onChange, ref } }) => (
<Input
id="email"
name="email"
type="email"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.email)}
placeholder="orville.wright@firstflight.com"
className="w-full h-[46px] text-onboarding-text-400 border border-onboarding-border-100 pr-12"
disabled
/>
)}
/>
<div>
<Controller
control={control}
name="password"
rules={{
required: "Password is required",
}}
render={({ field: { value, onChange } }) => (
<Input
type="password"
value={value}
onChange={onChange}
hasError={Boolean(errors.password)}
placeholder="Choose password"
className="w-full h-[46px] placeholder:text-onboarding-text-400 border border-onboarding-border-100 pr-12"
/>
)}
/>
<p className="text-xs text-onboarding-text-200 mt-3">
Whatever you choose now will be your account{"'"}s password until you change it.
</p>
</div>
<Button
type="submit"
variant="primary"
className="w-full"
size="xl"
disabled={!isValid}
loading={isSubmitting}
>
{isSubmitting ? "Signing in..." : "Go to workspace"}
</Button>
<p className="text-xs text-onboarding-text-200">
When you click the button above, you agree with our{" "}
<Link href="https://plane.so/terms-and-conditions" target="_blank" rel="noopener noreferrer">
<a className="font-semibold underline">terms and conditions of service.</a>
</Link>
</p>
</form>
</div>
<div className="flex py-2 bg-onboarding-background-100 border border-onboarding-border-200 mx-auto rounded-[3.5px] sm:w-96 mt-16">
<Lightbulb className="h-7 w-7 mr-2 mx-3" />
<p className="text-sm text-left text-onboarding-text-100">
Try the latest features, like Tiptap editor, to write compelling responses.{" "}
<Link href="https://plane.so/changelog">
<a
target="_blank"
rel="noopener noreferrer"
className="font-medium text-sm underline hover:cursor-pointer"
>
See new features
</a>
</Link>
</p>
</div>
<div className="flex justify-center border border-onboarding-border-200 sm:w-96 sm:h-52 object-cover mt-8 mx-auto rounded-md bg-onboarding-background-100 ">
<Image
src={signInIssues}
alt="Plane Issues"
className={`flex object-cover rounded-md ${
resolvedTheme === "dark" ? "bg-onboarding-background-100" : "bg-custom-primary-70"
} `}
/>
</div>
</div>
</div>
</div>
);
};
HomePage.getLayout = function getLayout(page: ReactElement) {
return <DefaultLayout>{page}</DefaultLayout>;
};
export default HomePage;

View File

@ -1,168 +0,0 @@
import React, { useEffect, useState, ReactElement } from "react";
import { useRouter } from "next/router";
import Image from "next/image";
import { useTheme } from "next-themes";
import { Controller, useForm } from "react-hook-form";
// hooks
import useToast from "hooks/use-toast";
// services
import { UserService } from "services/user.service";
// layouts
import DefaultLayout from "layouts/default-layout";
// ui
import { Button, Input, Spinner } from "@plane/ui";
// images
import BluePlaneLogoWithoutText from "public/plane-logos/blue-without-text.png";
// types
import { NextPageWithLayout } from "types/app";
type FormData = {
password: string;
confirmPassword: string;
};
// services
const userService = new UserService();
const ResetPasswordPage: NextPageWithLayout = () => {
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
const { uidb64, token } = router.query;
const { setToastAlert } = useToast();
const { setTheme } = useTheme();
const {
handleSubmit,
control,
formState: { errors, isSubmitting },
} = useForm<FormData>();
const onSubmit = async (formData: FormData) => {
if (!uidb64 || !token) return;
if (formData.password !== formData.confirmPassword) {
setToastAlert({
type: "error",
title: "Error!",
message: "Passwords do not match.",
});
return;
}
const payload = {
new_password: formData.password,
confirm_password: formData.confirmPassword,
};
await userService
.resetPassword(uidb64.toString(), token.toString(), payload)
.then(() => {
setToastAlert({
type: "success",
title: "Success!",
message: "Password reset successfully. You can now login with your new password.",
});
router.push("/");
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
})
);
};
useEffect(() => {
setTheme("system");
}, [setTheme]);
useEffect(() => {
if (parseInt(process.env.NEXT_PUBLIC_ENABLE_OAUTH || "0")) router.push("/");
else setIsLoading(false);
}, [router]);
if (isLoading)
return (
<div className="grid place-items-center h-screen w-full">
<Spinner />
</div>
);
return (
<>
<div className="hidden sm:block sm:fixed border-r-[0.5px] border-custom-border-200 h-screen w-[0.5px] top-0 left-20 lg:left-32" />
<div className="fixed grid place-items-center bg-custom-background-100 sm:py-5 top-11 sm:top-12 left-7 sm:left-16 lg:left-28">
<div className="grid place-items-center bg-custom-background-100">
<div className="h-[30px] w-[30px]">
<Image src={BluePlaneLogoWithoutText} alt="Plane Logo" />
</div>
</div>
</div>
<div className="grid place-items-center h-full w-full overflow-y-auto py-5 px-7">
<div className="w-full">
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-custom-text-100">Reset your password</h1>
<form className="space-y-4 mt-10 w-full sm:w-[360px] mx-auto" onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-1">
<Controller
control={control}
name="password"
rules={{
required: "Password is required",
}}
render={({ field: { value, onChange, ref } }) => (
<Input
id="password"
name="password"
type="password"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.password)}
placeholder="Enter new password..."
className="border-custom-border-300 h-[46px] w-full"
/>
)}
/>
</div>
<div className="space-y-1">
<Controller
control={control}
name="confirmPassword"
rules={{
required: "Password is required",
}}
render={({ field: { value, onChange, ref } }) => (
<Input
id="confirmPassword"
name="confirmPassword"
type="password"
value={value}
onChange={onChange}
ref={ref}
hasError={Boolean(errors.confirmPassword)}
placeholder="Confirm new password..."
className="border-custom-border-300 h-[46px] w-full"
/>
)}
/>
</div>
<Button variant="primary" type="submit" className="w-full" loading={isSubmitting}>
{isSubmitting ? "Resetting..." : "Reset"}
</Button>
</form>
</div>
</div>
</>
);
};
ResetPasswordPage.getLayout = function getLayout(page: ReactElement) {
return <DefaultLayout>{page}</DefaultLayout>;
};
export default ResetPasswordPage;

View File

@ -2,18 +2,25 @@
import { APIService } from "services/api.service";
// helpers
import { API_BASE_URL } from "helpers/common.helper";
export interface ILoginTokenResponse {
access_token: string;
refresh_toke: string;
}
// types
import { IEmailCheckData, ILoginTokenResponse, IMagicSignInData, IPasswordSignInData } from "types/auth";
export class AuthService extends APIService {
constructor() {
super(API_BASE_URL);
}
async emailLogin(data: any): Promise<ILoginTokenResponse> {
async emailCheck(data: IEmailCheckData): Promise<{
is_password_autoset: boolean;
}> {
return this.post("/api/email-check/", data, { headers: {} })
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
async passwordSignIn(data: IPasswordSignInData): Promise<ILoginTokenResponse> {
return this.post("/api/sign-in/", data, { headers: {} })
.then((response) => {
this.setAccessToken(response?.data?.access_token);
@ -25,6 +32,42 @@ export class AuthService extends APIService {
});
}
async sendResetPasswordLink(data: { email: string }): Promise<any> {
return this.post(`/api/forgot-password/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response;
});
}
async setPassword(data: { password: string }): Promise<any> {
return this.post(`/api/users/me/set-password/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
async resetPassword(
uidb64: string,
token: string,
data: {
new_password: string;
}
): Promise<ILoginTokenResponse> {
return this.post(`/api/reset-password/${uidb64}/${token}/`, data)
.then((response) => {
if (response?.status === 200) {
this.setAccessToken(response?.data?.access_token);
this.setRefreshToken(response?.data?.refresh_token);
return response?.data;
}
})
.catch((error) => {
throw error?.response?.data;
});
}
async emailSignUp(data: { email: string; password: string }): Promise<ILoginTokenResponse> {
return this.post("/api/sign-up/", data, { headers: {} })
.then((response) => {
@ -57,14 +100,18 @@ export class AuthService extends APIService {
});
}
async magicSignIn(data: any): Promise<any> {
const response = await this.post("/api/magic-sign-in/", data, { headers: {} });
if (response?.status === 200) {
this.setAccessToken(response?.data?.access_token);
this.setRefreshToken(response?.data?.refresh_token);
return response?.data;
}
throw response.response.data;
async magicSignIn(data: IMagicSignInData): Promise<any> {
return await this.post("/api/magic-sign-in/", data, { headers: {} })
.then((response) => {
if (response?.status === 200) {
this.setAccessToken(response?.data?.access_token);
this.setRefreshToken(response?.data?.refresh_token);
return response?.data;
}
})
.catch((error) => {
throw error?.response?.data;
});
}
async signOut(): Promise<any> {

View File

@ -117,29 +117,6 @@ export class UserService extends APIService {
});
}
async forgotPassword(data: { email: string }): Promise<any> {
return this.post(`/api/forgot-password/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response;
});
}
async resetPassword(
uidb64: string,
token: string,
data: {
new_password: string;
confirm_password: string;
}
): Promise<any> {
return this.post(`/api/reset-password/${uidb64}/${token}/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
async changePassword(data: { old_password: string; new_password: string; confirm_password: string }): Promise<any> {
return this.post(`/api/users/me/change-password/`, data)
.then((response) => response?.data)

22
web/types/auth.d.ts vendored Normal file
View File

@ -0,0 +1,22 @@
export type TEmailCheckTypes = "magic_code" | "password";
export interface IEmailCheckData {
email: string;
type: TEmailCheckTypes;
}
export interface ILoginTokenResponse {
access_token: string;
refresh_toke: string;
}
export interface IMagicSignInData {
email: string;
key: string;
token: string;
}
export interface IPasswordSignInData {
email: string;
password: string;
}