611 lines
19 KiB
Markdown
611 lines
19 KiB
Markdown
# Team Password Reset — Admin Panel Integration Guide
|
|
|
|
This guide documents how to implement **forgot password / password reset** for **team members** (admin panel staff) in the Rezina admin panel.
|
|
|
|
**Use this guide when:** a staff member cannot sign in and needs to reset their password via email link, or you are wiring the public “Forgot password” and “Reset password” screens on the admin app.
|
|
|
|
**Related:**
|
|
|
|
- [Team Member Invitation — Admin Panel Integration](./team-member-invitation-admin-panel-integration.md) (first-time password via invite)
|
|
- [Team Member Refresh Token — Admin Panel Integration](./team-member-refresh-token-admin-panel-integration.md) (login/session after reset)
|
|
|
|
> **Not for mobile learners.** Learner (mobile app) password reset uses `POST /api/v1/user/sendResetCode` and delivers a **numeric OTP code** by email/SMS. Team reset uses `POST /api/v1/team/sendResetCode` and delivers a **reset link**. Do not mix these endpoints.
|
|
|
|
---
|
|
|
|
## Table of contents
|
|
|
|
1. [Feature overview](#feature-overview)
|
|
2. [Architecture & end-to-end flow](#architecture--end-to-end-flow)
|
|
3. [Backend prerequisites](#backend-prerequisites)
|
|
4. [Authentication](#authentication)
|
|
5. [Data model](#data-model)
|
|
6. [Response envelopes](#response-envelopes)
|
|
7. [Public API reference](#public-api-reference)
|
|
8. [Reset email](#reset-email)
|
|
9. [Recommended admin UI screens](#recommended-admin-ui-screens)
|
|
10. [Reset-password page (public route)](#reset-password-page-public-route)
|
|
11. [Logged-in change password (related)](#logged-in-change-password-related)
|
|
12. [TypeScript types & API client](#typescript-types--api-client)
|
|
13. [Error handling](#error-handling)
|
|
14. [Security notes](#security-notes)
|
|
15. [Integration checklist](#integration-checklist)
|
|
16. [Testing checklist](#testing-checklist)
|
|
17. [Quick reference](#quick-reference)
|
|
18. [Learner vs team comparison](#learner-vs-team-comparison)
|
|
|
|
---
|
|
|
|
## Feature overview
|
|
|
|
Team password reset lets an **already activated** staff member recover access without an admin manually setting a password.
|
|
|
|
| Step | Who | What happens |
|
|
|------|-----|----------------|
|
|
| 1 | Staff (logged out) | Enters email on “Forgot password” |
|
|
| 2 | Backend | Validates active + email-verified team member; emails a **reset link** containing `email` + `otp` |
|
|
| 3 | Staff | Opens link → admin panel `/reset-password?email=...&otp=...` |
|
|
| 4 | Staff | Sets a new password (OTP prefilled from URL) |
|
|
| 5 | Backend | Validates OTP, updates `team_members.password`, marks OTP used, revokes refresh tokens |
|
|
| 6 | Staff | Signs in via `POST /api/v1/team/login` |
|
|
|
|
| Capability | Endpoint | Auth |
|
|
|------------|----------|------|
|
|
| Request reset email | `POST /api/v1/team/sendResetCode` | **Public** |
|
|
| Complete reset | `POST /api/v1/team/resetPassword` | **Public** |
|
|
| Staff login | `POST /api/v1/team/login` | **Public** |
|
|
| Change password while logged in | `POST /api/v1/team/members/:id/change-password` | Bearer + `team.members.change_password` |
|
|
|
|
### Eligibility rules
|
|
|
|
Reset email is sent only if **all** of the following are true:
|
|
|
|
| Condition | Otherwise |
|
|
|-----------|-----------|
|
|
| Email exists in `team_members` | `404` — Team member not found |
|
|
| `status = active` | `400` — Team member account is not active |
|
|
| `email_verified = true` (invitation accepted) | `400` — Accept your invitation before resetting password |
|
|
|
|
Pending invitees must use the **accept-invite** flow, not password reset.
|
|
|
|
---
|
|
|
|
## Architecture & end-to-end flow
|
|
|
|
```mermaid
|
|
sequenceDiagram
|
|
participant Staff as Admin panel (logged out)
|
|
participant API as Rezina API
|
|
participant Mail as Email (Resend)
|
|
participant DB as Postgres
|
|
|
|
Staff->>API: POST /team/sendResetCode { email }
|
|
API->>DB: Lookup team_members by email
|
|
API->>API: Require active + email_verified
|
|
API->>API: Generate OTP (5 min TTL)
|
|
API->>Mail: password_reset template with ResetLink
|
|
API->>DB: INSERT team_otps
|
|
API-->>Staff: 200 Password reset link sent
|
|
|
|
Staff->>Staff: Open email link (?email=&otp=)
|
|
Staff->>API: POST /team/resetPassword { email, otp, password }
|
|
API->>DB: Validate latest team_otps row
|
|
API->>DB: Update team_members.password
|
|
API->>DB: Mark OTP used; revoke refresh tokens
|
|
API-->>Staff: 200 Password reset successfully
|
|
|
|
Staff->>API: POST /team/login { email, password }
|
|
API-->>Staff: access_token + refresh_token
|
|
```
|
|
|
|
### Reset link format
|
|
|
|
The backend builds links from `TEAM_PASSWORD_RESET_BASE_URL` (preferred), or derives `{scheme}://{host}/reset-password` from `TEAM_INVITE_BASE_URL` if the dedicated env is empty:
|
|
|
|
```
|
|
{TEAM_PASSWORD_RESET_BASE_URL}?email={email}&otp={otp}
|
|
```
|
|
|
|
Example:
|
|
|
|
```
|
|
https://admin.rezinaacademy.com/reset-password?email=admin%40rezinaacademy.com&otp=482913
|
|
```
|
|
|
|
| Query param | Required | Notes |
|
|
|-------------|----------|-------|
|
|
| `email` | Yes | Lowercased when stored/sent; use as-is from URL for the reset form |
|
|
| `otp` | Yes | Numeric code embedded in the link; also submitted to `resetPassword` |
|
|
|
|
The **frontend route path** is your choice, but it **must match** what the server puts in the email (`TEAM_PASSWORD_RESET_BASE_URL` or the derived `/reset-password` path).
|
|
|
|
---
|
|
|
|
## Backend prerequisites
|
|
|
|
### Environment variables
|
|
|
|
| Variable | Required | Default / fallback | Purpose |
|
|
|----------|----------|--------------------|---------|
|
|
| `TEAM_PASSWORD_RESET_BASE_URL` | Recommended | If empty → derive from `TEAM_INVITE_BASE_URL` as `{origin}/reset-password` | Absolute base URL of the admin reset page (no query string) |
|
|
| `TEAM_INVITE_BASE_URL` | Needed if reset URL unset | — | Used only as fallback host for deriving `/reset-password` |
|
|
| `RESEND_API_KEY` | Yes (for email) | — | Transactional email delivery |
|
|
| `RESEND_SENDER_EMAIL` | Yes (for email) | — | From address |
|
|
|
|
**Examples:**
|
|
|
|
```env
|
|
TEAM_PASSWORD_RESET_BASE_URL=https://admin.rezinaacademy.com/reset-password
|
|
# Optional fallback source if the above is omitted:
|
|
TEAM_INVITE_BASE_URL=https://admin.rezinaacademy.com/accept-invite
|
|
```
|
|
|
|
If neither yields a usable base URL, `POST /team/sendResetCode` returns **500** with:
|
|
|
|
```text
|
|
TEAM_PASSWORD_RESET_BASE_URL is not configured
|
|
```
|
|
|
|
### Database migrations
|
|
|
|
Ensure migration **`000098_team_otps`** has been applied. It creates:
|
|
|
|
- Table `team_otps` (OTP rows keyed by `team_member_id`)
|
|
- Indexes on `team_member_id` / created order
|
|
|
|
### Email template
|
|
|
|
Uses system slug **`password_reset`** (same branded template as historical learner link emails).
|
|
|
|
| Variable | Meaning |
|
|
|----------|---------|
|
|
| `FirstName` | Team member first name |
|
|
| `ResetLink` | Full URL with `email` + `otp` query params |
|
|
| `ExpiresMinutes` | Always **5** for team reset |
|
|
|
|
Subject (default): `Reset your Rezina password`
|
|
|
|
---
|
|
|
|
## Authentication
|
|
|
|
Both forgot-password endpoints are **public** (no Bearer token).
|
|
|
|
Host these pages **outside** the authenticated admin shell (same pattern as `/accept-invite` and `/login`):
|
|
|
|
- `/forgot-password` — request link
|
|
- `/reset-password` — set new password from link
|
|
|
|
After a successful reset, redirect to `/login` and call `POST /api/v1/team/login` — **not** learner `auth/customer-login`.
|
|
|
|
---
|
|
|
|
## Data model
|
|
|
|
### `team_otps` (server-side)
|
|
|
|
| Column | Notes |
|
|
|--------|-------|
|
|
| `team_member_id` | FK → `team_members.id` (CASCADE delete) |
|
|
| `sent_to` | Email address |
|
|
| `medium` | `email` |
|
|
| `otp_for` | `reset` |
|
|
| `otp` | Code embedded in link |
|
|
| `used` / `used_at` | Set after successful `resetPassword` |
|
|
| `expires_at` | **5 minutes** from send |
|
|
| `created_at` | Latest row per member is used for validation |
|
|
|
|
Only the **latest** OTP for a member is checked. Requesting a new reset invalidates older codes for practical purposes (they are no longer “latest”).
|
|
|
|
### Related `team_members` fields
|
|
|
|
| Field | Relevance |
|
|
|-------|-----------|
|
|
| `email` | Lookup key (normalized to lowercase) |
|
|
| `status` | Must be `active` |
|
|
| `email_verified` | Must be `true` |
|
|
| `password` | bcrypt hash updated on successful reset |
|
|
|
|
---
|
|
|
|
## Response envelopes
|
|
|
|
Success:
|
|
|
|
```json
|
|
{
|
|
"message": "Password reset link sent successfully",
|
|
"success": true
|
|
}
|
|
```
|
|
|
|
Error:
|
|
|
|
```json
|
|
{
|
|
"message": "Failed to send password reset",
|
|
"error": "Team member not found"
|
|
}
|
|
```
|
|
|
|
Base URL for all calls: `{API_BASE}/api/v1`
|
|
|
|
---
|
|
|
|
## Public API reference
|
|
|
|
### 1. Request password reset email
|
|
|
|
```http
|
|
POST /api/v1/team/sendResetCode
|
|
Content-Type: application/json
|
|
```
|
|
|
|
**Body**
|
|
|
|
| Field | Type | Required | Validation |
|
|
|-------|------|----------|------------|
|
|
| `email` | string | Yes | Valid email |
|
|
|
|
```json
|
|
{
|
|
"email": "admin@rezinaacademy.com"
|
|
}
|
|
```
|
|
|
|
**Success — `200`**
|
|
|
|
```json
|
|
{
|
|
"message": "Password reset link sent successfully",
|
|
"success": true
|
|
}
|
|
```
|
|
|
|
**Errors**
|
|
|
|
| Status | `error` (typical) | When |
|
|
|--------|-------------------|------|
|
|
| `400` | Validation / invalid body | Bad email format |
|
|
| `400` | `Team member account is not active` | Inactive / suspended |
|
|
| `400` | `Accept your invitation before resetting password` | Invite not accepted yet |
|
|
| `404` | `Team member not found` | Unknown email |
|
|
| `500` | `TEAM_PASSWORD_RESET_BASE_URL is not configured` | Env misconfigured |
|
|
| `500` | Email provider / other | Delivery or server failure |
|
|
|
|
**UI tip:** On the forgot-password form, show a generic success message after `200`. For `404`, you may show “No account found” or a generic “If an account exists, we sent a link” depending on product preference (API currently distinguishes not-found).
|
|
|
|
---
|
|
|
|
### 2. Complete password reset
|
|
|
|
```http
|
|
POST /api/v1/team/resetPassword
|
|
Content-Type: application/json
|
|
```
|
|
|
|
**Body**
|
|
|
|
| Field | Type | Required | Validation |
|
|
|-------|------|----------|------------|
|
|
| `email` | string | Yes | Valid email |
|
|
| `otp` | string | Yes | From query param / email link |
|
|
| `password` | string | Yes | Min length **8** |
|
|
|
|
```json
|
|
{
|
|
"email": "admin@rezinaacademy.com",
|
|
"otp": "482913",
|
|
"password": "NewSecurePass1"
|
|
}
|
|
```
|
|
|
|
**Success — `200`**
|
|
|
|
```json
|
|
{
|
|
"message": "Password reset successfully",
|
|
"success": true
|
|
}
|
|
```
|
|
|
|
**Side effects on success**
|
|
|
|
- `team_members.password` updated (bcrypt)
|
|
- OTP marked used
|
|
- All active **team refresh tokens** for that member revoked (must log in again)
|
|
|
|
**Errors**
|
|
|
|
| Status | `error` (typical) | When |
|
|
|--------|-------------------|------|
|
|
| `400` | Validation | Missing fields / password < 8 chars |
|
|
| `400` | `Invalid or missing reset code` | Wrong OTP / no OTP row |
|
|
| `400` | `Reset code has expired` | Older than 5 minutes |
|
|
| `400` | `Reset code has already been used` | Replay |
|
|
| `404` | `Team member not found` | Email not in `team_members` |
|
|
| `500` | Server error | Unexpected failure |
|
|
|
|
---
|
|
|
|
### 3. Login after reset
|
|
|
|
```http
|
|
POST /api/v1/team/login
|
|
Content-Type: application/json
|
|
```
|
|
|
|
```json
|
|
{
|
|
"email": "admin@rezinaacademy.com",
|
|
"password": "NewSecurePass1"
|
|
}
|
|
```
|
|
|
|
See the refresh-token integration guide for storing `access_token` / `refresh_token`.
|
|
|
|
---
|
|
|
|
## Reset email
|
|
|
|
| Item | Value |
|
|
|------|--------|
|
|
| Template slug | `password_reset` |
|
|
| Primary CTA | `ResetLink` |
|
|
| Expiry copy | 5 minutes |
|
|
|
|
Staff should open the link promptly. If expired, they must request a new email from `/forgot-password`.
|
|
|
|
---
|
|
|
|
## Recommended admin UI screens
|
|
|
|
### A. Login screen
|
|
|
|
Add a **Forgot password?** link → `/forgot-password`.
|
|
|
|
### B. Forgot password (`/forgot-password`)
|
|
|
|
**Public route.**
|
|
|
|
1. Email input + submit
|
|
2. Call `POST /team/sendResetCode`
|
|
3. On success: “Check your email for a reset link. The link expires in 5 minutes.”
|
|
4. Link back to login
|
|
5. If error is invitation-pending: point user to check invite email / contact admin
|
|
|
|
### C. Reset password (`/reset-password`)
|
|
|
|
**Public route.** Must match `TEAM_PASSWORD_RESET_BASE_URL`.
|
|
|
|
1. On load, read `email` and `otp` from the query string
|
|
2. Prefill email (read-only recommended) and OTP (hidden or read-only)
|
|
3. New password + confirm password (client-side match; server enforces min 8)
|
|
4. Submit `POST /team/resetPassword`
|
|
5. On success: redirect to `/login` with a success toast
|
|
6. On expired OTP: CTA to `/forgot-password`
|
|
|
|
### D. Optional: deep-link without query params
|
|
|
|
If the user lands without `otp`/`email`, show a form that accepts email + OTP manually (same API). Prefer query-param prefill from the email link.
|
|
|
|
---
|
|
|
|
## Reset-password page (public route)
|
|
|
|
Suggested route: `/reset-password` (must match server env).
|
|
|
|
```text
|
|
Load /reset-password?email=...&otp=...
|
|
│
|
|
├─ missing email or otp? → show manual fields or redirect to /forgot-password
|
|
│
|
|
▼
|
|
User enters new password (+ confirm)
|
|
│
|
|
▼
|
|
POST /api/v1/team/resetPassword
|
|
│
|
|
├─ 200 → redirect /login
|
|
├─ expired → message + link /forgot-password
|
|
└─ invalid → show error, allow retry / request new link
|
|
```
|
|
|
|
### Example React/Next flow (pseudo)
|
|
|
|
```ts
|
|
// /reset-password page
|
|
const search = useSearchParams();
|
|
const email = search.get("email") ?? "";
|
|
const otp = search.get("otp") ?? "";
|
|
|
|
async function onSubmit(password: string) {
|
|
const res = await api.post("/team/resetPassword", { email, otp, password });
|
|
// on success → router.push("/login?reset=1")
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Logged-in change password (related)
|
|
|
|
When the user **already knows** their current password, use the authenticated endpoint instead of forgot-password:
|
|
|
|
```http
|
|
POST /api/v1/team/members/{id}/change-password
|
|
Authorization: Bearer <access_token>
|
|
Content-Type: application/json
|
|
```
|
|
|
|
```json
|
|
{
|
|
"current_password": "OldPassword1",
|
|
"new_password": "NewPassword1"
|
|
}
|
|
```
|
|
|
|
| Item | Value |
|
|
|------|--------|
|
|
| Permission | `team.members.change_password` |
|
|
| Typical UI | Profile / security settings |
|
|
| Does **not** send email | Direct update after verifying current password |
|
|
|
|
Do **not** use this for the logged-out forgot-password flow.
|
|
|
|
---
|
|
|
|
## TypeScript types & API client
|
|
|
|
```ts
|
|
export type TeamSendPasswordResetReq = {
|
|
email: string;
|
|
};
|
|
|
|
export type TeamResetPasswordReq = {
|
|
email: string;
|
|
otp: string;
|
|
password: string;
|
|
};
|
|
|
|
export type ApiSuccess = {
|
|
message: string;
|
|
success?: boolean;
|
|
data?: unknown;
|
|
};
|
|
|
|
export type ApiError = {
|
|
message: string;
|
|
error?: string;
|
|
};
|
|
```
|
|
|
|
```ts
|
|
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL; // e.g. https://api.example.com/api/v1
|
|
|
|
export async function sendTeamPasswordReset(email: string): Promise<ApiSuccess> {
|
|
const res = await fetch(`${API_BASE}/team/sendResetCode`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ email }),
|
|
});
|
|
const body = await res.json();
|
|
if (!res.ok) throw Object.assign(new Error(body.error || body.message), { status: res.status, body });
|
|
return body;
|
|
}
|
|
|
|
export async function resetTeamPassword(payload: TeamResetPasswordReq): Promise<ApiSuccess> {
|
|
const res = await fetch(`${API_BASE}/team/resetPassword`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(payload),
|
|
});
|
|
const body = await res.json();
|
|
if (!res.ok) throw Object.assign(new Error(body.error || body.message), { status: res.status, body });
|
|
return body;
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Error handling
|
|
|
|
Map API `error` strings to UI copy:
|
|
|
|
| HTTP | `error` | Suggested UI |
|
|
|------|---------|--------------|
|
|
| `400` | validation / `Email is required` | Inline field errors |
|
|
| `400` | `Team member account is not active` | “This account is inactive. Contact an administrator.” |
|
|
| `400` | `Accept your invitation before resetting password` | “Finish accepting your invitation first.” + link help |
|
|
| `400` | `Invalid or missing reset code` | “Invalid reset code. Request a new link.” |
|
|
| `400` | `Reset code has expired` | “This link expired (5 minutes). Request a new one.” |
|
|
| `400` | `Reset code has already been used` | “This link was already used. Request a new one.” |
|
|
| `404` | `Team member not found` | “No team account found for that email.” |
|
|
| `500` | `TEAM_PASSWORD_RESET_BASE_URL is not configured` | Ops/config message (not user fault) |
|
|
| `500` | other | Generic “Something went wrong. Try again.” |
|
|
|
|
---
|
|
|
|
## Security notes
|
|
|
|
1. **OTP TTL is 5 minutes** — surface this clearly in the UI and email.
|
|
2. **Single-use** — successful reset marks the OTP used; reuse fails.
|
|
3. **Latest OTP wins** — requesting again creates a new row; submit the OTP from the newest email.
|
|
4. **Sessions invalidated** — refresh tokens are revoked after reset; force a fresh login.
|
|
5. **Do not use learner endpoints** for admin staff (`/user/sendResetCode` looks up `users`, not `team_members`).
|
|
6. Prefer HTTPS admin URLs in `TEAM_PASSWORD_RESET_BASE_URL`.
|
|
7. OTP appears in the URL — treat the link as a secret; avoid logging full URLs client-side.
|
|
|
|
---
|
|
|
|
## Integration checklist
|
|
|
|
### Backend / ops
|
|
|
|
- [ ] Migration `000098_team_otps` applied
|
|
- [ ] `TEAM_PASSWORD_RESET_BASE_URL` set to the admin reset page (recommended)
|
|
- [ ] Or `TEAM_INVITE_BASE_URL` set so fallback `{origin}/reset-password` is correct
|
|
- [ ] Resend email env configured (`RESEND_API_KEY`, `RESEND_SENDER_EMAIL`)
|
|
- [ ] `password_reset` email template active / branded as expected
|
|
|
|
### Admin panel routes
|
|
|
|
- [ ] Public `/forgot-password` (no auth guard)
|
|
- [ ] Public `/reset-password` matching env base URL
|
|
- [ ] Login page link: “Forgot password?”
|
|
- [ ] After reset → `/login`
|
|
- [ ] Optional: profile “Change password” using authenticated change-password API
|
|
|
|
### Client behavior
|
|
|
|
- [ ] Prefill `email` + `otp` from query on reset page
|
|
- [ ] Password min length 8 + confirm match
|
|
- [ ] Handle expired / used / invalid OTP with resend path
|
|
- [ ] Use `/api/v1/team/*` only (not `/user/*`)
|
|
|
|
---
|
|
|
|
## Testing checklist
|
|
|
|
- [ ] Active verified member receives email with working link
|
|
- [ ] Link opens admin `/reset-password` with query params
|
|
- [ ] Reset with valid OTP updates password; old password fails login
|
|
- [ ] New password works with `POST /team/login`
|
|
- [ ] Expired OTP (> 5 min) returns expired error
|
|
- [ ] Reusing OTP after success returns already-used
|
|
- [ ] Unknown email → 404
|
|
- [ ] Inactive member → 400 inactive
|
|
- [ ] Pending invite (not verified) → 400 accept invitation first
|
|
- [ ] After reset, old refresh token no longer works
|
|
- [ ] Learner `/user/sendResetCode` with a team-only email does **not** reset team password
|
|
|
|
---
|
|
|
|
## Quick reference
|
|
|
|
| Action | Method | Path | Auth |
|
|
|--------|--------|------|------|
|
|
| Send reset link | `POST` | `/team/sendResetCode` | Public |
|
|
| Complete reset | `POST` | `/team/resetPassword` | Public |
|
|
| Staff login | `POST` | `/team/login` | Public |
|
|
| Change password (logged in) | `POST` | `/team/members/:id/change-password` | Bearer + permission |
|
|
|
|
**Send body:** `{ "email": "..." }`
|
|
**Reset body:** `{ "email": "...", "otp": "...", "password": "..." }`
|
|
**Link:** `{TEAM_PASSWORD_RESET_BASE_URL}?email=...&otp=...`
|
|
**OTP expiry:** 5 minutes
|
|
|
|
---
|
|
|
|
## Learner vs team comparison
|
|
|
|
| | Mobile learner | Admin team member |
|
|
|--|----------------|-------------------|
|
|
| Identity table | `users` | `team_members` |
|
|
| Request reset | `POST /user/sendResetCode` | `POST /team/sendResetCode` |
|
|
| Complete reset | `POST /user/resetPassword` | `POST /team/resetPassword` |
|
|
| Email content | **Numeric OTP code** | **Reset link** (`email` + `otp` in URL) |
|
|
| OTP storage | `otps` | `team_otps` |
|
|
| Login after | Customer / learner auth | `POST /team/login` |
|
|
|
|
Keep admin panel integration on the **team** column only.
|