Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update API client #1032

Merged
merged 22 commits into from
May 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/common-contexts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"dependencies": {
"@chainsafe/browser-storage-hooks": "^1.0.1",
"@chainsafe/files-api-client": "1.9.0",
"@chainsafe/files-api-client": "1.11.2",
"axios": "^0.21.1",
"uuid": "^8.3.1"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from "react"
import { useImployApi } from "../ImployApiContext"
import { useFilesApi } from "../FilesApiContext"
import axios, { AxiosResponse } from "axios"

type BillingContextProps = {
Expand Down Expand Up @@ -31,11 +31,11 @@ interface IStripeResponse {
}

const BillingProvider = ({ children }: BillingContextProps) => {
const { imployApiClient } = useImployApi()
const { filesApiClient } = useFilesApi()

const addCard = async (cardToken: string) => {
try {
await imployApiClient.addCard({ token: cardToken })
await filesApiClient.addCard({ token: cardToken })
return Promise.resolve()
} catch (error) {
return Promise.reject("There was an error adding card.")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useWeb3 } from "@chainsafe/web3-context"
import * as React from "react"
import { useState, useEffect, useMemo, useCallback } from "react"
import { IImployApiClient, ImployApiClient, Token, IdentityProvider, OAuthIdentityToken } from "@chainsafe/files-api-client"
import { IFilesApiClient, FilesApiClient, Token, IdentityProvider, OAuthIdentityToken } from "@chainsafe/files-api-client"
import jwtDecode from "jwt-decode"
import axios from "axios"
import { decryptFile } from "../helpers"
Expand All @@ -11,14 +11,14 @@ export { IdentityProvider as OAuthProvider }
const tokenStorageKey = "csf.refreshToken"
const isReturningUserStorageKey = "csf.isReturningUser"

type ImployApiContextProps = {
type FilesApiContextProps = {
apiUrl?: string
withLocalStorage?: boolean
children: React.ReactNode | React.ReactNode[]
}

type ImployApiContext = {
imployApiClient: IImployApiClient
type FilesApiContext = {
filesApiClient: IFilesApiClient
isLoggedIn: boolean | undefined
secured: boolean | undefined
isReturningUser: boolean
Expand Down Expand Up @@ -47,9 +47,9 @@ type ImployApiContext = {
isMasterPasswordSet: boolean
}

const ImployApiContext = React.createContext<ImployApiContext | undefined>(undefined)
const FilesApiContext = React.createContext<FilesApiContext | undefined>(undefined)

const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: ImployApiContextProps) => {
const FilesApiProvider = ({ apiUrl, withLocalStorage = true, children }: FilesApiContextProps) => {
const maintenanceMode = process.env.REACT_APP_MAINTENANCE_MODE === "true"

const { wallet, onboard, checkIsReady, isReady } = useWeb3()
Expand All @@ -63,11 +63,11 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
}), [])

const initialApiClient = useMemo(() => {
return new ImployApiClient({}, apiUrl, initialAxiosInstance)
return new FilesApiClient({}, apiUrl, initialAxiosInstance)
}, [apiUrl, initialAxiosInstance]
)

const [imployApiClient, setImployApiClient] = useState<ImployApiClient>(initialApiClient)
const [filesApiClient, setFilesApiClient] = useState<FilesApiClient>(initialApiClient)
const [isLoadingUser, setIsLoadingUser] = useState(true)

// access tokens
Expand All @@ -87,8 +87,8 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
setRefreshToken(refreshToken)
refreshToken.token && withLocalStorage && localStorageSet(tokenStorageKey, refreshToken.token)
!withLocalStorage && sessionStorageSet(tokenStorageKey, refreshToken.token)
accessToken.token && imployApiClient.setToken(accessToken.token)
}, [imployApiClient, localStorageSet, sessionStorageSet, withLocalStorage])
accessToken.token && filesApiClient.setToken(accessToken.token)
}, [filesApiClient, localStorageSet, sessionStorageSet, withLocalStorage])

const setReturningUser = () => {
// set returning user
Expand All @@ -115,7 +115,7 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
? localStorageGet(tokenStorageKey)
: sessionStorageGet(tokenStorageKey)
if (refreshTokenLocal) {
const refreshTokenApiClient = new ImployApiClient(
const refreshTokenApiClient = new FilesApiClient(
{},
apiUrl,
axiosInstance
Expand Down Expand Up @@ -148,9 +148,9 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
}
)

const apiClient = new ImployApiClient({}, apiUrl, axiosInstance)
const apiClient = new FilesApiClient({}, apiUrl, axiosInstance)
const savedRefreshToken = localStorageGet(tokenStorageKey)
setImployApiClient(apiClient)
setFilesApiClient(apiClient)
if (!maintenanceMode && savedRefreshToken) {
try {
const {
Expand Down Expand Up @@ -200,7 +200,7 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
const {
access_token,
refresh_token
} = await imployApiClient.verifyServiceIdentityToken({
} = await filesApiClient.verifyServiceIdentityToken({
signature: signature,
public_key: publicKey,
service_identity_token: identityToken
Expand Down Expand Up @@ -228,8 +228,8 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
}, [refreshToken])

useEffect(() => {
if (accessToken && accessToken.token && imployApiClient) {
imployApiClient?.setToken(accessToken.token)
if (accessToken && accessToken.token && filesApiClient) {
filesApiClient?.setToken(accessToken.token)
const decodedAccessToken = jwtDecode<{ perm: { secured?: string } }>(
accessToken.token
)
Expand All @@ -239,7 +239,7 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
setSecured(false)
}
}
}, [accessToken, imployApiClient])
}, [accessToken, filesApiClient])

const isLoggedIn = () => {
if (isLoadingUser) {
Expand All @@ -259,7 +259,7 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy

const getProviderUrl = async (provider: OAuthIdentityToken) => {
try {
const { url } = await imployApiClient.getOauth2Provider(provider)
const { url } = await filesApiClient.getOauth2Provider(provider)
return Promise.resolve(url)
} catch {
return Promise.reject("There was an error logging in")
Expand All @@ -271,7 +271,7 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
const {
access_token,
refresh_token
} = await imployApiClient.postOauth2CodeGithub(code, state)
} = await filesApiClient.postOauth2CodeGithub(code, state)
setTokensAndSave(access_token, refresh_token)
setReturningUser()
return Promise.resolve()
Expand All @@ -292,7 +292,7 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
const {
access_token,
refresh_token
} = await imployApiClient.postOauth2CodeGoogle(
} = await filesApiClient.postOauth2CodeGoogle(
code,
state,
scope,
Expand All @@ -314,7 +314,7 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
const {
access_token,
refresh_token
} = await imployApiClient.postOauth2CodeFacebook(code, state)
} = await filesApiClient.postOauth2CodeFacebook(code, state)

setTokensAndSave(access_token, refresh_token)
setReturningUser()
Expand All @@ -328,22 +328,22 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
setAccessToken(undefined)
setRefreshToken(undefined)
setDecodedRefreshToken(undefined)
imployApiClient.setToken("")
filesApiClient.setToken("")
localStorageRemove(tokenStorageKey)
!withLocalStorage && sessionStorageRemove(tokenStorageKey)
}

const secureThresholdKeyAccount = async (encryptedKey: string) => {
try {
if (decodedRefreshToken && refreshToken) {
await imployApiClient.secure({
await filesApiClient.secure({
encryption_key: encryptedKey
})

const {
access_token,
refresh_token
} = await imployApiClient.getRefreshToken({
} = await filesApiClient.getRefreshToken({
refresh: refreshToken.token
})

Expand Down Expand Up @@ -376,9 +376,9 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
}

return (
<ImployApiContext.Provider
<FilesApiContext.Provider
value={{
imployApiClient,
filesApiClient,
isLoggedIn: isLoggedIn(),
secured,
isReturningUser: isReturningUser,
Expand All @@ -397,17 +397,17 @@ const ImployApiProvider = ({ apiUrl, withLocalStorage = true, children }: Imploy
}}
>
{children}
</ImployApiContext.Provider>
</FilesApiContext.Provider>
)
}

const useImployApi = () => {
const context = React.useContext(ImployApiContext)
const useFilesApi = () => {
const context = React.useContext(FilesApiContext)
if (context === undefined) {
throw new Error("useAuth must be used within a AuthProvider")
}
return context
}

export { ImployApiProvider, useImployApi }
export { FilesApiProvider, useFilesApi }

7 changes: 7 additions & 0 deletions packages/common-contexts/src/FilesApiContext/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export {
FilesApiProvider,
useFilesApi,
OAuthProvider
} from "./FilesApiContext"

export { signMessage } from "./utils"
7 changes: 0 additions & 7 deletions packages/common-contexts/src/ImployApiContext/index.ts

This file was deleted.

13 changes: 8 additions & 5 deletions packages/common-contexts/src/UserContext/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import * as React from "react"
import { useCallback, useEffect } from "react"
import { useImployApi } from "../ImployApiContext"
import { useFilesApi } from "../FilesApiContext"
import { useState } from "react"

type UserContextProps = {
children: React.ReactNode | React.ReactNode[]
}

export type Profile = {
userId: string
firstName?: string
lastName?: string
publicAddress?: string
Expand All @@ -30,15 +31,16 @@ interface IUserContext {
const UserContext = React.createContext<IUserContext | undefined>(undefined)

const UserProvider = ({ children }: UserContextProps) => {
const { imployApiClient, isLoggedIn } = useImployApi()
const { filesApiClient, isLoggedIn } = useFilesApi()

const [profile, setProfile] = useState<Profile | undefined>(undefined)

const refreshProfile = useCallback(async () => {
try {
const profileApiData = await imployApiClient.getUser()
const profileApiData = await filesApiClient.getUser()

const profileState = {
userId: profileApiData.uuid,
firstName: profileApiData.first_name,
lastName: profileApiData.last_name,
email: profileApiData.email,
Expand All @@ -50,7 +52,7 @@ const UserProvider = ({ children }: UserContextProps) => {
} catch (error) {
return Promise.reject("There was an error getting profile.")
}
}, [imployApiClient])
}, [filesApiClient])

useEffect(() => {
if (isLoggedIn) {
Expand All @@ -63,13 +65,14 @@ const UserProvider = ({ children }: UserContextProps) => {
if (!profile) return Promise.reject("Profile not initialized")

try {
const profileData = await imployApiClient.updateUser({
const profileData = await filesApiClient.updateUser({
first_name: firstName || "",
last_name: lastName || "",
email: profile.email || ""
})

setProfile({
...profile,
firstName: profileData.first_name,
lastName: profileData.last_name,
email: profileData.email,
Expand Down
2 changes: 1 addition & 1 deletion packages/common-contexts/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from "./ImployApiContext"
export * from "./FilesApiContext"
export * from "./UserContext"
export * from "./BillingContext"
export * from "./helpers"
2 changes: 1 addition & 1 deletion packages/files-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"react-h5-audio-player": "^3.5.0",
"react-hotkeys-hook": "^2.4.0",
"react-markdown": "^5.0.3",
"react-pdf": "^5.0.0",
"react-pdf": "5.3.0",
"react-scripts": "3.4.4",
"react-swipeable": "^6.0.1",
"react-toast-notifications": "^2.4.0",
Expand Down
12 changes: 6 additions & 6 deletions packages/files-ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React, { useCallback, useEffect } from "react"
import { init as initSentry, ErrorBoundary, showReportDialog } from "@sentry/react"
import { Web3Provider } from "@chainsafe/web3-context"
import { ImployApiProvider, UserProvider, BillingProvider } from "@chainsafe/common-contexts"
import { FilesApiProvider, UserProvider, BillingProvider } from "@chainsafe/common-contexts"
import { ThemeSwitcher } from "@chainsafe/common-theme"
import "@chainsafe/common-theme/dist/font-faces.css"
import { Button, CssBaseline, Modal, Router, ToasterProvider, Typography } from "@chainsafe/common-components"
import { DriveProvider } from "./Contexts/DriveContext"
import { FilesProvider } from "./Contexts/FilesContext"
import FilesRoutes from "./Components/FilesRoutes"
import AppWrapper from "./Components/Layouts/AppWrapper"
import { useHotjar } from "react-use-hotjar"
Expand Down Expand Up @@ -110,7 +110,7 @@ const App: React.FC<{}> = () => {
checkNetwork={false}
cacheWalletSelection={canUseLocalStorage}
>
<ImployApiProvider
<FilesApiProvider
apiUrl={apiUrl}
withLocalStorage={false}
>
Expand All @@ -119,18 +119,18 @@ const App: React.FC<{}> = () => {
network={directAuthNetwork}
>
<UserProvider>
<DriveProvider>
<FilesProvider>
<BillingProvider>
<Router>
<AppWrapper>
<FilesRoutes />
</AppWrapper>
</Router>
</BillingProvider>
</DriveProvider>
</FilesProvider>
</UserProvider>
</ThresholdKeyProvider>
</ImployApiProvider>
</FilesApiProvider>
</Web3Provider>
</ToasterProvider>
</LanguageProvider>
Expand Down
2 changes: 1 addition & 1 deletion packages/files-ui/src/Components/Elements/PasswordForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { createStyles, makeStyles } from "@chainsafe/common-theme"
import { CSFTheme } from "../../Themes/types"
import zxcvbn from "zxcvbn"
import { t } from "@lingui/macro"
import StrengthIndicator from "../Modules/MasterKeySequence/SequenceSlides/StrengthIndicator"
import StrengthIndicator from "./StrengthIndicator"
import clsx from "clsx"

const useStyles = makeStyles(({ breakpoints, constants }: CSFTheme) =>
Expand Down
Loading