Đăng nhập và đăng ký
Trang đăng nhập và đăng ký dùng LoginForm, gọi API đăng nhập mà manh.run sinh từ app/auth.ts, lưu phiên bằng signIn, hiện nút Google và báo lỗi server ngay trên form.
Khi app có app/auth.ts, manh.run tự sinh bảng users cùng API đăng nhập và đăng ký. Trình duyệt giữ JWT và gửi kèm mỗi lần gọi API, không dùng cookie.
Lối tắt: block_add("auth") thêm app/auth.ts và hai trang /login, /register giống ví dụ dưới đây. Chỉ tự viết màn hình khi cần bố cục riêng.
// Đăng nhập: LoginForm của pro-components, có label (truy cập + test tìm theo label), lỗi server hiện trong `message`.
import { useState } from "react";
import { LoginForm, ProFormCheckbox, ProFormText } from "@ant-design/pro-components";
import { Alert, Flex, Typography, theme } from "antd";
import { AuditOutlined, LockOutlined, MailOutlined } from "@ant-design/icons";
export default function Page() {
const { token } = theme.useToken();
const [error, setError] = useState<string | null>(null);
return (
<Flex vertical justify="center" style={{ minHeight: "100vh", background: `linear-gradient(180deg, ${token.colorPrimaryBg} 0%, ${token.colorBgLayout} 45%)` }}>
<LoginForm
logo={<AuditOutlined style={{ fontSize: 40, color: token.colorPrimary }} />}
title="Duyệt mua sắm"
subTitle="Đề xuất, duyệt và theo dõi chi tiêu mua sắm"
submitter={{ searchConfig: { submitText: "Đăng nhập" } }}
initialValues={{ remember: true }}
message={error ? <Alert type="error" showIcon title={error} style={{ marginBottom: 24 }} /> : undefined}
actions={
<Flex vertical gap={8}>
<Typography.Text type="secondary">Chưa có tài khoản? <a>Đăng ký</a></Typography.Text>
{/* Mẫu giao diện (Playground / docs): nói rõ là demo để không ai nhập mật khẩu thật. */}
<Typography.Text type="secondary" style={{ fontSize: 12 }}>Bản demo giao diện — không nhập mật khẩu thật, không có dữ liệu nào được gửi đi. Mật khẩu thử: 123456.</Typography.Text>
</Flex>
}
onFinish={async (v: { email: string; password: string }) => {
// Thử: mật khẩu khác "123456" sẽ báo lỗi như server trả 401.
if (v.password !== "123456") { setError("Sai email hoặc mật khẩu"); return false; }
setError(null);
return true;
}}
>
<ProFormText name="email" label="Email" placeholder="ten@congty.vn" fieldProps={{ size: "large", prefix: <MailOutlined /> }} rules={[{ required: true, type: "email", message: "Nhập email hợp lệ" }]} />
<ProFormText.Password name="password" label="Mật khẩu" placeholder="Mật khẩu" fieldProps={{ size: "large", prefix: <LockOutlined />, autoComplete: "off" }} rules={[{ required: true, message: "Nhập mật khẩu" }]} />
<div style={{ marginBlockEnd: 24 }}>
<ProFormCheckbox noStyle name="remember">Ghi nhớ đăng nhập</ProFormCheckbox>
<a style={{ float: "right" }}>Quên mật khẩu?</a>
</div>
</LoginForm>
</Flex>
);
}
Làm màn hình "Đăng nhập" cho app của tôi theo mẫu manh.run UI playbook (framework_docs("pro")): Đăng nhập: LoginForm của pro-components, có label (truy cập + test tìm theo label), lỗi server hiện trong `message`. Dữ liệu lấy từ API của app qua useApiClient(); nhãn và trường theo spec của tôi.Các file của luồng đăng nhập
Bạn viết app/auth.ts và các trang giao diện. Phần server do manh.run sinh ra và không nằm trong project.
app/
├── login/page.tsx → /login (LoginForm)
├── register/page.tsx → /register (LoginForm, nút "Đăng ký")
├── components/role-guard.tsx chặn trang theo vai trò
├── components/sso-buttons.tsx nút Google, hiện khi app/auth.ts bật providers
└── auth.ts vai trò, cách đăng ký, providers
sinh sẵn: POST /auth/login → api.auth.login(body)
POST /auth/register → api.auth.register(body)
GET /auth/providers → api.auth.providers()Cách cấu hình app/auth.ts, access và các API sinh sẵn: xem Đăng nhập và phân quyền. Trang này chỉ nói về giao diện.
Trang đăng nhập
onFinish gọi API đăng nhập. Nếu thành công, signIn(...) lưu phiên rồi chuyển trang. Nếu lỗi, đưa thông báo lỗi của server vào message và trả false để form giữ nguyên.
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { LoginForm, ProFormText } from "@ant-design/pro-components";
import { Alert, Flex, Typography, theme } from "antd";
import { AuditOutlined, LockOutlined, MailOutlined } from "@ant-design/icons";
import { useApiClient } from "app/api";
import { signIn } from "app/hooks";
export default function Page() {
const api = useApiClient();
const nav = useNavigate();
const { token } = theme.useToken();
const [error, setError] = useState<string | null>(null);
return (
<Flex vertical justify="center" style={{ minHeight: "100vh", background: token.colorBgLayout }}>
<LoginForm
logo={<AuditOutlined style={{ fontSize: 40, color: token.colorPrimary }} />}
title="Duyệt mua sắm"
subTitle="Đề xuất, duyệt và theo dõi chi tiêu mua sắm"
submitter={{ searchConfig: { submitText: "Đăng nhập" } }}
message={error ? <Alert type="error" showIcon title={error} style={{ marginBottom: 24 }} /> : undefined}
actions={<Typography.Text type="secondary">Chưa có tài khoản? <a onClick={() => nav("/register")}>Đăng ký</a></Typography.Text>}
onFinish={async (v) => {
try {
signIn(await api.auth.login(v));
nav("/");
return true;
} catch (e: any) {
setError(e?.response?.data?.message ?? "Không đăng nhập được, thử lại sau");
return false;
}
}}
>
<ProFormText name="email" label="Email" fieldProps={{ size: "large", prefix: <MailOutlined /> }}
rules={[{ required: true, type: "email", message: "Nhập email hợp lệ" }]} />
<ProFormText.Password name="password" label="Mật khẩu" fieldProps={{ size: "large", prefix: <LockOutlined /> }}
rules={[{ required: true, message: "Nhập mật khẩu" }]} />
</LoginForm>
</Flex>
);
}Trang đăng ký
Trang đăng ký dùng lại LoginForm, thêm ô họ tên và ô nhập lại mật khẩu. API đăng ký sinh sẵn yêu cầu họ tên từ 2 ký tự và mật khẩu từ 8 ký tự. Đặt cùng điều kiện trên form để người dùng thấy lỗi trước khi gửi.
<LoginForm
title="Tạo tài khoản"
submitter={{ searchConfig: { submitText: "Đăng ký" } }}
message={error ? <Alert type="error" showIcon title={error} style={{ marginBottom: 24 }} /> : undefined}
actions={<Typography.Text type="secondary">Đã có tài khoản? <a onClick={() => nav("/login")}>Đăng nhập</a></Typography.Text>}
onFinish={async ({ confirm, ...v }) => {
try { signIn(await api.auth.register(v)); nav("/"); return true; }
catch (e: any) { setError(e?.response?.data?.message ?? "Không tạo được tài khoản"); return false; }
}}
>
<ProFormText name="name" label="Họ tên" fieldProps={{ size: "large" }} rules={[{ required: true }]} />
<ProFormText name="email" label="Email" fieldProps={{ size: "large" }} rules={[{ required: true, type: "email" }]} />
<ProFormText.Password name="password" label="Mật khẩu" fieldProps={{ size: "large" }} rules={[{ required: true, min: 8 }]} />
<ProFormText.Password name="confirm" label="Nhập lại mật khẩu" dependencies={["password"]} fieldProps={{ size: "large" }}
rules={[{ required: true }, ({ getFieldValue }) => ({
validator: (_, v) => (v === getFieldValue("password") ? Promise.resolve() : Promise.reject(new Error("Mật khẩu không khớp"))),
})]} />
</LoginForm>Nút đăng nhập bằng Google
Khối auth bật sẵn đăng nhập bằng Google: app/auth.ts có providers: ["google"]. Muốn chỉ dùng mật khẩu thì bỏ dòng đó. Trang /login và /register của khối auth tự hiện nút Google, vì app/components/sso-buttons.tsx đọc api.auth.providers().
Trong màn hình của riêng bạn, gọi signInWith:
import { Button } from "antd";
import { GoogleOutlined } from "@ant-design/icons";
import { signInWith } from "app/hooks";
// trong LoginForm, sau các trường:
<Button block size="large" icon={<GoogleOutlined />}
onClick={async () => { await signInWith("google"); nav("/"); }}>
Đăng nhập bằng Google
</Button>signInWith("google") mở cửa sổ Google và chờ tới khi đăng nhập xong. Nếu trình duyệt chặn cửa sổ bật lên, trang tự chuyển sang Google rồi quay về.
Giữ phiên và đăng xuất
Sau signIn(...), mọi lần gọi qua useApiClient() hoặc useApi() đều tự gửi header Authorization: Bearer <token>. Để đăng xuất, gọi signOut() rồi chuyển về /login.
const { user, hasRole } = useSession() trả về người đang đăng nhập (id, name, email, role, avatarUrl) và vẽ lại giao diện khi đăng nhập hay đăng xuất. Dùng hook này để quyết định menu và nút nào được hiện. Server vẫn kiểm quyền bằng access. Ngoài React thì dùng getUser().
Chặn trang theo vai trò
AppShell đã đưa người chưa đăng nhập về /login. Muốn chỉ một số vai trò mở được trang, bọc trang bằng một component đọc useSession().
import { Navigate } from "react-router-dom";
import { useSession } from "app/hooks";
export function RoleGuard({ role, children }: { role: string; children: React.ReactNode }) {
const { hasRole } = useSession();
return hasRole(role) ? <>{children}</> : <Navigate to="/" replace />;
}Khi API trả 401 (token hết hạn hoặc tài khoản bị khoá), app tự đăng xuất và chuyển về /login.
Cần biết
- Giữ
labeltrên mọi field, vì trình đọc màn hình và bài test tìm field theo label. - Lỗi server hiện trong
messagecủa form, không dùng toast.Alertcủa antd v6 nhậntitle; propmessagekhông còn được khuyên dùng, dùng sẽ hiện cảnh báo. - Không tự ghi token vào
localStoragehay thêm interceptor cho axios, vìsignInđã làm việc đó.setAuthToken/getAuthTokenlà hàm cấp thấp, ít khi cần. - Không dùng
manh/oauthhay session bằng cookie. manh.run không hỗ trợ hai cách này: đăng nhập luôn dùng JWT gửi trong header, còn Google thì bật bằngproviderstrongapp/auth.ts.
Bước tiếp theo
- Đăng nhập và phân quyền —
app/auth.ts,accessvà đăng nhập bằng Google. - API handler —
accessvà người dùng trong handler. - Form — các trường ProForm, độ rộng và cách kiểm giá trị.