feat: major login and signup changes

This commit is contained in:
swve 2024-06-04 23:12:01 +01:00
parent 5ca1ba75e1
commit 2ae8dbeba5
20 changed files with 217 additions and 141 deletions

View file

@ -1,70 +0,0 @@
import { LEARNHOUSE_TOP_DOMAIN } from '@services/config/config'
const cookiePrefix = '__LRN-'
const cookieDomain =
LEARNHOUSE_TOP_DOMAIN == `.${LEARNHOUSE_TOP_DOMAIN}`
const cookieSecure = LEARNHOUSE_TOP_DOMAIN == 'localhost' ? true : true
const cookieSameSite = LEARNHOUSE_TOP_DOMAIN == 'localhost' ? 'lax' : 'None'
export const cookiesOptions = {
sessionToken: {
name: `__Secure-next-auth.session-token`,
options: {
domain: cookieDomain,
httpOnly: true,
sameSite: cookieSameSite,
path: '/',
secure: cookieSecure,
},
},
callbackUrl: {
name: `__Secure-next-auth.callback-url`,
options: {
domain: cookieDomain,
httpOnly: true,
sameSite: cookieSameSite,
path: '/',
secure: cookieSecure,
},
},
csrfToken: {
name: `__Host-next-auth.csrf-token`,
options: {
domain: cookieDomain,
httpOnly: true,
sameSite: cookieSameSite,
path: '/',
secure: cookieSecure,
},
},
pkceCodeVerifier: {
name: `${cookiePrefix}next-auth.pkce.code_verifier`,
options: {
domain: cookieDomain,
httpOnly: true,
sameSite: cookieSameSite,
path: '/',
secure: cookieSecure,
},
},
state: {
name: `${cookiePrefix}next-auth.state`,
options: {
domain: cookieDomain,
httpOnly: true,
sameSite: cookieSameSite,
path: '/',
secure: cookieSecure,
},
},
nonce: {
name: `${cookiePrefix}next-auth.nonce`,
options: {
domain: cookieDomain,
httpOnly: true,
sameSite: cookieSameSite,
path: '/',
secure: cookieSecure,
},
},
}

View file

@ -0,0 +1,19 @@
'use client'
import { OrgProvider } from '@components/Contexts/OrgContext'
import ErrorUI from '@components/StyledElements/Error/Error'
import { useSearchParams } from 'next/navigation'
export default function AuthLayout({
children,
}: {
children: React.ReactNode
}) {
const searchParams = useSearchParams()
const orgslug = searchParams.get('orgslug')
if (orgslug) {
return <OrgProvider orgslug={orgslug}>{children}</OrgProvider>
} else {
return <ErrorUI message='Organization not specified' submessage='Please access this page from an Organization' />
}
}

View file

@ -8,7 +8,6 @@ import { LEARNHOUSE_TOP_DOMAIN, getUriWithOrg } from '@services/config/config'
import { getResponseMetadata } from '@services/utils/ts/requests' import { getResponseMetadata } from '@services/utils/ts/requests'
import CredentialsProvider from 'next-auth/providers/credentials' import CredentialsProvider from 'next-auth/providers/credentials'
import GoogleProvider from 'next-auth/providers/google' import GoogleProvider from 'next-auth/providers/google'
import { cookiesOptions } from './cookies'
const isDevEnv = LEARNHOUSE_TOP_DOMAIN == 'localhost' ? true : false const isDevEnv = LEARNHOUSE_TOP_DOMAIN == 'localhost' ? true : false

View file

