Skip to content

Commit

Permalink
support sign in email
Browse files Browse the repository at this point in the history
c

c
  • Loading branch information
nguyenhoaidanh committed Oct 13, 2023
1 parent 21508d9 commit 6a48c5a
Show file tree
Hide file tree
Showing 23 changed files with 424 additions and 233 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ jobs:
VITE_TAG: ${{ needs.prepare.outputs.image_tag }}
CURRENT_BRANCH: ${{ needs.prepare.outputs.current_branch }}
NODE_OPTIONS: '--max_old_space_size=4096'
run: yarn build
run: yarn build-dev

- name: Docker build and push
uses: docker/build-push-action@v2
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"@blocto/web3-react-connector": "^1.0.0",
"@coinbase/wallet-sdk": "^3.0.4",
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
"@kybernetwork/oauth2": "1.0.0",
"@kybernetwork/oauth2": "1.0.1-rc.2",
"@kyberswap/krystal-walletconnect-v2": "0.0.1",
"@kyberswap/ks-sdk-classic": "^1.0.3",
"@kyberswap/ks-sdk-core": "1.0.11",
Expand Down
2 changes: 1 addition & 1 deletion src/components/Header/web3/SelectWallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ function Web3StatusInner() {
style={{ cursor: 'pointer', fontSize: '12px', color: theme.primary }}
onClick={e => {
e.stopPropagation()
signIn(account)
signIn({ account })
}}
>
sign-in
Expand Down
8 changes: 6 additions & 2 deletions src/components/Header/web3/SignWallet/ConfirmModal.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { LoginMethod } from '@kybernetwork/oauth2'
import { Trans } from '@lingui/macro'
import { useEffect, useState } from 'react'
import { LogIn, X } from 'react-feather'
Expand Down Expand Up @@ -75,7 +76,10 @@ const ModalConfirmProfile: React.FC = () => {

const onCancel = async () => {
const isGuest = !desiredAccountExist
await signIn(isGuest ? undefined : account, isGuest)
await signIn({
account: isGuest ? undefined : account,
loginMethod: isGuest ? LoginMethod.ANONYMOUS : LoginMethod.ETH,
})
hideModal()
}

Expand Down Expand Up @@ -209,7 +213,7 @@ const ModalConfirmProfile: React.FC = () => {
{!desiredAccountExist && !connectSuccess && (
<ButtonEmpty
disabled={pendingAuthentication}
onClick={() => signIn(account)}
onClick={() => signIn({ account })}
style={{
color: theme.subText,
display: 'flex',
Expand Down
17 changes: 11 additions & 6 deletions src/components/Header/web3/SignWallet/ProfileContent.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import KyberOauth2 from '@kybernetwork/oauth2'
import KyberOauth2, { LoginMethod } from '@kybernetwork/oauth2'
import { Trans } from '@lingui/macro'
import { rgba } from 'polished'
import { useState } from 'react'
Expand All @@ -24,7 +24,7 @@ import { useToggleModal } from 'state/application/hooks'
import { ConnectedProfile, useProfileInfo } from 'state/profile/hooks'
import { MEDIA_WIDTHS } from 'theme'
import getShortenAddress from 'utils/getShortenAddress'
import { isEmailValid, shortString } from 'utils/string'
import { shortString } from 'utils/string'

const ContentWrapper = styled.div`
display: flex;
Expand Down Expand Up @@ -120,7 +120,7 @@ const ProfileItemWrapper = styled(RowBetween)<{ active: boolean }>`
`

const ProfileItem = ({
data: { active, guest, address: account, profile, id },
data: { active, name: account, profile, id, type },
totalGuest,
}: {
data: ConnectedProfile
Expand All @@ -132,11 +132,16 @@ const ProfileItem = ({
const toggleModal = useToggleModal(ApplicationModal.SWITCH_PROFILE_POPUP)
const { signIn, signOut } = useLogin()
const [loading, setLoading] = useState(false)
const guest = type === LoginMethod.ANONYMOUS

const onClick = async () => {
if (active || loading) return
setLoading(true)
await signIn(id, guest, true)
await signIn({
account: id,
loginMethod: type,
showSessionExpired: true,
})
setLoading(false)
toggleModal()
}
Expand Down Expand Up @@ -178,7 +183,7 @@ const ProfileItem = ({
fontSize={active ? '16px' : profile?.nickname ? '12px' : '16px'}
color={active ? theme.subText : theme.subText}
>
{guest || isEmailValid(account) ? shortString(account, 20) : getShortenAddress(account)}
{type === LoginMethod.ETH ? getShortenAddress(account) : shortString(account, 20)}
</Text>
</Column>
{active && signOutBtn}
Expand Down Expand Up @@ -220,7 +225,7 @@ const ProfileContent = ({ scroll, toggleModal }: { scroll?: boolean; toggleModal
<ProfileItem data={profiles[0]} totalGuest={totalGuest} />
<ListProfile hasData={!!listNotActive.length} scroll={scroll}>
{listNotActive.map(data => (
<ProfileItem key={data.address} data={data} totalGuest={totalGuest} />
<ProfileItem key={data.id} data={data} totalGuest={totalGuest} />
))}
</ListProfile>
</Column>
Expand Down
102 changes: 63 additions & 39 deletions src/hooks/useLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
useSaveUserProfile,
useSignedAccountInfo,
} from 'state/profile/hooks'
import { filterTruthy, isAddress } from 'utils'
import { isAddress } from 'utils'
import { setLoginRedirectUrl } from 'utils/redirectUponLogin'
import { isEmailValid } from 'utils/string'

Expand All @@ -38,7 +38,7 @@ KyberOauth2.initialize({
})

const useLogin = (autoLogin = false) => {
const { account, chainId, isEVM } = useActiveWeb3React()
const { account, chainId } = useActiveWeb3React()

const [createProfile] = useGetOrCreateProfileMutation()
// const [connectWalletToProfile] = useConnectWalletToProfileMutation()
Expand All @@ -55,27 +55,25 @@ const useLogin = (autoLogin = false) => {
const getProfile = useCallback(
async ({
walletAddress,
isAnonymous,
loginMethod,
session,
account,
}: {
walletAddress: string | undefined
isAnonymous: boolean
loginMethod: LoginMethod
account: string
session: any
}) => {
const isAnonymous = loginMethod === LoginMethod.ANONYMOUS
try {
const profile = await createProfile().unwrap()
if (walletAddress && isAddress(chainId, walletAddress)) {
if (loginMethod === LoginMethod.ETH && walletAddress && isAddress(chainId, walletAddress)) {
// await connectWalletToProfile({ walletAddress }) // temp off
}

const formatProfile = { ...profile }
if (isEmailValid(account) && session) {
// sign in with google
formatProfile.avatarUrl = session?.picture ?? ''
if (loginMethod === LoginMethod.EMAIL && session) {
formatProfile.email = session?.email ?? ''
formatProfile.nickname = filterTruthy([session?.first_name, session?.last_name]).join(' ')
}
setProfile({ profile: formatProfile, isAnonymous, account })
} catch (error) {
Expand All @@ -89,25 +87,29 @@ const useLogin = (autoLogin = false) => {
)

const showSignInSuccess = useCallback(
(desireAccount: string | undefined, guest = false) =>
!autoLogin &&
(desireAccount: string | undefined, loginMethod: LoginMethod) => {
const isGuest = loginMethod === LoginMethod.ANONYMOUS
if (autoLogin) return

const profileName =
loginMethod === LoginMethod.EMAIL
? `email ${desireAccount}`
: isGuest
? `Guest Profile`
: `profile ${getProfileName(desireAccount, isGuest)}`

notify(
{
type: NotificationType.SUCCESS,
title: t`Signed in successfully`,
summary:
desireAccount?.toLowerCase() === account?.toLowerCase()
? t`Connected successfully with the current wallet address`
: t`Connected successfully with ${
isEmailValid(desireAccount)
? `email ${desireAccount}`
: guest
? `Guest Profile`
: `profile ${getProfileName(desireAccount, guest)}`
}`,
: t`Connected successfully with ${profileName}`,
},
10_000,
),
)
},
[account, notify, autoLogin, getProfileName],
)

Expand All @@ -126,8 +128,13 @@ const useLogin = (autoLogin = false) => {
hasError = true
} finally {
setLoading(false)
await getProfile({ walletAddress: account, isAnonymous: true, account: guestAccount, session: userInfo })
!hasError && showSuccessMsg && showSignInSuccess(guestAccount, true)
await getProfile({
walletAddress: account,
account: guestAccount,
session: userInfo,
loginMethod: LoginMethod.ANONYMOUS,
})
!hasError && showSuccessMsg && showSignInSuccess(guestAccount, LoginMethod.ANONYMOUS)
}
},
[getProfile, setLoading, account, saveSignedAccount, showSignInSuccess],
Expand All @@ -139,19 +146,19 @@ const useLogin = (autoLogin = false) => {
try {
setLoading(true)
const { loginMethod, userInfo } = await KyberOauth2.getSession(
isEmailValid(desireAccount ?? '') || !desireAccount
isEmailValid(desireAccount) || !desireAccount
? { account: desireAccount }
: { method: LoginMethod.ETH, account: desireAccount },
)
const respAccount = userInfo.email || userInfo.wallet_address || desireAccount
saveSignedAccount({ account: respAccount, method: loginMethod })
await getProfile({
walletAddress: respAccount,
isAnonymous: false,
loginMethod,
session: userInfo,
account: respAccount,
})
showSignInSuccess(respAccount)
showSignInSuccess(respAccount, loginMethod)
} catch (error) {
console.log('sdk get session err:', desireAccount, error.message)
if (loginAnonymousIfFailed) {
Expand All @@ -164,22 +171,29 @@ const useLogin = (autoLogin = false) => {
[setLoading, signInAnonymous, getProfile, saveSignedAccount, showSignInSuccess],
)

const redirectSignIn = useCallback(
(account: string) => {
setLoginRedirectUrl(window.location.href)
KyberOauth2.authenticate(isEVM ? { wallet_address: account } : {}) // navigate to login page
},
[isEVM],
)
const redirectSignIn = useCallback((account: string, loginMethod = LoginMethod.ETH) => {
setLoginRedirectUrl(window.location.href)
const accountKey = loginMethod === LoginMethod.ETH ? 'wallet_address' : 'email'
KyberOauth2.authenticate({ [accountKey]: account, type: loginMethod }) // navigate to login page
}, [])

// check account info and redirect if needed
const [, setAutoSignIn] = useIsAutoLoginAfterConnectWallet()
const signIn = useCallback(
async (desireAccount?: string, showSessionExpired = false) => {
async ({
desireAccount,
showSessionExpired,
loginMethod = LoginMethod.ETH,
}: {
desireAccount?: string
showSessionExpired?: boolean
loginMethod?: LoginMethod
}) => {
const isAddAccount = !desireAccount
const isSelectAccount = !!desireAccount
const isEth = loginMethod === LoginMethod.ETH

if (isAddAccount && !account) {
if (isAddAccount && !account && isEth) {
toggleWalletModal()
setAutoSignIn({ value: true, account: desireAccount })
return
Expand All @@ -193,19 +207,19 @@ const useLogin = (autoLogin = false) => {
return
}

const formatAccount = desireAccount || account || ''
const formatAccount = desireAccount || (isEth ? account : '') || ''
if (showSessionExpired && isSelectAccount && !isTokenExist) {
showConfirm({
isOpen: true,
content: t`Your session has expired. Please sign-in to continue.`,
title: t`Session Expired`,
confirmText: t`Sign-in`,
onConfirm: () => redirectSignIn(formatAccount),
onConfirm: () => redirectSignIn(formatAccount, loginMethod),
cancelText: t`Cancel`,
})
return
}
redirectSignIn(formatAccount)
redirectSignIn(formatAccount, loginMethod)
},
[account, checkSessionSignIn, toggleWalletModal, showConfirm, setAutoSignIn, redirectSignIn],
)
Expand Down Expand Up @@ -300,8 +314,18 @@ const useLogin = (autoLogin = false) => {
)

const signInWrapped = useCallback(
(desireAccount: string | undefined = undefined, isGuest = false, showSessionExpired = false) => {
return isGuest ? signInAnonymous(desireAccount) : signIn(desireAccount, showSessionExpired)
({
account = undefined,
loginMethod = LoginMethod.ETH,
showSessionExpired = false,
}: {
account?: string
loginMethod?: LoginMethod
showSessionExpired?: boolean
} = {}) => {
return loginMethod === LoginMethod.ANONYMOUS
? signInAnonymous(account)
: signIn({ desireAccount: account, showSessionExpired, loginMethod })
},
[signInAnonymous, signIn],
)
Expand Down Expand Up @@ -348,7 +372,7 @@ export const useAutoLogin = () => {
useIsAutoLoginAfterConnectWallet()
useEffect(() => {
if (!account || !needSignInAfterConnectWallet) return
signIn(accountSignAfterConnectedWallet)
signIn({ account: accountSignAfterConnectedWallet })
setAutoSignIn({ value: false, account: undefined })
}, [account, needSignInAfterConnectWallet, accountSignAfterConnectedWallet, signIn, setAutoSignIn])

Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useSessionExpire.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import KyberOauth2, { KyberOauth2Event, LoginMethod } from '@kybernetwork/oauth2'
import KyberOauth2, { KyberOauth2Event } from '@kybernetwork/oauth2'
import { t } from '@lingui/macro'
import { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
Expand Down Expand Up @@ -54,7 +54,7 @@ export default function useSessionExpiredGlobal() {
const accountSignHasChanged = signedMethod !== newLoginMethod || signedAccount !== newSignedAccount
if (document.visibilityState === 'visible' && accountSignHasChanged) {
// sync account in multi window tab
signIn(newSignedAccount, newLoginMethod === LoginMethod.ANONYMOUS)
signIn({ account: newSignedAccount, loginMethod: newLoginMethod })
}
} catch (error) {}
}
Expand Down
Loading

0 comments on commit 6a48c5a

Please sign in to comment.