feat: all in one preview

This commit is contained in:
Zhang Minghan 2023-12-23 15:35:04 +08:00
parent 6268a10959
commit f1ae776843
27 changed files with 1149 additions and 151 deletions

111
app/src/api/auth.ts Normal file
View File

@ -0,0 +1,111 @@
import axios from "axios";
import { getErrorMessage } from "@/utils/base.ts";
export type LoginForm = {
username: string;
password: string;
};
export type DeepLoginForm = {
token: string;
};
export type LoginResponse = {
status: boolean;
error: string;
token: string;
};
export type StateResponse = {
status: boolean;
user: string;
admin: boolean;
};
export type RegisterForm = {
username: string;
password: string;
repassword: string;
email: string;
code: string;
};
export type RegisterResponse = {
status: boolean;
error: string;
token: string;
};
export type VerifyForm = {
email: string;
};
export type VerifyResponse = {
status: boolean;
error: string;
};
export type ResetForm = {
email: string;
code: string;
password: string;
repassword: string;
};
export type ResetResponse = {
status: boolean;
error: string;
};
export async function doLogin(
data: DeepLoginForm | LoginForm,
): Promise<LoginResponse> {
const response = await axios.post("/login", data);
return response.data as LoginResponse;
}
export async function doState(): Promise<StateResponse> {
const response = await axios.post("/state");
return response.data as StateResponse;
}
export async function doRegister(
data: RegisterForm,
): Promise<RegisterResponse> {
try {
const response = await axios.post("/register", data);
return response.data as RegisterResponse;
} catch (e) {
return {
status: false,
error: getErrorMessage(e),
token: "",
};
}
}
export async function doVerify(email: string): Promise<VerifyResponse> {
try {
const response = await axios.post("/verify", {
email,
} as VerifyForm);
return response.data as VerifyResponse;
} catch (e) {
return {
status: false,
error: getErrorMessage(e),
};
}
}
export async function doReset(data: ResetForm): Promise<ResetResponse> {
try {
const response = await axios.post("/reset", data);
return response.data as ResetResponse;
} catch (e) {
return {
status: false,
error: getErrorMessage(e),
};
}
}

View File