@ -9,10 +9,10 @@ type MetadataProps = {
searchParams: { [key: string]: string | string[] | undefined } searchParams: { [key: string]: string | string[] | undefined }
} }
export async function generateMetadata({ export async function generateMetadata(
params, params
}: MetadataProps): Promise<Metadata> { : MetadataProps): Promise<Metadata> {
const orgslug = params.orgslug const orgslug = params.searchParams.orgslug
// Get Org context information // Get Org context information
const org = await getOrganizationContextInfo(orgslug, { const org = await getOrganizationContextInfo(orgslug, {
revalidate: 0, revalidate: 0,
@ -25,7 +25,7 @@ export async function generateMetadata({
} }
const SignUp = async (params: any) => { const SignUp = async (params: any) => {
const orgslug = params.params.orgslug const orgslug = params.searchParams.orgslug
const org = await getOrganizationContextInfo(orgslug, { const org = await getOrganizationContextInfo(orgslug, {
revalidate: 0, revalidate: 0,
tags: ['organizations'], tags: ['organizations'],

View file

@ -69,7 +69,7 @@ function SignUpClient(props: SignUpClientProps) {
props.org.org_uuid, props.org.org_uuid,
props.org?.logo_image props.org?.logo_image
)}`} )}`}
alt="Learnhouse" alt="LearnHouse"
style={{ width: 'auto', height: 70 }} style={{ width: 'auto', height: 70 }}
className="rounded-xl shadow-xl inset-0 ring-1 ring-inset ring-black/10 bg-white" className="rounded-xl shadow-xl inset-0 ring-1 ring-inset ring-black/10 bg-white"
/> />
@ -161,7 +161,7 @@ const NoTokenScreen = (props: any) => {
"Invite code is valid, you'll be redirected to the signup page in a few seconds" "Invite code is valid, you'll be redirected to the signup page in a few seconds"
) )
setTimeout(() => { setTimeout(() => {
router.push(`/signup?inviteCode=${inviteCode}`) router.push(`/signup?inviteCode=${inviteCode}&orgslug=${org.slug}`)
}, 2000) }, 2000)
} else { } else {
toast.error('Invite code is invalid') toast.error('Invite code is invalid')

View file

@ -0,0 +1,57 @@
'use client'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import UserAvatar from '@components/Objects/UserAvatar';
import { getAPIUrl, getUriWithOrg, getUriWithoutOrg } from '@services/config/config';
import { swrFetcher } from '@services/utils/ts/requests';
import { ArrowRightCircle, Info } from 'lucide-react';
import { signOut } from 'next-auth/react';
import Image from 'next/image';
import Link from 'next/link';
import learnhouseIcon from 'public/learnhouse_bigicon_1.png'
import React, { useEffect } from 'react'
import useSWR from 'swr';
function HomeClient() {
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
const { data: orgs } = useSWR(`${getAPIUrl()}orgs/user/page/1/limit/10`, (url) => swrFetcher(url, access_token))
useEffect(() => {
console.log(orgs)
}, [session, orgs])
return (
<div className='flex flex-col'>
<div className='flex space-x-4 mx-auto font-semibold text-3xl pt-16 items-center bg-black rounded-b-2xl'>
<Image
quality={100}
width={60}
height={60}
src={learnhouseIcon}
alt=""
/>
</div>
<div className='flex space-x-4 mx-auto font-semibold text-2xl pt-16 items-center'><span>Hello,</span> <UserAvatar /> <span className='capitalize'>{session?.data?.user.first_name} {session?.data?.user.last_name}</span></div>
<div className='flex space-x-4 mx-auto font-semibold text-sm mt-12 items-center uppercase bg-slate-200 text-gray-600 px-3 py-2 rounded-md'>Your Organizations</div>
{orgs && orgs.length == 0 && <div className='flex mx-auto my-5 space-x-3 bg-rose-200 rounded-lg px-3 py-2'>
<Info />
<span>It seems you're not part of an organization yet, join one to be able to see it here </span>
</div>}
<div className='flex mx-auto pt-10 rounded-lg'>
{orgs && orgs.map((org: any) => (
<Link href={getUriWithOrg(org.slug, '/')} key={org.id} className='flex space-x-2 mx-auto w-fit justify-between items-center outline outline-1 outline-slate-200 px-3 py-2 rounded-lg'>
<div>{org.name}</div>
<ArrowRightCircle />
</Link>
))}
</div>
<div className='flex cursor-pointer space-x-4 mx-auto font-semibold text-2xl pt-16 items-center'><span onClick={() => signOut({ redirect: true, callbackUrl: getUriWithoutOrg('/') })}>Sign out</span></div>
</div>
)
}
export default HomeClient

View file

@ -0,0 +1,16 @@
import React from 'react'
import HomeClient from './home'
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Home',
}
function Home() {
return (
<div>
<HomeClient/>
</div>
)
}
export default Home

View file

@ -9,7 +9,6 @@ function LHSessionProvider({ children }: { children: React.ReactNode }) {
const session = useSession(); const session = useSession();
useEffect(() => { useEffect(() => {
console.log('useLHSession', session);
}, []) }, [])
@ -20,7 +19,6 @@ function LHSessionProvider({ children }: { children: React.ReactNode }) {
else if (session) { else if (session) {
return ( return (
<SessionContext.Provider value={session}> <SessionContext.Provider value={session}>
{console.log('rendered')}
{children} {children}
</SessionContext.Provider> </SessionContext.Provider>
) )

View file

@ -1,51 +1,48 @@
'use client' 'use client'
import { getAPIUrl } from '@services/config/config' import { getAPIUrl, getUriWithoutOrg } from '@services/config/config'
import { swrFetcher } from '@services/utils/ts/requests' import { swrFetcher } from '@services/utils/ts/requests'
import React, { useContext, useEffect, useState } from 'react' import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'
import useSWR from 'swr' import useSWR from 'swr'
import { createContext } from 'react'
import { useRouter } from 'next/navigation'
import { useLHSession } from '@components/Contexts/LHSessionContext' import { useLHSession } from '@components/Contexts/LHSessionContext'
import ErrorUI from '@components/StyledElements/Error/Error' import ErrorUI from '@components/StyledElements/Error/Error'
import InfoUI from '@components/StyledElements/Info/Info'
import { usePathname } from 'next/navigation'
export const OrgContext = createContext({}) as any export const OrgContext = createContext(null)
export function OrgProvider({ export function OrgProvider({ children, orgslug }: { children: React.ReactNode, orgslug: string }) {
children, const session = useLHSession() as any
orgslug, const pathname = usePathname()
}: { const accessToken = session?.data?.tokens?.access_token
children: React.ReactNode const isAllowedPathname = ['/login', '/signup'].includes(pathname);
orgslug: string
}) {
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
const { data: org } = useSWR(`${getAPIUrl()}orgs/slug/${orgslug}`, (url) => swrFetcher(url, access_token))
const [isLoading, setIsLoading] = useState(true);
const [isOrgActive, setIsOrgActive] = useState(true);
// Check if Org is Active const { data: org, error: orgError } = useSWR(
const verifyIfOrgIsActive = () => { `${getAPIUrl()}orgs/slug/${orgslug}`,
if (org && org?.config.config.GeneralConfig.active === false) { (url) => swrFetcher(url, accessToken)
setIsOrgActive(false) )
} const { data: orgs, error: orgsError } = useSWR(
else { `${getAPIUrl()}orgs/user/page/1/limit/10`,
setIsOrgActive(true) (url) => swrFetcher(url, accessToken)
} )
const isOrgActive = useMemo(() => org?.config?.config?.GeneralConfig?.active !== false, [org])
const isUserPartOfTheOrg = useMemo(() => orgs?.some((userOrg: any) => userOrg.id === org?.id), [orgs, org?.id])
if (orgError || orgsError) return <ErrorUI message='An error occurred while fetching data' />
if (!org || !orgs || !session) return <div>Loading...</div>
if (!isOrgActive) return <ErrorUI message='This organization is no longer active' />
if (!isUserPartOfTheOrg && session.status == 'authenticated' && !isAllowedPathname) {
return (
<InfoUI
href={getUriWithoutOrg(`/signup?orgslug=${orgslug}`)}
message='You are not part of this Organization'
cta={`Join ${org?.name}`}
/>
)
} }
useEffect(() => {
if (org && session) {
verifyIfOrgIsActive()
setIsLoading(false)
}
}, [org, session])
if (!isLoading) {
return <OrgContext.Provider value={org}>{children}</OrgContext.Provider> return <OrgContext.Provider value={org}>{children}</OrgContext.Provider>
}
if (!isOrgActive) {
return <ErrorUI message='This organization is no longer active' />
}
} }
export function useOrg() { export function useOrg() {

View file

@ -1,9 +1,11 @@
'use client' 'use client'
import { AlertTriangle, RefreshCcw } from 'lucide-react' import { getUriWithoutOrg } from '@services/config/config'
import { AlertTriangle, HomeIcon, RefreshCcw } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import React from 'react' import React from 'react'
function ErrorUI(params: { message?: string }) { function ErrorUI(params: { message?: string, submessage?: string }) {
const router = useRouter() const router = useRouter()
function reloadPage() { function reloadPage() {
@ -15,9 +17,12 @@ function ErrorUI(params: { message?: string }) {
<div className="flex flex-col py-10 mx-auto antialiased items-center space-y-6 bg-gradient-to-b from-rose-100 to-rose-100/5 "> <div className="flex flex-col py-10 mx-auto antialiased items-center space-y-6 bg-gradient-to-b from-rose-100 to-rose-100/5 ">
<div className="flex flex-row items-center space-x-5 rounded-xl "> <div className="flex flex-row items-center space-x-5 rounded-xl ">
<AlertTriangle className="text-rose-700" size={45} /> <AlertTriangle className="text-rose-700" size={45} />
<div className='flex flex-col'>
<p className="text-3xl font-bold text-rose-700">{params.message ? params.message : 'Something went wrong'}</p> <p className="text-3xl font-bold text-rose-700">{params.message ? params.message : 'Something went wrong'}</p>
<p className="text-lg font-bold text-rose-700">{params.submessage ? params.submessage : ''}</p>
</div> </div>
<div> </div>
<div className='flex space-x-4'>
<button <button
onClick={() => reloadPage()} onClick={() => reloadPage()}
className="flex space-x-2 items-center rounded-full px-4 py-1 text-rose-200 bg-rose-700 hover:bg-rose-800 transition-all ease-linear shadow-lg " className="flex space-x-2 items-center rounded-full px-4 py-1 text-rose-200 bg-rose-700 hover:bg-rose-800 transition-all ease-linear shadow-lg "
@ -25,6 +30,13 @@ function ErrorUI(params: { message?: string }) {
<RefreshCcw className="text-rose-200" size={17} /> <RefreshCcw className="text-rose-200" size={17} />
<span className="text-md font-bold">Retry</span> <span className="text-md font-bold">Retry</span>
</button> </button>
<Link
href={getUriWithoutOrg('/home')}
className="flex space-x-2 items-center rounded-full px-4 py-1 text-gray-200 bg-gray-700 hover:bg-gray-800 transition-all ease-linear shadow-lg "
>
<HomeIcon className="text-gray-200" size={17} />
<span className="text-md font-bold">Home</span>
</Link>
</div> </div>
</div> </div>
) )

View file

@ -0,0 +1,37 @@
'use client'
import { getUriWithoutOrg } from '@services/config/config'
import { AlertTriangle, Diamond, Home, PersonStanding, RefreshCcw } from 'lucide-react'
import Link from 'next/link'
import React from 'react'
function InfoUI(params: { message?: string, submessage?: string, cta?: string, href: string }) {
return (
<div className="flex flex-col py-10 mx-auto antialiased items-center space-y-6 bg-gradient-to-b from-yellow-100 to-yellow-100/5 ">
<div className="flex flex-row items-center space-x-5 rounded-xl ">
<Diamond className="text-yellow-700" size={45} />
<div className='flex flex-col'>
<p className="text-3xl font-bold text-yellow-700">{params.message ? params.message : 'Something went wrong'}</p>
<p className="text-lg font-bold text-yellow-700">{params.submessage ? params.submessage : ''}</p>
</div>
</div>
{params.cta && <div className='flex space-x-4'>
<Link
href={params.href}
className="flex space-x-2 items-center rounded-full px-4 py-1 text-yellow-200 bg-yellow-700 hover:bg-yellow-800 transition-all ease-linear shadow-lg "
>
<PersonStanding className="text-yellow-200" size={17} />
<span className="text-md font-bold">{params.cta}</span>
</Link>
<Link
href={getUriWithoutOrg('/home')}
className="flex space-x-2 items-center rounded-full px-4 py-1 text-gray-200 bg-gray-700 hover:bg-gray-800 transition-all ease-linear shadow-lg "
>
<Home className="text-gray-200" size={17} />
<span className="text-md font-bold">Home</span>
</Link>
</div>}
</div>
)
}
export default InfoUI

View file

@ -35,12 +35,24 @@ export default async function middleware(req: NextRequest) {
? fullhost.replace(`.${LEARNHOUSE_DOMAIN}`, '') ? fullhost.replace(`.${LEARNHOUSE_DOMAIN}`, '')
: (default_org as string) : (default_org as string)
// Out of orgslug paths & rewrite
const standard_paths = ['/home']
const auth_paths = ['/login', '/signup', '/reset']
if (standard_paths.includes(pathname)) {
// Redirect to the same pathname with the original search params
return NextResponse.rewrite(new URL(`${pathname}${search}`, req.url))
}
if (auth_paths.includes(pathname)) {
// Redirect to the same pathname with the original search params
return NextResponse.rewrite(new URL(`/auth${pathname}${search}`, req.url))
}
// Login // Login
if (orgslug == 'auth' || pathname.startsWith('/login')) { if (orgslug == 'auth' || pathname.startsWith('/login')) {
return NextResponse.rewrite(new URL(`/login${search}`, req.url)) return NextResponse.rewrite(new URL(`/login${search}`, req.url))
} }
// Install Page // Install Page (depreceated)
if (pathname.startsWith('/install')) { if (pathname.startsWith('/install')) {
// Check if install mode is enabled // Check if install mode is enabled
const install_mode = await isInstallModeEnabled() const install_mode = await isInstallModeEnabled()
@ -71,8 +83,7 @@ export default async function middleware(req: NextRequest) {
redirectUrl.search = queryString redirectUrl.search = queryString
} }
return NextResponse.redirect(redirectUrl) return NextResponse.redirect(redirectUrl)
} else{ } else {
} }
} }