feat: register or login with email and password (#2075)

* feat: login with password

* chore: auto-fix linting and formatting issues

* feat: show email

* refactor: login form

* chore: update

* fix: show login error

* chore: update

* credential provider

* feat: confirm password

* chore: update

* revokeOtherSessions when update password

* changelog

* typecheck

* chore: update

* chore: update hono

* feat: forget password

* chore: update

* feat: reset password page

* feat: register form

* chore: update

* chore: update

* chore: update

* chore: update

* fix: email login handler

* fix: navigate to login after register

* chore: remove forget password button for now

* chore: update

* feat: forget password page

* chore: update hono

* fix: forget-password link

* feat: login email text

* refactor: enhance login and forget password functionality

- Updated the forget password page to include a back navigation button using MotionButtonBase.
- Refactored the login component to utilize the new Login module, simplifying the structure.
- Adjusted translations for consistency in the login text across English and German locales.
- Improved the useAuthProviders hook to return a more structured AuthProvider interface.

Signed-off-by: Innei <tukon479@gmail.com>

* feat: add form validation and UI enhancements for login-related pages

- Introduced form validation state management in forget-password, register, and reset-password components.
- Updated button states to be disabled when forms are invalid, improving user experience.
- Enhanced UI elements with consistent styling and layout adjustments, including the addition of MotionButtonBase for navigation.
- Improved accessibility and responsiveness of card components.

Signed-off-by: Innei <tukon479@gmail.com>

* feat: enhance login component with dynamic provider buttons

- Added MotionButtonBase for improved button animations and interactions.
- Refactored the rendering logic to conditionally display login options based on the presence of credential providers.
- Introduced a new icon mapping for providers to enhance visual representation.
- Improved layout and styling for better user experience during login.

Signed-off-by: Innei <tukon479@gmail.com>

* feat: add GitHub provider icon and adjust button margin in login component

- Introduced a GitHub icon to the provider icon map for enhanced visual representation.
- Adjusted the margin of the submit button to improve layout consistency.

Signed-off-by: Innei <tukon479@gmail.com>

* chore: update

---------

Signed-off-by: Innei <tukon479@gmail.com>
Co-authored-by: hyoban <hyoban@users.noreply.github.com>
Co-authored-by: DIYgod <i@diygod.me>
Co-authored-by: Innei <tukon479@gmail.com>
Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Stephen Zhou
2024-12-17 01:02:17 +08:00
committed by Innei
co-authored by hyoban DIYgod Innei
parent 123320b6f7
commit ae0dc2c30d
18 changed files with 1303 additions and 341 deletions
@@ -10,6 +10,7 @@ import {
FormMessage,
} from "@follow/components/ui/form/index.jsx"
import { Input } from "@follow/components/ui/input/index.js"
import { Label } from "@follow/components/ui/label/index.js"
import { cn } from "@follow/utils/utils"
import { zodResolver } from "@hookform/resolvers/zod"
import { useMutation } from "@tanstack/react-query"
@@ -72,6 +73,10 @@ export const ProfileSettingForm = ({
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className={cn("mt-4 space-y-4", className)}>
<div className="space-y-2">
<Label>{t("profile.email.label")}</Label>
<p className="text-sm text-muted-foreground">{user?.email}</p>
</div>
<FormField
control={form.control}
name="handle"
@@ -0,0 +1,138 @@
import { Button } from "@follow/components/ui/button/index.js"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@follow/components/ui/form/index.jsx"
import { Input } from "@follow/components/ui/input/index.js"
import { changePassword } from "@follow/shared/auth"
import { zodResolver } from "@hookform/resolvers/zod"
import { useMutation } from "@tanstack/react-query"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { toast } from "sonner"
import { z } from "zod"
import { useHasPassword } from "~/queries/auth"
const passwordSchema = z.string().min(8).max(128)
const updatePasswordFormSchema = z
.object({
currentPassword: passwordSchema,
newPassword: passwordSchema,
confirmPassword: passwordSchema,
})
.refine((data) => data.newPassword === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"],
})
const UpdateExistingPasswordForm = () => {
const { t } = useTranslation("settings")
const form = useForm<z.infer<typeof updatePasswordFormSchema>>({
resolver: zodResolver(updatePasswordFormSchema),
defaultValues: {
currentPassword: "",
newPassword: "",
confirmPassword: "",
},
})
const updateMutation = useMutation({
mutationFn: async (values: z.infer<typeof updatePasswordFormSchema>) => {
const res = await changePassword({
currentPassword: values.currentPassword,
newPassword: values.newPassword,
revokeOtherSessions: true,
})
if (res.error) {
throw new Error(res.error.message)
}
},
onError: (error) => {
toast.error(error.message)
},
onSuccess: (_) => {
toast(t("profile.update_password_success"), {
duration: 3000,
})
form.reset()
},
})
function onSubmit(values: z.infer<typeof updatePasswordFormSchema>) {
updateMutation.mutate(values)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="mt-4 space-y-4">
<FormField
control={form.control}
name="currentPassword"
render={({ field }) => (
<FormItem>
<FormLabel>{t("profile.change_password.label")}</FormLabel>
<FormControl>
<Input
type="password"
placeholder={t("profile.current_password.label")}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="newPassword"
render={({ field }) => (
<FormItem>
<FormControl>
<Input type="password" placeholder={t("profile.new_password.label")} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
type="password"
placeholder={t("profile.confirm_password.label")}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="text-right">
<Button type="submit" isLoading={updateMutation.isPending}>
{t("profile.submit")}
</Button>
</div>
</form>
</Form>
)
}
export const UpdatePasswordForm = () => {
const { data: hasPassword, isLoading } = useHasPassword()
if (isLoading || !hasPassword) {
return null
}
return <UpdateExistingPasswordForm />
}
@@ -1,4 +1,5 @@
import { ProfileSettingForm } from "~/modules/profile/profile-setting-form"
import { UpdatePasswordForm } from "~/modules/profile/update-password-form"
import { SettingsTitle } from "~/modules/settings/title"
import { defineSettingPageData } from "~/modules/settings/utils"
@@ -15,6 +16,7 @@ export function Component() {
<>
<SettingsTitle />
<ProfileSettingForm />
<UpdatePasswordForm />
</>
)
}
+18 -1
View File
@@ -1,4 +1,4 @@
import { getSession } from "@follow/shared/auth"
import { getSession, listAccounts } from "@follow/shared/auth"
import type { AuthSession } from "@follow/shared/hono"
import type { FetchError } from "ofetch"
@@ -7,6 +7,23 @@ import { defineQuery } from "~/lib/defineQuery"
export const auth = {
getSession: () => defineQuery(["auth", "session"], () => getSession()),
getAccounts: () =>
defineQuery(["auth", "accounts"], async () => {
const accounts = await listAccounts()
return accounts.data as Array<{ id: string; provider: string }>
}),
}
export const useAccounts = () => {
return useAuthQuery(auth.getAccounts())
}
export const useHasPassword = () => {
const accounts = useAccounts()
return {
...accounts,
data: !!accounts.data?.find((account) => account.provider === "credential"),
}
}
export const useSession = (options?: { enabled?: boolean }) => {
+302
View File
@@ -0,0 +1,302 @@
import { UserAvatar } from "@client/components/ui/user-avatar"
import { queryClient } from "@client/lib/query-client"
import { useSession } from "@client/query/auth"
import { useAuthProviders } from "@client/query/users"
import { Logo } from "@follow/components/icons/logo.jsx"
import { AutoResizeHeight } from "@follow/components/ui/auto-resize-height/index.jsx"
import { Button, MotionButtonBase } from "@follow/components/ui/button/index.js"
import { Divider } from "@follow/components/ui/divider/index.js"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@follow/components/ui/form/index.jsx"
import { Input } from "@follow/components/ui/input/index.js"
import { LoadingCircle } from "@follow/components/ui/loading/index.jsx"
import { authProvidersConfig } from "@follow/constants"
import { createSession, loginHandler, signOut } from "@follow/shared/auth"
import { DEEPLINK_SCHEME } from "@follow/shared/constants"
import { cn } from "@follow/utils/utils"
import { zodResolver } from "@hookform/resolvers/zod"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useForm } from "react-hook-form"
import { Trans, useTranslation } from "react-i18next"
import { Link, useLocation, useNavigate } from "react-router"
import { toast } from "sonner"
import { z } from "zod"
const overrideProviderIconMap: Record<string, React.ReactNode> = {
apple: <i className="i-mgc-apple-cute-fi size-5 text-black dark:text-white" />,
github: <i className="i-mgc-github-cute-fi size-5 text-black dark:text-white" />,
}
export function Login() {
const { status, refetch } = useSession()
const [redirecting, setRedirecting] = useState(false)
const { data: authProviders, isLoading } = useAuthProviders()
const location = useLocation()
const urlParams = new URLSearchParams(location.search)
const provider = urlParams.get("provider")
const isCredentialProvider = provider === "credential"
const isAuthenticated = status === "authenticated"
const { t } = useTranslation("external")
useEffect(() => {
if (provider && !isCredentialProvider && status === "unauthenticated") {
loginHandler(provider)
setRedirecting(true)
}
}, [isCredentialProvider, provider, status])
const getCallbackUrl = useCallback(async () => {
const { data } = await createSession()
if (!data) return null
return {
url: `${DEEPLINK_SCHEME}auth?ck=${data.ck}&userId=${data.userId}`,
userId: data.userId,
}
}, [])
const handleOpenApp = useCallback(async () => {
const callbackUrl = await getCallbackUrl()
if (!callbackUrl) return
window.open(callbackUrl.url, "_top")
}, [getCallbackUrl])
const onceRef = useRef(false)
useEffect(() => {
if (isAuthenticated && !onceRef.current) {
handleOpenApp()
}
onceRef.current = true
}, [handleOpenApp, isAuthenticated])
const LoginOrStatusContent = useMemo(() => {
switch (true) {
case isAuthenticated: {
return (
<div className="flex w-full flex-col items-center justify-center gap-10 px-4">
<div className="relative flex items-center justify-center">
<UserAvatar className="gap-4 px-10 py-4 text-2xl" />
<div className="absolute right-0">
<Button
variant="ghost"
onClick={async () => {
await signOut()
await refetch()
}}
>
<i className="i-mingcute-exit-line text-xl" />
</Button>
</div>
</div>
<h2 className="text-center">
{t("redirect.successMessage", { app_name: APP_NAME })} <br />
<br />
{t("redirect.instruction", { app_name: APP_NAME })}
</h2>
<div className="center flex flex-col gap-20 sm:flex-row">
<Button
variant="text"
className="h-14 text-base"
onClick={() => {
window.location.href = "/"
}}
>
{t("redirect.continueInBrowser")}
</Button>
<Button className="h-14 !rounded-full px-5 text-lg" onClick={handleOpenApp}>
{t("redirect.openApp", { app_name: APP_NAME })}
</Button>
</div>
</div>
)
}
default: {
if (!authProviders?.credential) {
return (
<div className="flex w-[350px] max-w-full flex-col gap-3">
{Object.entries(authProviders || [])
.filter(([key]) => key !== "credential")
.map(([key, provider]) => (
<Button
key={key}
buttonClassName={cn(
"h-[48px] w-full rounded-[8px] font-sans text-base text-white hover:!bg-black/80 focus:!border-black/80 focus:!ring-black/80",
authProvidersConfig[key]?.buttonClassName,
)}
onClick={() => {
loginHandler(key)
}}
>
<i className={cn("mr-2 text-xl", authProvidersConfig[key].iconClassName)} />{" "}
{t("login.continueWith", { provider: provider.name })}
</Button>
))}
</div>
)
} else {
return (
<>
<LoginWithPassword />
<div className="mt-2 w-full space-y-2">
<div className="flex items-center justify-center">
<Divider className="flex-1" />
<p className="px-4 text-center text-sm text-muted-foreground">{t("login.or")}</p>
<Divider className="flex-1" />
</div>
</div>
<div className="flex items-center justify-center gap-4">
{Object.entries(authProviders || [])
.filter(([key]) => key !== "credential")
.map(([key, provider]) => (
<MotionButtonBase
key={key}
onClick={() => {
loginHandler(key)
}}
>
{overrideProviderIconMap[provider.id] ? (
<div className="center box-content inline-flex size-5 rounded-full border p-2 duration-200 hover:bg-muted">
{overrideProviderIconMap[provider.id]}
</div>
) : (
<div
className="center inline-flex rounded-full border p-2 duration-200 hover:bg-muted [&_svg]:size-5"
dangerouslySetInnerHTML={{
__html: provider.icon,
}}
style={{
color: provider.color,
}}
/>
)}
</MotionButtonBase>
))}
</div>
</>
)
}
}
}
}, [authProviders, handleOpenApp, isAuthenticated, refetch, t])
const Content = useMemo(() => {
switch (true) {
case redirecting: {
return <div>{t("login.redirecting")}</div>
}
default: {
return <div className="flex flex-col gap-3">{LoginOrStatusContent}</div>
}
}
}, [LoginOrStatusContent, redirecting, t])
return (
<div className="flex h-screen w-full flex-col items-center justify-center">
<Logo className="size-16" />
{isLoading && <LoadingCircle className="mt-8" size="large" />}
<AutoResizeHeight>
<>
{!isAuthenticated && !isLoading && (
<h1 className="center mb-6 mt-8 flex text-2xl font-bold">
{t("login.logInTo")}
{` ${APP_NAME}`}
</h1>
)}
{Content}
</>
</AutoResizeHeight>
</div>
)
}
const formSchema = z.object({
email: z.string().email(),
password: z.string().max(128),
})
async function onSubmit(values: z.infer<typeof formSchema>) {
const res = await loginHandler("credential", "browser", values)
if (res?.error) {
toast.error(res.error.message)
return
}
queryClient.invalidateQueries({ queryKey: ["auth", "session"] })
}
function LoginWithPassword() {
const { t } = useTranslation("external")
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
password: "",
},
})
const { isValid } = form.formState
const navigate = useNavigate()
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-1">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>{t("login.email")}</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>{t("login.password")}</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Link to="/forget-password" className="block py-1 text-xs text-accent hover:underline">
{t("login.forget_password.note")}
</Link>
<Button
type="submit"
className="w-full"
buttonClassName="text-base !mt-3"
disabled={!isValid}
>
{t("login.continueWith", { provider: "email" })}
</Button>
<Button
buttonClassName="!mt-3 text-base"
className="w-full"
variant="outline"
onClick={() => {
navigate("/register")
}}
>
<Trans ns="external" i18nKey="login.signUp" />
</Button>
</form>
</Form>
)
}
@@ -0,0 +1,112 @@
import { Button, MotionButtonBase } from "@follow/components/ui/button/index.jsx"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@follow/components/ui/card/index.jsx"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@follow/components/ui/form/index.jsx"
import { Input } from "@follow/components/ui/input/index.js"
import { forgetPassword } from "@follow/shared/auth"
import { env } from "@follow/shared/env"
import { zodResolver } from "@hookform/resolvers/zod"
import { useMutation } from "@tanstack/react-query"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { useNavigate } from "react-router"
import { toast } from "sonner"
import { z } from "zod"
const forgetPasswordFormSchema = z.object({
email: z.string().email(),
})
export function Component() {
const { t } = useTranslation("external")
const form = useForm<z.infer<typeof forgetPasswordFormSchema>>({
resolver: zodResolver(forgetPasswordFormSchema),
defaultValues: {
email: "",
},
})
const { isValid } = form.formState
const updateMutation = useMutation({
mutationFn: async (values: z.infer<typeof forgetPasswordFormSchema>) => {
const res = await forgetPassword({
email: values.email,
redirectTo: `${env.VITE_WEB_URL}/reset-password`,
})
if (res.error) {
throw new Error(res.error.message)
}
},
onError: (error) => {
toast.error(error.message)
},
onSuccess: () => {
toast.success(t("login.forget_password.success"))
},
})
function onSubmit(values: z.infer<typeof forgetPasswordFormSchema>) {
updateMutation.mutate(values)
}
const navigate = useNavigate()
return (
<div className="flex h-full items-center justify-center">
<Card className="w-[350px] max-w-full">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MotionButtonBase
onClick={() => {
history.length > 1 ? history.back() : navigate("/login")
}}
className="-ml-1 inline-flex cursor-pointer items-center"
>
<i className="i-mingcute-left-line" />
</MotionButtonBase>
<span>{t("login.forget_password.label")}</span>
</CardTitle>
</CardHeader>
<CardContent>
<CardDescription className="mb-4">
{t("login.forget_password.description")}
</CardDescription>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>{t("login.email")}</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="text-right">
<Button disabled={!isValid} type="submit" isLoading={updateMutation.isPending}>
{t("login.submit")}
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
</div>
)
}
+1 -131
View File
@@ -1,135 +1,5 @@
import { UserAvatar } from "@client/components/ui/user-avatar"
import { useSession } from "@client/query/auth"
import { useAuthProviders } from "@client/query/users"
import { Logo } from "@follow/components/icons/logo.jsx"
import { Button } from "@follow/components/ui/button/index.js"
import { authProvidersConfig } from "@follow/constants"
import { createSession, loginHandler, signOut } from "@follow/shared/auth"
import { DEEPLINK_SCHEME } from "@follow/shared/constants"
import { cn } from "@follow/utils/utils"
import { useCallback, useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useLocation } from "react-router"
import { Login } from "@client/modules/login"
export function Component() {
return <Login />
}
function Login() {
const { status, refetch } = useSession()
const [redirecting, setRedirecting] = useState(false)
const { data: authProviders } = useAuthProviders()
const location = useLocation()
const urlParams = new URLSearchParams(location.search)
const provider = urlParams.get("provider")
const isAuthenticated = status === "authenticated"
const { t } = useTranslation("external")
useEffect(() => {
if (provider && status === "unauthenticated") {
loginHandler(provider)
setRedirecting(true)
}
}, [status])
const getCallbackUrl = useCallback(async () => {
const { data } = await createSession()
if (!data) return null
return {
url: `${DEEPLINK_SCHEME}auth?ck=${data.ck}&userId=${data.userId}`,
userId: data.userId,
}
}, [])
const handleOpenApp = useCallback(async () => {
const callbackUrl = await getCallbackUrl()
if (!callbackUrl) return
window.open(callbackUrl.url, "_top")
}, [getCallbackUrl])
const onceRef = useRef(false)
useEffect(() => {
if (isAuthenticated && !onceRef.current) {
handleOpenApp()
}
onceRef.current = true
}, [handleOpenApp, isAuthenticated])
return (
<div className="flex h-screen w-full flex-col items-center justify-center gap-10">
<Logo className="size-20" />
{!isAuthenticated && (
<h1 className="text-3xl font-bold">
{t("login.logInTo")}
{` ${APP_NAME}`}
</h1>
)}
{redirecting ? (
<div>{t("login.redirecting")}</div>
) : (
<div className="flex flex-col gap-3">
{isAuthenticated ? (
<div className="flex w-full flex-col items-center justify-center gap-10 px-4">
<div className="relative flex items-center justify-center">
<UserAvatar className="gap-4 px-10 py-4 text-2xl" />
<div className="absolute right-0">
<Button
variant="ghost"
onClick={async () => {
await signOut()
await refetch()
}}
>
<i className="i-mingcute-exit-line text-xl" />
</Button>
</div>
</div>
<h2 className="text-center">
{t("redirect.successMessage", { app_name: APP_NAME })} <br />
<br />
{t("redirect.instruction", { app_name: APP_NAME })}
</h2>
<div className="center flex flex-col gap-20 sm:flex-row">
<Button
variant="text"
className="h-14 text-base"
onClick={() => {
window.location.href = "/"
}}
>
{t("redirect.continueInBrowser")}
</Button>
<Button className="h-14 !rounded-full px-5 text-lg" onClick={handleOpenApp}>
{t("redirect.openApp", { app_name: APP_NAME })}
</Button>
</div>
</div>
) : (
<>
{Object.entries(authProviders || []).map(([key, provider]) => (
<Button
key={key}
buttonClassName={cn(
"h-[48px] w-[320px] rounded-[8px] font-sans text-base text-white hover:!bg-black/80 focus:!border-black/80 focus:!ring-black/80",
authProvidersConfig[key]?.buttonClassName,
)}
onClick={() => {
loginHandler(key)
}}
>
<i className={cn("mr-2 text-xl", authProvidersConfig[key].iconClassName)} />{" "}
{t("login.continueWith", { provider: provider.name })}
</Button>
))}
</>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,139 @@
import { Logo } from "@follow/components/icons/logo.jsx"
import { Button } from "@follow/components/ui/button/index.jsx"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@follow/components/ui/form/index.jsx"
import { Input } from "@follow/components/ui/input/index.js"
import { signUp } from "@follow/shared/auth"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { Trans, useTranslation } from "react-i18next"
import { Link, useNavigate } from "react-router"
import { toast } from "sonner"
import { z } from "zod"
export function Component() {
return (
<div className="flex h-full flex-col items-center justify-center gap-10">
<Logo className="size-20" />
<RegisterForm />
</div>
)
}
const formSchema = z
.object({
email: z.string().email(),
password: z.string().min(8).max(128),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"],
})
function RegisterForm() {
const { t } = useTranslation("external")
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
password: "",
confirmPassword: "",
},
})
const { isValid } = form.formState
const navigate = useNavigate()
function onSubmit(values: z.infer<typeof formSchema>) {
return signUp.email({
email: values.email,
password: values.password,
name: values.email.split("@")[0],
callbackURL: "/",
fetchOptions: {
onSuccess() {
navigate("/login")
},
onError(context) {
toast.error(context.error.message)
},
},
})
}
return (
<div className="relative">
<h1 className="center flex text-2xl font-bold">
{t("register.label", { app_name: APP_NAME })}
</h1>
<div className="mt-2 text-center text-muted-foreground">
<Trans
ns="external"
i18nKey="register.note"
components={{
LoginLink: (
<Link to="/login" className="text-accent hover:underline">
{t("register.login")}
</Link>
),
}}
/>
</div>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="mt-6 space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>{t("register.email")}</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>{t("register.password")}</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel>{t("register.confirm_password")}</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button disabled={!isValid} type="submit" className="w-full">
{t("register.submit")}
</Button>
</form>
</Form>
</div>
)
}
@@ -0,0 +1,130 @@
import { Button, MotionButtonBase } from "@follow/components/ui/button/index.jsx"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@follow/components/ui/card/index.jsx"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@follow/components/ui/form/index.jsx"
import { Input } from "@follow/components/ui/input/index.js"
import { resetPassword } from "@follow/shared/auth"
import { zodResolver } from "@hookform/resolvers/zod"
import { useMutation } from "@tanstack/react-query"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { useNavigate } from "react-router"
import { toast } from "sonner"
import { z } from "zod"
const passwordSchema = z.string().min(8).max(128)
const initPasswordFormSchema = z
.object({
newPassword: passwordSchema,
confirmPassword: passwordSchema,
})
.refine((data) => data.newPassword === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"],
})
export function Component() {
const { t } = useTranslation("external")
const form = useForm<z.infer<typeof initPasswordFormSchema>>({
resolver: zodResolver(initPasswordFormSchema),
defaultValues: {
newPassword: "",
confirmPassword: "",
},
})
const { isValid } = form.formState
const navigate = useNavigate()
const updateMutation = useMutation({
mutationFn: async (values: z.infer<typeof initPasswordFormSchema>) => {
const res = await resetPassword({ newPassword: values.newPassword })
const error = res.error?.message
if (error) {
throw new Error(error)
}
},
onError: (error) => {
toast.error(error.message)
},
onSuccess: () => {
toast.success(t("login.reset_password.success"))
navigate("/login")
},
})
function onSubmit(values: z.infer<typeof initPasswordFormSchema>) {
updateMutation.mutate(values)
}
return (
<div className="flex h-full items-center justify-center">
<Card className="w-[350px] max-w-full">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MotionButtonBase
onClick={() => {
history.length > 1 ? history.back() : navigate("/login")
}}
className="-ml-1 inline-flex cursor-pointer items-center"
>
<i className="i-mingcute-left-line" />
</MotionButtonBase>
<span>{t("login.forget_password.label")}</span>
</CardTitle>
</CardHeader>
<CardContent>
<CardDescription>{t("login.reset_password.description")}</CardDescription>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="mt-4 space-y-4">
<FormField
control={form.control}
name="newPassword"
render={({ field }) => (
<FormItem>
<FormLabel>{t("login.new_password.label")}</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel>{t("login.confirm_password.label")}</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="text-right">
<Button disabled={!isValid} type="submit" isLoading={updateMutation.isPending}>
{t("login.submit")}
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
</div>
)
}
+7 -12
View File
@@ -56,20 +56,15 @@ export const useUserQuery = (handleOrId: string | undefined) => {
initialData: getHydrateData(`profiles.$get,query:id=${handleOrId}`),
})
}
export interface AuthProvider {
name: string
id: string
color: string
icon: string
}
export const useAuthProviders = () => {
return useQuery({
queryKey: ["providers"],
queryFn: async () => (await getProviders()).data,
placeholderData: {
google: {
id: "google",
name: "Google",
},
github: {
id: "github",
name: "GitHub",
},
},
queryFn: async () => (await getProviders()).data as Record<string, AuthProvider>,
})
}
+3 -1
View File
@@ -27,6 +27,7 @@
"rc-modal-sheet": "0.3.2",
"react": "^18.3.1",
"react-blurhash": "^0.3.0",
"react-hook-form": "7.54.0",
"react-hotkeys-hook": "4.6.1",
"react-i18next": "^15.1.3",
"react-photo-view": "1.2.6",
@@ -35,7 +36,8 @@
"sonner": "1.7.1",
"tailwindcss": "3.4.16",
"use-context-selector": "2.0.0",
"xss": "1.0.15"
"xss": "1.0.15",
"zod": "3.23.8"
},
"devDependencies": {
"@follow/components": "workspace:*",
+2
View File
@@ -2,6 +2,8 @@
## New Features
- Register or Login with email and password
## Improvements
## Bug Fixes
+1 -1
View File
@@ -15,7 +15,7 @@
"invitation.getCodeMessage": "You can get an invitation code through the following ways:",
"invitation.title": "Invitation Code",
"login.backToWebApp": "Back to the web app",
"login.logInTo": "Log in to ",
"login.logInTo": "Login to ",
"login.openApp": "Open app",
"login.redirecting": "Redirecting",
"login.welcomeTo": "Welcome to ",
+25 -2
View File
@@ -34,14 +34,37 @@
"invitation.getCodeMessage": "You can get an invitation code in the following ways:",
"invitation.title": "Invitation Code",
"login.backToWebApp": "Back To Web App",
"login.confirm_password.label": "Confirm Password",
"login.continueWith": "Continue with {{provider}}",
"login.logInTo": "Log in to ",
"login.email": "Email",
"login.forget_password.description": "Enter the email address associated with your account and we’ll send you an email about how to reset your password.",
"login.forget_password.label": "Forget Password",
"login.forget_password.note": "Forgot your password?",
"login.forget_password.success": "Email has been sent successfully",
"login.logInTo": "Login to ",
"login.logInWithEmail": "Login with email",
"login.new_password.label": "New Password",
"login.openApp": "Open App",
"login.or": "Or",
"login.password": "Password",
"login.redirecting": "Redirecting",
"login.register": "Create one",
"login.reset_password.description": "Enter new password and confirm it to reset your password",
"login.reset_password.label": "Reset Password",
"login.reset_password.success": "Password has been successfully reset",
"login.signOut": "Sign out",
"login.signUp": "Sign up with email",
"login.submit": "Submit",
"login.welcomeTo": "Welcome to ",
"redirect.continueInBrowser": "Continue in Browser",
"redirect.instruction": "Now is the time to open {{app_name}} and safely close this page.",
"redirect.openApp": "Open {{app_name}}",
"redirect.successMessage": "You have successfully connected to {{app_name}} Account."
"redirect.successMessage": "You have successfully connected to {{app_name}} Account.",
"register.confirm_password": "Confirm Password",
"register.email": "Email",
"register.label": "Create a {{app_name}} account",
"register.login": "Login",
"register.note": "Already have an account? <LoginLink />",
"register.password": "Password",
"register.submit": "Create account"
}
+7
View File
@@ -259,14 +259,21 @@
"lists.title": "Title",
"lists.view": "View",
"profile.avatar.label": "Avatar",
"profile.change_password.label": "Change Password",
"profile.confirm_password.label": "Confirm Password",
"profile.current_password.label": "Current Password",
"profile.email.label": "Email",
"profile.handle.description": "Your unique identifier.",
"profile.handle.label": "Handle",
"profile.name.description": "Your public display name.",
"profile.name.label": "Display Name",
"profile.new_password.label": "New Password",
"profile.reset_password_mail_sent": "Reset password mail sent.",
"profile.sidebar_title": "Profile",
"profile.submit": "Submit",
"profile.title": "Profile Settings",
"profile.updateSuccess": "Profile updated.",
"profile.update_password_success": "Password updated.",
"titles.about": "About",
"titles.actions": "Actions",
"titles.appearance": "Appearance",
+40 -2
View File
@@ -14,6 +14,14 @@ const serverPlugins = [
id: "createSession",
$InferServerPlugin: {} as (typeof authPlugins)[1],
},
inferAdditionalFields({
user: {
handle: {
type: "string",
required: false,
},
},
}),
] satisfies BetterAuthClientPlugin[]
const authClient = createAuthClient({
@@ -21,14 +29,44 @@ const authClient = createAuthClient({
plugins: serverPlugins,
})
export const { signIn, signOut, getSession, getProviders, createSession } = authClient
// @keep-sorted
export const {
changePassword,
createSession,
forgetPassword,
getProviders,
getSession,
linkSocial,
listAccounts,
resetPassword,
signIn,
signOut,
signUp,
updateUser,
} = authClient
export const LOGIN_CALLBACK_URL = `${WEB_URL}/login`
export type LoginRuntime = "browser" | "app"
export const loginHandler = (provider: string, runtime: LoginRuntime = "app") => {
export const loginHandler = async (
provider: string,
runtime?: LoginRuntime,
args?: {
email?: string
password?: string
},
) => {
const { email, password } = args ?? {}
if (IN_ELECTRON) {
window.open(`${WEB_URL}/login?provider=${provider}`)
} else {
if (provider === "credential") {
if (!email || !password) {
window.location.href = "/login"
return
}
return signIn.email({ email, password })
}
signIn.social({
provider: provider as "google" | "github" | "apple",
callbackURL: runtime === "app" ? LOGIN_CALLBACK_URL : undefined,
File diff suppressed because it is too large Load Diff
+6
View File
@@ -804,6 +804,9 @@ importers:
react-blurhash:
specifier: ^0.3.0
version: 0.3.0(blurhash@2.0.5)(react@18.3.1)
react-hook-form:
specifier: 7.54.0
version: 7.54.0(react@18.3.1)
react-hotkeys-hook:
specifier: 4.6.1
version: 4.6.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
@@ -831,6 +834,9 @@ importers:
xss:
specifier: 1.0.15
version: 1.0.15
zod:
specifier: 3.23.8
version: 3.23.8
devDependencies:
'@follow/components':
specifier: workspace:*