feat: split learner OTP and team password-reset link flows

Learners get email/SMS OTP codes via /user/sendResetCode; team members get reset links via new /team/sendResetCode and /team/resetPassword APIs, with admin panel integration docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-10 01:52:49 -07:00
parent 3ff43a3a22
commit 815ac1576e
19 changed files with 1128 additions and 36 deletions

View File

@ -342,6 +342,7 @@ func main() {
emailTemplateSvc,
messengerSvc,
cfg.TeamInviteBaseURL,
cfg.TeamPasswordResetBaseURL,
cfg.TeamInviteExpiry,
)

View File

@ -0,0 +1,3 @@
DROP INDEX IF EXISTS idx_team_otps_member_created;
DROP INDEX IF EXISTS idx_team_otps_member_id;
DROP TABLE IF EXISTS team_otps;

View File

@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS team_otps (
id BIGSERIAL PRIMARY KEY,
team_member_id BIGINT NOT NULL REFERENCES team_members(id) ON DELETE CASCADE,
sent_to VARCHAR(255) NOT NULL,
medium VARCHAR(50) NOT NULL DEFAULT 'email',
otp_for VARCHAR(50) NOT NULL DEFAULT 'reset',
otp VARCHAR(10) NOT NULL,
used BOOLEAN NOT NULL DEFAULT FALSE,
used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_team_otps_member_id ON team_otps(team_member_id);
CREATE INDEX IF NOT EXISTS idx_team_otps_member_created ON team_otps(team_member_id, created_at DESC);

22
db/query/team_otps.sql Normal file
View File

@ -0,0 +1,22 @@
-- name: CreateTeamOtp :exec
INSERT INTO team_otps (
team_member_id,
sent_to,
medium,
otp_for,
otp,
expires_at
)
VALUES ($1, $2, $3, $4, $5, $6);
-- name: GetLatestTeamOtp :one
SELECT id, team_member_id, sent_to, medium, otp_for, otp, used, used_at, created_at, expires_at
FROM team_otps
WHERE team_member_id = $1
ORDER BY id DESC
LIMIT 1;
-- name: MarkTeamOtpAsUsed :exec
UPDATE team_otps
SET used = TRUE, used_at = $2
WHERE id = $1;

View File

@ -0,0 +1,610 @@
# 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 Yimaru 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 Yimaru 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.yimaruacademy.com/reset-password?email=admin%40yimaruacademy.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.yimaruacademy.com/reset-password
# Optional fallback source if the above is omitted:
TEAM_INVITE_BASE_URL=https://admin.yimaruacademy.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 Yimaru Academy 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@yimaruacademy.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@yimaruacademy.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 &lt; 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@yimaruacademy.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 (&gt; 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.

View File

@ -585,6 +585,19 @@ type TeamMember struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type TeamOtp struct {
ID int64 `json:"id"`
TeamMemberID int64 `json:"team_member_id"`
SentTo string `json:"sent_to"`
Medium string `json:"medium"`
OtpFor string `json:"otp_for"`
Otp string `json:"otp"`
Used bool `json:"used"`
UsedAt pgtype.Timestamptz `json:"used_at"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type TeamRefreshToken struct {
ID int64 `json:"id"`
TeamMemberID int64 `json:"team_member_id"`

100
gen/db/team_otps.sql.go Normal file
View File

@ -0,0 +1,100 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: team_otps.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const CreateTeamOtp = `-- name: CreateTeamOtp :exec
INSERT INTO team_otps (
team_member_id,
sent_to,
medium,
otp_for,
otp,
expires_at
)
VALUES ($1, $2, $3, $4, $5, $6)
`
type CreateTeamOtpParams struct {
TeamMemberID int64 `json:"team_member_id"`
SentTo string `json:"sent_to"`
Medium string `json:"medium"`
OtpFor string `json:"otp_for"`
Otp string `json:"otp"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
}
func (q *Queries) CreateTeamOtp(ctx context.Context, arg CreateTeamOtpParams) error {
_, err := q.db.Exec(ctx, CreateTeamOtp,
arg.TeamMemberID,
arg.SentTo,
arg.Medium,
arg.OtpFor,
arg.Otp,
arg.ExpiresAt,
)
return err
}
const GetLatestTeamOtp = `-- name: GetLatestTeamOtp :one
SELECT id, team_member_id, sent_to, medium, otp_for, otp, used, used_at, created_at, expires_at
FROM team_otps
WHERE team_member_id = $1
ORDER BY id DESC
LIMIT 1
`
type GetLatestTeamOtpRow struct {
ID int64 `json:"id"`
TeamMemberID int64 `json:"team_member_id"`
SentTo string `json:"sent_to"`
Medium string `json:"medium"`
OtpFor string `json:"otp_for"`
Otp string `json:"otp"`
Used bool `json:"used"`
UsedAt pgtype.Timestamptz `json:"used_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
}
func (q *Queries) GetLatestTeamOtp(ctx context.Context, teamMemberID int64) (GetLatestTeamOtpRow, error) {
row := q.db.QueryRow(ctx, GetLatestTeamOtp, teamMemberID)
var i GetLatestTeamOtpRow
err := row.Scan(
&i.ID,
&i.TeamMemberID,
&i.SentTo,
&i.Medium,
&i.OtpFor,
&i.Otp,
&i.Used,
&i.UsedAt,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const MarkTeamOtpAsUsed = `-- name: MarkTeamOtpAsUsed :exec
UPDATE team_otps
SET used = TRUE, used_at = $2
WHERE id = $1
`
type MarkTeamOtpAsUsedParams struct {
ID int64 `json:"id"`
UsedAt pgtype.Timestamptz `json:"used_at"`
}
func (q *Queries) MarkTeamOtpAsUsed(ctx context.Context, arg MarkTeamOtpAsUsedParams) error {
_, err := q.db.Exec(ctx, MarkTeamOtpAsUsed, arg.ID, arg.UsedAt)
return err
}

View File

@ -138,6 +138,7 @@ type Config struct {
ResendApiKey string
ResendSenderEmail string
TeamInviteBaseURL string
TeamPasswordResetBaseURL string
TeamInviteExpiry time.Duration
LearnerAppBaseURL string
PasswordResetBaseURL string
@ -488,6 +489,7 @@ func (c *Config) loadEnv() error {
c.ResendSenderEmail = resendSenderEmail
c.TeamInviteBaseURL = strings.TrimSpace(os.Getenv("TEAM_INVITE_BASE_URL"))
c.TeamPasswordResetBaseURL = strings.TrimSpace(os.Getenv("TEAM_PASSWORD_RESET_BASE_URL"))
inviteExpiryHours := 168
if raw := strings.TrimSpace(os.Getenv("TEAM_INVITE_EXPIRY_HOURS")); raw != "" {
if h, err := strconv.Atoi(raw); err == nil && h > 0 {

View File

@ -12,6 +12,7 @@ var (
ErrTeamInvitationRevoked = errors.New("team invitation has been revoked")
ErrTeamMemberPendingInvitation = errors.New("team member must accept their invitation before signing in")
ErrTeamInviteBaseURLNotConfigured = errors.New("team invite base URL is not configured")
ErrTeamPasswordResetBaseURLNotConfigured = errors.New("team password reset base URL is not configured")
)
type TeamInvitationStatus string

View File

@ -0,0 +1,27 @@
package domain
import "time"
// TeamOtp stores password-reset OTPs for team_members (admin panel).
type TeamOtp struct {
ID int64
TeamMemberID int64
SentTo string
Medium OtpMedium
For OtpFor
Otp string
Used bool
UsedAt time.Time
CreatedAt time.Time
ExpiresAt time.Time
}
type TeamSendPasswordResetReq struct {
Email string `json:"email" validate:"required,email"`
}
type TeamResetPasswordReq struct {
Email string `json:"email" validate:"required,email"`
Otp string `json:"otp" validate:"required"`
Password string `json:"password" validate:"required,min=8"`
}

View File

@ -48,4 +48,8 @@ type TeamStore interface {
RevokeTeamInvitation(ctx context.Context, invitationID int64) (domain.TeamInvitation, error)
ExpireTeamInvitation(ctx context.Context, invitationID int64) error
ListTeamInvitations(ctx context.Context, status *string, limit, offset int32) ([]domain.TeamInvitationWithMember, int64, error)
CreateTeamOtp(ctx context.Context, otp domain.TeamOtp) error
GetLatestTeamOtp(ctx context.Context, teamMemberID int64) (domain.TeamOtp, error)
MarkTeamOtpAsUsed(ctx context.Context, otp domain.TeamOtp) error
}

View File

@ -517,6 +517,55 @@ func (s *Store) RevokeTeamRefreshTokenByToken(ctx context.Context, token string)
return s.queries.RevokeTeamRefreshTokenByToken(ctx, token)
}
func (s *Store) CreateTeamOtp(ctx context.Context, otp domain.TeamOtp) error {
return s.queries.CreateTeamOtp(ctx, dbgen.CreateTeamOtpParams{
TeamMemberID: otp.TeamMemberID,
SentTo: otp.SentTo,
Medium: string(otp.Medium),
OtpFor: string(otp.For),
Otp: otp.Otp,
ExpiresAt: pgtype.Timestamptz{
Time: otp.ExpiresAt,
Valid: true,
},
})
}
func (s *Store) GetLatestTeamOtp(ctx context.Context, teamMemberID int64) (domain.TeamOtp, error) {
row, err := s.queries.GetLatestTeamOtp(ctx, teamMemberID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.TeamOtp{}, domain.ErrOtpNotFound
}
return domain.TeamOtp{}, err
}
if !row.ExpiresAt.Valid {
return domain.TeamOtp{}, domain.ErrOtpNotFound
}
return domain.TeamOtp{
ID: row.ID,
TeamMemberID: row.TeamMemberID,
SentTo: row.SentTo,
Medium: domain.OtpMedium(row.Medium),
For: domain.OtpFor(row.OtpFor),
Otp: row.Otp,
Used: row.Used,
UsedAt: row.UsedAt.Time,
CreatedAt: row.CreatedAt.Time,
ExpiresAt: row.ExpiresAt.Time,
}, nil
}
func (s *Store) MarkTeamOtpAsUsed(ctx context.Context, otp domain.TeamOtp) error {
return s.queries.MarkTeamOtpAsUsed(ctx, dbgen.MarkTeamOtpAsUsedParams{
ID: otp.ID,
UsedAt: pgtype.Timestamptz{
Time: otp.UsedAt,
Valid: true,
},
})
}
func optionalPgText(value string) pgtype.Text {
if value == "" {
return pgtype.Text{}

View File

@ -0,0 +1,139 @@
package team
import (
"Yimaru-Backend/internal/domain"
"Yimaru-Backend/internal/pkgs/helpers"
"context"
"crypto/subtle"
"fmt"
"net/url"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
)
const teamPasswordResetOtpExpiry = 5 * time.Minute
func (s *Service) SendPasswordReset(ctx context.Context, email string) error {
baseURL := s.passwordResetBaseURL()
if baseURL == "" {
return domain.ErrTeamPasswordResetBaseURLNotConfigured
}
if s.messengerSvc == nil || s.emailTemplateSvc == nil {
return fmt.Errorf("email services are not configured")
}
email = strings.TrimSpace(strings.ToLower(email))
member, err := s.teamStore.GetTeamMemberByEmail(ctx, email)
if err != nil {
return err
}
if member.Status != domain.TeamMemberStatusActive {
return domain.ErrInvalidTeamMemberStatus
}
if !member.EmailVerified {
return domain.ErrTeamMemberPendingInvitation
}
otpCode := helpers.GenerateOTP()
resetLink := buildTeamPasswordResetLink(baseURL, email, otpCode)
rendered, err := s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugPasswordReset, map[string]any{
"FirstName": member.FirstName,
"ResetLink": resetLink,
"ExpiresMinutes": int(teamPasswordResetOtpExpiry.Minutes()),
})
if err != nil {
return err
}
if err := s.messengerSvc.SendEmail(ctx, email, rendered.Text, rendered.HTML, rendered.Subject); err != nil {
return err
}
return s.teamStore.CreateTeamOtp(ctx, domain.TeamOtp{
TeamMemberID: member.ID,
SentTo: email,
Medium: domain.OtpMediumEmail,
For: domain.OtpReset,
Otp: otpCode,
ExpiresAt: time.Now().Add(teamPasswordResetOtpExpiry),
})
}
func (s *Service) ResetPasswordWithOtp(ctx context.Context, req domain.TeamResetPasswordReq) error {
email := strings.TrimSpace(strings.ToLower(req.Email))
member, err := s.teamStore.GetTeamMemberByEmail(ctx, email)
if err != nil {
return err
}
otp, err := s.teamStore.GetLatestTeamOtp(ctx, member.ID)
if err != nil {
return err
}
if otp.For != domain.OtpReset {
return domain.ErrInvalidOtp
}
if otp.Used {
return domain.ErrOtpAlreadyUsed
}
if time.Now().After(otp.ExpiresAt) {
return domain.ErrOtpExpired
}
if subtle.ConstantTimeCompare([]byte(otp.Otp), []byte(strings.TrimSpace(req.Otp))) != 1 {
return domain.ErrInvalidOtp
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcryptCost)
if err != nil {
return err
}
if err := s.teamStore.UpdateTeamMemberPassword(ctx, member.ID, string(hashedPassword)); err != nil {
return err
}
otp.UsedAt = time.Now()
if err := s.teamStore.MarkTeamOtpAsUsed(ctx, otp); err != nil {
return err
}
_ = s.teamStore.RevokeAllActiveTeamRefreshTokensForMember(ctx, member.ID)
return nil
}
func (s *Service) passwordResetBaseURL() string {
if base := strings.TrimSpace(s.passwordResetURL); base != "" {
return strings.TrimRight(base, "/")
}
// Derive from invite URL host: .../accept-invite → .../reset-password
invite := strings.TrimSpace(s.inviteBaseURL)
if invite == "" {
return ""
}
u, err := url.Parse(invite)
if err != nil || u.Scheme == "" || u.Host == "" {
return ""
}
u.Path = "/reset-password"
u.RawQuery = ""
u.Fragment = ""
return strings.TrimRight(u.String(), "/")
}
func buildTeamPasswordResetLink(baseURL, email, otp string) string {
base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
u, err := url.Parse(base)
if err != nil {
return fmt.Sprintf("%s?email=%s&otp=%s", base, url.QueryEscape(email), url.QueryEscape(otp))
}
q := u.Query()
q.Set("email", email)
q.Set("otp", otp)
u.RawQuery = q.Encode()
return u.String()
}

View File

@ -0,0 +1,27 @@
package team
import "testing"
func TestBuildTeamPasswordResetLink(t *testing.T) {
got := buildTeamPasswordResetLink("https://admin.example.com/reset-password", "a@b.com", "123456")
want := "https://admin.example.com/reset-password?email=a%40b.com&otp=123456"
if got != want {
t.Fatalf("got %q want %q", got, want)
}
}
func TestPasswordResetBaseURLFallback(t *testing.T) {
s := &Service{inviteBaseURL: "https://admin.example.com/accept-invite"}
got := s.passwordResetBaseURL()
want := "https://admin.example.com/reset-password"
if got != want {
t.Fatalf("got %q want %q", got, want)
}
s.passwordResetURL = "https://admin.example.com/forgot-password"
got = s.passwordResetBaseURL()
want = "https://admin.example.com/forgot-password"
if got != want {
t.Fatalf("explicit URL: got %q want %q", got, want)
}
}

View File

@ -4,6 +4,7 @@ import (
"Yimaru-Backend/internal/ports"
emailtemplates "Yimaru-Backend/internal/services/emailtemplates"
"Yimaru-Backend/internal/services/messenger"
"strings"
"time"
)
@ -14,6 +15,7 @@ type Service struct {
emailTemplateSvc *emailtemplates.Service
messengerSvc *messenger.Service
inviteBaseURL string
passwordResetURL string
inviteExpiry time.Duration
}
@ -24,6 +26,7 @@ func NewService(
emailTemplateSvc *emailtemplates.Service,
messengerSvc *messenger.Service,
inviteBaseURL string,
passwordResetURL string,
inviteExpiry time.Duration,
) *Service {
if refreshExpirySeconds <= 0 {
@ -39,6 +42,7 @@ func NewService(
emailTemplateSvc: emailTemplateSvc,
messengerSvc: messengerSvc,
inviteBaseURL: inviteBaseURL,
passwordResetURL: strings.TrimSpace(passwordResetURL),
inviteExpiry: inviteExpiry,
}
}

View File

@ -4,14 +4,12 @@ import (
"Yimaru-Backend/internal/domain"
"context"
"fmt"
"net/url"
"strings"
)
func (s *Service) renderOtpMessage(ctx context.Context, otpCode, firstName string, otpFor domain.OtpFor, medium domain.OtpMedium, sentTo string) (domain.RenderedEmail, error) {
if otpFor == domain.OtpReset && medium == domain.OtpMediumEmail {
return s.renderPasswordResetEmail(ctx, otpCode, firstName, sentTo)
}
func (s *Service) renderOtpMessage(ctx context.Context, otpCode, firstName string, _ domain.OtpFor, _ domain.OtpMedium, _ string) (domain.RenderedEmail, error) {
// Learners (mobile app) always receive a numeric OTP code for email and SMS.
// Team/admin password-reset links are handled by the team service.
return s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugOTP, map[string]any{
"OTP": otpCode,
"FirstName": firstName,
@ -19,36 +17,6 @@ func (s *Service) renderOtpMessage(ctx context.Context, otpCode, firstName strin
})
}
func (s *Service) renderPasswordResetEmail(ctx context.Context, otpCode, firstName, email string) (domain.RenderedEmail, error) {
resetLink := buildPasswordResetLink(s.config.PasswordResetBaseURL, s.config.LearnerAppBaseURL, email, otpCode)
return s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugPasswordReset, map[string]any{
"FirstName": firstName,
"ResetLink": resetLink,
"ExpiresMinutes": int(OtpExpiry.Minutes()),
})
}
func buildPasswordResetLink(passwordResetBaseURL, learnerAppBaseURL, email, otp string) string {
base := strings.TrimRight(strings.TrimSpace(passwordResetBaseURL), "/")
if base == "" {
learnerBase := strings.TrimRight(strings.TrimSpace(learnerAppBaseURL), "/")
if learnerBase == "" {
learnerBase = "https://app.yimaruacademy.com"
}
base = learnerBase + "/reset-password"
}
u, err := url.Parse(base)
if err != nil {
return fmt.Sprintf("%s?email=%s&otp=%s", base, url.QueryEscape(email), url.QueryEscape(otp))
}
q := u.Query()
q.Set("email", email)
q.Set("otp", otp)
u.RawQuery = q.Encode()
return u.String()
}
func (s *Service) learnerLoginURL() string {
base := strings.TrimRight(strings.TrimSpace(s.config.LearnerAppBaseURL), "/")
if base == "" {

View File

@ -0,0 +1,105 @@
package handlers
import (
"Yimaru-Backend/internal/domain"
"errors"
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
)
// SendTeamPasswordReset godoc
// @Summary Send team password reset link
// @Description Sends a password-reset email with a link to the team member (admin panel). Public.
// @Tags team
// @Accept json
// @Produce json
// @Param body body domain.TeamSendPasswordResetReq true "Email"
// @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/team/sendResetCode [post]
func (h *Handler) SendTeamPasswordReset(c *fiber.Ctx) error {
var req domain.TeamSendPasswordResetReq
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Failed to send password reset",
Error: "Invalid request body: " + err.Error(),
})
}
if valErrs, ok := h.validator.Validate(c, req); !ok {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Failed to send password reset",
Error: firstValidationError(valErrs),
})
}
if err := h.teamSvc.SendPasswordReset(c.Context(), req.Email); err != nil {
return h.teamPasswordResetError(c, err, "Failed to send password reset")
}
return c.JSON(domain.Response{
Message: "Password reset link sent successfully",
Success: true,
})
}
// ResetTeamPassword godoc
// @Summary Reset team member password
// @Description Completes team password reset using email + OTP from the reset link. Public.
// @Tags team
// @Accept json
// @Produce json
// @Param body body domain.TeamResetPasswordReq true "Reset payload"
// @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/team/resetPassword [post]
func (h *Handler) ResetTeamPassword(c *fiber.Ctx) error {
var req domain.TeamResetPasswordReq
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Failed to reset password",
Error: "Invalid request body: " + err.Error(),
})
}
if valErrs, ok := h.validator.Validate(c, req); !ok {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Failed to reset password",
Error: firstValidationError(valErrs),
})
}
if err := h.teamSvc.ResetPasswordWithOtp(c.Context(), req); err != nil {
return h.teamPasswordResetError(c, err, "Failed to reset password")
}
return c.JSON(domain.Response{
Message: "Password reset successfully",
Success: true,
})
}
func (h *Handler) teamPasswordResetError(c *fiber.Ctx, err error, message string) error {
switch {
case errors.Is(err, domain.ErrTeamMemberNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: message, Error: "Team member not found"})
case errors.Is(err, domain.ErrInvalidTeamMemberStatus):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: message, Error: "Team member account is not active"})
case errors.Is(err, domain.ErrTeamMemberPendingInvitation):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: message, Error: "Accept your invitation before resetting password"})
case errors.Is(err, domain.ErrTeamPasswordResetBaseURLNotConfigured):
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: message, Error: "TEAM_PASSWORD_RESET_BASE_URL is not configured"})
case errors.Is(err, domain.ErrOtpNotFound), errors.Is(err, domain.ErrInvalidOtp):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: message, Error: "Invalid or missing reset code"})
case errors.Is(err, domain.ErrOtpExpired):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: message, Error: "Reset code has expired"})
case errors.Is(err, domain.ErrOtpAlreadyUsed):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: message, Error: "Reset code has already been used"})
default:
h.mongoLoggerSvc.Error(message, zap.Error(err))
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: message, Error: err.Error()})
}
}

View File

@ -1208,7 +1208,7 @@ type ResetCodeReq struct {
// SendResetCode godoc
// @Summary Send reset code
// @Description Send reset code
// @Description Sends a password-reset OTP code by email or SMS for learner (mobile) accounts. Email delivers the numeric code (not a link).
// @Tags user
// @Accept json
// @Produce json

View File

@ -468,6 +468,8 @@ func (a *App) initAppRoutes() {
teamGroup := groupV1.Group("/team")
teamGroup.Post("/login", h.TeamMemberLogin)
teamGroup.Post("/refresh", h.TeamMemberRefresh)
teamGroup.Post("/sendResetCode", h.SendTeamPasswordReset)
teamGroup.Post("/resetPassword", h.ResetTeamPassword)
teamGroup.Get("/invitations/verify", h.VerifyTeamInvitation)
teamGroup.Post("/invitations/accept", h.AcceptTeamInvitation)
teamGroup.Get("/me", a.authMiddleware, a.RequirePermission("team.profile.get_mine"), h.GetMyTeamProfile)