Skip to content

Commit

Permalink
fix: Correctly redirect user to the request page (#116)
Browse files Browse the repository at this point in the history
* fix: Correctly redirect user to the request page

* fix: Redirect user to log in with redirect to when setting up

* fix: Use toSetupPage

* fix: Add getCurrentConnectionData function

* fix: Restore setup page redirect
  • Loading branch information
LautaroPetaccio authored May 3, 2024
1 parent 9b93830 commit c49b6a3
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 63 deletions.
18 changes: 5 additions & 13 deletions src/components/Pages/DefaultPage/DefaultPage.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,22 @@
import { useCallback, useEffect } from 'react'
import { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Loader } from 'decentraland-ui/dist/components/Loader/Loader'
import { connection } from 'decentraland-connect'
import { getCurrentConnectionData } from '../../../shared/connection'
import styles from './DefaultPage.module.css'

export const DefaultPage = () => {
const navigate = useNavigate()
const location = useLocation()
const checkIfConnected = useCallback(async () => {
try {
const connectionDetails = await connection.tryPreviousConnection()
return Boolean(connectionDetails.account && connectionDetails.provider)
} catch (error) {
return false
}
}, [])

useEffect(() => {
checkIfConnected().then(isConnected => {
if (isConnected) {
getCurrentConnectionData().then(connectionData => {
if (connectionData) {
window.location.href = '/'
} else {
navigate({ pathname: '/login', search: location.search })
}
})
}, [checkIfConnected, navigate])
}, [getCurrentConnectionData, navigate])

return (
<div className={styles.main}>
Expand Down
36 changes: 23 additions & 13 deletions src/components/Pages/RequestPage/RequestPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { getAnalytics } from '../../../modules/analytics/segment'
import { ClickEvents, TrackingEvents } from '../../../modules/analytics/types'
import { config } from '../../../modules/config'
import { fetchProfile } from '../../../modules/profile'
import { getCurrentConnectionData } from '../../../shared/connection'
import { isErrorWithMessage, isRpcError } from '../../../shared/errors'
import { CustomWearablePreview } from '../../CustomWearablePreview'
import styles from './RequestPage.module.css'
Expand Down Expand Up @@ -56,31 +57,37 @@ export const RequestPage = () => {
// Goes to the login page where the user will have to connect a wallet.
const toLoginPage = useCallback(() => {
navigate(`/login?redirectTo=${encodeURIComponent(`/auth/requests/${requestId}?targetConfigId=${targetConfigId}`)}`)
}, [])
}, [requestId, targetConfigId])

const toSetupPage = useCallback(() => {
navigate(`/setup?redirectTo=${encodeURIComponent(`/auth/requests/${requestId}?targetConfigId=${targetConfigId}`)}`)
}, [requestId, targetConfigId])

useEffect(() => {
;(async () => {
try {
// Try to restablish connection with the wallet.
const connectionData = await connection.tryPreviousConnection()
providerRef.current = new ethers.BrowserProvider(connectionData.provider)

// Try to re-stablish connection with the wallet.
const connectionData = await getCurrentConnectionData()
// Goes to the login page if no account is returned in the data.
if (!connectionData.account) {
if (!connectionData) {
throw new Error('No account connected')
}
const provider = await connection.getProvider()
providerRef.current = new ethers.BrowserProvider(provider)

const profile = await fetchProfile(connectionData.account)

// `alternative` has its own set up
if (!targetConfig.skipSetup) {
// Goes to the setup page if the connected account does not have a profile yet.
if (!profile) {
navigate(`/setup?redirectTo=/auth/requests/${requestId}`)
console.log("There's no profile but the user is logged in, going to setup page")
toSetupPage()
return
}
}
} catch (e) {
console.log("The user isn't logged in, redirecting to the log in page")
toLoginPage()
return
}
Expand Down Expand Up @@ -123,7 +130,7 @@ export const RequestPage = () => {
return () => {
clearTimeout(timeoutRef.current)
}
}, [])
}, [toLoginPage, toSetupPage])

useEffect(() => {
// The timeout is only necessary on the verify sign in and wallet interaction views.
Expand Down Expand Up @@ -240,11 +247,14 @@ export const RequestPage = () => {
}
}, [])

const onChangeAccount = useCallback(async evt => {
evt.preventDefault()
await connection.disconnect()
toLoginPage()
}, [])
const onChangeAccount = useCallback(
async evt => {
evt.preventDefault()
await connection.disconnect()
toLoginPage()
},
[toLoginPage]
)

const Container = useCallback(
(props: { children: ReactNode; canChangeAccount?: boolean; isLoading?: boolean }) => {
Expand Down
53 changes: 16 additions & 37 deletions src/components/Pages/SetupPage/SetupPage.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import classNames from 'classnames'
import { AuthIdentity } from '@dcl/crypto'
import { localStorageGetIdentity } from '@dcl/single-sign-on-client'
import { Button } from 'decentraland-ui/dist/components/Button/Button'
import { Checkbox } from 'decentraland-ui/dist/components/Checkbox/Checkbox'
import { Field } from 'decentraland-ui/dist/components/Field/Field'
import { Loader } from 'decentraland-ui/dist/components/Loader/Loader'
import { Mobile, NotMobile } from 'decentraland-ui/dist/components/Media/Media'
import { connection } from 'decentraland-connect'
import { InputOnChangeData } from 'decentraland-ui'
import backImg from '../../../assets/images/back.svg'
import diceImg from '../../../assets/images/dice.svg'
Expand All @@ -17,6 +15,7 @@ import { useAfterLoginRedirection } from '../../../hooks/redirection'
import { getAnalytics } from '../../../modules/analytics/segment'
import { ClickEvents, TrackingEvents } from '../../../modules/analytics/types'
import { fetchProfile } from '../../../modules/profile'
import { getCurrentConnectionData } from '../../../shared/connection'
import { CustomWearablePreview } from '../../CustomWearablePreview'
import { FeatureFlagsContext, FeatureFlagsKeys } from '../../FeatureFlagsProvider'
import { deployProfileFromDefault, subscribeToNewsletter } from './utils'
Expand All @@ -31,7 +30,7 @@ function getRandomDefaultProfile() {
return 'default' + (Math.floor(Math.random() * (160 - 1 + 1)) + 1)
}

const Error = (props: { message: string; className?: string }) => {
const ErrorMessage = (props: { message: string; className?: string }) => {
return (
<div className={classNames(styles.error, props.className)}>
<img src={wrongImg} />
Expand Down Expand Up @@ -226,33 +225,24 @@ export const SetupPage = () => {
useEffect(() => {
;(async () => {
const toLogin = () => {
window.location.href = '/auth/login'
window.location.href = `/auth/login${redirectTo ? `?redirectTo=${redirectTo}` : ''}`
}

// Check if the wallet is connected.
try {
await connection.tryPreviousConnection()
const connectionData = await getCurrentConnectionData()
if (!connectionData) {
throw new Error('No connection data found')
}
accountRef.current = connectionData.account
identityRef.current = connectionData.identity
} catch (e) {
console.warn('No previous connection found')
toLogin()
return
}

const provider = await connection.getProvider()
const accounts = (await provider.request({ method: 'eth_accounts' })) as string[]

// Check that there is at least one account connected.
if (!accounts.length) {
console.warn('No accounts found')
toLogin()
return
}

const account = accounts[0]

accountRef.current = account

const profile = await fetchProfile(account)
const profile = await fetchProfile(accountRef.current)

// Check that the connected account does not have a profile already.
if (profile) {
Expand All @@ -268,17 +258,6 @@ export const SetupPage = () => {
return
}

const identity = localStorageGetIdentity(account)

// Check that the connected account has an identity.
if (!identity) {
console.warn('No identity found for the connected account')
toLogin()
return
}

identityRef.current = identity

setInitialized(true)
})()
}, [redirectTo])
Expand Down Expand Up @@ -384,7 +363,7 @@ export const SetupPage = () => {
label="Username"
placeholder="Enter your Username"
onChange={handleNameChange}
message={showErrors && nameError ? <Error message={nameError} /> : undefined}
message={showErrors && nameError ? <ErrorMessage message={nameError} /> : undefined}
/>
</div>
<div>
Expand All @@ -393,7 +372,7 @@ export const SetupPage = () => {
placeholder="Enter your email"
message={
<>
{showErrors && emailError ? <Error className={styles.emailError} message={emailError} /> : null}
{showErrors && emailError ? <ErrorMessage className={styles.emailError} message={emailError} /> : null}
<span>
Subscribe to Decentraland's newsletter to receive the latest news about events, updates, contests and more.
</span>
Expand All @@ -416,7 +395,7 @@ export const SetupPage = () => {
.
</div>
</div>
{showErrors && agreeError ? <Error className={styles.agreeError} message={agreeError} /> : null}
{showErrors && agreeError ? <ErrorMessage className={styles.agreeError} message={agreeError} /> : null}
<div className={styles.jumpIn}>
<Button primary fluid type="submit" disabled={!agree || deploying} loading={deploying}>
{continueMessage}
Expand All @@ -443,7 +422,7 @@ export const SetupPage = () => {
label="Username"
placeholder="Enter your username"
onChange={handleNameChange}
message={showErrors && nameError ? <Error message={nameError} /> : undefined}
message={showErrors && nameError ? <ErrorMessage message={nameError} /> : undefined}
/>
</div>
<div>
Expand All @@ -452,7 +431,7 @@ export const SetupPage = () => {
placeholder="Enter your email"
message={
<>
{showErrors && emailError ? <Error className={styles.emailError} message={emailError} /> : null}
{showErrors && emailError ? <ErrorMessage className={styles.emailError} message={emailError} /> : null}
<span>
Subscribe to Decentraland's newsletter to receive the latest news about events, updates, contests and more.
</span>
Expand All @@ -472,7 +451,7 @@ export const SetupPage = () => {
</a>
.
</div>
{showErrors && agreeError ? <Error className={styles.agreeError} message={agreeError} /> : null}
{showErrors && agreeError ? <ErrorMessage className={styles.agreeError} message={agreeError} /> : null}
<div className={styles.jumpIn}>
<Button primary fluid type="submit" disabled={!agree || deploying} loading={deploying}>
{continueMessage}
Expand Down
25 changes: 25 additions & 0 deletions src/shared/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { AuthIdentity } from '@dcl/crypto'
import { localStorageGetIdentity } from '@dcl/single-sign-on-client'
import { ConnectionResponse, connection } from 'decentraland-connect'

export type DefinedConnectionResponse = Omit<ConnectionResponse, 'account'> & { account: string }
export type ConnectionData = DefinedConnectionResponse & { identity: AuthIdentity }

/**
* Gets the current connection data.
* @returns {Promise<ConnectionData | null>} The connection data or null if the user isn't connected or has no identity.
*/
export const getCurrentConnectionData = async (): Promise<ConnectionData | null> => {
try {
const previousConnection = await connection.tryPreviousConnection()
if (previousConnection.account && previousConnection.provider) {
const identity = localStorageGetIdentity(previousConnection.account)
if (identity) {
return { ...(previousConnection as DefinedConnectionResponse), identity }
}
}
return null
} catch (error) {
return null
}
}

0 comments on commit c49b6a3

Please sign in to comment.