Skip to Content

Đă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Đă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`.
ví-dụ.manh.run · dữ liệu mẫuMở để sửa ↗
Ví dụ chạy khi bạn cuộn 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.

app/login/page.tsx
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.

app/register/page.tsx
<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:

app/login/page.tsx
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().

app/components/role-guard.tsx
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ữ label trê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 message của form, không dùng toast. Alert của antd v6 nhận title; prop message không còn được khuyên dùng, dùng sẽ hiện cảnh báo.
  • Không tự ghi token vào localStorage hay thêm interceptor cho axios, vì signIn đã làm việc đó. setAuthToken / getAuthToken là hàm cấp thấp, ít khi cần.
  • Không dùng manh/oauth hay 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ằng providers trong app/auth.ts.

Bước tiếp theo

Cập nhật