@ -59,6 +59,7 @@
--assistant-shadow: hsla(218, 100%, 64%, .03);
--gold: 45 100% 50%;
--link: 210 100% 63%;
}
.dark {

View File

@ -43,6 +43,7 @@ html, body {
outline: 0;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
-webkit-overflow-scrolling: touch;
}
body {

View File

@ -4,3 +4,79 @@
overflow: hidden;
background: hsla(var(--background-container));
}
.auth-container {
display: flex;
flex-direction: column;
align-items: center;
margin: 2.5rem 2rem;
user-select: none;
.logo {
width: 4rem;
height: 4rem;
}
& > * {
margin-bottom: 0.5rem;
&:last-child {
margin-bottom: 0;
}
}
}
.auth-card {
width: 80vw;
max-width: 360px;
min-width: 280px;
margin: 1rem 0;
}
.auth-wrapper {
display: flex;
flex-direction: column;
padding: 1.5rem 0;
& > * {
margin-bottom: 1rem;
&:last-child {
margin-bottom: 0;
}
}
}
.addition-wrapper {
display: flex;
flex-direction: column;
border-radius: var(--radius);
border: 1px solid hsla(var(--border));
padding: 1.25rem;
align-items: center;
transform: translateY(-1rem);
font-size: 0.875rem;
text-align: center;
a {
text-decoration: underline;
text-underline-offset: 0.25rem;
text-underline: 2px solid hsl(var(--text-secondary));
color: hsl(var(--text-secondary));
transition: 0.2s ease-in-out;
cursor: pointer;
&:hover {
color: hsl(var(--text));
text-underline-color: hsl(var(--text));
}
}
.row {
margin-bottom: 0.5rem;
&:last-child {
margin-bottom: 0;
}
}
}

View File

@ -16,7 +16,7 @@ function I18nProvider() {
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon">
<Languages className="absolute h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all" />
<Languages className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>

View File

@ -26,7 +26,7 @@ function ProjectLink() {
>
<svg
viewBox="0 0 438.549 438.549"
className="absolute h-[1.2rem] w-[1.2rem] rotate-0 scale-100"
className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100"
>
<path
fill="currentColor"

View File

@ -1,5 +1,90 @@
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import { isEmailValid } from "@/utils/form.ts";
function Required() {
return <span className={`text-red-500 mr-0.5`}>*</span>;
}
export type LengthRangeRequiredProps = {
content: string;
min: number;
max: number;
hideOnEmpty?: boolean;
};
export function LengthRangeRequired({
content,
min,
max,
hideOnEmpty,
}: LengthRangeRequiredProps) {
const { t } = useTranslation();
const onDisplay = useMemo(() => {
if (hideOnEmpty && content.length === 0) return false;
return content.length < min || content.length > max;
}, [content, min, max, hideOnEmpty]);
return (
<span
className={`ml-1 text-red-500 transition-opacity ${
onDisplay ? "" : "opacity-0"
}`}
>
({t("auth.length-range", { min, max })})
</span>
);
}
export type SameRequiredProps = {
content: string;
compare: string;
hideOnEmpty?: boolean;
};
export function SameRequired({
content,
compare,
hideOnEmpty,
}: SameRequiredProps) {
const { t } = useTranslation();
const onDisplay = useMemo(() => {
if (hideOnEmpty && compare.length === 0) return false;
return content !== compare;
}, [content, compare, hideOnEmpty]);
return (
<span
className={`ml-1 text-red-500 transition-opacity ${
onDisplay ? "" : "opacity-0"
}`}
>
({t("auth.same-rule")})
</span>
);
}
export type EmailRequireProps = {
content: string;
hideOnEmpty?: boolean;
};
export function EmailRequire({ content, hideOnEmpty }: EmailRequireProps) {
const { t } = useTranslation();
const onDisplay = useMemo(() => {
if (hideOnEmpty && content.length === 0) return false;
return !isEmailValid(content);
}, [content, hideOnEmpty]);
return (
<span
className={`ml-1 text-red-500 transition-opacity ${
onDisplay ? "" : "opacity-0"
}`}
>
({t("auth.invalid-email")})
</span>
);
}
export default Required;

View File

@ -95,8 +95,12 @@ export function ModeToggle() {
return (
<Button variant="outline" size="icon" onClick={() => toggleTheme?.()}>
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<Sun
className={`relative dark:absolute h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0`}
/>
<Moon
className={`absolute dark:relative h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100`}
/>
</Button>
);
}

View File

@ -0,0 +1,53 @@
import { Button, ButtonProps } from "@/components/ui/button.tsx";
import React, { useEffect, useRef, useState } from "react";
import { isAsyncFunc } from "@/utils/base.ts";
export interface TickButtonProps extends ButtonProps {
tick: number;
onTickChange?: (tick: number) => void;
onClick?: (
e: React.MouseEvent<HTMLButtonElement>,
) => boolean | Promise<boolean>;
}
function TickButton({
tick,
onTickChange,
onClick,
children,
...props
}: TickButtonProps) {
const stamp = useRef(0);
const [timer, setTimer] = useState(0);
useEffect(() => {
setInterval(() => {
const offset = Math.floor((Number(Date.now()) - stamp.current) / 1000);
let value = tick - offset;
if (value <= 0) value = 0;
setTimer(value);
onTickChange && onTickChange(value);
}, 250);
}, []);
const onReset = () => (stamp.current = Number(Date.now()));
// if is async function, use this:
const onTrigger = isAsyncFunc(onClick)
? async (e: React.MouseEvent<HTMLButtonElement>) => {
if (timer !== 0 || !onClick) return;
if (await onClick(e)) onReset();
}
: (e: React.MouseEvent<HTMLButtonElement>) => {
if (timer !== 0 || !onClick) return;
if (onClick(e)) onReset();
};
return (
<Button {...props} onClick={onTrigger}>
{timer === 0 ? children : `${timer}s`}
</Button>
);
}
export default TickButton;

View File

@ -9,7 +9,7 @@ import {
import { Button } from "@/components/ui/button.tsx";
import { Menu } from "lucide-react";
import { useEffect } from "react";
import { login, tokenField } from "@/conf.ts";
import { tokenField } from "@/conf.ts";
import { toggleMenu } from "@/store/menu.ts";
import ProjectLink from "@/components/ProjectLink.tsx";
import ModeToggle from "@/components/ThemeProvider.tsx";
@ -17,6 +17,7 @@ import router from "@/router.tsx";
import MenuBar from "./MenuBar.tsx";
import { getMemory } from "@/utils/memory.ts";
import { deeptrainApiEndpoint } from "@/utils/env.ts";
import { goAuth } from "@/utils/app.ts";
function NavMenu() {
const username = useSelector(selectUsername);
@ -62,7 +63,7 @@ function NavBar() {
{auth ? (
<NavMenu />
) : (
<Button size={`sm`} onClick={login}>
<Button size={`sm`} onClick={goAuth}>
{t("login")}
</Button>
)}

View File

@ -1,5 +1,5 @@
import SelectGroup, { SelectItemProps } from "@/components/SelectGroup.tsx";
import { expensiveModels, login, supportModels } from "@/conf.ts";
import { expensiveModels, supportModels } from "@/conf.ts";
import {
getPlanModels,
openMarket,
@ -18,6 +18,7 @@ import { teenagerSelector } from "@/store/package.ts";
import { ToastAction } from "@/components/ui/toast.tsx";
import { useMemo } from "react";
import { Sparkles } from "lucide-react";
import { goAuth } from "@/utils/app.ts";
function GetModel(name: string): Model {
return supportModels.find((model) => model.id === name) as Model;
@ -99,7 +100,7 @@ function ModelFinder(props: ModelSelectorProps) {
toast({
title: t("login-require"),
action: (
<ToastAction altText={t("login")} onClick={login}>
<ToastAction altText={t("login")} onClick={goAuth}>
{t("login")}
</ToastAction>
),

View File

@ -10,7 +10,7 @@ import {
X,
} from "lucide-react";
import React, { useMemo, useState } from "react";
import { login, modelAvatars, supportModels } from "@/conf.ts";
import { modelAvatars, supportModels } from "@/conf.ts";
import { splitList } from "@/utils/base.ts";
import { Model } from "@/api/types.ts";
import { useDispatch, useSelector } from "react-redux";
@ -30,6 +30,7 @@ import { ToastAction } from "@/components/ui/toast.tsx";
import { selectAuthenticated } from "@/store/auth.ts";
import { useToast } from "@/components/ui/use-toast.ts";
import { docsEndpoint } from "@/utils/env.ts";
import { goAuth } from "@/utils/app.ts";
type SearchBarProps = {
value: string;
@ -100,7 +101,7 @@ function ModelItem({ model, className, style }: ModelProps) {
toast({
title: t("login-require"),
action: (
<ToastAction altText={t("login")} onClick={login}>
<ToastAction altText={t("login")} onClick={goAuth}>
{t("login")}
</ToastAction>
),

View File

@ -39,10 +39,10 @@ import {
} from "@/components/ui/alert-dialog.tsx";
import { getSharedLink, shareConversation } from "@/api/sharing.ts";
import { Input } from "@/components/ui/input.tsx";
import { login } from "@/conf.ts";
import MenuBar from "@/components/app/MenuBar.tsx";
import { Separator } from "@/components/ui/separator.tsx";
import { deeptrainApiEndpoint } from "@/utils/env.ts";
import { goAuth } from "@/utils/app.ts";
type Operation = {
target: ConversationInstance | null;
@ -358,7 +358,7 @@ function SideBar() {
<SidebarMenu />
</div>
) : (
<Button className={`login-action`} variant={`default`} onClick={login}>
<Button className={`login-action`} variant={`default`} onClick={goAuth}>
<LogIn className={`h-3 w-3 mr-2`} /> {t("login")}
</Button>
)}

View File

@ -4,6 +4,7 @@
"not-found": "页面未找到",
"home": "首页",
"login": "登录",
"register": "注册",
"login-require": "您需要登录才能使用此功能",
"logout": "登出",
"quota": "点数",
@ -34,6 +35,34 @@
"fatal": "应用崩溃",
"download-fatal-log": "下载错误日志",
"fatal-tips": "请您先检查您的网络,浏览器兼容性,尝试清除浏览器缓存并刷新页面。如果问题仍然存在,请将日志提供给开发者以便我们排查问题。",
"auth": {
"username": "用户名",
"username-placeholder": "请输入用户名",
"password": "密码",
"password-placeholder": "请输入密码",
"check-password": "确认密码",
"check-password-placeholder": "请再次输入密码",
"email": "邮箱",
"email-placeholder": "请输入邮箱",
"username-or-email": "用户名或邮箱",
"username-or-email-placeholder": "请输入用户名或邮箱",
"code": "验证码",
"code-placeholder": "请输入验证码",
"send-code": "发送",
"incorrect-info": "填错信息?",
"fall-back": "回退一步",
"forgot-password": "忘记密码?",
"reset-password": "重置密码",
"no-account": "没有账号?",
"register": "注册一个",
"have-account": "已有账号?",
"login": "现在登录",
"next-step": "下一步",
"verify": "验证",
"length-range": "应为 {{min}} ~ {{max}} 位",
"same-rule": "两次输入不一致",
"invalid-email": "邮箱格式错误"
},
"tag": {
"free": "免费",
"official": "官方",

View File

@ -423,5 +423,34 @@
"title": "Mask Settings",
"search": "Search Mask Name",
"context": "Contains {{length}} context"
},
"register": "Register",
"auth": {
"username": "Username",
"password": "Password",
"username-or-email": "Username or E-mail",
"username-or-email-placeholder": "Please enter your username or mailbox",
"password-placeholder": "Please enter the password",
"forgot-password": "Lost Password?",
"reset-password": "Password Reset",
"no-account": "No account?",
"register": "Sign up for a",
"username-placeholder": "Please enter username",
"check-password": "Enter Password again",
"check-password-placeholder": "Please enter the password again",
"email": "Email",
"email-placeholder": "Enter email",
"have-account": "Already have an account? ",
"login": "Login Now",
"next-step": "Next",
"verify": "Verification",
"code": "CAPTCHA",
"code-placeholder": "Please enter OTP code",
"send-code": "Post",
"incorrect-info": "Wrong information?",
"fall-back": "Go back one step",
"length-range": "Expected {{min}} ~ {{max}} digits",
"same-rule": "* Fields do not match",
"invalid-email": "The email doesn't look right !"
}
}

View File

@ -423,5 +423,34 @@
"title": "プリセット設定",
"search": "プリセット名を検索",
"context": "{{length}}のコンテキストが含まれています"
},
"register": "登録",
"auth": {
"username": "ユーザー名",
"password": "パスワード",
"username-or-email": "ユーザー名またはメールアドレス",
"username-or-email-placeholder": "ユーザー名またはメールアドレスを入力してください",
"password-placeholder": "パスワードを入力してください",
"forgot-password": "パスワードを忘れた!",
"reset-password": "パスワードをリセット",
"no-account": "アカウントをお持ちではありませんか?",
"register": "にサインアップする",
"username-placeholder": "ここにあなたのユーザ名を入力",
"check-password": "パスワード確認",
"check-password-placeholder": "もう一度、パスワードを入力し直して下さい。",
"email": "メールアドレス",
"email-placeholder": "メールアドレスを入力してください",
"have-account": "すでにアカウントをお持ちですか?",
"login": "ログインしました。",
"next-step": "次へ",
"verify": "検証",
"code": "認証コード",
"code-placeholder": "認証コードを入力してください",
"send-code": "送信する",
"incorrect-info": "情報が間違っていますか?",
"fall-back": "1つ前のステップに戻る",
"length-range": "{{min }}〜{{ max}}桁が必要です",
"same-rule": "一貫性のない入力",
"invalid-email": "メールの形式が正しくありません"
}
}

View File

@ -423,5 +423,34 @@
"title": "Настройки маски",
"search": "Поиск по имени маски",
"context": "Содержит {{length}} контекст"
},
"register": "Постановка на учет",
"auth": {
"username": "имя пользователя",
"password": "пароль",
"username-or-email": "Имя пользователя или адрес электронной почты",
"username-or-email-placeholder": "Введите имя пользователя или адрес электронной почты",
"password-placeholder": "Пожалуйста, введите пароль",
"forgot-password": "Забыли пароль?",
"reset-password": "Восстановить пароль",
"no-account": "У вас нет аккаунта?",
"register": "Зарегистрируйтесь на",
"username-placeholder": "Введите здесь имя пользователя",
"check-password": "Подтверждение пароля",
"check-password-placeholder": "Введите, пожалуйста, пароль снова",
"email": "Эл. почта",
"email-placeholder": "Введите адрес электронной почты",
"have-account": "Уже есть аккаунт?",
"login": "Войти",
"next-step": "Cледующий шаг",
"verify": "Сертификация",
"code": "Код подтверждения",
"code-placeholder": "Введите проверочный код",
"send-code": "Посл",
"incorrect-info": "Неверная информация?",
"fall-back": "Вернитесь на шаг назад",
"length-range": "Ожидаемые цифры: {{min}} ~ {{max}}",
"same-rule": "Несогласованные входные данные",
"invalid-email": "Неверный формат электронной почты"
}
}

View File

@ -3,6 +3,9 @@ import Home from "./routes/Home.tsx";
import NotFound from "./routes/NotFound.tsx";
import Auth from "./routes/Auth.tsx";
import { lazy, Suspense } from "react";
import { useDeeptrain } from "@/utils/env.ts";
import Register from "@/routes/Register.tsx";
import Forgot from "@/routes/Forgot.tsx";
const Generation = lazy(() => import("@/routes/Generation.tsx"));
const Sharing = lazy(() => import("@/routes/Sharing.tsx"));
@ -16,7 +19,8 @@ const Charge = lazy(() => import("@/routes/admin/Charge.tsx"));
const Users = lazy(() => import("@/routes/admin/Users.tsx"));
const Broadcast = lazy(() => import("@/routes/admin/Broadcast.tsx"));
const router = createBrowserRouter([
const router = createBrowserRouter(
[
{
id: "home",
path: "/",
@ -29,6 +33,20 @@ const router = createBrowserRouter([
Component: Auth,
ErrorBoundary: NotFound,
},
!useDeeptrain &&
({
id: "register",
path: "/register",
Component: Register,
ErrorBoundary: NotFound,
} as any),
!useDeeptrain &&
({
id: "forgot",
path: "/forgot",
Component: Forgot,
ErrorBoundary: NotFound,
} as any),
{
id: "generation",
path: "/generate",
@ -125,7 +143,8 @@ const router = createBrowserRouter([
],
ErrorBoundary: NotFound,
},
]);
].filter(Boolean),
);
export function AppRouter() {
return <RouterProvider router={router} />;

View File

@ -1,18 +1,27 @@
import { useToast } from "@/components/ui/use-toast.ts";
import { ToastAction } from "@/components/ui/toast.tsx";
import { login, tokenField } from "@/conf.ts";
import { useEffect } from "react";
import { tokenField } from "@/conf.ts";
import { useEffect, useReducer } from "react";
import Loader from "@/components/Loader.tsx";
import "@/assets/pages/auth.less";
import axios from "axios";
import { validateToken } from "@/store/auth.ts";
import { useDispatch } from "react-redux";
import router from "@/router.tsx";
import { useTranslation } from "react-i18next";
import { getQueryParam } from "@/utils/path.ts";
import { setMemory } from "@/utils/memory.ts";
import { useDeeptrain } from "@/utils/env.ts";
import { Card, CardContent } from "@/components/ui/card.tsx";
import { goAuth } from "@/utils/app.ts";
import { Label } from "@/components/ui/label.tsx";
import { Input } from "@/components/ui/input.tsx";
import Require from "@/components/Require.tsx";
import { Button } from "@/components/ui/button.tsx";
import { formReducer } from "@/utils/form.ts";
import { doLogin, LoginForm } from "@/api/auth.ts";
import { getErrorMessage } from "@/utils/base.ts";
function Auth() {
function DeepAuth() {
const { toast } = useToast();
const { t } = useTranslation();
const dispatch = useDispatch();
@ -24,39 +33,38 @@ function Auth() {
title: t("invalid-token"),
description: t("invalid-token-prompt"),
action: (
<ToastAction altText={t("try-again")} onClick={login}>
<ToastAction altText={t("try-again")} onClick={goAuth}>
{t("try-again")}
</ToastAction>
),
});
setTimeout(login, 2500);
setTimeout(goAuth, 2500);
return;
}
setMemory(tokenField, token);
axios
.post("/login", { token })
.then((res) => {
const data = res.data;
doLogin({ token })
.then((data) => {
if (!data.status) {
toast({
title: t("login-failed"),
description: t("login-failed-prompt", { reason: data.error }),
action: (
<ToastAction altText={t("try-again")} onClick={login}>
<ToastAction altText={t("try-again")} onClick={goAuth}>
{t("try-again")}
</ToastAction>
),
});
} else
validateToken(dispatch, data.token, () => {
validateToken(dispatch, data.token, async () => {
toast({
title: t("login-success"),
description: t("login-success-prompt"),
});
router.navigate("/");
await router.navigate("/");
});
})
.catch((err) => {
@ -65,7 +73,7 @@ function Auth() {
title: t("server-error"),
description: `${t("server-error-prompt")}\n${err.message}`,
action: (
<ToastAction altText={t("try-again")} onClick={login}>
<ToastAction altText={t("try-again")} onClick={goAuth}>
{t("try-again")}
</ToastAction>
),
@ -80,4 +88,99 @@ function Auth() {
);
}
function Login() {
const { t } = useTranslation();
const { toast } = useToast();
const globalDispatch = useDispatch();
const [form, dispatch] = useReducer(formReducer<LoginForm>(), {
username: sessionStorage.getItem("username") || "",
password: sessionStorage.getItem("password") || "",
});
const onSubmit = async () => {
if (!form.username.trim().length || !form.password.trim().length) return;
try {
const resp = await doLogin(form);
if (!resp.status) {
toast({
title: t("login-failed"),
description: t("login-failed-prompt", { reason: resp.error }),
});
return;
}
toast({
title: t("login-success"),
description: t("login-success-prompt"),
});
validateToken(globalDispatch, resp.token);
await router.navigate("/");
} catch (err) {
console.debug(err);
toast({
title: t("server-error"),
description: `${t("server-error-prompt")}\n${getErrorMessage(err)}`,
});
}
};
return (
<div className={`auth-container`}>
<img className={`logo`} src="/favicon.ico" alt="" />
<div className={`title`}>{t("login")} Chat Nio</div>
<Card className={`auth-card`}>
<CardContent className={`pb-0`}>
<div className={`auth-wrapper`}>
<Label>
<Require /> {t("auth.username-or-email")}
</Label>
<Input
placeholder={t("auth.username-or-email-placeholder")}
value={form.username}
onChange={(e) =>
dispatch({ type: "update:username", payload: e.target.value })
}
/>
<Label>
<Require /> {t("auth.password")}
</Label>
<Input
placeholder={t("auth.password-placeholder")}
value={form.password}
onChange={(e) =>
dispatch({ type: "update:password", payload: e.target.value })
}
/>
<Button onClick={onSubmit} className={`mt-2`} loading={true}>
{t("login")}
</Button>
</div>
</CardContent>
</Card>
<div className={`auth-card addition-wrapper`}>
<div className={`row`}>
{t("auth.no-account")}
<a className={`link`} onClick={() => router.navigate("/register")}>
{t("auth.register")}
</a>
</div>
<div className={`row`}>
{t("auth.forgot-password")}
<a className={`link`} onClick={() => router.navigate("/forgot")}>
{t("auth.reset-password")}
</a>
</div>
</div>
</div>
);
}
function Auth() {
return useDeeptrain ? <DeepAuth /> : <Login />;
}
export default Auth;

109
app/src/routes/Forgot.tsx Normal file
View File

@ -0,0 +1,109 @@
import { useTranslation } from "react-i18next";
import { useToast } from "@/components/ui/use-toast.ts";
import { useDispatch } from "react-redux";
import { useReducer } from "react";
import { formReducer } from "@/utils/form.ts";
import { doLogin, LoginForm, ResetForm } from "@/api/auth.ts";
import { validateToken } from "@/store/auth.ts";
import router from "@/router.tsx";
import { getErrorMessage } from "@/utils/base.ts";
import { Card, CardContent } from "@/components/ui/card.tsx";
import { Label } from "@/components/ui/label.tsx";
import Require from "@/components/Require.tsx";
import { Input } from "@/components/ui/input.tsx";
import { Button } from "@/components/ui/button.tsx";
function Forgot() {
const { t } = useTranslation();
const { toast } = useToast();
const globalDispatch = useDispatch();
const [form, dispatch] = useReducer(formReducer<ResetForm>(), {
email: "",
code: "",
password: "",
repassword: "",
});
const onSubmit = async () => {
if (!form.username.trim().length || !form.password.trim().length) return;
try {
const resp = await doLogin(form);
if (!resp.status) {
toast({
title: t("login-failed"),
description: t("login-failed-prompt", { reason: resp.error }),
});
return;
}
toast({
title: t("login-success"),
description: t("login-success-prompt"),
});
validateToken(globalDispatch, resp.token);
await router.navigate("/");
} catch (err) {
console.debug(err);
toast({
title: t("server-error"),
description: `${t("server-error-prompt")}\n${getErrorMessage(err)}`,
});
}
};
return (
<div className={`auth-container`}>
<img className={`logo`} src="/favicon.ico" alt="" />
<div className={`title`}>{t("auth.reset-password")}</div>
<Card className={`auth-card`}>
<CardContent className={`pb-0`}>
<div className={`auth-wrapper`}>
<Label>
<Require /> {t("auth.username-or-email")}
</Label>
<Input
placeholder={t("auth.username-or-email-placeholder")}
value={form.username}
onChange={(e) =>
dispatch({ type: "update:username", payload: e.target.value })
}
/>
<Label>
<Require /> {t("auth.password")}
</Label>
<Input
placeholder={t("auth.password-placeholder")}
value={form.password}
onChange={(e) =>
dispatch({ type: "update:password", payload: e.target.value })
}
/>
<Button onClick={onSubmit} className={`mt-2`} loading={true}>
{t("login")}
</Button>
</div>
</CardContent>
</Card>
<div className={`auth-card addition-wrapper`}>
<div className={`row`}>
{t("auth.no-account")}
<a className={`link`} onClick={() => router.navigate("/register")}>
{t("auth.register")}
</a>
</div>
<div className={`row`}>
{t("auth.have-account")}
<a className={`link`} onClick={() => router.navigate("/login")}>
{t("auth.login")}
</a>
</div>
</div>
</div>
);
}
export default Forgot;

268
app/src/routes/Register.tsx Normal file
View File

@ -0,0 +1,268 @@
import { Card, CardContent } from "@/components/ui/card.tsx";
import { Label } from "@/components/ui/label.tsx";
import Require, {
EmailRequire,
LengthRangeRequired,
SameRequired,
} from "@/components/Require.tsx";
import { Input } from "@/components/ui/input.tsx";
import { Button } from "@/components/ui/button.tsx";
import router from "@/router.tsx";
import { useTranslation } from "react-i18next";
import { formReducer, isEmailValid, isTextInRange } from "@/utils/form.ts";
import React, { useReducer, useState } from "react";
import { doRegister, doVerify, RegisterForm } from "@/api/auth.ts";
import { useToast } from "@/components/ui/use-toast.ts";
import TickButton from "@/components/TickButton.tsx";
type CompProps = {
form: RegisterForm;
dispatch: React.Dispatch<any>;
next: boolean;
setNext: (next: boolean) => void;
};
function Preflight({ form, dispatch, setNext }: CompProps) {
const { t } = useTranslation();
const onSubmit = () => {
if (
!isTextInRange(form.username, 2, 24) ||
!isTextInRange(form.password, 6, 36) ||
form.password.trim() !== form.repassword.trim()
)
return;
setNext(true);
};
return (
<div className={`auth-wrapper`}>
<Label>
<Require />
{t("auth.username")}
<LengthRangeRequired
content={form.username}
min={2}
max={24}
hideOnEmpty={true}
/>
</Label>
<Input
placeholder={t("auth.username-placeholder")}
value={form.username}
onChange={(e) =>
dispatch({
type: "update:username",
payload: e.target.value,
})
}
/>
<Label>
<Require />
{t("auth.password")}
<LengthRangeRequired
content={form.password}
min={6}
max={36}
hideOnEmpty={true}
/>
</Label>
<Input
placeholder={t("auth.password-placeholder")}
value={form.password}
onChange={(e) =>
dispatch({
type: "update:password",
payload: e.target.value,
})
}
/>
<Label>
<Require />
{t("auth.check-password")}
<SameRequired
content={form.password}
compare={form.repassword}
hideOnEmpty={true}
/>
</Label>
<Input
placeholder={t("auth.check-password-placeholder")}
value={form.repassword}
onChange={(e) =>
dispatch({
type: "update:repassword",
payload: e.target.value,
})
}
/>
<Button className={`mt-2`} onClick={onSubmit}>
{t("auth.next-step")}
</Button>
</div>
);
}
function doFormat(form: RegisterForm): RegisterForm {
return {
...form,
username: form.username.trim(),
password: form.password.trim(),
repassword: form.repassword.trim(),
email: form.email.trim(),
code: form.code.trim(),
};
}
function Verify({ form, dispatch, setNext }: CompProps) {
const { t } = useTranslation();
const { toast } = useToast();
const onSubmit = async () => {
const data = doFormat(form);
if (!isEmailValid(data.email) || !data.code.trim().length) return;
const res = await doRegister(data);
if (!res.status) {
toast({
title: t("error"),
description: res.error,
});
return;
}
};
const onVerify = async () => {
if (form.email.trim().length === 0 || !isEmailValid(form.email))
return false;
const res = await doVerify(form.email);
if (!res.status) {
toast({
title: t("error"),
description: res.error,
});
return false;
}
return true;
};
return (
<div className={`auth-wrapper`}>
<Label>
<Require />
{t("auth.email")}
<EmailRequire content={form.email} hideOnEmpty={true} />
</Label>
<Input
placeholder={t("auth.email-placeholder")}
value={form.email}
onChange={(e) =>
dispatch({
type: "update:email",
payload: e.target.value,
})
}
/>
<Label>
<Require /> {t("auth.code")}
</Label>
<div className={`flex flex-row`}>
<Input
placeholder={t("auth.code-placeholder")}
value={form.code}
onChange={(e) =>
dispatch({
type: "update:code",
payload: e.target.value,
})
}
/>
<TickButton
className={`ml-2 whitespace-nowrap`}
loading={true}
onClick={onVerify}
tick={60}
>
{t("auth.send-code")}
</TickButton>
</div>
<Button className={`mt-2`} loading={true} onClick={onSubmit}>
{t("register")}
</Button>
<div className={`mt-1 translate-y-1 text-center text-sm`}>
{t("auth.incorrect-info")}
<a
className={`underline underline-offset-4 cursor-pointer`}
onClick={() => setNext(false)}
>
{t("auth.fall-back")}
</a>
</div>
</div>
);
}
function Register() {
const { t } = useTranslation();
const [next, setNext] = useState(false);
const [form, dispatch] = useReducer(formReducer<RegisterForm>(), {
username: "",
password: "",
repassword: "",
email: "",
code: "",
});
return (
<div className={`auth-container`}>
<img className={`logo`} src="/favicon.ico" alt="" />
<div className={`title`}>{t("register")} Chat Nio</div>
<Card className={`auth-card`}>
<CardContent className={`pb-0`}>
{!next ? (
<Preflight
form={form}
dispatch={dispatch}
next={next}
setNext={setNext}
/>
) : (
<Verify
form={form}
dispatch={dispatch}
next={next}
setNext={setNext}
/>
)}
</CardContent>
</Card>
<div className={`auth-card addition-wrapper`}>
<div className={`row`}>
{t("auth.have-account")}
<a className={`link`} onClick={() => router.navigate("/login")}>
{t("auth.login")}
</a>
</div>
<div className={`row`}>
{t("auth.forgot-password")}
<a className={`link`} onClick={() => router.navigate("/forgot")}>
{t("auth.reset-password")}
</a>
</div>
</div>
</div>
);
}
export default Register;

View File

@ -3,6 +3,7 @@ import axios from "axios";
import { tokenField } from "@/conf.ts";
import { AppDispatch, RootState } from "./index.ts";
import { forgetMemory, setMemory } from "@/utils/memory.ts";
import { doState } from "@/api/auth.ts";
export const authSlice = createSlice({
name: "auth",
@ -32,6 +33,12 @@ export const authSlice = createSlice({
setAdmin: (state, action) => {
state.admin = action.payload as boolean;
},
updateData: (state, action) => {
state.init = true;
state.authenticated = action.payload.authenticated as boolean;
state.username = action.payload.username as string;
state.admin = action.payload.admin as boolean;
},
logout: (state) => {
state.token = "";
state.authenticated = false;
@ -53,18 +60,26 @@ export function validateToken(
dispatch(setToken(token));
if (token.length === 0) {
dispatch(setAuthenticated(false));
dispatch(setUsername(""));
dispatch(setInit(true));
dispatch(
updateData({
authenticated: false,
username: "",
admin: false,
}),
);
return;
} else
axios
.post("/state")
.then((res) => {
dispatch(setAuthenticated(res.data.status));
dispatch(setUsername(res.data.user));
dispatch(setInit(true));
dispatch(setAdmin(res.data.admin));
doState()
.then((data) => {
dispatch(
updateData({
authenticated: data.status,
username: data.user,
admin: data.admin,
}),
);
hook && hook();
})
.catch((err) => {
@ -86,5 +101,6 @@ export const {
logout,
setInit,
setAdmin,
updateData,
} = authSlice.actions;
export default authSlice.reducer;

View File

@ -1,3 +1,7 @@
import router from "@/router.tsx";
import { useDeeptrain } from "@/utils/env.ts";
import { login } from "@/conf.ts";
export let event: BeforeInstallPromptEvent | undefined;
window.addEventListener("beforeinstallprompt", (e: Event) => {
@ -40,3 +44,14 @@ export function getMemoryPerformance(): number {
if (!performance || !performance.memory) return NaN;
return performance.memory.usedJSHeapSize / 1024 / 1024;
}
export function navigate(path: string): void {
router
.navigate(path)
.then(() => console.debug(`[service] navigate to ${path}`))
.catch((err) => console.debug(`[service] navigate error`, err));
}
export function goAuth(): void {
useDeeptrain ? login() : navigate("/login");
}

View File

@ -48,3 +48,7 @@ export function getErrorMessage(error: any): string {
if (typeof error === "string") return error;
return JSON.stringify(error);
}
export function isAsyncFunc(fn: any): boolean {
return fn.constructor.name === "AsyncFunction";
}

View File

@ -30,3 +30,15 @@ export const formReducer = <T>() => {
}
};
};
export function isEmailValid(email: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) && email.length <= 255;
}
export function isInRange(value: number, min: number, max: number) {
return value >= min && value <= max;
}
export function isTextInRange(value: string, min: number, max: number) {
return value.trim().length >= min && value.trim().length <= max;
}

View File

@ -57,8 +57,10 @@ func CreateUserTable(db *sql.DB) {
bind_id INT UNIQUE,
username VARCHAR(24) UNIQUE,
token VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE,
password VARCHAR(64) NOT NULL,
is_admin BOOLEAN DEFAULT FALSE
is_admin BOOLEAN DEFAULT FALSE,
is_banned BOOLEAN DEFAULT FALSE
);
`)
if err != nil {