Skip to content

Commit

Permalink
feat(unlock-app): cleanup more auth (#15693)
Browse files Browse the repository at this point in the history
* cleanup

* nore cleanup

* deleted file

* Update provider/src/handler.ts

* window is not always defined

* type fixes

---------

Co-authored-by: 0xtxbi <[email protected]>
  • Loading branch information
julien51 and 0xTxbi authored Mar 6, 2025
1 parent c2236d2 commit 4917ff1
Show file tree
Hide file tree
Showing 10 changed files with 52 additions and 148 deletions.
10 changes: 5 additions & 5 deletions provider/src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import supportedNetworks from './supportedNetworks'
import { Env } from './types'
import { shouldRateLimit } from './rateLimit'
import { getRPCResponseFromCache, storeRPCResponseInCache } from './cache'
import { RpcRequest, getCacheTTL, getClientIP } from './utils'
import { RpcRequest, getClientIP } from './utils'

const handler = async (request: Request, env: Env): Promise<Response> => {
try {
Expand All @@ -22,7 +22,10 @@ const handler = async (request: Request, env: Env): Promise<Response> => {

// Blocking requests from the Chrome extension
const origin = request.headers.get('origin')
if (origin === 'chrome-extension://mnkbccinkbalkmmnmbcicdobcmgggmfc') {
if (
origin &&
origin.match(/\b[a-zA-Z0-9_-]+-extension:\/\/[^ \n\r]+/) !== null
) {
return Response.json(
{ message: '' },
{
Expand All @@ -31,9 +34,6 @@ const handler = async (request: Request, env: Env): Promise<Response> => {
)
}

// Get the cache TTL from environment or use default
const cacheTTL = getCacheTTL(env)

// Handling CORS
if (request.method === 'OPTIONS') {
return new Response('', {
Expand Down
33 changes: 15 additions & 18 deletions unlock-app/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import React, { Suspense } from 'react'
import { QueryClientProvider } from '@tanstack/react-query'
import { ReCaptchaProvider } from 'next-recaptcha-v3'

import { SessionProvider } from '~/hooks/useSession'
import { AirstackProvider } from '@airstack/airstack-react'
import { ErrorBoundary } from '@sentry/nextjs'
import { ErrorFallback } from '~/components/interface/ErrorFallback'
Expand All @@ -23,24 +22,22 @@ export default function Providers({ children }: { children: React.ReactNode }) {
<QueryClientProvider client={queryClient}>
<ReCaptchaProvider reCaptchaKey={config.recaptchaKey}>
<GlobalWrapper>
<SessionProvider>
<Suspense fallback={<LoadingFallback />}>
<ConnectModalProvider>
<ToastProvider>
<AirstackProvider
apiKey={'162b7c4dda5c44afdb0857b6b04454f99'}
<Suspense fallback={<LoadingFallback />}>
<ConnectModalProvider>
<ToastProvider>
<AirstackProvider
apiKey={'162b7c4dda5c44afdb0857b6b04454f99'}
>
<ErrorBoundary
fallback={(props: any) => <ErrorFallback {...props} />}
>
<ErrorBoundary
fallback={(props: any) => <ErrorFallback {...props} />}
>
<ShouldOpenConnectModal />
{children}
</ErrorBoundary>
</AirstackProvider>
</ToastProvider>
</ConnectModalProvider>
</Suspense>
</SessionProvider>
<ShouldOpenConnectModal />
{children}
</ErrorBoundary>
</AirstackProvider>
</ToastProvider>
</ConnectModalProvider>
</Suspense>
</GlobalWrapper>
</ReCaptchaProvider>
</QueryClientProvider>
Expand Down
11 changes: 1 addition & 10 deletions unlock-app/src/components/content/HomeContent.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
'use client'

import { Launcher } from '../interface/Launcher'
import { useSession } from '~/hooks/useSession'
import { useAuthenticate } from '~/hooks/useAuthenticate'
import LocksContent from './lock/LocksContent'
import { Placeholder } from '@unlock-protocol/ui'

export const HomeContent = () => {
const { isLoading } = useSession()

const { account } = useAuthenticate()

return (
<>
{isLoading && (
<Placeholder.Root>
<Placeholder.Card />
</Placeholder.Root>
)}
{account && (
<div className="flex flex-col gap-4">
<LocksContent />
</div>
)}
{!account && !isLoading && <Launcher />}
{!account && <Launcher />}
</>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ export const LockList = ({ owner }: LockListProps) => {
]
}, [networks, defaultNetwork])

const results = useLocksByManagerOnNetworks(owner, networkItems)
const result = results[0]
const result = useLocksByManagerOnNetworks(owner, networkItems)

const [favoriteLocks, setFavoriteLocks] = useState<FavoriteLocks>(() => {
return getStorage('favoriteLocks') || {}
Expand Down Expand Up @@ -155,7 +154,7 @@ export const LockList = ({ owner }: LockListProps) => {
)
}

const allLocks = (result.data as Lock[]) || []
const allLocks = (result.data as unknown as Lock[]) || []
const isEmpty = !isLoading && allLocks.length === 0

return (
Expand Down
3 changes: 3 additions & 0 deletions unlock-app/src/config/PrivyProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { locksmith } from './locksmith'
import AuthenticationContext from '~/contexts/AuthenticationContext'
import { MigrationModal } from '~/components/legacy-auth/MigrationNotificationModal'
import { isInIframe } from '~/utils/iframe'
import { setLocalStorageItem } from '~/hooks/useAppStorage'

// check for legacy account
export const checkLegacyAccount = async (
Expand Down Expand Up @@ -108,8 +109,10 @@ export const PrivyChild = ({ children }: { children: ReactNode }) => {
// Detects when login was successful via an event
// This should render only once!
useEffect(() => {
// this is called only once when a user is authenticated!
const onAuthenticated = async (event: any) => {
setAccount(event.detail)
setLocalStorageItem('account', event.detail)
}
window.addEventListener('locksmith.authenticated', onAuthenticated)
return () => {
Expand Down
6 changes: 6 additions & 0 deletions unlock-app/src/config/queryClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,9 @@ export const queryClient = new QueryClient({
},
},
})
if (typeof window !== 'undefined') {
window.addEventListener('locksmith.authenticated', async () => {
console.log('refetching queries')
queryClient.refetchQueries()
})
}
33 changes: 6 additions & 27 deletions unlock-app/src/hooks/useAuthenticate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { usePrivy, useWallets } from '@privy-io/react-auth'
import { useAppStorage } from './useAppStorage'
import { useContext, useEffect } from 'react'
import {
getAccessToken,
Expand All @@ -8,21 +7,17 @@ import {
} from '~/utils/session'
import { locksmith } from '~/config/locksmith'
import { useQueryClient } from '@tanstack/react-query'
import { useSession } from './useSession'
import { useSIWE } from './useSIWE'
import { ToastHelper } from '@unlock-protocol/ui'
import { useProvider } from './useProvider'
import AuthenticationContext from '~/contexts/AuthenticationContext'
import { onSignedInWithPrivy } from '~/config/PrivyProvider'

// This hook includes *all* signIn and signOut methods
// TODO: consider adding useSession() stuff here too?
export function useAuthenticate() {
const { account, setAccount } = useContext(AuthenticationContext)

const { setProvider } = useProvider()
const { refetchSession } = useSession()
const { setStorage } = useAppStorage()
const {
logout: privyLogout,
ready: privyReady,
Expand All @@ -36,19 +31,13 @@ export function useAuthenticate() {

// When a user is logged in, this method is called to set the account and refetch the session
const onSignedIn = async (walletAddress: string) => {
const changed = setStorage('account', walletAddress)
if (changed) {
await Promise.all([queryClient.refetchQueries(), refetchSession()])
}
window.dispatchEvent(
new CustomEvent('locksmith.authenticated', {
detail: walletAddress,
})
)
}

// Detects when login was successful via an event
useEffect(() => {
if (account) {
onSignedIn(account)
}
}, [account])

// Method that tries to sign in with an existing session
const signInWithExistingSession = async () => {
const existingAccessToken = getAccessToken()
Expand All @@ -73,11 +62,6 @@ export function useAuthenticate() {
const { walletAddress } = response.data
if (walletAddress && wallets.length > 0) {
await onSignedIn(walletAddress)
window.dispatchEvent(
new CustomEvent('locksmith.authenticated', {
detail: walletAddress,
})
)
return true
}
} catch (error) {
Expand All @@ -99,7 +83,7 @@ export function useAuthenticate() {
removeAccessToken()
}
setAccount(undefined)
await Promise.all([queryClient.invalidateQueries(), refetchSession()])
await Promise.all([queryClient.invalidateQueries()])
} catch (error) {
console.error(error)
}
Expand All @@ -122,11 +106,6 @@ export function useAuthenticate() {
walletAddress,
})
await onSignedIn(walletAddress)
window.dispatchEvent(
new CustomEvent('locksmith.authenticated', {
detail: walletAddress,
})
)
} else {
console.error('Error logging in with SIWE:', response)
ToastHelper.error(
Expand Down
27 changes: 12 additions & 15 deletions unlock-app/src/hooks/useLocksByManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { QueriesOptions, useQueries } from '@tanstack/react-query'
import { useQuery } from '@tanstack/react-query'
import { LockOrderBy } from '@unlock-protocol/unlock-js'
import { OrderDirection } from '@unlock-protocol/unlock-js'
import { graphService } from '~/config/subgraph'
Expand Down Expand Up @@ -47,23 +47,20 @@ const useLocksByManagerOnNetworks = (
networkItems: [string, any][]
) => {
const networks = networkItems.map(([network]) => Number(network))

const query: QueriesOptions<any> = {
return useQuery({
queryKey: ['getLocks', networks.join(','), manager],
queryFn: async () =>
await getLocksByNetworks({
queryFn: async () => {
return getLocksByNetworks({
account: manager,
networks,
}),
staleTime: 5 * 60 * 1000, // 5 minutes
cacheTime: 30 * 60 * 1000, // 30 minutes
retry: 2,
refetchOnWindowFocus: false,
}

// Maintain backwards compatibility by wrapping the result in an array
return useQueries({
queries: [query],
})
},
retryOnMount: false,
staleTime: Infinity,
// staleTime: 5 * 60 * 1000, // 5 minutes
// gcTime: 30 * 60 * 1000, // 30 minutes
// retry: 2,
// refetchOnWindowFocus: false,
})
}

Expand Down
4 changes: 2 additions & 2 deletions unlock-app/src/hooks/useProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { useContext } from 'react'
import { WalletService } from '@unlock-protocol/unlock-js'
import ProviderContext from '../contexts/ProviderContext'
import { ToastHelper } from '@unlock-protocol/ui'
import { useSession } from './useSession'
import { config } from '~/config/app'
import { ethers } from 'ethers'
import networks from '@unlock-protocol/networks'
import AuthenticationContext from '~/contexts/AuthenticationContext'

interface WatchAssetInterface {
address: string
Expand All @@ -15,7 +15,7 @@ interface WatchAssetInterface {

export const useProvider = () => {
const { setProvider, provider } = useContext(ProviderContext)
const { session: account } = useSession()
const { account } = useContext(AuthenticationContext)

const createBrowserProvider = (
provider: any
Expand Down
68 changes: 0 additions & 68 deletions unlock-app/src/hooks/useSession.tsx

This file was deleted.

0 comments on commit 4917ff1

Please sign in to comment.