initial
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
# Copy to `.env` for local development (never commit `.env`).
|
||||
VITE_API_BASE_URL=http://localhost:8080/api
|
||||
VITE_APP_NAME=APLP
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Test coverage
|
||||
coverage
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
.env
|
||||
*.md
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2
|
||||
}
|
||||
@@ -1,93 +1,83 @@
|
||||
# aplp.frontend.reactjs
|
||||
# aplp.frontend.react
|
||||
|
||||
Frontend (React) cho **APLP — Adaptive Personal Learning Platform** (learner application `aplp-web`).
|
||||
|
||||
React 19 + TypeScript + Vite · Client mỏng (thin client) gọi API của backend `aplp.backend.spring`. Frontend **không** chứa business rules; mọi quyết định domain (mastery, progress, adaptive) đến từ backend.
|
||||
|
||||
## Getting started
|
||||
## Stack
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
| Lĩnh vực | Công nghệ |
|
||||
| --- | --- |
|
||||
| Framework | React 19 |
|
||||
| Language | TypeScript |
|
||||
| Build | Vite 8 |
|
||||
| Routing | React Router 7 |
|
||||
| HTTP client | Axios (wrapper tại `src/api`) |
|
||||
| Server-state | TanStack Query |
|
||||
| Client-state | Zustand |
|
||||
| Styling | Tailwind CSS 4 |
|
||||
| Lint | oxlint |
|
||||
| Format | Prettier |
|
||||
| Test | Vitest + Testing Library |
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
## Quick Start
|
||||
|
||||
## Add your files
|
||||
Prerequisite: Node.js 18+ (LTS khuyến nghị).
|
||||
|
||||
* [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files
|
||||
* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://gitlab.com/aplp/aplp.frontend.reactjs.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```bash
|
||||
npm install
|
||||
cp .env.example .env # chỉnh VITE_API_BASE_URL nếu cần
|
||||
npm run dev # mở địa chỉ Vite (mặc định http://localhost:5173)
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
Backend chạy local để API hoạt động (xem `docs/SETUP.md`).
|
||||
|
||||
* [Set up project integrations](https://gitlab.com/aplp/aplp.frontend.reactjs/-/settings/integrations)
|
||||
## Scripts
|
||||
|
||||
## Collaborate with your team
|
||||
| Lệnh | Mô tả |
|
||||
| --- | --- |
|
||||
| `npm run dev` | Dev server (Vite) |
|
||||
| `npm run build` | Typecheck + production build |
|
||||
| `npm run preview` | Preview production build |
|
||||
| `npm run lint` | Lint (oxlint) |
|
||||
| `npm run format` / `format:check` | Format bằng Prettier |
|
||||
| `npm run typecheck` | Typecheck (tsc) |
|
||||
| `npm test` / `test:watch` | Unit test (Vitest) |
|
||||
|
||||
* [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/)
|
||||
* [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/)
|
||||
* [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically)
|
||||
* [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/)
|
||||
* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
|
||||
## Structure
|
||||
|
||||
## Test and Deploy
|
||||
```text
|
||||
src/
|
||||
├── app/ # app entry, router, providers, layout, pages
|
||||
├── api/ # api client (axios), token storage
|
||||
├── features/ # feature modules (auth, learner, course, ...)
|
||||
│ └── auth/ # api, components, hooks, pages, store
|
||||
├── shared/ # shared components, hooks, config
|
||||
└── types/ # shared types / DTO contracts
|
||||
```
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
Chi tiết: [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md), [docs/CONVENTIONS.md](./docs/CONVENTIONS.md).
|
||||
|
||||
* [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/)
|
||||
* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/)
|
||||
* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/)
|
||||
* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/)
|
||||
* [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/)
|
||||
## Auth Flow
|
||||
|
||||
***
|
||||
- Access token lưu **in-memory** (`src/api/tokenStorage.ts`), không persist vào storage trình duyệt.
|
||||
- Refresh token do backend quản lý (HttpOnly cookie); client không chạm tới.
|
||||
- `401` → api client tự gọi `/auth/refresh` rồi retry request gốc (không loop trên endpoint auth).
|
||||
- Route bảo vệ qua `ProtectedRoute` (redirect `/login` nếu chưa đăng nhập).
|
||||
|
||||
# Editing this README
|
||||
Chi tiết: [docs/PHASES.md](./docs/PHASES.md) (Phase 0).
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
## Documents
|
||||
|
||||
## Suggestions for a good README
|
||||
| Tài liệu | Mô tả |
|
||||
| --- | --- |
|
||||
| [docs/PHASES.md](./docs/PHASES.md) | Công việc frontend theo từng phase APLP |
|
||||
| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | Kiến trúc: folder structure, data flow, auth |
|
||||
| [docs/CONVENTIONS.md](./docs/CONVENTIONS.md) | Coding conventions |
|
||||
| [docs/SETUP.md](./docs/SETUP.md) | Setup / khởi tạo dự án |
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
Backend: [aplp.backend.spring](../aplp.backend.spring) — kế hoạch phase tổng thể: [APLP-Project-Phases.md](../aplp.backend.spring/APLP-Project-Phases.md).
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
## Status
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
Phase 0 (Foundation) — hoàn tất. Xem danh sách completion criteria tại [docs/PHASES.md](./docs/PHASES.md).
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>APLP — Adaptive Personal Learning Platform</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+3938
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "aplp.frontend.react",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"lint:fix": "oxlint --fix",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"typecheck": "tsc -b --noEmit",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.90.20",
|
||||
"axios": "^1.13.2",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-router-dom": "^7.14.3",
|
||||
"zustand": "^5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.1.16",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.4",
|
||||
"@vitest/coverage-v8": "^4.1.10",
|
||||
"jsdom": "^27.2.0",
|
||||
"oxlint": "^1.75.0",
|
||||
"prettier": "^3.6.2",
|
||||
"tailwindcss": "^4.1.16",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.2.0",
|
||||
"vitest": "^4.0.14"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,94 @@
|
||||
import axios from 'axios';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { registerAuthHandlers } from '@/api/client';
|
||||
import { tokenStorage } from '@/api/tokenStorage';
|
||||
|
||||
// Import after env default is fixed by importing the real module tree.
|
||||
import client from '@/api/client';
|
||||
|
||||
describe('api client', () => {
|
||||
const refresh = vi.fn();
|
||||
const unauthorized = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
registerAuthHandlers(refresh, unauthorized);
|
||||
tokenStorage.clear();
|
||||
refresh.mockReset();
|
||||
refresh.mockResolvedValue('new-access');
|
||||
unauthorized.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function stubErrorResponse(status: number, url: string) {
|
||||
const error = {
|
||||
config: { url, headers: new axios.AxiosHeaders(), method: 'get' },
|
||||
response: { status, data: { message: 'boom', code: 'E_TEST' } },
|
||||
isAxiosError: true,
|
||||
message: 'Request failed',
|
||||
};
|
||||
return error;
|
||||
}
|
||||
|
||||
it('attaches Bearer token from storage on request', async () => {
|
||||
tokenStorage.set('tok-1');
|
||||
const handlers = client.interceptors.request.handlers;
|
||||
const config = { headers: new axios.AxiosHeaders() };
|
||||
|
||||
const result = handlers?.[0]?.fulfilled?.(config) as typeof config;
|
||||
|
||||
expect(result.headers.get('Authorization')).toBe('Bearer tok-1');
|
||||
});
|
||||
|
||||
it('refreshes token and retries the original request on 401', async () => {
|
||||
const adapter = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => Promise.reject(stubErrorResponse(401, '/courses')))
|
||||
.mockImplementationOnce(() =>
|
||||
Promise.resolve({
|
||||
data: { data: [{ id: 'c1' }] },
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {},
|
||||
config: {},
|
||||
}),
|
||||
);
|
||||
|
||||
client.defaults.adapter = adapter;
|
||||
const result = await client.get('/courses');
|
||||
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
expect(unauthorized).not.toHaveBeenCalled();
|
||||
expect(adapter).toHaveBeenCalledTimes(2);
|
||||
expect(result.data.data).toEqual([{ id: 'c1' }]);
|
||||
});
|
||||
|
||||
it('does not retry 401 on auth endpoints (avoids refresh loop)', async () => {
|
||||
const adapter = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => Promise.reject(stubErrorResponse(401, '/auth/login')));
|
||||
|
||||
client.defaults.adapter = adapter;
|
||||
|
||||
await expect(client.post('/auth/login', {})).rejects.toMatchObject({ status: 401 });
|
||||
expect(refresh).not.toHaveBeenCalled();
|
||||
expect(adapter).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls unauthorized handler when refresh fails', async () => {
|
||||
refresh.mockResolvedValue(null);
|
||||
const adapter = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => Promise.reject(stubErrorResponse(401, '/courses')))
|
||||
.mockImplementationOnce(() => Promise.reject(stubErrorResponse(401, '/courses')));
|
||||
|
||||
client.defaults.adapter = adapter;
|
||||
|
||||
await expect(client.get('/courses')).rejects.toMatchObject({ status: 401 });
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
expect(unauthorized).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import axios, { AxiosError, type AxiosInstance, type InternalAxiosRequestConfig } from 'axios';
|
||||
|
||||
import env from '@/shared/config/env';
|
||||
import type { ApiError, ApiErrorPayload } from '@/types/api';
|
||||
import { tokenStorage } from '@/api/tokenStorage';
|
||||
|
||||
export interface ApiClientConfig {
|
||||
baseURL: string;
|
||||
timeout: number;
|
||||
}
|
||||
|
||||
interface RetryableRequestConfig extends InternalAxiosRequestConfig {
|
||||
_retried?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh callback, registered by the auth feature. Returns the new access
|
||||
* token, or null when the refresh fails (e.g. the refresh token is expired).
|
||||
*/
|
||||
export type RefreshHandler = () => Promise<string | null>;
|
||||
export type UnauthorizedHandler = () => void;
|
||||
|
||||
let refreshHandler: RefreshHandler | null = null;
|
||||
let unauthorizedHandler: UnauthorizedHandler | null = null;
|
||||
|
||||
/** Register the auth handlers used by the client (called by the auth feature). */
|
||||
export function registerAuthHandlers(
|
||||
refresh: RefreshHandler,
|
||||
unauthorized: UnauthorizedHandler,
|
||||
): void {
|
||||
refreshHandler = refresh;
|
||||
unauthorizedHandler = unauthorized;
|
||||
}
|
||||
|
||||
let refreshPromise: Promise<string | null> | null = null;
|
||||
|
||||
export function createApiClient(config: ApiClientConfig): AxiosInstance {
|
||||
const client = axios.create({
|
||||
baseURL: config.baseURL,
|
||||
timeout: config.timeout,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
withCredentials: true, // send HttpOnly refresh-token cookie
|
||||
});
|
||||
|
||||
client.interceptors.request.use((requestConfig) => {
|
||||
const token = tokenStorage.get();
|
||||
if (token) {
|
||||
requestConfig.headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
return requestConfig;
|
||||
});
|
||||
|
||||
client.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error: AxiosError<ApiErrorPayload>) => {
|
||||
const original = error.config as RetryableRequestConfig | undefined;
|
||||
const isAuthEndpoint = original?.url?.startsWith('/auth');
|
||||
|
||||
if (error.response?.status === 401 && original && !original._retried && !isAuthEndpoint) {
|
||||
original._retried = true;
|
||||
try {
|
||||
if (!refreshPromise && refreshHandler) {
|
||||
refreshPromise = refreshHandler();
|
||||
}
|
||||
const newToken = await refreshPromise;
|
||||
if (newToken) {
|
||||
original.headers.set('Authorization', `Bearer ${newToken}`);
|
||||
return client(original);
|
||||
}
|
||||
unauthorizedHandler?.();
|
||||
} catch {
|
||||
unauthorizedHandler?.();
|
||||
} finally {
|
||||
refreshPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(normalizeError(error));
|
||||
},
|
||||
);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
function normalizeError(error: AxiosError<ApiErrorPayload>): ApiError {
|
||||
const payload = error.response?.data;
|
||||
return {
|
||||
status: error.response?.status ?? 0,
|
||||
code: payload?.code,
|
||||
message: payload?.message ?? error.message ?? 'Unexpected error',
|
||||
fieldErrors: payload?.fieldErrors,
|
||||
raw: error,
|
||||
};
|
||||
}
|
||||
|
||||
const client = createApiClient({ baseURL: env.VITE_API_BASE_URL, timeout: 15_000 });
|
||||
|
||||
export default client;
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* In-memory token storage.
|
||||
*
|
||||
* Access token is kept in memory only (never persisted to localStorage /
|
||||
* sessionStorage) to reduce XSS exposure. The refresh token is handled by the
|
||||
* backend (HttpOnly cookie), so the client never touches it directly.
|
||||
*/
|
||||
let accessToken: string | null = null;
|
||||
|
||||
export const tokenStorage = {
|
||||
get: (): string | null => accessToken,
|
||||
set: (token: string): void => {
|
||||
accessToken = token;
|
||||
},
|
||||
clear: (): void => {
|
||||
accessToken = null;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Navigate, Route, Routes } from 'react-router-dom';
|
||||
|
||||
import { AppLayout } from '@/app/layouts/AppLayout';
|
||||
import { HomePage } from '@/app/pages/HomePage';
|
||||
import { NotFoundPage } from '@/app/pages/NotFoundPage';
|
||||
import { ProtectedRoute } from '@/features/auth/components/ProtectedRoute';
|
||||
import { LoginPage } from '@/features/auth/pages/LoginPage';
|
||||
import { useAuthStore } from '@/features/auth/store/authStore';
|
||||
|
||||
export default function App() {
|
||||
useEffect(() => {
|
||||
void useAuthStore.getState().init();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route element={<AppLayout />}>
|
||||
<Route index element={<HomePage />} />
|
||||
<Route path="/learn" element={<div>Learn (placeholder)</div>} />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="/404" element={<NotFoundPage />} />
|
||||
<Route path="*" element={<Navigate to="/404" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Link, Outlet } from 'react-router-dom';
|
||||
|
||||
import env from '@/shared/config/env';
|
||||
import { useLogout } from '@/features/auth/hooks/useLogout';
|
||||
import { useAuthStore } from '@/features/auth/store/authStore';
|
||||
|
||||
export function AppLayout() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const logout = useLogout();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<header className="border-b border-gray-200 bg-white">
|
||||
<div className="mx-auto flex h-14 max-w-5xl items-center justify-between px-4">
|
||||
<div className="flex items-center gap-6">
|
||||
<Link to="/" className="text-lg font-semibold text-gray-900">
|
||||
{env.VITE_APP_NAME}
|
||||
</Link>
|
||||
<nav className="flex items-center gap-4 text-sm text-gray-600">
|
||||
<Link to="/" className="hover:text-gray-900">
|
||||
Home
|
||||
</Link>
|
||||
<Link to="/learn" className="hover:text-gray-900">
|
||||
Learn
|
||||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
{user && <span className="text-sm text-gray-500">{user.email}</span>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => logout.mutate()}
|
||||
disabled={logout.isPending}
|
||||
className="rounded-md border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100 disabled:opacity-50"
|
||||
>
|
||||
{logout.isPending ? 'Signing out…' : 'Sign out'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main className="mx-auto max-w-5xl px-4 py-8">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import env from '@/shared/config/env';
|
||||
import { useAuthUser } from '@/features/auth/hooks/useAuthUser';
|
||||
|
||||
export function HomePage() {
|
||||
const { user, isLoading, isError } = useAuthUser();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">
|
||||
Welcome{user ? `, ${user.name}` : ''} 👋
|
||||
</h1>
|
||||
<p className="mt-2 text-gray-600">{env.VITE_APP_NAME} — your adaptive learning workspace.</p>
|
||||
<div className="mt-6 rounded-lg border border-gray-200 bg-white p-6 text-sm text-gray-600">
|
||||
{isLoading && <p>Loading profile…</p>}
|
||||
{isError && <p>Could not load profile details.</p>}
|
||||
{user && !isLoading && (
|
||||
<ul className="space-y-1">
|
||||
<li>ID: {user.id}</li>
|
||||
<li>Email: {user.email}</li>
|
||||
<li>Name: {user.name}</li>
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-gray-50 px-4 text-center">
|
||||
<h1 className="text-4xl font-semibold text-gray-900">404</h1>
|
||||
<p className="mt-2 text-gray-600">This page does not exist.</p>
|
||||
<Link to="/" className="mt-4 text-sm font-medium text-indigo-600 hover:text-indigo-700">
|
||||
Back home
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
|
||||
import { ErrorBoundary } from '@/shared/components/ErrorBoundary';
|
||||
|
||||
interface QueryProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function QueryProvider({ children }: QueryProviderProps) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 60_000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ErrorBoundary>{children}</ErrorBoundary>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import client from '@/api/client';
|
||||
import type { ApiListResponse, ApiResponse } from '@/types/api';
|
||||
import type { AuthUser, LoginCredentials, LoginResponse, RefreshResponse } from '../types';
|
||||
|
||||
/**
|
||||
* Endpoint constants live here (not scattered in components).
|
||||
* Contract per backend `aplp.backend.spring` (candidate, confirm at Phase 0).
|
||||
*/
|
||||
const ENDPOINTS = {
|
||||
login: '/auth/login',
|
||||
logout: '/auth/logout',
|
||||
refresh: '/auth/refresh',
|
||||
me: '/auth/me',
|
||||
} as const;
|
||||
|
||||
export const authApi = {
|
||||
async login(credentials: LoginCredentials): Promise<LoginResponse> {
|
||||
const { data } = await client.post<ApiResponse<LoginResponse>>(ENDPOINTS.login, credentials);
|
||||
return data.data;
|
||||
},
|
||||
|
||||
async logout(): Promise<void> {
|
||||
await client.post(ENDPOINTS.logout);
|
||||
},
|
||||
|
||||
async refresh(): Promise<RefreshResponse> {
|
||||
const { data } = await client.post<ApiResponse<RefreshResponse>>(ENDPOINTS.refresh);
|
||||
return data.data;
|
||||
},
|
||||
|
||||
async getMe(): Promise<AuthUser> {
|
||||
const { data } = await client.get<ApiResponse<AuthUser>>(ENDPOINTS.me);
|
||||
return data.data;
|
||||
},
|
||||
|
||||
async listUsers(): Promise<ApiListResponse<AuthUser>> {
|
||||
const { data } = await client.get<ApiListResponse<AuthUser>>('/users');
|
||||
return data;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { ProtectedRoute } from '@/features/auth/components/ProtectedRoute';
|
||||
import { useAuthStore } from '@/features/auth/store/authStore';
|
||||
|
||||
function renderProtected() {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/secret']}>
|
||||
<Routes>
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="/secret" element={<div>secret content</div>} />
|
||||
</Route>
|
||||
<Route path="/login" element={<div>login page</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ProtectedRoute', () => {
|
||||
it('shows spinner while session is initializing', () => {
|
||||
useAuthStore.setState({ user: null, isInitializing: true });
|
||||
renderProtected();
|
||||
|
||||
expect(screen.getByRole('status')).toBeInTheDocument();
|
||||
expect(screen.queryByText('secret content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to /login', () => {
|
||||
useAuthStore.setState({ user: null, isInitializing: false });
|
||||
renderProtected();
|
||||
|
||||
expect(screen.getByText('login page')).toBeInTheDocument();
|
||||
expect(screen.queryByText('secret content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders protected content for authenticated users', () => {
|
||||
useAuthStore.setState({
|
||||
user: { id: 'u1', email: 'learner@aplp.io', name: 'Learner' },
|
||||
isInitializing: false,
|
||||
});
|
||||
renderProtected();
|
||||
|
||||
expect(screen.getByText('secret content')).toBeInTheDocument();
|
||||
expect(screen.queryByText('login page')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Navigate, Outlet, useLocation } from 'react-router-dom';
|
||||
|
||||
import { FullPageSpinner } from '@/shared/components/FullPageSpinner';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
|
||||
/**
|
||||
* Route guard: only renders the protected subtree when the user is
|
||||
* authenticated. While the session is bootstrapping, shows a full-page spinner.
|
||||
* Unauthenticated users are redirected to `/login` (remembering where they
|
||||
* came from).
|
||||
*/
|
||||
export function ProtectedRoute() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isInitializing = useAuthStore((s) => s.isInitializing);
|
||||
const location = useLocation();
|
||||
|
||||
if (isInitializing) {
|
||||
return <FullPageSpinner />;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
|
||||
}
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { authApi } from '../api/authApi';
|
||||
|
||||
/** Current authenticated user (server state via React Query). */
|
||||
export function useAuthUser() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isAuthenticated = user !== null;
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['auth', 'me'],
|
||||
queryFn: authApi.getMe,
|
||||
enabled: isAuthenticated,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
return {
|
||||
user: query.data ?? user,
|
||||
isLoading: query.isLoading,
|
||||
isError: query.isError,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import type { LoginCredentials } from '../types';
|
||||
|
||||
export function useLogin() {
|
||||
const login = useAuthStore((s) => s.login);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (credentials: LoginCredentials) => login(credentials.email, credentials.password),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
|
||||
export function useLogout() {
|
||||
const logout = useAuthStore((s) => s.logout);
|
||||
|
||||
return useMutation({ mutationFn: () => logout() });
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { authApi } from '@/features/auth/api/authApi';
|
||||
import { LoginPage } from '@/features/auth/pages/LoginPage';
|
||||
import { useAuthStore } from '@/features/auth/store/authStore';
|
||||
|
||||
vi.mock('@/features/auth/api/authApi', () => ({
|
||||
authApi: {
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
getMe: vi.fn(),
|
||||
listUsers: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockedAuthApi = vi.mocked(authApi);
|
||||
|
||||
function renderLogin() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/login']}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/" element={<div>home page</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('LoginPage', () => {
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({ user: null, isInitializing: false });
|
||||
vi.clearAllMocks();
|
||||
mockedAuthApi.login.mockResolvedValue({
|
||||
accessToken: 'access-123',
|
||||
user: { id: 'u1', email: 'learner@aplp.io', name: 'Learner' },
|
||||
});
|
||||
});
|
||||
|
||||
it('renders the login form', () => {
|
||||
renderLogin();
|
||||
|
||||
expect(screen.getByTestId('login-form')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Email')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('submits credentials and navigates to home on success', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderLogin();
|
||||
|
||||
await user.type(screen.getByLabelText('Email'), 'learner@aplp.io');
|
||||
await user.type(screen.getByLabelText('Password'), 'secret');
|
||||
await user.click(screen.getByRole('button', { name: /sign in/i }));
|
||||
|
||||
expect(mockedAuthApi.login).toHaveBeenCalledWith({
|
||||
email: 'learner@aplp.io',
|
||||
password: 'secret',
|
||||
});
|
||||
|
||||
await waitFor(() => expect(screen.getByText('home page')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('shows an error message on failed login', async () => {
|
||||
mockedAuthApi.login.mockRejectedValue(new Error('Invalid credentials'));
|
||||
const user = userEvent.setup();
|
||||
renderLogin();
|
||||
|
||||
await user.type(screen.getByLabelText('Email'), 'learner@aplp.io');
|
||||
await user.type(screen.getByLabelText('Password'), 'wrong');
|
||||
await user.click(screen.getByRole('button', { name: /sign in/i }));
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Invalid credentials'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
|
||||
import env from '@/shared/config/env';
|
||||
import { useLogin } from '../hooks/useLogin';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
|
||||
export function LoginPage() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const { state } = useLocation();
|
||||
const login = useLogin();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
|
||||
const from = (state as { from?: string } | null)?.from ?? '/';
|
||||
|
||||
if (user) {
|
||||
return <Navigate to={from} replace />;
|
||||
}
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
login.mutate({ email, password });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50 px-4">
|
||||
<div className="w-full max-w-sm rounded-lg border border-gray-200 bg-white p-8 shadow-sm">
|
||||
<h1 className="mb-1 text-2xl font-semibold text-gray-900">{env.VITE_APP_NAME}</h1>
|
||||
<p className="mb-6 text-sm text-gray-500">Sign in to your learning account</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4" data-testid="login-form">
|
||||
<div>
|
||||
<label htmlFor="email" className="mb-1 block text-sm font-medium text-gray-700">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="mb-1 block text-sm font-medium text-gray-700">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{login.isError && (
|
||||
<p role="alert" className="text-sm text-red-600">
|
||||
{login.error instanceof Error ? login.error.message : 'Login failed'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={login.isPending}
|
||||
className="w-full rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50"
|
||||
>
|
||||
{login.isPending ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { tokenStorage } from '@/api/tokenStorage';
|
||||
import { authApi } from '@/features/auth/api/authApi';
|
||||
import { useAuthStore } from '@/features/auth/store/authStore';
|
||||
|
||||
vi.mock('@/features/auth/api/authApi', () => ({
|
||||
authApi: {
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
getMe: vi.fn(),
|
||||
listUsers: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockedAuthApi = vi.mocked(authApi);
|
||||
|
||||
describe('authStore', () => {
|
||||
beforeEach(() => {
|
||||
tokenStorage.clear();
|
||||
useAuthStore.setState({ user: null, isInitializing: true });
|
||||
vi.clearAllMocks();
|
||||
mockedAuthApi.login.mockResolvedValue({
|
||||
accessToken: 'access-123',
|
||||
user: { id: 'u1', email: 'learner@aplp.io', name: 'Learner' },
|
||||
});
|
||||
mockedAuthApi.refresh.mockResolvedValue({
|
||||
accessToken: 'access-refreshed',
|
||||
user: { id: 'u1', email: 'learner@aplp.io', name: 'Learner' },
|
||||
});
|
||||
});
|
||||
|
||||
it('login stores token and user', async () => {
|
||||
await useAuthStore.getState().login('learner@aplp.io', 'secret');
|
||||
|
||||
expect(mockedAuthApi.login).toHaveBeenCalledWith({
|
||||
email: 'learner@aplp.io',
|
||||
password: 'secret',
|
||||
});
|
||||
expect(tokenStorage.get()).toBe('access-123');
|
||||
expect(useAuthStore.getState().user?.email).toBe('learner@aplp.io');
|
||||
expect(useAuthStore.getState().isInitializing).toBe(false);
|
||||
});
|
||||
|
||||
it('login failure leaves user signed out', async () => {
|
||||
mockedAuthApi.login.mockRejectedValue(new Error('invalid credentials'));
|
||||
|
||||
await expect(useAuthStore.getState().login('learner@aplp.io', 'wrong')).rejects.toThrow(
|
||||
'invalid credentials',
|
||||
);
|
||||
expect(tokenStorage.get()).toBeNull();
|
||||
expect(useAuthStore.getState().user).toBeNull();
|
||||
});
|
||||
|
||||
it('logout clears token and user even when API call fails', async () => {
|
||||
await useAuthStore.getState().login('learner@aplp.io', 'secret');
|
||||
mockedAuthApi.logout.mockRejectedValue(new Error('network'));
|
||||
|
||||
await useAuthStore.getState().logout();
|
||||
|
||||
expect(tokenStorage.get()).toBeNull();
|
||||
expect(useAuthStore.getState().user).toBeNull();
|
||||
});
|
||||
|
||||
it('init restores session from refresh token', async () => {
|
||||
await useAuthStore.getState().init();
|
||||
|
||||
expect(mockedAuthApi.refresh).toHaveBeenCalledOnce();
|
||||
expect(tokenStorage.get()).toBe('access-refreshed');
|
||||
expect(useAuthStore.getState().user?.id).toBe('u1');
|
||||
expect(useAuthStore.getState().isInitializing).toBe(false);
|
||||
});
|
||||
|
||||
it('init handles expired refresh token gracefully', async () => {
|
||||
mockedAuthApi.refresh.mockRejectedValue(new Error('401'));
|
||||
|
||||
await useAuthStore.getState().init();
|
||||
|
||||
expect(tokenStorage.get()).toBeNull();
|
||||
expect(useAuthStore.getState().user).toBeNull();
|
||||
expect(useAuthStore.getState().isInitializing).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { registerAuthHandlers } from '@/api/client';
|
||||
import { tokenStorage } from '@/api/tokenStorage';
|
||||
import { authApi } from '../api/authApi';
|
||||
import type { AuthUser } from '../types';
|
||||
|
||||
interface AuthState {
|
||||
/** Authenticated user, or null when signed out. */
|
||||
user: AuthUser | null;
|
||||
/** Whether a session bootstrap is in progress. */
|
||||
isInitializing: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
/** Bootstrap session: try refresh on app start. */
|
||||
init: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()((set) => ({
|
||||
user: null,
|
||||
isInitializing: true,
|
||||
|
||||
login: async (email, password) => {
|
||||
const { accessToken, user } = await authApi.login({ email, password });
|
||||
tokenStorage.set(accessToken);
|
||||
set({ user, isInitializing: false });
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
try {
|
||||
await authApi.logout();
|
||||
} catch {
|
||||
// Best-effort: always clear the local session, even if the API call fails.
|
||||
} finally {
|
||||
tokenStorage.clear();
|
||||
set({ user: null, isInitializing: false });
|
||||
}
|
||||
},
|
||||
|
||||
init: async () => {
|
||||
try {
|
||||
const { accessToken, user } = await authApi.refresh();
|
||||
tokenStorage.set(accessToken);
|
||||
set({ user, isInitializing: false });
|
||||
} catch {
|
||||
tokenStorage.clear();
|
||||
set({ user: null, isInitializing: false });
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
* Wire the API client to this store: refresh access token and clear session on
|
||||
* hard 401 (unrecoverable). Keeps the auth concern centralized, not scattered.
|
||||
*/
|
||||
registerAuthHandlers(
|
||||
async () => {
|
||||
try {
|
||||
const { accessToken } = await authApi.refresh();
|
||||
tokenStorage.set(accessToken);
|
||||
return accessToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
() => {
|
||||
tokenStorage.clear();
|
||||
useAuthStore.setState({ user: null, isInitializing: false });
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface LoginCredentials {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
accessToken: string;
|
||||
user: AuthUser;
|
||||
}
|
||||
|
||||
export interface RefreshResponse {
|
||||
accessToken: string;
|
||||
user: AuthUser;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@import 'tailwindcss';
|
||||
@@ -0,0 +1,17 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
|
||||
import App from '@/app/App';
|
||||
import { QueryProvider } from '@/app/providers/QueryProvider';
|
||||
import './index.css';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryProvider>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</QueryProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,8 @@
|
||||
export function EmptyState({ title, description }: { title: string; description?: string }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed border-gray-300 bg-white px-6 py-12 text-center">
|
||||
<p className="text-sm font-medium text-gray-700">{title}</p>
|
||||
{description && <p className="mt-1 text-sm text-gray-500">{description}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
}
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
/** Catches render-time errors in the tree and shows a fallback UI. */
|
||||
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||||
state: ErrorBoundaryState = { hasError: false };
|
||||
|
||||
static getDerivedStateFromError(): ErrorBoundaryState {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
console.error('Unhandled error in component tree', error, info.componentStack);
|
||||
}
|
||||
|
||||
render(): ReactNode {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
this.props.fallback ?? (
|
||||
<div className="flex min-h-screen items-center justify-center px-4 text-center">
|
||||
<p className="text-sm text-gray-600">Something went wrong. Please reload the page.</p>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ApiError } from '@/types/api';
|
||||
|
||||
interface ErrorStateProps {
|
||||
title?: string;
|
||||
error?: ApiError | Error | null;
|
||||
}
|
||||
|
||||
export function ErrorState({ title = 'Something went wrong', error }: ErrorStateProps) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-red-200 bg-red-50 px-6 py-8 text-center">
|
||||
<p className="text-sm font-medium text-red-700">{title}</p>
|
||||
{error && <p className="mt-1 text-sm text-red-600">{error.message}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Spinner } from '@/shared/components/Spinner';
|
||||
|
||||
export function FullPageSpinner({ label = 'Loading' }: { label?: string }) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<Spinner label={label} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export function Spinner({ label = 'Loading' }: { label?: string }) {
|
||||
return (
|
||||
<span role="status" className="inline-flex items-center gap-2 text-sm text-gray-500">
|
||||
<svg className="h-4 w-4 animate-spin text-indigo-600" viewBox="0 0 24 24" fill="none">
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
/>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
|
||||
</svg>
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
interface Env {
|
||||
/** Base URL of the APLP backend REST API. */
|
||||
VITE_API_BASE_URL: string;
|
||||
/** Display name of the application. */
|
||||
VITE_APP_NAME: string;
|
||||
}
|
||||
|
||||
const env: Env = {
|
||||
VITE_API_BASE_URL: import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8080/api',
|
||||
VITE_APP_NAME: import.meta.env.VITE_APP_NAME ?? 'APLP',
|
||||
};
|
||||
|
||||
export default env;
|
||||
@@ -0,0 +1 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
@@ -0,0 +1,30 @@
|
||||
export interface ApiErrorPayload {
|
||||
/** Backend error code (stable identifier for the error). */
|
||||
code?: string;
|
||||
/** Human-readable message. */
|
||||
message?: string;
|
||||
/** Field-level validation errors, keyed by field name. */
|
||||
fieldErrors?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
}
|
||||
|
||||
export interface ApiListResponse<T> {
|
||||
data: T[];
|
||||
meta?: {
|
||||
page?: number;
|
||||
size?: number;
|
||||
total?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** Normalized error thrown by the API layer. */
|
||||
export interface ApiError {
|
||||
status: number;
|
||||
code?: string;
|
||||
message: string;
|
||||
fieldErrors?: Record<string, string[]>;
|
||||
raw: unknown;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client", "vitest/globals"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Paths */
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { fileURLToPath, URL } from 'node:url';
|
||||
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
globals: true,
|
||||
setupFiles: ['./src/test/setup.ts'],
|
||||
css: false,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user