feat: email resetting frontend code

This commit is contained in:
swve 2024-03-19 21:51:26 +01:00
parent 15677a6946
commit 1987e56b9a
9 changed files with 451 additions and 5 deletions

View file

@ -25,11 +25,12 @@ def send_account_creation_email(
def send_password_reset_email(
reset_email_invite_uuid: str,
generated_reset_code: str,
user: UserRead,
organization: OrganizationRead,
email: EmailStr,
):
# send email
return send_email(
to=email,
@ -38,7 +39,7 @@ def send_password_reset_email(
<html>
<body>
<p>Hello {user.username}</p>
<p>Click <a href="https://{organization.slug}.learnhouse.io/reset-password?resetEmailInviteUuid={reset_email_invite_uuid}">here</a> to reset your password.</p>
<p>Click <a href="https://{organization.slug}.learnhouse.io/reset?email={email}&resetCode={generated_reset_code}">here</a> to reset your password.</p>
</body>
</html>
""",

View file

@ -99,7 +99,7 @@ async def send_reset_password_code(
# Send reset code via email
isEmailSent = send_password_reset_email(
reset_email_invite_uuid=reset_email_invite_uuid,
generated_reset_code=generated_reset_code,
user=user,
organization=org,
email=user.email,
@ -132,7 +132,7 @@ async def change_password_with_reset_code(
status_code=400,
detail="User does not exist",
)
# Get org
statement = select(Organization).where(Organization.id == org_id)
org = db_session.exec(statement).first()
@ -142,7 +142,6 @@ async def change_password_with_reset_code(
status_code=400,
detail="Organization not found",
)
# Redis init
LH_CONFIG = get_learnhouse_config()

View file

@ -1,8 +1,13 @@
import SessionProvider from '@components/Contexts/SessionContext'
import LeftMenu from '@components/Dashboard/UI/LeftMenu'
import AdminAuthorization from '@components/Security/AdminAuthorization'
import { Metadata } from 'next'
import React from 'react'
export const metadata: Metadata = {
title: 'LearnHouse Dashboard',
}
function DashboardLayout({
children,
params,

View file

@ -0,0 +1,156 @@
'use client'
import Image from 'next/image'
import React from 'react'
import learnhouseIcon from 'public/learnhouse_bigicon_1.png'
import FormLayout, {
FormField,
FormLabelAndMessage,
Input,
} from '@components/StyledElements/Form/Form'
import * as Form from '@radix-ui/react-form'
import { getOrgLogoMediaDirectory } from '@services/media/media'
import { AlertTriangle, Info } from 'lucide-react'
import Link from 'next/link'
import { getUriWithOrg } from '@services/config/config'
import { useOrg } from '@components/Contexts/OrgContext'
import { useRouter } from 'next/navigation'
import { useFormik } from 'formik'
import { sendResetLink } from '@services/auth/auth'
const validate = (values: any) => {
const errors: any = {}
if (!values.email) {
errors.email = 'Required'
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
return errors
}
function ForgotPasswordClient() {
const org = useOrg() as any;
const [isSubmitting, setIsSubmitting] = React.useState(false)
const router = useRouter()
const [error, setError] = React.useState('')
const [message, setMessage] = React.useState('')
const formik = useFormik({
initialValues: {
email: ''
},
validate,
onSubmit: async (values) => {
setIsSubmitting(true)
let res = await sendResetLink(values.email, org?.id)
if (res.status == 200) {
setMessage(res.data + ', please check your email')
setIsSubmitting(false)
} else {
setError(res.data.detail)
setIsSubmitting(false)
}
},
})
return (
<div className="grid grid-flow-col justify-stretch h-screen">
<div
className="right-login-part"
style={{
background:
'linear-gradient(041.61deg, #202020 7.15%, #000000 90.96%)',
}}
>
<div className="login-topbar m-10">
<Link prefetch href={getUriWithOrg(org?.slug, '/')}>
<Image
quality={100}
width={30}
height={30}
src={learnhouseIcon}
alt=""
/>
</Link>
</div>
<div className="ml-10 h-4/6 flex flex-row text-white">
<div className="m-auto flex space-x-4 items-center flex-wrap">
<div className="shadow-[0px_4px_16px_rgba(0,0,0,0.02)]">
{org?.logo_image ? (
<img
src={`${getOrgLogoMediaDirectory(
org?.org_uuid,
org?.logo_image
)}`}
alt="Learnhouse"
style={{ width: 'auto', height: 70 }}
className="rounded-xl shadow-xl inset-0 ring-1 ring-inset ring-black/10 bg-white"
/>
) : (
<Image
quality={100}
width={70}
height={70}
src={learnhouseIcon}
alt=""
/>
)}
</div>
<div className="font-bold text-xl">{org?.name}</div>
</div>
</div>
</div>
<div className="left-login-part bg-white flex flex-row">
<div className="login-form m-auto w-72">
<h1 className="text-2xl font-bold mb-4">Forgot Password</h1>
<p className="text-sm mb-4">
Enter your email address and we will send you a link to reset your
password
</p>
{error && (
<div className="flex justify-center bg-red-200 rounded-md text-red-950 space-x-2 items-center p-4 transition-all shadow-sm">
<AlertTriangle size={18} />
<div className="font-bold text-sm">{error}</div>
</div>
)}
{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">
<Info size={18} />
<div className="font-bold text-sm">{message}</div>
</div>
)}
<FormLayout onSubmit={formik.handleSubmit}>
<FormField name="email">
<FormLabelAndMessage
label="Email"
message={formik.errors.email}
/>
<Form.Control asChild>
<Input
onChange={formik.handleChange}
value={formik.values.email}
type="email"
required
/>
</Form.Control>
</FormField>
<div className="flex py-4">
<Form.Submit asChild>
<button className="w-full bg-black text-white font-bold text-center p-2 rounded-md shadow-md hover:cursor-pointer">
{isSubmitting ? 'Loading...' : 'Send Reset Link'}
</button>
</Form.Submit>
</div>
</FormLayout>
</div>
</div>
</div>
)
}
export default ForgotPasswordClient

View file

@ -0,0 +1,17 @@
import React from 'react'
import ForgotPasswordClient from './forgot'
import { Metadata } from 'next'
export const metadata: Metadata = {
title: 'LearnHouse - Forgot Password',
}
function ForgotPasswordPage() {
return (
<>
<ForgotPasswordClient />
</>
)
}
export default ForgotPasswordPage

View file

@ -156,6 +156,15 @@ const LoginClient = (props: LoginClientProps) => {
/>
</Form.Control>
</FormField>
<div>
<Link
href={getUriWithOrg(props.org.slug, '/forgot')}
passHref
className="text-xs text-gray-500 hover:underline"
>
Forgot password?
</Link>
</div>
<div className="flex py-4">
<Form.Submit asChild>

View file

@ -0,0 +1,15 @@
import { Metadata } from 'next'
import React from 'react'
import ResetPasswordClient from './reset'
export const metadata: Metadata = {
title: 'LearnHouse - Reset Password',
}
function ResetPasswordPage() {
return (
<ResetPasswordClient />
)
}
export default ResetPasswordPage

View file

@ -0,0 +1,220 @@
'use client'
import Image from 'next/image'
import React from 'react'
import learnhouseIcon from 'public/learnhouse_bigicon_1.png'
import FormLayout, {
FormField,
FormLabelAndMessage,
Input,
} from '@components/StyledElements/Form/Form'
import * as Form from '@radix-ui/react-form'
import { getOrgLogoMediaDirectory } from '@services/media/media'
import { AlertTriangle, Info } from 'lucide-react'
import Link from 'next/link'
import { getUriWithOrg } from '@services/config/config'
import { useOrg } from '@components/Contexts/OrgContext'
import { useRouter, useSearchParams } from 'next/navigation'
import { useFormik } from 'formik'
import { resetPassword, sendResetLink } from '@services/auth/auth'
const validate = (values: any) => {
const errors: any = {}
if (!values.email) {
errors.email = 'Required'
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
if (!values.new_password) {
errors.new_password = 'Required'
}
if (!values.confirm_password) {
errors.confirm_password = 'Required'
}
if (values.new_password !== values.confirm_password) {
errors.confirm_password = 'Passwords do not match'
}
if (!values.reset_code) {
errors.reset_code = 'Required'
}
return errors
}
function ResetPasswordClient() {
const org = useOrg() as any;
const [isSubmitting, setIsSubmitting] = React.useState(false)
const searchParams = useSearchParams()
const reset_code = searchParams.get('resetCode') || ''
const email = searchParams.get('email') || ''
const router = useRouter()
const [error, setError] = React.useState('')
const [message, setMessage] = React.useState('')
const formik = useFormik({
initialValues: {
email: email,
new_password: '',
confirm_password: '',
reset_code: reset_code
},
validate,
enableReinitialize: true,
onSubmit: async (values) => {
setIsSubmitting(true)
let res = await resetPassword(values.email, values.new_password, org?.id, values.reset_code)
if (res.status == 200) {
setMessage(res.data + ', please login')
setIsSubmitting(false)
} else {
setError(res.data.detail)
setIsSubmitting(false)
}
},
})
return (
<div className="grid grid-flow-col justify-stretch h-screen">
<div
className="right-login-part"
style={{
background:
'linear-gradient(041.61deg, #202020 7.15%, #000000 90.96%)',
}}
>
<div className="login-topbar m-10">
<Link prefetch href={getUriWithOrg(org?.slug, '/')}>
<Image
quality={100}
width={30}
height={30}
src={learnhouseIcon}
alt=""
/>
</Link>
</div>
<div className="ml-10 h-4/6 flex flex-row text-white">
<div className="m-auto flex space-x-4 items-center flex-wrap">
<div className="shadow-[0px_4px_16px_rgba(0,0,0,0.02)]">
{org?.logo_image ? (
<img
src={`${getOrgLogoMediaDirectory(
org?.org_uuid,
org?.logo_image
)}`}
alt="Learnhouse"
style={{ width: 'auto', height: 70 }}
className="rounded-xl shadow-xl inset-0 ring-1 ring-inset ring-black/10 bg-white"
/>
) : (
<Image
quality={100}
width={70}
height={70}
src={learnhouseIcon}
alt=""
/>
)}
</div>
<div className="font-bold text-xl">{org?.name}</div>
</div>
</div>
</div>
<div className="left-login-part bg-white flex flex-row">
<div className="login-form m-auto w-72">
<h1 className="text-2xl font-bold mb-4">Reset Password</h1>
<p className="text-sm mb-4">
Enter your email and reset code to reset your password
</p>
{error && (
<div className="flex justify-center bg-red-200 rounded-md text-red-950 space-x-2 items-center p-4 transition-all shadow-sm">
<AlertTriangle size={18} />
<div className="font-bold text-sm">{error}</div>
</div>
)}
{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">
<Info size={18} />
<div className="font-bold text-sm">{message}</div>
</div>
)}
<FormLayout onSubmit={formik.handleSubmit}>
<FormField name="email">
<FormLabelAndMessage
label="Email"
message={formik.errors.email}
/>
<Form.Control asChild>
<Input
onChange={formik.handleChange}
value={formik.values.email}
type="email"
/>
</Form.Control>
</FormField>
<FormField name="reset_code">
<FormLabelAndMessage
label="Reset Code"
message={formik.errors.reset_code}
/>
<Form.Control asChild>
<Input
onChange={formik.handleChange}
value={formik.values.reset_code}
type="text"
/>
</Form.Control>
</FormField>
<FormField name="new_password">
<FormLabelAndMessage
label="New Password"
message={formik.errors.new_password}
/>
<Form.Control asChild>
<Input
onChange={formik.handleChange}
value={formik.values.new_password}
type="password"
/>
</Form.Control>
</FormField>
<FormField name="confirm_password">
<FormLabelAndMessage
label="Confirm Password"
message={formik.errors.confirm_password}
/>
<Form.Control asChild>
<Input
onChange={formik.handleChange}
value={formik.values.confirm_password}
type="password"
/>
</Form.Control>
</FormField>
<div className="flex py-4">
<Form.Submit asChild>
<button className="w-full bg-black text-white font-bold text-center p-2 rounded-md shadow-md hover:cursor-pointer">
{isSubmitting ? 'Loading...' : 'Change Password'}
</button>
</Form.Submit>
</div>
</FormLayout>
</div>
</div>
</div>
)
}
export default ResetPasswordClient

View file

@ -1,4 +1,5 @@
import { getAPIUrl } from '@services/config/config'
import { RequestBody, getResponseMetadata } from '@services/utils/ts/requests'
interface LoginAndGetTokenResponse {
access_token: 'string'
@ -36,6 +37,29 @@ export async function loginAndGetToken(
return response
}
export async function sendResetLink(email: string, org_id: number) {
const result = await fetch(
`${getAPIUrl()}users/reset_password/send_reset_code/${email}?org_id=${org_id}`,
RequestBody('POST', null, null)
)
const res = await getResponseMetadata(result)
return res
}
export async function resetPassword(
email: string,
new_password: string,
org_id: number,
reset_code: string
) {
const result = await fetch(
`${getAPIUrl()}users/reset_password/change_password/${email}?reset_code=${reset_code}&new_password=${new_password}&org_id=${org_id}`,
RequestBody('POST', null, null)
)
const res = await getResponseMetadata(result)
return res
}
export async function logout(): Promise<any> {
// Request Config