merge new_starr_app@qas history into apps/web

git-subtree-dir: apps/web
git-subtree-mainline: eaa6d2276a
git-subtree-split: 459af9d46a
This commit is contained in:
2026-08-24 12:21:16 +08:00
699 changed files with 103969 additions and 0 deletions
@@ -0,0 +1,22 @@
import { Sun, Moon } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useTheme } from '@/contexts/ThemeContext'
export function AuthThemeToggle({ className }) {
const { toggleTheme } = useTheme()
return (
<button
type="button"
onClick={toggleTheme}
aria-label="Toggle light/dark theme"
className={cn(
'flex size-9 items-center justify-center rounded-xl border dark:border-blue-500 bg-background/80 backdrop-blur-sm transition-colors hover:bg-accent',
className,
)}
>
<Sun className="size-4 block dark:hidden" />
<Moon className="size-4 hidden dark:block" />
</button>
)
}
@@ -0,0 +1,520 @@
/***********************************************************************************************************************************************************************
* File Name: ForgotPasswordForm.jsx
* Type of Program: Frontend Component
* Description: Password reset flow — same procedure for every acc_type (admin,
* staff, user); only reg_type matters (Google accounts are turned
* away, see LoginForm's "Please log in with Google" precedent).
* Step 1 — Email (checks reg_type server-side, sends OTP if system)
* Step 2 — OTP only (verified server-side before advancing)
* Step 3 — New password + confirm, submitted with the verified OTP
* Module: User Credentials
* Author: lash0000
* Date Created: Jul. 4, 2026
* Date Modified: Jul. 7, 2026 — split combined OTP+password step into its own
* verify-then-set-password steps (Kenneth Obsequio)
***********************************************************************************************************************************************************************/
import { useState, useEffect } from 'react'
import { useNavigate, useBlocker, Link } from 'react-router-dom'
import { useForm, Controller } from 'react-hook-form'
import { useAuth } from '@/contexts/AuthContext'
import { PageMeta } from '@/contexts/MetadataContext'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Separator } from '@/components/ui/separator'
import { InputOTP, InputOTPGroup, InputOTPSlot } from '@/components/ui/input-otp'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Eye, EyeOff, LoaderCircle } from 'lucide-react'
const emailSchema = z.object({
email: z.string().email('Invalid email address'),
})
const otpSchema = z.object({
otp: z.string().length(6, 'Enter all 6 digits').regex(/^\d{6}$/, 'OTP must contain only digits'),
})
const passwordSchema = z
.object({
new_password: z
.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Must contain at least one uppercase letter')
.regex(/[0-9]/, 'Must contain at least one number'),
confirm_password: z.string().min(1, 'Please confirm your password'),
})
.refine((d) => d.new_password === d.confirm_password, {
message: 'Passwords do not match',
path: ['confirm_password'],
})
const STEP_META = [
{ title: 'Forgot Password', description: 'Reset your account password.' },
{ title: 'Enter Verification Code', description: 'Enter the 6-digit code sent to your email.' },
{ title: 'Reset Password', description: 'Choose a new password for your account.' },
]
export function ForgotPasswordForm({ className, ...props }) {
const navigate = useNavigate()
const { forgotPassword, verifyResetOtp, resetPassword } = useAuth()
// 0 = email, 1 = otp, 2 = new password
const [step, setStep] = useState(0)
const [pendingEmail, setPendingEmail] = useState('')
const [pendingOtp, setPendingOtp] = useState('')
const [showPassword, setShowPassword] = useState(false)
const [showConfirm, setShowConfirm] = useState(false)
const [resendCooldown, setResendCooldown] = useState(0)
const [errorDialogOpen, setErrorDialogOpen] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [successDialogOpen, setSuccessDialogOpen] = useState(false)
const [googleDialogOpen, setGoogleDialogOpen] = useState(false)
const [confirmDialogOpen, setConfirmDialogOpen] = useState(false)
const [pendingNewPassword, setPendingNewPassword] = useState('')
const [isConfirmingReset, setIsConfirmingReset] = useState(false)
useEffect(() => {
if (resendCooldown <= 0) return
const t = setTimeout(() => setResendCooldown((c) => c - 1), 1000)
return () => clearTimeout(t)
}, [resendCooldown])
// Past the email step there's an in-progress code/password reset to lose —
// warn on tab close/refresh/URL change (native dialog) and on in-app back/
// forward navigation (native window.confirm via the router's blocker).
const midFlow = step > 0
useEffect(() => {
if (!midFlow) return
const handleBeforeUnload = (e) => {
e.preventDefault()
e.returnValue = ''
}
window.addEventListener('beforeunload', handleBeforeUnload)
return () => window.removeEventListener('beforeunload', handleBeforeUnload)
}, [midFlow])
const blocker = useBlocker(midFlow)
useEffect(() => {
if (blocker.state !== 'blocked') return
const leave = window.confirm('You have an unfinished password reset. Leave this page anyway?')
if (leave) blocker.proceed()
else blocker.reset()
}, [blocker])
// ── Step 1: Email ──────────────────────────────────────────────────────────
const {
register: regEmail,
handleSubmit: submitEmail,
formState: { errors: errEmail, isSubmitting: isRequesting },
} = useForm({
resolver: zodResolver(emailSchema),
defaultValues: { email: '' },
})
const onEmailSubmit = async ({ email }) => {
const result = await forgotPassword({ email })
if (!result.success) {
if (result.isGoogleAccount) {
setGoogleDialogOpen(true)
} else {
setErrorMessage(result.message)
setErrorDialogOpen(true)
}
return
}
setPendingEmail(email)
setResendCooldown(30)
setStep(1)
}
const handleGoogleSignIn = () => {
window.location.href = `${import.meta.env.VITE_API_URL}/auth/google`
}
// ── Step 2: OTP ─────────────────────────────────────────────────────────────
const {
control: otpControl,
handleSubmit: submitOtp,
formState: { errors: errOtp, isSubmitting: isVerifying },
} = useForm({
resolver: zodResolver(otpSchema),
defaultValues: { otp: '' },
})
const onOtpSubmit = async ({ otp }) => {
const result = await verifyResetOtp({ email: pendingEmail, otp })
if (!result.success) {
setErrorMessage(result.message)
setErrorDialogOpen(true)
return
}
setPendingOtp(otp)
setStep(2)
}
const handleResend = async () => {
if (resendCooldown > 0) return
const result = await forgotPassword({ email: pendingEmail })
if (!result.success) {
setErrorMessage(result.message)
setErrorDialogOpen(true)
return
}
setResendCooldown(30)
}
// ── Step 3: New password ────────────────────────────────────────────────────
const {
register: regPassword,
handleSubmit: submitPassword,
formState: { errors: errPassword, isSubmitting: isResetting },
} = useForm({
resolver: zodResolver(passwordSchema),
defaultValues: { new_password: '', confirm_password: '' },
})
// Reset revokes every active session and trusted device on every one of the
// user's devices (see resetPassword in auth.controller.js) — surface that
// up front instead of silently signing the user out everywhere.
const onPasswordSubmit = async ({ new_password }) => {
setPendingNewPassword(new_password)
setConfirmDialogOpen(true)
}
const handleConfirmReset = async () => {
setIsConfirmingReset(true)
const result = await resetPassword({ email: pendingEmail, otp: pendingOtp, new_password: pendingNewPassword })
setIsConfirmingReset(false)
setConfirmDialogOpen(false)
if (!result.success) {
setErrorMessage(result.message)
setErrorDialogOpen(true)
// The verified code may have expired/rotated by now — send them back to re-verify.
setStep(1)
return
}
setSuccessDialogOpen(true)
}
return (
<>
<PageMeta
title={`${STEP_META[step].title} - Philproperties`}
description={STEP_META[step].description}
keywords="forgot password, reset password, verification code, philproperties"
/>
<div className={cn('flex flex-col', className)} {...props}>
{/* ── Step 1: Email ── */}
{step === 0 && (
<form onSubmit={submitEmail(onEmailSubmit)} className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">Forgot your password?</h1>
<p className="text-muted-foreground text-sm text-balance">
Enter your email and we'll send you a code to reset it.
</p>
</div>
<div className="flex flex-col gap-1.5">
<label htmlFor="email" className="text-sm font-medium">Email address</label>
<Input
id="email"
type="email"
placeholder="you@example.com"
autoComplete="off"
disabled={isRequesting}
readOnly
onFocus={(e) => e.target.removeAttribute('readonly')}
{...regEmail('email')}
/>
{errEmail.email && (
<p className="text-xs text-destructive">{errEmail.email.message}</p>
)}
</div>
<Button type="submit" className="w-full" disabled={isRequesting}>
{isRequesting ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Sending...
</span>
) : (
'Send reset code'
)}
</Button>
<p className="text-center text-sm text-muted-foreground">
Remembered it?{' '}
<Link to="/login" className="font-medium underline underline-offset-4">
Back to login
</Link>
</p>
</form>
)}
{/* ── Step 2: OTP ── */}
{step === 1 && (
<form onSubmit={submitOtp(onOtpSubmit)} className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">Enter verification code.</h1>
<p className="text-muted-foreground text-sm text-balance">
We sent a 6-digit code to{' '}
<span className="font-medium text-foreground">{pendingEmail}</span>.
</p>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium text-center">Verification code</label>
<Controller
control={otpControl}
name="otp"
render={({ field }) => (
<InputOTP
maxLength={6}
value={field.value}
onChange={field.onChange}
containerClassName="justify-center"
>
<InputOTPGroup>
{Array.from({ length: 6 }).map((_, i) => (
<InputOTPSlot key={i} index={i} />
))}
</InputOTPGroup>
</InputOTP>
)}
/>
{errOtp.otp && (
<p className="text-xs text-destructive text-center">{errOtp.otp.message}</p>
)}
</div>
<div className="flex items-center justify-between text-sm -mt-2">
<span className="text-muted-foreground">
{resendCooldown > 0 ? `Resend in ${resendCooldown}s` : "Didn't receive it?"}
</span>
<Button
type="button"
variant="link"
size="sm"
className="p-0 h-auto font-medium"
disabled={resendCooldown > 0}
onClick={handleResend}
>
Resend code
</Button>
</div>
<Button type="submit" className="w-full" disabled={isVerifying}>
{isVerifying ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Verifying...
</span>
) : (
'Verify'
)}
</Button>
<Separator />
<Button
type="button"
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => setStep(0)}
>
← Back
</Button>
</form>
)}
{/* ── Step 3: New password ── */}
{step === 2 && (
<form onSubmit={submitPassword(onPasswordSubmit)} className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">Choose a new password.</h1>
<p className="text-muted-foreground text-sm text-balance">
Your code has been verified. Set a new password for your account.
</p>
</div>
{/* New password */}
<div className="flex flex-col gap-1.5">
<label htmlFor="new_password" className="text-sm font-medium">New password</label>
<div className="relative">
<Input
id="new_password"
type={showPassword ? 'text' : 'password'}
placeholder="Min. 8 chars, 1 uppercase, 1 number"
autoComplete="new-password"
disabled={isResetting}
className="pr-10"
{...regPassword('new_password')}
/>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => setShowPassword((v) => !v)}
className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
{errPassword.new_password && (
<p className="text-xs text-destructive">{errPassword.new_password.message}</p>
)}
</div>
{/* Confirm password */}
<div className="flex flex-col gap-1.5">
<label htmlFor="confirm_password" className="text-sm font-medium">Confirm new password</label>
<div className="relative">
<Input
id="confirm_password"
type={showConfirm ? 'text' : 'password'}
placeholder="Repeat your new password"
autoComplete="new-password"
disabled={isResetting}
className="pr-10"
{...regPassword('confirm_password')}
/>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => setShowConfirm((v) => !v)}
className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showConfirm ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
{errPassword.confirm_password && (
<p className="text-xs text-destructive">{errPassword.confirm_password.message}</p>
)}
</div>
<Button type="submit" className="w-full" disabled={isResetting}>
{isResetting ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Resetting...
</span>
) : (
'Submit'
)}
</Button>
<Separator />
<Button
type="button"
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => setStep(1)}
>
← Back
</Button>
</form>
)}
</div>
{/* Error Dialog */}
<AlertDialog open={errorDialogOpen} onOpenChange={setErrorDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Something went wrong</AlertDialogTitle>
<AlertDialogDescription>{errorMessage}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setErrorDialogOpen(false)}>Okay</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Google Account Dialog */}
<AlertDialog open={googleDialogOpen} onOpenChange={setGoogleDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>This account signs in with Google</AlertDialogTitle>
<AlertDialogDescription>
We detected that this email is linked to an account created through Google Sign-In.
Accounts created this way don't have a password stored with us, so there's nothing
to reset here — sign in with Google instead to access your account. If you'd like a
password-based login too, you can set one from your account settings after signing in.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setGoogleDialogOpen(false)}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleGoogleSignIn}>Sign in with Google</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Confirm Reset Dialog */}
<AlertDialog open={confirmDialogOpen} onOpenChange={(open) => !isConfirmingReset && setConfirmDialogOpen(open)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Sign out of all devices?</AlertDialogTitle>
<AlertDialogDescription>
Resetting your password will end every active session and sign you out on all
devices, including this one. You'll need to log in again with your new password
everywhere.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isConfirmingReset}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleConfirmReset} disabled={isConfirmingReset}>
{isConfirmingReset ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Resetting...
</span>
) : (
'Reset and sign out everywhere'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Success Dialog */}
<AlertDialog open={successDialogOpen} onOpenChange={setSuccessDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Password changed</AlertDialogTitle>
<AlertDialogDescription>
Your password has been reset successfully. Please log in with your new password.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => navigate('/login')}>Go to login</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
@@ -0,0 +1,254 @@
/***********************************************************************************************************************************************************************
* File Name: LoginForm.jsx
* Type of Program: Frontend Component
* Description: Login form using react-hook-form + Zod (no shadcn Form wrapper).
* Supports system login and Google OAuth redirect.
* Module: User Credentials
* Author: lash0000
* Date Created: Oct. 10, 2025
***********************************************************************************************************************************************************************
* Change History:
* DATE AUTHOR LOG NUMBER DESCRIPTION
* Oct. 10, 2025 lash0000 001 Initial creation - STAR Phase 1 Project
* May 23, 2026 lash0000 002 Migrated to Zod + zodResolver; removed shadcn Form wrapper
***********************************************************************************************************************************************************************/
import { useState } from 'react'
import { useNavigate, Link, useSearchParams } from 'react-router-dom'
import { useAuth } from '@/contexts/AuthContext'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { cn } from '@/lib/utils'
import { getRoleHomePath } from '@/utils/roleRedirect.util'
import { OtpVerifyForm } from './OtpVerifyForm'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Separator } from '@/components/ui/separator'
import {
AlertDialog,
AlertDialogAction,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Eye, EyeOff, LoaderCircle, Users } from 'lucide-react'
// ─── Schema ──────────────────────────────────────────────────────────────────
const loginSchema = z.object({
email: z.string().email('Invalid email address'),
password: z.string().min(1, 'Password is required'),
})
// ─── Component ───────────────────────────────────────────────────────────────
export function LoginForm({ className, ...props }) {
const { login } = useAuth()
const navigate = useNavigate()
const [searchParams] = useSearchParams()
const groupCode = searchParams.get('group_code') || ''
const [passwordVisible, setPasswordVisible] = useState(false)
const [errorDialogOpen, setErrorDialogOpen] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [otpEmail, setOtpEmail] = useState(null)
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm({
resolver: zodResolver(loginSchema),
defaultValues: { email: '', password: '' },
})
const handleAuthSuccess = (user) => {
navigate(getRoleHomePath(user))
}
const onSubmit = async ({ email, password }) => {
const result = await login({ email, password, group_code: groupCode || undefined })
if (result.success) {
if (result.otpRequired === false) {
// Trusted device — session was issued directly, no OTP step needed.
handleAuthSuccess(result.user)
return
}
// Credentials confirmed — an OTP was emailed. Tokens aren't issued yet.
setOtpEmail(result.email)
return
}
if (result.errors?.banned) {
navigate('/suspended', {
state: {
reason: result.errors.reason ?? null,
ban_type: result.errors.ban_type ?? null,
ban_expires_at: result.errors.ban_expires_at ?? null,
},
})
return
}
setErrorMessage(result.message || 'Invalid credentials.')
setErrorDialogOpen(true)
}
const handleGoogle = () => {
const params = groupCode ? `?group_code=${encodeURIComponent(groupCode)}` : ''
window.location.href = `${import.meta.env.VITE_API_URL}/auth/google${params}`
}
if (otpEmail) {
return (
<OtpVerifyForm
email={otpEmail}
onSuccess={handleAuthSuccess}
title="Verify your sign-in"
description={`We sent a 6-digit code to ${otpEmail} to finish signing in. It expires in 10 minutes.`}
onBack={() => setOtpEmail(null)}
/>
)
}
return (
<>
<form
onSubmit={handleSubmit(onSubmit)}
className={cn('flex flex-col gap-6', className)}
{...props}
>
{/* Header */}
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">
Take the next step towards new learnings.
</h1>
<p className="text-muted-foreground text-sm text-balance">
Learn and grow for your career.
</p>
</div>
{/* Group code notice */}
{groupCode && (
<div className="flex items-center gap-2 rounded-md border border-dashed px-3 py-2 bg-muted/40">
<Users className="size-4 text-muted-foreground shrink-0" />
<p className="text-sm text-muted-foreground">
Signing in will join group{' '}
<span className="font-semibold text-foreground">{groupCode}</span>
</p>
</div>
)}
{/* Google OAuth */}
<Button variant="outline" type="button" onClick={handleGoogle} className="w-full">
<svg viewBox="0 0 128 128" className="size-4 mr-2">
<path fill="#fff" d="M44.59 4.21a63.28 63.28 0 004.33 120.9 67.6 67.6 0 0032.36.35 57.13 57.13 0 0025.9-13.46 57.44 57.44 0 0016-26.26 74.33 74.33 0 001.61-33.58H65.27v24.69h34.47a29.72 29.72 0 01-12.66 19.52 36.16 36.16 0 01-13.93 5.5 41.29 41.29 0 01-15.1 0A37.16 37.16 0 0144 95.74a39.3 39.3 0 01-14.5-19.42 38.31 38.31 0 010-24.63 39.25 39.25 0 019.18-14.91A37.17 37.17 0 0176.13 27a34.28 34.28 0 0113.64 8q5.83-5.8 11.64-11.63c2-2.09 4.18-4.08 6.15-6.22A61.22 61.22 0 0087.2 4.59a64 64 0 00-42.61-.38z" />
<path fill="#e33629" d="M44.59 4.21a64 64 0 0142.61.37 61.22 61.22 0 0120.35 12.62c-2 2.14-4.11 4.14-6.15 6.22Q95.58 29.23 89.77 35a34.28 34.28 0 00-13.64-8 37.17 37.17 0 00-37.46 9.74 39.25 39.25 0 00-9.18 14.91L8.76 35.6A63.53 63.53 0 0144.59 4.21z" />
<path fill="#f8bd00" d="M3.26 51.5a62.93 62.93 0 015.5-15.9l20.73 16.09a38.31 38.31 0 000 24.63q-10.36 8-20.73 16.08a63.33 63.33 0 01-5.5-40.9z" />
<path fill="#587dbd" d="M65.27 52.15h59.52a74.33 74.33 0 01-1.61 33.58 57.44 57.44 0 01-16 26.26c-6.69-5.22-13.41-10.4-20.1-15.62a29.72 29.72 0 0012.66-19.54H65.27c-.01-8.22 0-16.45 0-24.68z" />
<path fill="#319f43" d="M8.75 92.4q10.37-8 20.73-16.08A39.3 39.3 0 0044 95.74a37.16 37.16 0 0014.08 6.08 41.29 41.29 0 0015.1 0 36.16 36.16 0 0013.93-5.5c6.69 5.22 13.41 10.4 20.1 15.62a57.13 57.13 0 01-25.9 13.47 67.6 67.6 0 01-32.36-.35 63 63 0 01-23-11.59A63.73 63.73 0 018.75 92.4z" />
</svg>
Login with Google
</Button>
<div className="relative flex items-center gap-3 text-xs text-muted-foreground">
<Separator className="flex-1" />
<span>Or continue with</span>
<Separator className="flex-1" />
</div>
{/* Email */}
<div className="flex flex-col gap-1.5">
<label htmlFor="email" className="text-sm font-medium">Email</label>
<Input
id="email"
type="email"
placeholder="Enter your email"
autoComplete="off"
disabled={isSubmitting}
readOnly
onFocus={(e) => e.target.removeAttribute('readonly')}
{...register('email')}
/>
{errors.email && (
<p className="text-sm text-destructive">{errors.email.message}</p>
)}
</div>
{/* Password */}
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<label htmlFor="password" className="text-sm font-medium">Password</label>
<Link
to="/forgot-password"
className="text-sm text-muted-foreground underline-offset-4 hover:underline"
>
Forgot password?
</Link>
</div>
<div className="relative">
<Input
id="password"
type={passwordVisible ? 'text' : 'password'}
placeholder="Enter your password"
autoComplete="off"
disabled={isSubmitting}
className="pr-10"
readOnly
onFocus={(e) => e.target.removeAttribute('readonly')}
{...register('password')}
/>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => setPasswordVisible((v) => !v)}
title={passwordVisible ? 'Hide password' : 'Show password'}
aria-label={passwordVisible ? 'Hide password' : 'Show password'}
className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{passwordVisible ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
{errors.password && (
<p className="text-sm text-destructive">{errors.password.message}</p>
)}
</div>
{/* Submit */}
<Button type="submit" className="w-full" disabled={isSubmitting}>
{isSubmitting ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Logging in...
</span>
) : (
'Login'
)}
</Button>
<p className="text-center text-sm text-muted-foreground">
Don&apos;t have an account?{' '}
<Link to="/signup" className="font-medium underline underline-offset-4">
Sign up
</Link>
</p>
</form>
{/* Error Dialog */}
<AlertDialog open={errorDialogOpen} onOpenChange={setErrorDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Login failed</AlertDialogTitle>
<AlertDialogDescription>{errorMessage}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setErrorDialogOpen(false)}>Okay</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
@@ -0,0 +1,186 @@
/***********************************************************************************************************************************************************************
* File Name: OtpVerifyForm.jsx
* Type of Program: Frontend Component
* Description: Shared OTP step used by every auth path — registration email
* verification, post-password login, and post-Google login.
* All three funnel through POST /auth/verify-otp, which mints
* tokens/session on success regardless of which path led here.
* Module: User Credentials
* Author: lash0000
* Date Created: Jul. 4, 2026
***********************************************************************************************************************************************************************/
import { useState, useEffect } from 'react'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useAuth } from '@/contexts/AuthContext'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { InputOTP, InputOTPGroup, InputOTPSlot } from '@/components/ui/input-otp'
import {
AlertDialog,
AlertDialogAction,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { LoaderCircle } from 'lucide-react'
const otpSchema = z.object({
otp: z
.string()
.length(6, 'Enter all 6 digits')
.regex(/^\d{6}$/, 'OTP must contain only digits'),
})
/**
* @param {string} email — the account this OTP was sent to
* @param {function} onSuccess — called with the authenticated user on success
* @param {string} [title]
* @param {string|JSX.Element} [description]
* @param {function} [onBack] — if provided, renders a "back" action (e.g. registration's "back to credentials")
*/
export function OtpVerifyForm({ email, onSuccess, title = 'Check your email.', description, onBack }) {
const { verifyOTP, resendOTP } = useAuth()
const [resendCooldown, setResendCooldown] = useState(30)
const [errorDialogOpen, setErrorDialogOpen] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
useEffect(() => {
if (resendCooldown <= 0) return
const t = setTimeout(() => setResendCooldown((c) => c - 1), 1000)
return () => clearTimeout(t)
}, [resendCooldown])
const {
control,
handleSubmit,
reset,
formState: { errors, isSubmitting: isVerifying },
} = useForm({
resolver: zodResolver(otpSchema),
defaultValues: { otp: '' },
})
const onVerify = async ({ otp }) => {
const result = await verifyOTP({ email, otp })
if (!result.success) {
setErrorMessage(result.message)
setErrorDialogOpen(true)
return
}
onSuccess(result.user)
}
const handleResend = async () => {
if (resendCooldown > 0) return
const result = await resendOTP({ email })
if (!result.success) {
setErrorMessage(result.message)
setErrorDialogOpen(true)
return
}
setResendCooldown(30)
reset()
}
return (
<>
<form onSubmit={handleSubmit(onVerify)} className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">{title}</h1>
<p className="text-muted-foreground text-sm text-balance">
{description ?? (
<>
We sent a 6-digit code to{' '}
<span className="font-medium text-foreground">{email}</span>.
It expires in 10 minutes.
</>
)}
</p>
</div>
<div className="flex flex-col gap-1.5">
<Controller
control={control}
name="otp"
render={({ field }) => (
<InputOTP
maxLength={6}
value={field.value}
onChange={field.onChange}
containerClassName="justify-center"
>
<InputOTPGroup>
{Array.from({ length: 6 }).map((_, i) => (
<InputOTPSlot key={i} index={i} />
))}
</InputOTPGroup>
</InputOTP>
)}
/>
{errors.otp && (
<p className="text-xs text-destructive text-center">{errors.otp.message}</p>
)}
</div>
<Button type="submit" className="w-full" disabled={isVerifying}>
{isVerifying ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Verifying...
</span>
) : (
'Verify'
)}
</Button>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
{resendCooldown > 0 ? `Resend in ${resendCooldown}s` : "Didn't receive it?"}
</span>
<Button
type="button"
variant="link"
size="sm"
className="p-0 h-auto font-medium"
disabled={resendCooldown > 0}
onClick={handleResend}
>
Resend code
</Button>
</div>
{onBack && (
<>
<Separator />
<Button type="button" variant="ghost" className="w-full text-muted-foreground" onClick={onBack}>
← Back
</Button>
</>
)}
</form>
<AlertDialog open={errorDialogOpen} onOpenChange={setErrorDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Verification failed</AlertDialogTitle>
<AlertDialogDescription>{errorMessage}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setErrorDialogOpen(false)}>Okay</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
@@ -0,0 +1,779 @@
/***********************************************************************************************************************************************************************
* File Name: RegisterForm.jsx
* Type of Program: Frontend Component
* Description: Multi-step registration form with Zod + react-hook-form (no shadcn Form wrapper).
* Step 1 — Personal Info (given name, last name, middle name, extension, birthday, occupation, phone)
* Step 2 — Credentials (email, password, confirm, group_code from URL)
* Step 3 — OTP Verify (6-cell input, resend countdown)
* Reads optional group_code from URL (/register?group_code=XXX).
* Module: User Credentials
* Author: lash0000
* Date Created: May 23, 2026
***********************************************************************************************************************************************************************
* Change History:
* DATE AUTHOR LOG NUMBER DESCRIPTION
* May 23, 2026 lash0000 001 Initial creation - STAR Phase 1 Project
* May 23, 2026 lash0000 002 birthday + occupation required; all calls via useAuth (register, verifyOTP, resendOTP)
***********************************************************************************************************************************************************************/
import { useState, useEffect } from 'react'
import { useNavigate, Link, useSearchParams } from 'react-router-dom'
import { useForm, Controller } from 'react-hook-form'
import { useAuth } from '@/contexts/AuthContext'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { format, parseISO, isValid as isValidDate } from 'date-fns'
import { isValidPhoneNumber, parsePhoneNumber } from 'react-phone-number-input'
import { cn } from '@/lib/utils'
import { useDetectedCountry } from '@/hooks/useDetectedCountry'
import { OtpVerifyForm } from './OtpVerifyForm'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { PhoneInput } from '@/components/ui/phone-input'
import { Badge } from '@/components/ui/badge'
import { Calendar } from '@/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Separator } from '@/components/ui/separator'
import {
AlertDialog,
AlertDialogAction,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Eye, EyeOff, LoaderCircle, Users, Check, CalendarIcon } from 'lucide-react'
// Birthday must put the user's birth year between 3 and 120 years ago (mirrors personalSchema below).
// Bounds are whole calendar years (Jan 1 / Dec 31) so every month/day is selectable within a boundary year.
const MIN_BIRTHDATE = new Date(new Date().getFullYear() - 120, 0, 1)
const MAX_BIRTHDATE = new Date(new Date().getFullYear() - 3, 11, 31)
// ─── Step schemas ─────────────────────────────────────────────────────────────
const personalSchema = z.object({
given_name: z.string().min(1, 'First name is required').max(50),
last_name: z.string().min(1, 'Last name is required').max(50),
middle_name: z.string().max(50).optional(),
extension_name: z.string().max(10).optional(),
date_of_birth: z
.string()
.min(1, 'Birthday is required')
.refine((v) => !isNaN(Date.parse(v)), { message: 'Invalid date' })
.refine((v) => {
const yearsAgo = new Date().getFullYear() - new Date(v).getFullYear()
return yearsAgo >= 3 && yearsAgo <= 120
}, { message: 'Must be at least 3 years old' }),
occupation: z.string().min(1, 'Occupation is required').max(100),
phone: z
.string()
.min(1, 'Phone number is required')
.refine((v) => isValidPhoneNumber(v), { message: 'Invalid phone number' }),
})
const credentialsSchema = z
.object({
email: z.string().email('Invalid email address'),
password: z
.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Must contain at least one uppercase letter')
.regex(/[0-9]/, 'Must contain at least one number'),
confirm_password: z.string().min(1, 'Please confirm your password'),
group_code: z.string().optional(),
})
.refine((d) => d.password === d.confirm_password, {
message: 'Passwords do not match',
path: ['confirm_password'],
})
// ─── Stepper indicator ────────────────────────────────────────────────────────
const STEPS = [
{ label: 'Personal info' },
{ label: 'Credentials' },
{ label: 'Verify email' },
]
function StepIndicator({ current }) {
return (
<div className="flex items-center gap-0 mb-6">
{STEPS.map((s, i) => {
const done = i < current
const active = i === current
const isLast = i === STEPS.length - 1
return (
<div key={i} className="flex items-center flex-1 last:flex-none">
{/* Circle */}
<div className="flex flex-col items-center gap-1 shrink-0">
<div
className={cn(
'w-7 h-7 rounded-full flex items-center justify-center text-xs font-semibold border transition-colors',
done && 'bg-primary border-primary text-primary-foreground',
active && 'border-primary text-primary bg-background',
!done && !active && 'border-muted-foreground/30 text-muted-foreground/50 bg-background',
)}
>
{done ? <Check className="size-3.5" strokeWidth={2.5} /> : i + 1}
</div>
<span
className={cn(
'text-[10px] font-medium whitespace-nowrap',
active ? 'text-primary' : done ? 'text-foreground' : 'text-muted-foreground/50',
)}
>
{s.label}
</span>
</div>
{/* Connector */}
{!isLast && (
<div
className={cn(
'h-px flex-1 mx-2 mb-4 transition-colors',
done ? 'bg-primary' : 'bg-muted-foreground/20',
)}
/>
)}
</div>
)
})}
</div>
)
}
// ─── RegisterForm ─────────────────────────────────────────────────────────────
export function RegisterForm({ className, ...props }) {
const navigate = useNavigate()
const { register: authRegister } = useAuth()
const [searchParams] = useSearchParams()
const groupCode = searchParams.get('group_code') || ''
// 'choice' = Google vs. manual signup entry screen, 0 = personal, 1 = credentials, 2 = otp
const [step, setStep] = useState('choice')
const [pendingEmail, setPendingEmail] = useState('')
const [showPassword, setShowPassword] = useState(false)
const [showConfirm, setShowConfirm] = useState(false)
const [errorDialogOpen, setErrorDialogOpen] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [birthdayOpen, setBirthdayOpen] = useState(false)
const detectedCountry = useDetectedCountry()
// Accumulated data across steps
const [personalData, setPersonalData] = useState({})
// ── Pending-verification resume (email already has an unverified account) ──
const [resumeDialogOpen, setResumeDialogOpen] = useState(false)
const [isResuming, setIsResuming] = useState(false)
const [pendingCreds, setPendingCreds] = useState(null)
// ── Confirm-before-create (asked before the register request ever fires) ──
const [confirmCreateOpen, setConfirmCreateOpen] = useState(false)
const [isCreating, setIsCreating] = useState(false)
const [pendingCredsData, setPendingCredsData] = useState(null)
// ── Warn before the tab is closed/reloaded mid-registration ────────────────
// Once the user reaches Credentials, submitting can already create a
// server-side account + send an OTP — losing the tab here (slow internet,
// accidental reload) is what leaves an orphaned unverified account behind.
useEffect(() => {
if (step === 'choice' || step === 0) return
const handleBeforeUnload = (e) => {
e.preventDefault()
e.returnValue = ''
}
window.addEventListener('beforeunload', handleBeforeUnload)
return () => window.removeEventListener('beforeunload', handleBeforeUnload)
}, [step])
// ── Step 1: Personal info ─────────────────────────────────────────────────
const {
register: regPersonal,
handleSubmit: submitPersonal,
control: controlPersonal,
formState: { errors: errPersonal },
} = useForm({
resolver: zodResolver(personalSchema),
defaultValues: { given_name: '', last_name: '', middle_name: '', extension_name: '', date_of_birth: '', occupation: '', phone: '' },
})
const onPersonalNext = (data) => {
setPersonalData(data)
setStep(1)
}
const handleGoogle = () => {
const params = groupCode ? `?group_code=${encodeURIComponent(groupCode)}` : ''
window.location.href = `${import.meta.env.VITE_API_URL}/auth/google${params}`
}
// ── Step 2: Credentials ───────────────────────────────────────────────────
const {
register: regCreds,
handleSubmit: submitCreds,
formState: { errors: errCreds, isSubmitting: isRegistering },
} = useForm({
resolver: zodResolver(credentialsSchema),
defaultValues: { email: '', password: '', confirm_password: '', group_code: groupCode },
})
const buildPersonalInfo = () => ({
name: {
given_name: personalData.given_name,
middle_name: personalData.middle_name || '',
last_name: personalData.last_name,
extension_name: personalData.extension_name || '',
full_name: [
`${personalData.last_name},`,
personalData.given_name,
personalData.middle_name || '',
personalData.extension_name || '',
].filter(Boolean).join(' ').trim(),
},
date_of_birth: personalData.date_of_birth,
occupation: personalData.occupation,
phone_number: personalData.phone
? (() => {
const parsed = parsePhoneNumber(personalData.phone)
return [{
number: parsed.nationalNumber,
country_code: parsed.countryCallingCode,
full_number: `${parsed.countryCallingCode}${parsed.nationalNumber}`,
phone_type: 'mobile',
}]
})()
: [],
addresses: [],
})
const submitRegistration = async ({ email, password, group_code }, { confirmResume = false } = {}) => {
const result = await authRegister({
email,
password,
personal_info: buildPersonalInfo(),
...(group_code ? { group_code } : {}),
...(confirmResume ? { confirm_resume: true } : {}),
})
if (!result.success) {
if (result.errors?.pendingVerification && !confirmResume) {
// Same email already has an unverified account sitting server-side —
// likely this same user retrying after a dropped connection. Ask
// before resending the OTP and reusing that account rather than
// dead-ending on a generic "already registered" error.
setPendingCreds({ email, password, group_code })
setResumeDialogOpen(true)
return
}
setErrorMessage(result.message)
setErrorDialogOpen(true)
return
}
setPendingEmail(email)
setStep(2)
}
// Validated credentials don't submit yet — stage them and ask for explicit
// confirmation first, since this is the step that actually creates the
// server-side account and sends an OTP.
const onCredentialsSubmit = (data) => {
setPendingCredsData(data)
setConfirmCreateOpen(true)
}
const handleConfirmCreate = async () => {
if (!pendingCredsData) return
setIsCreating(true)
try {
await submitRegistration(pendingCredsData)
} finally {
setIsCreating(false)
setConfirmCreateOpen(false)
}
}
const handleConfirmResume = async () => {
if (!pendingCreds) return
setIsResuming(true)
try {
await submitRegistration(pendingCreds, { confirmResume: true })
} finally {
setIsResuming(false)
setResumeDialogOpen(false)
}
}
// ─────────────────────────────────────────────────────────────────────────
return (
<>
<div className={cn('flex flex-col', className)} {...props}>
{step !== 'choice' && <StepIndicator current={step} />}
{/* ── Entry: Google vs. manual signup ── */}
{step === 'choice' && (
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">Create your account.</h1>
<p className="text-muted-foreground text-sm">Join Philproperties to start learning.</p>
</div>
{/* Group code notice */}
{groupCode && (
<div className="flex items-center gap-2 rounded-md border border-dashed px-3 py-2 bg-muted/40">
<Users className="size-4 text-muted-foreground shrink-0" />
<p className="text-sm text-muted-foreground">
Joining group{' '}
<span className="font-semibold text-foreground">{groupCode}</span>
</p>
</div>
)}
{/* Google OAuth */}
<Button variant="outline" type="button" onClick={handleGoogle} className="w-full">
<svg viewBox="0 0 128 128" className="size-4 mr-2">
<path fill="#fff" d="M44.59 4.21a63.28 63.28 0 004.33 120.9 67.6 67.6 0 0032.36.35 57.13 57.13 0 0025.9-13.46 57.44 57.44 0 0016-26.26 74.33 74.33 0 001.61-33.58H65.27v24.69h34.47a29.72 29.72 0 01-12.66 19.52 36.16 36.16 0 01-13.93 5.5 41.29 41.29 0 01-15.1 0A37.16 37.16 0 0144 95.74a39.3 39.3 0 01-14.5-19.42 38.31 38.31 0 010-24.63 39.25 39.25 0 019.18-14.91A37.17 37.17 0 0176.13 27a34.28 34.28 0 0113.64 8q5.83-5.8 11.64-11.63c2-2.09 4.18-4.08 6.15-6.22A61.22 61.22 0 0087.2 4.59a64 64 0 00-42.61-.38z" />
<path fill="#e33629" d="M44.59 4.21a64 64 0 0142.61.37 61.22 61.22 0 0120.35 12.62c-2 2.14-4.11 4.14-6.15 6.22Q95.58 29.23 89.77 35a34.28 34.28 0 00-13.64-8 37.17 37.17 0 00-37.46 9.74 39.25 39.25 0 00-9.18 14.91L8.76 35.6A63.53 63.53 0 0144.59 4.21z" />
<path fill="#f8bd00" d="M3.26 51.5a62.93 62.93 0 015.5-15.9l20.73 16.09a38.31 38.31 0 000 24.63q-10.36 8-20.73 16.08a63.33 63.33 0 01-5.5-40.9z" />
<path fill="#587dbd" d="M65.27 52.15h59.52a74.33 74.33 0 01-1.61 33.58 57.44 57.44 0 01-16 26.26c-6.69-5.22-13.41-10.4-20.1-15.62a29.72 29.72 0 0012.66-19.54H65.27c-.01-8.22 0-16.45 0-24.68z" />
<path fill="#319f43" d="M8.75 92.4q10.37-8 20.73-16.08A39.3 39.3 0 0044 95.74a37.16 37.16 0 0014.08 6.08 41.29 41.29 0 0015.1 0 36.16 36.16 0 0013.93-5.5c6.69 5.22 13.41 10.4 20.1 15.62a57.13 57.13 0 01-25.9 13.47 67.6 67.6 0 01-32.36-.35 63 63 0 01-23-11.59A63.73 63.73 0 018.75 92.4z" />
</svg>
Login with Google
</Button>
<div className="relative flex items-center gap-3 text-xs text-muted-foreground">
<Separator className="flex-1" />
<span>Or continue with</span>
<Separator className="flex-1" />
</div>
<Button type="button" className="w-full" onClick={() => setStep(0)}>
Proceed
</Button>
<p className="text-center text-sm text-muted-foreground">
Already have an account?{' '}
<Link
to={groupCode ? `/login?group_code=${groupCode}` : '/login'}
className="font-medium underline underline-offset-4"
>
Sign in
</Link>
</p>
</div>
)}
{/* ── Step 1: Personal info ── */}
{step === 0 && (
<form onSubmit={submitPersonal(onPersonalNext)} className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">Personal information.</h1>
<p className="text-muted-foreground text-sm">Tell us a bit about yourself.</p>
</div>
{/* Given + Last name row */}
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-1.5">
<label htmlFor="given_name" className="text-sm font-medium">
First name <span className="text-destructive">*</span>
</label>
<Input
id="given_name"
placeholder="Juan"
className="text-sm"
{...regPersonal('given_name')}
/>
{errPersonal.given_name && (
<p className="text-xs text-destructive">{errPersonal.given_name.message}</p>
)}
</div>
<div className="flex flex-col gap-1.5">
<label htmlFor="last_name" className="text-sm font-medium">
Last name <span className="text-destructive">*</span>
</label>
<Input
id="last_name"
placeholder="Dela Cruz"
className="text-sm"
{...regPersonal('last_name')}
/>
{errPersonal.last_name && (
<p className="text-xs text-destructive">{errPersonal.last_name.message}</p>
)}
</div>
</div>
{/* Middle name */}
<div className="flex flex-col gap-1.5">
<label htmlFor="middle_name" className="text-sm font-medium flex items-center gap-1.5">
Middle name
<span className="text-xs font-normal text-muted-foreground">(optional)</span>
</label>
<Input
id="middle_name"
placeholder="Santos"
className="text-sm"
{...regPersonal('middle_name')}
/>
{errPersonal.middle_name && (
<p className="text-xs text-destructive">{errPersonal.middle_name.message}</p>
)}
</div>
{/* Extension name + Birthday row */}
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-1.5">
<label htmlFor="extension_name" className="text-sm font-medium flex items-center gap-1.5">
Extension name
<span className="text-xs font-normal text-muted-foreground">(optional)</span>
</label>
<Input
id="extension_name"
placeholder="Jr., Sr., III"
className="text-sm"
{...regPersonal('extension_name')}
/>
{errPersonal.extension_name && (
<p className="text-xs text-destructive">{errPersonal.extension_name.message}</p>
)}
</div>
<div className="flex flex-col gap-1.5">
<label htmlFor="date_of_birth" className="text-sm font-medium">
Birthday <span className="text-destructive">*</span>
</label>
<Controller
name="date_of_birth"
control={controlPersonal}
render={({ field }) => {
const selectedDate = field.value ? parseISO(field.value) : undefined
const validSelected = selectedDate && isValidDate(selectedDate) ? selectedDate : undefined
return (
<Popover open={birthdayOpen} onOpenChange={setBirthdayOpen}>
<PopoverTrigger asChild>
<Button
type="button"
id="date_of_birth"
variant="outline"
className="w-full justify-between font-normal text-sm"
>
{validSelected ? format(validSelected, 'MMM d, yyyy') : 'Select date'}
<CalendarIcon className="h-4 w-4 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
<Calendar
mode="single"
selected={validSelected}
captionLayout="dropdown"
defaultMonth={validSelected ?? MAX_BIRTHDATE}
startMonth={MIN_BIRTHDATE}
endMonth={MAX_BIRTHDATE}
disabled={{ before: MIN_BIRTHDATE, after: MAX_BIRTHDATE }}
onSelect={(date) => {
field.onChange(date ? format(date, 'yyyy-MM-dd') : '')
setBirthdayOpen(false)
}}
/>
</PopoverContent>
</Popover>
)
}}
/>
{errPersonal.date_of_birth && (
<p className="text-xs text-destructive">{errPersonal.date_of_birth.message}</p>
)}
</div>
</div>
{/* Occupation */}
<div className="flex flex-col gap-1.5">
<label htmlFor="occupation" className="text-sm font-medium">
Occupation <span className="text-destructive">*</span>
</label>
<Input
id="occupation"
placeholder="e.g. Real Estate Broker"
className="text-sm"
{...regPersonal('occupation')}
/>
{errPersonal.occupation && (
<p className="text-xs text-destructive">{errPersonal.occupation.message}</p>
)}
</div>
{/* Phone */}
<div className="flex flex-col gap-1.5">
<label htmlFor="phone" className="text-sm font-medium">
Phone number <span className="text-destructive">*</span>
</label>
<Controller
name="phone"
control={controlPersonal}
render={({ field }) => (
<PhoneInput
{...field}
id="phone"
international
defaultCountry={detectedCountry}
className="text-sm"
/>
)}
/>
{errPersonal.phone && (
<p className="text-xs text-destructive">{errPersonal.phone.message}</p>
)}
</div>
<div className="flex gap-2 mt-1">
<Button type="button" variant="outline" className="flex-1" onClick={() => setStep('choice')}>
← Back
</Button>
<Button type="submit" className="flex-1">
Proceed
</Button>
</div>
<p className="text-center text-sm text-muted-foreground">
Already have an account?{' '}
<Link
to={groupCode ? `/login?group_code=${groupCode}` : '/login'}
className="font-medium underline underline-offset-4"
>
Sign in
</Link>
</p>
</form>
)}
{/* ── Step 2: Credentials ── */}
{step === 1 && (
<form onSubmit={submitCreds(onCredentialsSubmit)} className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-bold tracking-tighter">Account credentials.</h1>
<p className="text-muted-foreground text-sm">Set your login email and password.</p>
</div>
{/* Group code notice */}
{groupCode && (
<div className="flex items-center gap-2 rounded-md border border-dashed px-3 py-2 bg-muted/40">
<Users className="size-4 text-muted-foreground shrink-0" />
<p className="text-sm text-muted-foreground">
Joining group{' '}
<span className="font-semibold text-foreground">{groupCode}</span>
</p>
</div>
)}
{/* Email */}
<div className="flex flex-col gap-1.5">
<label htmlFor="email" className="text-sm font-medium">
Email address <span className="text-destructive">*</span>
</label>
<Input
id="email"
type="email"
placeholder="you@example.com"
autoComplete="off"
disabled={isRegistering}
readOnly
onFocus={(e) => e.target.removeAttribute('readonly')}
className="text-sm"
{...regCreds('email')}
/>
{errCreds.email && (
<p className="text-xs text-destructive">{errCreds.email.message}</p>
)}
</div>
{/* Password */}
<div className="flex flex-col gap-1.5">
<label htmlFor="password" className="text-sm font-medium">
Password <span className="text-destructive">*</span>
</label>
<div className="relative">
<Input
id="password"
type={showPassword ? 'text' : 'password'}
placeholder="Min. 8 chars, 1 uppercase, 1 number"
autoComplete="new-password"
disabled={isRegistering}
className="pr-10 text-sm"
{...regCreds('password')}
/>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => setShowPassword((v) => !v)}
className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
{errCreds.password && (
<p className="text-xs text-destructive">{errCreds.password.message}</p>
)}
</div>
{/* Confirm password */}
<div className="flex flex-col gap-1.5">
<label htmlFor="confirm_password" className="text-sm font-medium">
Confirm password <span className="text-destructive">*</span>
</label>
<div className="relative">
<Input
id="confirm_password"
type={showConfirm ? 'text' : 'password'}
placeholder="Repeat your password"
autoComplete="new-password"
disabled={isRegistering}
className="pr-10 text-sm"
{...regCreds('confirm_password')}
/>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => setShowConfirm((v) => !v)}
className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showConfirm ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
{errCreds.confirm_password && (
<p className="text-xs text-destructive">{errCreds.confirm_password.message}</p>
)}
</div>
{/* Group code — disabled, auto-filled from URL */}
<div className="flex flex-col gap-1.5">
<label htmlFor="group_code" className="text-sm font-medium flex items-center gap-2">
Group code
<Badge variant="secondary" className="text-xs font-normal">Auto-filled</Badge>
</label>
<Input
id="group_code"
placeholder="No group code"
disabled
className="text-sm"
{...regCreds('group_code')}
/>
<p className="text-xs text-muted-foreground">
Provided by your group admin via invite link.
</p>
</div>
{/* Navigation */}
<div className="flex gap-2 mt-1">
<Button
type="button"
variant="outline"
className="flex-1"
onClick={() => setStep(0)}
disabled={isRegistering}
>
← Back
</Button>
<Button type="submit" className="flex-1" disabled={isRegistering || isCreating}>
Create account →
</Button>
</div>
<p className="text-center text-sm text-muted-foreground">
Already have an account?{' '}
<Link
to={groupCode ? `/login?group_code=${groupCode}` : '/login'}
className="font-medium underline underline-offset-4"
>
Sign in
</Link>
</p>
</form>
)}
{/* ── Step 3: OTP ── */}
{step === 2 && (
<OtpVerifyForm
email={pendingEmail}
onSuccess={() => navigate('/dashboard', { state: { justRegistered: true } })}
onBack={() => setStep(1)}
/>
)}
</div>
<AlertDialog open={errorDialogOpen} onOpenChange={setErrorDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Registration failed</AlertDialogTitle>
<AlertDialogDescription>{errorMessage}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogAction onClick={() => setErrorDialogOpen(false)}>Okay</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={confirmCreateOpen} onOpenChange={(open) => !isCreating && setConfirmCreateOpen(open)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Create this account?</AlertDialogTitle>
<AlertDialogDescription>
We'll create your account with{' '}
<span className="font-medium text-foreground">{pendingCredsData?.email}</span>{' '}
and email a 6-digit verification code to that address.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<Button variant="outline" disabled={isCreating} onClick={() => setConfirmCreateOpen(false)}>
Cancel
</Button>
<AlertDialogAction onClick={handleConfirmCreate} disabled={isCreating}>
{isCreating ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Creating...
</span>
) : (
'Proceed'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={resumeDialogOpen} onOpenChange={(open) => !isResuming && setResumeDialogOpen(open)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Pending verification found</AlertDialogTitle>
<AlertDialogDescription>
This email already started registration but was never verified — likely from a dropped
connection. Resend the verification code and continue with the details you just entered?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<Button variant="outline" disabled={isResuming} onClick={() => setResumeDialogOpen(false)}>
Cancel
</Button>
<AlertDialogAction onClick={handleConfirmResume} disabled={isResuming}>
{isResuming ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Sending...
</span>
) : (
'Resend code'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
+11
View File
@@ -0,0 +1,11 @@
import React from 'react'
const Auth = () => {
return (
<div>
Auth Page
</div>
)
}
export default Auth
@@ -0,0 +1,173 @@
/***********************************************************************************************************************************************************************
* File Name: ChangePasswordPage.jsx
* Type of Program: Frontend Page
* Description: Forced password change page shown after first login when
* must_change_password is true. Redirects to the user's dashboard
* on success and clears the flag via the backend.
* Author: rgrgogu
* Date Created: May 23, 2026
***********************************************************************************************************************************************************************/
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Eye, EyeOff, LoaderCircle, ShieldCheck } from 'lucide-react';
import { cn } from '@/lib/utils';
import api from '@/utils/api.util';
import { toast } from 'sonner';
// ─── Schema ───────────────────────────────────────────────────────────────────
const schema = z
.object({
new_password: z
.string()
.min(8, 'Password must be at least 8 characters.')
.regex(/[A-Z]/, 'Must contain at least one uppercase letter.')
.regex(/[a-z]/, 'Must contain at least one lowercase letter.')
.regex(/[0-9]/, 'Must contain at least one number.')
.regex(/[^A-Za-z0-9]/, 'Must contain at least one special character.'),
confirm_password: z.string().min(1, 'Please confirm your password.'),
})
.refine((d) => d.new_password === d.confirm_password, {
path: ['confirm_password'],
message: 'Passwords do not match.',
});
// ─── Field wrapper ─────────────────────────────────────────────────────────────
function Field({ label, error, children }) {
return (
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium">{label}</label>
{children}
{error && <p className="text-sm text-destructive">{error}</p>}
</div>
);
}
// ─── Password input with toggle ───────────────────────────────────────────────
function PasswordInput({ visible, onToggle, ...props }) {
return (
<div className="relative">
<Input
type={visible ? 'text' : 'password'}
className="pr-10"
{...props}
/>
<Button
type="button"
size="sm"
variant="ghost"
onClick={onToggle}
className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{visible ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
);
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function ChangePassword() {
const navigate = useNavigate();
const { user, setUser } = useAuth();
const [showNew, setShowNew] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm({
resolver: zodResolver(schema),
defaultValues: { new_password: '', confirm_password: '' },
});
const onSubmit = async ({ new_password }) => {
try {
await api.post('/auth/change-password', { new_password });
// Update local user state so must_change_password is cleared
setUser((prev) => ({ ...prev, must_change_password: false }));
toast('Password changed successfully. Welcome!');
// Redirect to the correct dashboard
switch (user?.acc_type) {
case 'admin': navigate('/admin'); break;
case 'staff': navigate('/staff'); break;
case 'client': navigate('/client'); break;
default: navigate('/');
}
} catch (err) {
toast(err?.response?.data?.message || 'Could not change password.');
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-background px-4">
<div className="w-full max-w-md space-y-6">
{/* Header */}
<div className="flex flex-col items-center gap-2 text-center">
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
<ShieldCheck className="h-6 w-6 text-primary" />
</div>
<h1 className="text-2xl font-bold tracking-tight">Set your password</h1>
<p className="text-sm text-muted-foreground">
Your account requires a new password before you can continue.
</p>
</div>
{/* Form */}
<form
onSubmit={handleSubmit(onSubmit)}
className="border border-border rounded-xl p-6 bg-card space-y-4"
>
<Field label="New Password" error={errors.new_password?.message}>
<PasswordInput
visible={showNew}
onToggle={() => setShowNew((v) => !v)}
placeholder="Enter new password"
disabled={isSubmitting}
{...register('new_password')}
/>
</Field>
<Field label="Confirm Password" error={errors.confirm_password?.message}>
<PasswordInput
visible={showConfirm}
onToggle={() => setShowConfirm((v) => !v)}
placeholder="Confirm new password"
disabled={isSubmitting}
{...register('confirm_password')}
/>
</Field>
{/* Password rules hint */}
<ul className="text-xs text-muted-foreground space-y-0.5 pl-4 list-disc">
<li>At least 8 characters</li>
<li>One uppercase &amp; one lowercase letter</li>
<li>One number and one special character</li>
</ul>
<Button type="submit" className="w-full" disabled={isSubmitting}>
{isSubmitting ? (
<span className="flex items-center gap-2">
<LoaderCircle className="size-4 animate-spin" />
Saving…
</span>
) : (
'Set Password & Continue'
)}
</Button>
</form>
</div>
</div>
);
}
@@ -0,0 +1,56 @@
/***********************************************************************************************************************************************************************
* File Name: ForgotPassword.jsx
* Type of Program: Frontend Page
* Description: Forgot-password page. Route: /forgot-password
* Module: User Credentials
* Author: lash0000
* Date Created: Jul. 4, 2026
***********************************************************************************************************************************************************************/
import { Link } from 'react-router-dom'
import { ForgotPasswordForm } from '../components/ForgotPasswordForm'
import { AuthThemeToggle } from '../components/AuthThemeToggle'
import { MetadataProvider } from '@/contexts/MetadataContext'
export default function ForgotPassword() {
return (
<MetadataProvider
value={{
title: 'Forgot Password - Philproperties',
description: 'Reset your account password.',
keywords: 'forgot password, reset password, philproperties',
ogTitle: 'Forgot Password - Philproperties',
ogDescription: 'Reset your account password.',
}}
>
<div className="relative grid min-h-svh lg:grid-cols-2">
<AuthThemeToggle className="absolute top-4 right-4 z-10" />
<div className="flex flex-col gap-4 p-6 md:p-10">
<div className="flex justify-center">
<Link to="/" className="flex items-center gap-2 font-medium">
<div className="xs:w-40 sm:w-48 md:w-56 2xl:w-64 block dark:hidden">
<img src="/philpro-white.png" alt="Philproperties" />
</div>
<div className="xs:w-40 sm:w-48 md:w-56 2xl:w-64 hidden dark:block">
<img src="/philpro-dark.png" alt="Philproperties" />
</div>
</Link>
</div>
<div className="flex flex-1 items-center justify-center">
<div className="w-full max-w-sm">
<ForgotPasswordForm />
</div>
</div>
</div>
<div className="relative hidden lg:block">
<img
src="https://cq5as7pc73.ufs.sh/f/pHNnzIw3VjcgzIbC8SR4stTZRKXP3cfbD6e2p9jmdAUQBuox"
alt="Philproperties"
className="absolute inset-0 h-full w-full object-cover rounded-3xl p-2"
/>
</div>
</div>
</MetadataProvider>
)
}
+282
View File
@@ -0,0 +1,282 @@
/***********************************************************************************************************************************************************************
* File Name: Intro.jsx
* Type of Program: Frontend Page
* Description: "Tell us about yourself" onboarding page shown once to every new user
* (system-registered or Google OAuth) before they reach the dashboard.
* Skips rendering and redirects if user.needs_intro is already false.
* On submit: PUT /client/profile → clears needs_intro → navigate /dashboard.
* Author: lash0000
* Date Created: Jun. 23, 2026
***********************************************************************************************************************************************************************/
import { useState } from 'react'
import { Navigate, useNavigate, Link } from 'react-router-dom'
import { isValidPhoneNumber, parsePhoneNumber } from 'react-phone-number-input'
import { useAuth } from '@/contexts/AuthContext'
import { useDetectedCountry } from '@/hooks/useDetectedCountry'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { PhoneInput } from '@/components/ui/phone-input'
import { Label } from '@/components/ui/label'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { resolveAssetSrc } from '@/utils/media.util'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { Toaster } from '@/components/ui/sonner'
import api from '@/utils/api.util'
// ─── Helpers ──────────────────────────────────────────────────────────────────
function getInitials(given = '', last = '') {
const g = given.trim()[0]?.toUpperCase() ?? ''
const l = last.trim()[0]?.toUpperCase() ?? ''
return g + l || '?'
}
// ─── Component ────────────────────────────────────────────────────────────────
export default function IntroPage() {
const navigate = useNavigate()
const { user, setUser } = useAuth()
// Already completed intro — send straight to dashboard
if (!user?.needs_intro) return <Navigate to="/dashboard" replace />
const pi = user?.personal_info ?? {}
// ── Form state seeded from existing personal_info (Google already has name) ──
const [givenName, setGivenName] = useState(pi.name?.given_name ?? '')
const [middleName, setMiddleName] = useState(pi.name?.middle_name ?? '')
const [lastName, setLastName] = useState(pi.name?.last_name ?? '')
const [extensionName, setExtensionName] = useState(pi.name?.extension_name ?? '')
const [dateOfBirth, setDateOfBirth] = useState(pi.date_of_birth ?? '')
const [occupation, setOccupation] = useState(pi.occupation ?? '')
const [phone, setPhone] = useState(
pi.phone_number?.[0]?.full_number ? `+${pi.phone_number[0].full_number}` : ''
)
const [loading, setLoading] = useState(false)
const [errors, setErrors] = useState({})
const detectedCountry = useDetectedCountry()
// ── Derived ────────────────────────────────────────────────────────────────
const avatarUrl = resolveAssetSrc(pi.avatar) ?? ''
const initials = getInitials(givenName, lastName)
const displayEmail = user?.email ?? ''
// ── Validation ─────────────────────────────────────────────────────────────
const validate = () => {
const e = {}
if (!givenName.trim()) e.givenName = 'First name is required.'
if (!lastName.trim()) e.lastName = 'Last name is required.'
if (!occupation.trim()) e.occupation = 'Occupation is required.'
if (!dateOfBirth) {
e.dateOfBirth = 'Date of birth is required.'
} else {
const age = (Date.now() - new Date(dateOfBirth)) / (1000 * 60 * 60 * 24 * 365.25)
if (isNaN(age) || age < 13 || age > 120) e.dateOfBirth = 'Please enter a valid date of birth.'
}
if (!phone.trim()) {
e.phone = 'Phone number is required.'
} else if (!isValidPhoneNumber(phone)) {
e.phone = 'Invalid phone number.'
}
return e
}
// ── Submit ─────────────────────────────────────────────────────────────────
const handleSubmit = async (e) => {
e.preventDefault()
const errs = validate()
if (Object.keys(errs).length) {
setErrors(errs)
return
}
setErrors({})
setLoading(true)
const fullName = [givenName, middleName, lastName, extensionName].filter(Boolean).join(' ')
const personal_info = {
name: {
given_name: givenName,
middle_name: middleName,
last_name: lastName,
extension_name: extensionName,
full_name: fullName,
},
date_of_birth: dateOfBirth,
occupation,
phone_number: phone.trim()
? (() => {
const parsed = parsePhoneNumber(phone)
return [{
number: parsed.nationalNumber,
country_code: parsed.countryCallingCode,
full_number: `${parsed.countryCallingCode}${parsed.nationalNumber}`,
phone_type: 'mobile',
}]
})()
: (pi.phone_number ?? []),
// Preserve existing avatar and addresses
...(pi.avatar ? { avatar: pi.avatar } : {}),
...(pi.addresses ? { addresses: pi.addresses } : {}),
}
try {
const { data } = await api.put('/client/profile', { personal_info })
// Merge the full returned user object — needs_intro will now be false
setUser(prev => ({ ...prev, ...data.data }))
navigate('/dashboard')
} catch (err) {
toast(
err?.response?.data?.message ?? 'Could not save your info. Please try again.'
)
} finally {
setLoading(false)
}
}
// ── Render ─────────────────────────────────────────────────────────────────
return (
<>
<Toaster position="bottom-right" richColors />
<div className="min-h-svh bg-muted flex items-center justify-center p-6">
<div className="w-full max-w-lg">
{/* Logo */}
<div className="flex justify-center mb-8">
<Link to="/">
<img src="/philpro-white.png" alt="Philproperties" className="w-44 dark:hidden" />
<img src="/philpro-dark.png" alt="Philproperties" className="w-44 hidden dark:block" />
</Link>
</div>
{/* Card */}
<div className="bg-card rounded-2xl border shadow-sm p-8 space-y-6">
{/* Header */}
<div className="flex flex-col items-center gap-3 text-center">
<Avatar className="h-16 w-16">
<AvatarImage src={avatarUrl} />
<AvatarFallback className="text-lg font-semibold">{initials}</AvatarFallback>
</Avatar>
<div>
<h1 className="text-xl font-bold tracking-tight">Tell us about yourself</h1>
<p className="text-sm text-muted-foreground mt-1">
{displayEmail} &nbsp;·&nbsp; This info appears on your profile.
</p>
</div>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-4">
{/* Name row */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">First name <span className="text-destructive">*</span></Label>
<Input
value={givenName}
onChange={e => setGivenName(e.target.value)}
placeholder="Juan"
disabled={loading}
/>
{errors.givenName && <p className="text-xs text-destructive">{errors.givenName}</p>}
</div>
<div className="space-y-1.5">
<Label className="text-xs">Last name <span className="text-destructive">*</span></Label>
<Input
value={lastName}
onChange={e => setLastName(e.target.value)}
placeholder="Dela Cruz"
disabled={loading}
/>
{errors.lastName && <p className="text-xs text-destructive">{errors.lastName}</p>}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">
Middle name <span className="text-xs font-normal text-muted-foreground">(optional)</span>
</Label>
<Input
value={middleName}
onChange={e => setMiddleName(e.target.value)}
placeholder="Santos"
disabled={loading}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">
Extension <span className="text-xs font-normal text-muted-foreground">(optional)</span>
</Label>
<Input
value={extensionName}
onChange={e => setExtensionName(e.target.value)}
placeholder="Jr., Sr., III"
disabled={loading}
/>
</div>
</div>
{/* Date of birth */}
<div className="space-y-1.5">
<Label className="text-xs">Date of birth <span className="text-destructive">*</span></Label>
<Input
type="date"
value={dateOfBirth}
onChange={e => setDateOfBirth(e.target.value)}
max={new Date().toISOString().split('T')[0]}
disabled={loading}
/>
{errors.dateOfBirth && <p className="text-xs text-destructive">{errors.dateOfBirth}</p>}
</div>
{/* Occupation */}
<div className="space-y-1.5">
<Label className="text-xs">Occupation <span className="text-destructive">*</span></Label>
<Input
value={occupation}
onChange={e => setOccupation(e.target.value)}
placeholder="e.g. Real Estate Broker"
disabled={loading}
/>
{errors.occupation && <p className="text-xs text-destructive">{errors.occupation}</p>}
</div>
{/* Phone */}
<div className="space-y-1.5">
<Label className="text-xs">
Phone number <span className="text-destructive">*</span>
</Label>
<PhoneInput
value={phone}
onChange={setPhone}
international
defaultCountry={detectedCountry}
disabled={loading}
/>
{errors.phone && <p className="text-xs text-destructive">{errors.phone}</p>}
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading
? <><Loader2 className="size-4 animate-spin" /> Saving...</>
: "Let's get started →"
}
</Button>
</form>
</div>
</div>
</div>
</>
)
}
+52
View File
@@ -0,0 +1,52 @@
import { Link } from 'react-router-dom'
import { LoginForm } from "../components/LoginForm";
import { AuthThemeToggle } from "../components/AuthThemeToggle";
import { MetadataProvider } from "@/contexts/MetadataContext";
export default function Login() {
return (
<MetadataProvider
value={{
title: "Login - Philproperties",
description: "Kindly login to access our online course platform.",
keywords: "login, philproperties, training, onboarding, real-estate",
ogTitle: "Login - Philproperties",
ogDescription: "Kindly login to access our online course platform.",
}}
>
<div className="relative grid min-h-svh lg:grid-cols-2">
<AuthThemeToggle className="absolute top-4 right-4 z-10" />
<div className="flex flex-col gap-4 p-6 md:p-10">
<div className="flex justify-center">
<Link to="/" className="flex items-center gap-2 font-medium">
<div className="xs:w-40 sm:w-48 md:w-56 2xl:w-64 block dark:hidden">
<img
src="/philpro-white.png"
alt="Image"
/>
</div>
<div className="xs:w-40 sm:w-48 md:w-56 2xl:w-64 hidden dark:block">
<img
src="/philpro-dark.png"
alt="Image"
/>
</div>
</Link>
</div>
<div className="flex flex-1 items-center justify-center">
<div className="w-full max-w-sm">
<LoginForm />
</div>
</div>
</div>
<div className="relative hidden lg:block">
<img
src="https://cq5as7pc73.ufs.sh/f/pHNnzIw3VjcgzIbC8SR4stTZRKXP3cfbD6e2p9jmdAUQBuox"
alt="Image"
className="absolute inset-0 h-full w-full object-cover rounded-3xl p-2"
/>
</div>
</div>
</MetadataProvider>
)
}
@@ -0,0 +1,189 @@
/***********************************************************************************************************************************************************************
* File Name: OAuthCallback.jsx
* Type of Program: Frontend Page
* Description: Landing page after the backend completes Google OIDC.
*
* The backend redirects here with NO query params — the outcome (otpRequired/
* email, ban details, or an error code) never touches the URL. Instead, this
* page fetches it from GET /auth/google/result, a single-use endpoint that
* reads a short-lived signed cookie the callback controller set.
*
* OTP path → result = { otpRequired: true, email }. No refresh cookie was
* set yet. Renders the shared OtpVerifyForm; once verified,
* AuthContext has user/tokens set and we navigate to the
* account's home route ourselves.
*
* Trusted path → result = {} (nothing pending) — this device already cleared
* an OTP recently, so the backend set the real refresh cookie
* directly. This page calls restoreSession() to pull the
* access token from it, then navigates to the account's home
* route.
*
* Error path → result = { error: <code>, ... }. No refresh cookie was set,
* so the user stays on this page to see the error.
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jun. 21, 2026
* Date Modified: Jul. 6, 2026 — outcome moved from URL params to /auth/google/result
***********************************************************************************************************************************************************************/
import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { LoaderCircle, ShieldBan, UserX, AlertTriangle, RefreshCw, Clock } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useAuth } from '@/contexts/AuthContext'
import { useDateFormat } from '@/hooks/useDateFormat'
import { getRoleHomePath } from '@/utils/roleRedirect.util'
import { OtpVerifyForm } from '@/modules/auth/components/OtpVerifyForm'
import api from '@/utils/api.util'
const ERROR_MAP = {
access_denied: { icon: UserX, message: 'You cancelled the Google sign-in.' },
account_deactivated: { icon: UserX, message: 'Your account has been deactivated. Please contact support.' },
session_expired: { icon: Clock, message: 'The sign-in session expired. Please try again.' },
state_mismatch: { icon: AlertTriangle, message: 'Security check failed. Please try signing in again.' },
auth_failed: { icon: RefreshCw, message: 'Google sign-in failed. Please try again.' },
}
export default function OAuthCallback() {
const navigate = useNavigate()
const { restoreSession } = useAuth()
const { fmtDateTime } = useDateFormat()
// null = still resolving; otherwise the parsed /auth/google/result payload.
const [result, setResult] = useState(null)
useEffect(() => {
let cancelled = false
;(async () => {
let pending = {}
try {
const { data } = await api.get('/auth/google/result')
pending = data.data ?? {}
} catch {
// network hiccup — fall through to the trusted-device path below
}
if (pending.otpRequired || pending.error) {
if (!cancelled) setResult(pending)
return
}
// Nothing pending → trusted-device fast path. The refresh cookie was
// already set by the backend; restoreSession() just picks it up.
const { success, user } = await restoreSession()
if (cancelled) return
navigate(success ? getRoleHomePath(user) : '/login', {
replace: true,
state: success && pending.justLinkedGoogle ? { justLinkedGoogle: true } : undefined,
})
})()
return () => { cancelled = true }
}, [])
const error = result?.error
const otpRequired = !!result?.otpRequired
const email = result?.email
if (otpRequired && email) {
return (
<div className="flex min-h-svh items-center justify-center p-6">
<div className="w-full max-w-sm">
<OtpVerifyForm
email={email}
onSuccess={(user) => navigate(getRoleHomePath(user), {
replace: true,
state: result?.justLinkedGoogle ? { justLinkedGoogle: true } : undefined,
})}
title="Verify your sign-in"
description={`We sent a 6-digit code to ${email} to finish signing in with Google. It expires in 10 minutes.`}
/>
</div>
</div>
)
}
if (error === 'account_banned') {
const reason = result.reason
const banType = result.ban_type
const expiresAt = result.expires_at
const expiryText = expiresAt ? fmtDateTime(expiresAt) : null
return (
<div className="min-h-svh flex items-center justify-center bg-muted/40 px-4">
<div className="flex flex-col items-center text-center gap-6 max-w-md w-full">
<div className="flex items-center justify-center w-20 h-20 rounded-full bg-destructive/10">
<ShieldBan className="size-10 text-destructive" />
</div>
<div className="space-y-2">
<h1 className="text-2xl font-semibold tracking-tight">Account Suspended</h1>
<p className="text-sm text-muted-foreground text-balance">
Your account has been suspended and you cannot access the platform at this time.
</p>
</div>
{(reason || banType) && (
<div className="w-full rounded-lg border bg-card p-4 text-left flex flex-col gap-3">
{reason && (
<div>
<p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-0.5">Reason</p>
<p className="text-sm">{reason}</p>
</div>
)}
{banType === 'temporary' && expiryText && (
<div>
<p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-0.5">Suspended Until</p>
<p className="text-sm">{expiryText}</p>
</div>
)}
{banType === 'permanent' && (
<div>
<p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-0.5">Duration</p>
<p className="text-sm">Permanent</p>
</div>
)}
</div>
)}
<p className="text-sm text-muted-foreground">
If you believe this is a mistake, please reach out to your administrator for assistance.
</p>
<Button asChild variant="outline" size="sm">
<Link to="/login">Back to Login</Link>
</Button>
</div>
</div>
)
}
if (error) {
const { icon: Icon, message } = ERROR_MAP[error] ?? { icon: AlertTriangle, message: 'An unexpected error occurred. Please try again.' }
return (
<div className="flex min-h-svh items-center justify-center p-6">
<div className="flex flex-col items-center gap-4 text-center max-w-sm">
<div className="flex items-center justify-center w-12 h-12 rounded-full bg-muted">
<Icon className="size-5 text-muted-foreground" />
</div>
<p className="text-sm text-destructive font-medium">{message}</p>
<Button asChild variant="outline" size="sm">
<Link to="/login">Back to Login</Link>
</Button>
</div>
</div>
)
}
return (
<div className="flex min-h-svh items-center justify-center">
<div className="flex flex-col items-center gap-3">
<LoaderCircle className="size-6 animate-spin text-muted-foreground" />
<p className="text-sm text-muted-foreground">Signing you in...</p>
</div>
</div>
)
}
@@ -0,0 +1,70 @@
/***********************************************************************************************************************************************************************
* File Name: Register.jsx
* Type of Program: Frontend Page
* Description: Registration page. Accepts optional ?group_code= query param to
* auto-enroll new users into a user group on verification.
* Route: /register or /register?group_code=XXXX
* Module: User Credentials
* Author: lash0000
* Date Created: May 23, 2026
***********************************************************************************************************************************************************************
* Change History:
* DATE AUTHOR LOG NUMBER DESCRIPTION
* May 23, 2026 lash0000 001 Initial creation - STAR Phase 1 Project
***********************************************************************************************************************************************************************/
import { Link } from 'react-router-dom'
import { RegisterForm } from '../components/RegisterForm'
import { AuthThemeToggle } from '../components/AuthThemeToggle'
import { MetadataProvider } from '@/contexts/MetadataContext'
// TODO: flip to true once the hero banner asset is ready; grid auto-centers the
// left panel while this is false so no other classes need to change either way.
const SHOW_BANNER = false
export default function Register() {
return (
<MetadataProvider
value={{
title: 'Register - Philproperties',
description: 'Create an account to access our online course platform.',
keywords: 'register, signup, philproperties, training, onboarding, real-estate',
ogTitle: 'Register - Philproperties',
ogDescription: 'Create an account to access our online course platform.',
}}
>
<div className={`relative grid min-h-svh ${SHOW_BANNER ? 'lg:grid-cols-2' : ''}`}>
<AuthThemeToggle className="absolute top-4 right-4 z-10" />
{/* ── Left panel ── */}
<div className="flex flex-col gap-4 p-6 md:p-10">
<div className="flex justify-center">
<Link to="/" className="flex items-center gap-2 font-medium">
<div className="xs:w-40 sm:w-48 md:w-56 2xl:w-64 block dark:hidden">
<img src="/philpro-white.png" alt="Philproperties" />
</div>
<div className="xs:w-40 sm:w-48 md:w-56 2xl:w-64 hidden dark:block">
<img src="/philpro-dark.png" alt="Philproperties" />
</div>
</Link>
</div>
<div className="flex flex-1 items-center justify-center">
<div className="w-full max-w-xl">
<RegisterForm />
</div>
</div>
</div>
{/* ── Right panel — hero image ── */}
{SHOW_BANNER && (
<div className="relative hidden lg:block">
<img
src="https://cq5as7pc73.ufs.sh/f/pHNnzIw3VjcgzIbC8SR4stTZRKXP3cfbD6e2p9jmdAUQBuox"
alt="Philproperties"
className="absolute inset-0 h-full w-full object-cover rounded-3xl p-2"
/>
</div>
)}
</div>
</MetadataProvider>
)
}
@@ -0,0 +1,29 @@
import { Outlet } from 'react-router-dom'
import PublicRoute from '../../../routes/PublicRoute'
import LandingLayout from '@/modules/public/layouts/LandingLayout'
import LandingPage from '@/modules/public/pages/LandingPage'
import Login from '../pages/Login'
import Register from '../pages/Register'
import ForgotPassword from '../pages/ForgotPassword'
import OAuthCallback from '../pages/OAuthCallback'
import Suspended from '@/modules/public/pages/Suspended'
export const AuthRoutes = {
element: <PublicRoute />,
children: [
{
path: '/',
element: <Outlet />,
children: [
{ index: true, element: <LandingLayout><LandingPage /></LandingLayout> },
{ path: "login", element: <Login />},
{ path: "signup", element: <Register />},
{ path: "forgot-password", element: <ForgotPassword /> },
{ path: "auth/callback/google", element: <OAuthCallback /> },
{ path: "suspended", element: <Suspended /> },
]
},
],
}