feat: enhance user account management with password and profile updates

- Added validation for user profile and password update forms using Yup.
- Implemented user feedback for successful profile and password updates, including prompts to re-login.
- Improved UI for profile editing and password change sections, enhancing user experience.
- Updated password update service to include response metadata handling.
This commit is contained in:
swve 2025-01-24 22:46:05 +01:00
parent 943ceff813
commit 79a31dd8ec
4 changed files with 352 additions and 132 deletions

View file

@ -11,7 +11,7 @@ import * as Form from '@radix-ui/react-form'
import { getOrgLogoMediaDirectory } from '@services/media/media' import { getOrgLogoMediaDirectory } from '@services/media/media'
import { AlertTriangle, Info } from 'lucide-react' import { AlertTriangle, Info } from 'lucide-react'
import Link from 'next/link' import Link from 'next/link'
import { getUriWithOrg } from '@services/config/config' import { getUriWithOrg, getUriWithoutOrg } from '@services/config/config'
import { useOrg } from '@components/Contexts/OrgContext' import { useOrg } from '@components/Contexts/OrgContext'
import { useRouter, useSearchParams } from 'next/navigation' import { useRouter, useSearchParams } from 'next/navigation'
import { useFormik } from 'formik' import { useFormik } from 'formik'
@ -139,9 +139,14 @@ function ResetPasswordClient() {
</div> </div>
)} )}
{message && ( {message && (
<div className="flex justify-center bg-green-200 rounded-md text-green-950 space-x-2 items-center p-4 transition-all shadow-sm"> <div className="flex flex-col gap-2">
<Info size={18} /> <div className="flex justify-center bg-green-200 rounded-md text-green-950 space-x-2 items-center p-4 transition-all shadow-sm">
<div className="font-bold text-sm">{message}</div> <Info size={18} />
<div className="font-bold text-sm">{message}</div>
</div>
<Link href={getUriWithoutOrg('/login?orgslug=' + org.slug)} className="text-center text-sm text-blue-600 hover:text-blue-800">
Please login again with your new password
</Link>
</div> </div>
)} )}
<FormLayout onSubmit={formik.handleSubmit}> <FormLayout onSubmit={formik.handleSubmit}>

View file

@ -1,7 +1,7 @@
'use client'; 'use client';
import { updateProfile } from '@services/settings/profile' import { updateProfile } from '@services/settings/profile'
import React, { useEffect } from 'react' import React, { useEffect } from 'react'
import { Formik, Form, Field } from 'formik' import { Formik, Form } from 'formik'
import { useLHSession } from '@components/Contexts/LHSessionContext' import { useLHSession } from '@components/Contexts/LHSessionContext'
import { import {
ArrowBigUpDash, ArrowBigUpDash,
@ -9,13 +9,39 @@ import {
FileWarning, FileWarning,
Info, Info,
UploadCloud, UploadCloud,
AlertTriangle,
LogOut
} from 'lucide-react' } from 'lucide-react'
import UserAvatar from '@components/Objects/UserAvatar' import UserAvatar from '@components/Objects/UserAvatar'
import { updateUserAvatar } from '@services/users/users' import { updateUserAvatar } from '@services/users/users'
import { constructAcceptValue } from '@/lib/constants'; import { constructAcceptValue } from '@/lib/constants'
import * as Yup from 'yup'
import { Input } from "@components/ui/input"
import { Textarea } from "@components/ui/textarea"
import { Button } from "@components/ui/button"
import { Label } from "@components/ui/label"
import { toast } from 'react-hot-toast'
import { signOut } from 'next-auth/react'
import { getUriWithoutOrg } from '@services/config/config';
const SUPPORTED_FILES = constructAcceptValue(['image']) const SUPPORTED_FILES = constructAcceptValue(['image'])
const validationSchema = Yup.object().shape({
email: Yup.string().email('Invalid email').required('Email is required'),
username: Yup.string().required('Username is required'),
first_name: Yup.string().required('First name is required'),
last_name: Yup.string().required('Last name is required'),
bio: Yup.string().max(400, 'Bio must be 400 characters or less'),
})
interface FormValues {
username: string;
first_name: string;
last_name: string;
email: string;
bio: string;
}
function UserEditGeneral() { function UserEditGeneral() {
const session = useLHSession() as any; const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token; const access_token = session?.data?.tokens?.access_token;
@ -40,116 +66,231 @@ function UserEditGeneral() {
} }
} }
const handleEmailChange = async (newEmail: string) => {
toast.success('Profile Updated Successfully', { duration: 4000 })
// Show message about logging in with new email
toast((t) => (
<div className="flex items-center gap-2">
<span>Please login again with your new email: {newEmail}</span>
</div>
), {
duration: 4000,
icon: '📧'
})
// Wait for 4 seconds before signing out
await new Promise(resolve => setTimeout(resolve, 4000))
signOut({ redirect: true, callbackUrl: getUriWithoutOrg('/') })
}
useEffect(() => { }, [session, session.data]) useEffect(() => { }, [session, session.data])
return ( return (
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-6 py-5 sm:mb-0 mb-16"> <div className="sm:mx-10 mx-0 bg-white rounded-xl nice-shadow">
{session.data.user && ( {session.data.user && (
<Formik <Formik<FormValues>
enableReinitialize enableReinitialize
initialValues={{ initialValues={{
username: session.data.user.username, username: session.data.user.username,
first_name: session.data.user.first_name, first_name: session.data.user.first_name,
last_name: session.data.user.last_name, last_name: session.data.user.last_name,
email: session.data.user.email, email: session.data.user.email,
bio: session.data.user.bio, bio: session.data.user.bio || '',
}} }}
validationSchema={validationSchema}
onSubmit={(values, { setSubmitting }) => { onSubmit={(values, { setSubmitting }) => {
const isEmailChanged = values.email !== session.data.user.email
const loadingToast = toast.loading('Updating profile...')
setTimeout(() => { setTimeout(() => {
setSubmitting(false) setSubmitting(false)
updateProfile(values, session.data.user.id, access_token) updateProfile(values, session.data.user.id, access_token)
.then(() => {
toast.dismiss(loadingToast)
if (isEmailChanged) {
handleEmailChange(values.email)
} else {
toast.success('Profile Updated Successfully')
}
})
.catch(() => {
toast.error('Failed to update profile', { id: loadingToast })
})
}, 400) }, 400)
}} }}
> >
{({ isSubmitting }) => ( {({ isSubmitting, values, handleChange, errors, touched }) => (
<div className="flex flex-col lg:flex-row gap-8"> <Form>
<Form className="flex-1 min-w-0"> <div className="flex flex-col gap-0">
<div className="space-y-4"> <div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 mx-3 my-3 rounded-md">
{[ <h1 className="font-bold text-xl text-gray-800">
{ label: 'Email', name: 'email', type: 'email' }, Account Settings
{ label: 'Username', name: 'username', type: 'text' }, </h1>
{ label: 'First Name', name: 'first_name', type: 'text' }, <h2 className="text-gray-500 text-md">
{ label: 'Last Name', name: 'last_name', type: 'text' }, Manage your personal information and preferences
{ label: 'Bio', name: 'bio', type: 'text' }, </h2>
].map((field) => (
<div key={field.name}>
<label className="block mb-2 font-bold" htmlFor={field.name}>
{field.label}
</label>
<Field
className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type={field.type}
name={field.name}
/>
</div>
))}
</div> </div>
<button
type="submit" <div className="flex flex-col lg:flex-row mt-0 mx-5 my-5 gap-8">
disabled={isSubmitting} {/* Profile Information Section */}
className="mt-6 px-6 py-3 text-white bg-black rounded-lg shadow-md hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500" <div className="flex-1 min-w-0 space-y-4">
> <div>
Submit <Label htmlFor="email">Email</Label>
</button> <Input
</Form> id="email"
<div className="flex-1 min-w-0"> name="email"
<div className="flex flex-col items-center space-y-4"> type="email"
<label className="font-bold">Avatar</label> value={values.email}
{error && ( onChange={handleChange}
<div className="flex items-center bg-red-200 rounded-md text-red-950 px-4 py-2 text-sm"> placeholder="Your email address"
<FileWarning size={16} className="mr-2" /> />
<span className="font-semibold first-letter:uppercase">{error}</span> {touched.email && errors.email && (
</div> <p className="text-red-500 text-sm mt-1">{errors.email}</p>
)}
{success && (
<div className="flex items-center bg-green-200 rounded-md text-green-950 px-4 py-2 text-sm">
<Check size={16} className="mr-2" />
<span className="font-semibold first-letter:uppercase">{success}</span>
</div>
)}
<div className="w-full max-w-xs bg-gray-50 rounded-xl outline outline-1 outline-gray-200 shadow p-6">
<div className="flex flex-col items-center space-y-4">
{localAvatar ? (
<UserAvatar
border="border-8"
width={100}
avatar_url={URL.createObjectURL(localAvatar)}
/>
) : (
<UserAvatar border="border-8" width={100} />
)} )}
{isLoading ? ( {values.email !== session.data.user.email && (
<div className="font-bold animate-pulse antialiased bg-green-200 text-gray text-sm rounded-md px-4 py-2 flex items-center"> <div className="flex items-center space-x-2 mt-2 text-amber-600 bg-amber-50 p-2 rounded-md">
<ArrowBigUpDash size={16} className="mr-2" /> <AlertTriangle size={16} />
<span>Uploading</span> <span className="text-sm">You will be logged out after changing your email</span>
</div> </div>
) : ( )}
<> </div>
<input
type="file" <div>
id="fileInput" <Label htmlFor="username">Username</Label>
accept={SUPPORTED_FILES} <Input
className="hidden" id="username"
onChange={handleFileChange} name="username"
/> value={values.username}
<button onChange={handleChange}
className="font-bold antialiased text-gray text-sm rounded-md px-4 py-2 flex items-center" placeholder="Your username"
onClick={() => document.getElementById('fileInput')?.click()} />
> {touched.username && errors.username && (
<UploadCloud size={16} className="mr-2" /> <p className="text-red-500 text-sm mt-1">{errors.username}</p>
<span>Change Avatar</span> )}
</button> </div>
</>
<div>
<Label htmlFor="first_name">First Name</Label>
<Input
id="first_name"
name="first_name"
value={values.first_name}
onChange={handleChange}
placeholder="Your first name"
/>
{touched.first_name && errors.first_name && (
<p className="text-red-500 text-sm mt-1">{errors.first_name}</p>
)}
</div>
<div>
<Label htmlFor="last_name">Last Name</Label>
<Input
id="last_name"
name="last_name"
value={values.last_name}
onChange={handleChange}
placeholder="Your last name"
/>
{touched.last_name && errors.last_name && (
<p className="text-red-500 text-sm mt-1">{errors.last_name}</p>
)}
</div>
<div>
<Label htmlFor="bio">
Bio
<span className="text-gray-500 text-sm ml-2">
({400 - (values.bio?.length || 0)} characters left)
</span>
</Label>
<Textarea
id="bio"
name="bio"
value={values.bio}
onChange={handleChange}
placeholder="Tell us about yourself"
className="min-h-[150px]"
maxLength={400}
/>
{touched.bio && errors.bio && (
<p className="text-red-500 text-sm mt-1">{errors.bio}</p>
)} )}
</div> </div>
</div> </div>
<div className="flex items-center text-xs text-gray-500">
<Info size={13} className="mr-2" /> {/* Profile Picture Section */}
<p>Recommended size 100x100</p> <div className="lg:w-80 w-full">
<div className="bg-gray-50/50 p-6 rounded-lg nice-shadow h-full">
<div className="flex flex-col items-center space-y-6">
<Label className="font-bold">Profile Picture</Label>
{error && (
<div className="flex items-center bg-red-200 rounded-md text-red-950 px-4 py-2 text-sm">
<FileWarning size={16} className="mr-2" />
<span className="font-semibold first-letter:uppercase">{error}</span>
</div>
)}
{success && (
<div className="flex items-center bg-green-200 rounded-md text-green-950 px-4 py-2 text-sm">
<Check size={16} className="mr-2" />
<span className="font-semibold first-letter:uppercase">{success}</span>
</div>
)}
{localAvatar ? (
<UserAvatar
border="border-8"
width={120}
avatar_url={URL.createObjectURL(localAvatar)}
/>
) : (
<UserAvatar border="border-8" width={120} />
)}
{isLoading ? (
<div className="font-bold animate-pulse antialiased bg-green-200 text-gray text-sm rounded-md px-4 py-2 flex items-center">
<ArrowBigUpDash size={16} className="mr-2" />
<span>Uploading</span>
</div>
) : (
<>
<input
type="file"
id="fileInput"
accept={SUPPORTED_FILES}
className="hidden"
onChange={handleFileChange}
/>
<Button
type="button"
variant="outline"
onClick={() => document.getElementById('fileInput')?.click()}
className="w-full"
>
<UploadCloud size={16} className="mr-2" />
Change Avatar
</Button>
</>
)}
<div className="flex items-center text-xs text-gray-500">
<Info size={13} className="mr-2" />
<p>Recommended size 100x100</p>
</div>
</div>
</div>
</div> </div>
</div> </div>
<div className="flex flex-row-reverse mt-0 mx-5 mb-5">
<Button
type="submit"
disabled={isSubmitting}
className="bg-black text-white hover:bg-black/90"
>
{isSubmitting ? 'Saving...' : 'Save Changes'}
</Button>
</div>
</div> </div>
</div> </Form>
)} )}
</Formik> </Formik>
)} )}

View file

@ -1,61 +1,134 @@
import { useLHSession } from '@components/Contexts/LHSessionContext' import { useLHSession } from '@components/Contexts/LHSessionContext'
import { updatePassword } from '@services/settings/password' import { updatePassword } from '@services/settings/password'
import { Formik, Form, Field } from 'formik' import { Formik, Form } from 'formik'
import React, { useEffect } from 'react' import React, { useEffect } from 'react'
import { AlertTriangle } from 'lucide-react'
import { Input } from "@components/ui/input"
import { Button } from "@components/ui/button"
import { Label } from "@components/ui/label"
import { toast } from 'react-hot-toast'
import { signOut } from 'next-auth/react'
import { getUriWithoutOrg } from '@services/config/config'
import * as Yup from 'yup'
const validationSchema = Yup.object().shape({
old_password: Yup.string().required('Current password is required'),
new_password: Yup.string()
.required('New password is required')
.min(8, 'Password must be at least 8 characters'),
})
function UserEditPassword() { function UserEditPassword() {
const session = useLHSession() as any const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token; const access_token = session?.data?.tokens?.access_token;
const updatePasswordUI = async (values: any) => { const updatePasswordUI = async (values: any) => {
let user_id = session.data.user.id const loadingToast = toast.loading('Updating password...')
await updatePassword(user_id, values, access_token) try {
let user_id = session.data.user.id
const response = await updatePassword(user_id, values, access_token)
if (response.success) {
toast.dismiss(loadingToast)
// Show success message and notify about logout
toast.success('Password updated successfully', { duration: 4000 })
toast((t) => (
<div className="flex items-center gap-2">
<span>Please login again with your new password</span>
</div>
), {
duration: 4000,
icon: '🔑'
})
// Wait for 4 seconds before signing out
await new Promise(resolve => setTimeout(resolve, 4000))
signOut({ redirect: true, callbackUrl: getUriWithoutOrg('/') })
} else {
toast.error(response.data.detail || 'Failed to update password', { id: loadingToast })
}
} catch (error: any) {
const errorMessage = error.data?.detail || 'Failed to update password. Please try again.'
toast.error(errorMessage, { id: loadingToast })
console.error('Password update error:', error)
}
} }
useEffect(() => { }, [session]) useEffect(() => { }, [session])
return ( return (
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-6 py-5"> <div className="sm:mx-10 mx-0 bg-white rounded-xl nice-shadow">
<Formik <div className="flex flex-col">
initialValues={{ old_password: '', new_password: '' }} <div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 mx-3 my-3 rounded-md">
enableReinitialize <h1 className="font-bold text-xl text-gray-800">
onSubmit={(values, { setSubmitting }) => { Change Password
setTimeout(() => { </h1>
setSubmitting(false) <h2 className="text-gray-500 text-md">
updatePasswordUI(values) Update your password to keep your account secure
}, 400) </h2>
}} </div>
>
{({ isSubmitting }) => (
<Form className="max-w-md">
<label className="block mb-2 font-bold" htmlFor="old_password">
Old Password
</label>
<Field
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type="password"
name="old_password"
/>
<label className="block mb-2 font-bold" htmlFor="new_password"> <div className="px-8 py-6">
New Password <Formik
</label> initialValues={{ old_password: '', new_password: '' }}
<Field validationSchema={validationSchema}
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" onSubmit={(values, { setSubmitting }) => {
type="password" setTimeout(() => {
name="new_password" setSubmitting(false)
/> updatePasswordUI(values)
}, 400)
}}
>
{({ isSubmitting, handleChange, errors, touched }) => (
<Form className="w-full max-w-2xl mx-auto space-y-6">
<div>
<Label htmlFor="old_password">Current Password</Label>
<Input
type="password"
id="old_password"
name="old_password"
onChange={handleChange}
className="mt-1"
/>
{touched.old_password && errors.old_password && (
<p className="text-red-500 text-sm mt-1">{errors.old_password}</p>
)}
</div>
<button <div>
type="submit" <Label htmlFor="new_password">New Password</Label>
disabled={isSubmitting} <Input
className="px-6 py-3 text-white bg-black rounded-lg shadow-md hover:bg-black focus:outline-none focus:ring-2 focus:ring-blue-500" type="password"
> id="new_password"
Submit name="new_password"
</button> onChange={handleChange}
</Form> className="mt-1"
)} />
</Formik> {touched.new_password && errors.new_password && (
<p className="text-red-500 text-sm mt-1">{errors.new_password}</p>
)}
</div>
<div className="flex items-center space-x-2 text-amber-600 bg-amber-50 p-3 rounded-md">
<AlertTriangle size={16} />
<span className="text-sm">You will be logged out after changing your password</span>
</div>
<div className="flex justify-end pt-2">
<Button
type="submit"
disabled={isSubmitting}
className="bg-black text-white hover:bg-black/90"
>
{isSubmitting ? 'Updating...' : 'Update Password'}
</Button>
</div>
</Form>
)}
</Formik>
</div>
</div>
</div> </div>
) )
} }

View file

@ -2,6 +2,7 @@ import { getAPIUrl } from '@services/config/config'
import { import {
RequestBodyWithAuthHeader, RequestBodyWithAuthHeader,
errorHandling, errorHandling,
getResponseMetadata,
} from '@services/utils/ts/requests' } from '@services/utils/ts/requests'
/* /*
@ -18,6 +19,6 @@ export async function updatePassword(
`${getAPIUrl()}users/change_password/` + user_id, `${getAPIUrl()}users/change_password/` + user_id,
RequestBodyWithAuthHeader('PUT', data, null, access_token) RequestBodyWithAuthHeader('PUT', data, null, access_token)
) )
const res = await errorHandling(result) const res = await getResponseMetadata(result)
return res return res
} }