Skip to content

Commit

Permalink
feat: Implement MVP feature
Browse files Browse the repository at this point in the history
  • Loading branch information
acezard committed Jan 17, 2022
1 parent a6bfa1e commit dd3b769
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 65 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"base-64": "^1.0.0",
"bluebird-retry": "^0.11.0",
"cheerio": "^1.0.0-rc.9",
"cozy-client": "^27.8.0",
"cozy-client": "^27.12.0",
"cozy-client-js": "^0.20.0",
"cozy-intent": "^1.2.0",
"cozy-ui": "^52.0.0",
Expand Down
5 changes: 4 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {SplashScreenProvider} from './screens/providers/SplashScreenProvider'
import {clearClient, getClient} from './libs/client'
import {lightTheme} from './theme'
import {useSplashScreen} from './hooks/useSplashScreen'
import {SessionProvider} from './libs/services/SessionService.js'

const Root = createStackNavigator()
const MainStack = createStackNavigator()
Expand Down Expand Up @@ -80,7 +81,9 @@ const App = () => {

return client ? (
<CozyProvider client={client}>
<Routing auth={true} />
<SessionProvider>
<Routing auth={true} />
</SessionProvider>
</CozyProvider>
) : (
<Routing auth={false} />
Expand Down
2 changes: 1 addition & 1 deletion src/libs/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const COZY_PREFIX = 'cozy://'
* Clears the storage key related to client authentication
*/
export const clearClient = () => {
return AsyncStorage.removeItem(OAUTH_STORAGE_KEY)
return AsyncStorage.multiRemove(OAUTH_STORAGE_KEY, 'FLAG_TOKEN')
}

/**
Expand Down
99 changes: 61 additions & 38 deletions src/libs/services/SessionService.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,82 +3,105 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
import {useClient} from 'cozy-client'

class SessionService {
SESSION_CODE = 'sessioncode'
SESSION_CODE = 'session_code'
LOGIN = 'login'
DID_CONSUME_TOKEN = 'didconsumetoken'

state = {
consumedToken: false,
sessionCode: '',
}
FLAG_TOKEN = 'flagtoken'
IS_REDIRECT = '/auth/login'

constructor(client) {
this.client = client
this.responseToken = this.getFlagToken()
}

init = async () => {
const didConsumeToken = await AsyncStorage.getItem(this.DID_CONSUME_TOKEN)
getInitialParams = async () => {
const token = await this.responseToken
const parsedToken = Boolean(token)

if (parsedToken) {
return
}

if (!parsedToken) {
await this.getSessionCode()
await this.setFlagToken()

didConsumeToken ? this.initWithoutCode() : await this.initCode()
return [this.SESSION_CODE, this.sessionCode]
}
}

initWithoutCode = () => (this.state.consumedToken = true)
getSessionCode = async () => {
if (this.sessionCode) {
return this.sessionCode
}

const {session_code} = await this.client.stackClient.fetchSessionCode()

initCode = async () => {
const sessionCode = await this.client.getSessionCode()
this.state.sessionCode = sessionCode
this.sessionCode = session_code
}

wrapUrl = (url) => {
const {href} = new URL(url).append(
this.SESSION_CODE,
this.state.sessionCode,
)
wrapUrl = async urlArg => {
const url = new URL(urlArg)
const params = new URLSearchParams(url.search)
const {session_code} = await this.client.stackClient.fetchSessionCode()

params.append(this.SESSION_CODE, await session_code)

url.search = params

return href
return url
}

interceptLogin = async (request) => {
if (this.state.consumedToken) {
interceptLogin = async (request, setUri) => {
const url = new URL(request.url)
const {pathname, search} = url

if (pathname !== this.IS_REDIRECT) {
return true
}

if (request?.url.includes(this.LOGIN)) {
await this.initCode()
// const wrappedUrl = this.wrapUrl(request.url) Do a redirect with the wrappedUrl
await this.consumeToken()
const redirect = new URLSearchParams(search).get('redirect')
const wrappedUrl = await this.wrapUrl(redirect)

await this.setFlagToken()

setUri(wrappedUrl)

return false
}

getFlagToken = async () => {
try {
const token = await AsyncStorage.getItem(this.FLAG_TOKEN)
return token
} catch (error) {
return false
}

return true
}

consumeToken = () => AsyncStorage.setItem(this.DID_CONSUME_TOKEN, 'true')
setFlagToken = () => AsyncStorage.setItem(this.FLAG_TOKEN, '1')

onLogout = () => AsyncStorage.removeItem(this.DID_CONSUME_TOKEN)
unsetFlagToken = () => AsyncStorage.setItem(this.FLAG_TOKEN, '')
}

const SessionContext = React.createContext(undefined)

export const useSession = () => useContext(SessionContext)

export const SessionProvider = ({children}) => {
const [sessionService, createSessionService] = useState()
const [sessionService, setSessionService] = useState()
const client = useClient()

useEffect(() => {
if (!sessionService) {
createSessionService(new SessionService(client))
}

if (sessionService) {
sessionService.init()
setSessionService(new SessionService(client))
}
}, [sessionService, client])
}, [client, sessionService])

return (
return sessionService ? (
<SessionContext.Provider value={sessionService}>
{children}
</SessionContext.Provider>
) : (
children
)
}
37 changes: 24 additions & 13 deletions src/screens/connectors/HomeView.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,22 @@ import {useClient, Q, generateWebLink} from 'cozy-client'
import {useNativeIntent} from 'cozy-intent'

import CozyWebView from '../CozyWebView'
import {useSession} from '../../libs/services/SessionService'
import {URLSearchParams} from 'react-native-url-polyfill'

const HomeView = ({route, navigation, setLauncherContext}) => {
const client = useClient()
const [uri, setUri] = useState('')
const [run, setRun] = useState('')
const [ref, setRef] = useState('')
const nativeIntent = useNativeIntent()
const session = useSession()

useEffect(() => {
if (ref && route.name === 'home') {
nativeIntent.registerWebview(ref)
}

const getHomeUri = async () => {
setUri(
generateWebLink({
cozyUrl: client.getStackClient().uri,
pathname: '/',
slug: 'home',
subDomainType: await getSubDomainType(),
}),
)
}

const getSubDomainType = async () => {
try {
const {
Expand Down Expand Up @@ -66,10 +58,29 @@ const HomeView = ({route, navigation, setLauncherContext}) => {
return true;
`)

if (!uri) {
const getHomeUri = async () => {
const sessionSearchParams = await session.getInitialParams()

const baseUri = new URL(
generateWebLink({
cozyUrl: client.getStackClient().uri,
pathname: '/',
slug: 'home',
subDomainType: await getSubDomainType(),
}),
)

const params = new URLSearchParams(baseUri.search)

params.append(...sessionSearchParams)

setUri(`${baseUri.toString().replace('#/', '')}?${params.toString()}`)
}

if (!uri && !run && session) {
getHomeUri()
}
}, [uri, client, run, route, nativeIntent, ref, navigation])
}, [uri, client, run, route, nativeIntent, ref, navigation, session])

return uri ? (
<CozyWebView
Expand Down
11 changes: 9 additions & 2 deletions src/screens/routes/CozyAppView.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import React from 'react'
import React, {useState} from 'react'
import {WebView} from 'react-native-webview'
import {useSession} from '../../libs/services/SessionService'

export const CozyAppView = ({route}) => {
const session = useSession()
const [uri, setUri] = useState()

const run = `
window.cozy = {
isFlagshipApp: true
Expand All @@ -12,10 +16,13 @@ export const CozyAppView = ({route}) => {
return (
<WebView
injectedJavaScriptBeforeContentLoaded={run}
source={{uri: route.params.href}}
source={{uri: route.params.href || uri}}
originWhitelist={['*']}
javaScriptEnabled={true}
useWebKit={true}
onShouldStartLoadWithRequest={async request => {
await session.interceptLogin(request, setUri)
}}
/>
)
}
18 changes: 9 additions & 9 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6403,10 +6403,10 @@ cozy-client-js@^0.20.0:
pouchdb-browser "7.0.0"
pouchdb-find "7.0.0"

cozy-client@^27.8.0:
version "27.8.0"
resolved "https://registry.yarnpkg.com/cozy-client/-/cozy-client-27.8.0.tgz#08cbd8e778a3a721732b6e42b88d10775c0dd067"
integrity sha512-ZzdGJo4Jnjtf3v3mON5JjXpO+Qu+aKy1ePxyP037lktWq7N/eYvv3EMOgSbYztEbtnd9euIggEYgwN+sj2FhGg==
cozy-client@^27.12.0:
version "27.12.0"
resolved "https://registry.yarnpkg.com/cozy-client/-/cozy-client-27.12.0.tgz#b3f5753f267744172c475e81a0fb12b93a149cf0"
integrity sha512-FbxmUSEW9n235VD4MMOaCHG451YDecSXSwviCs8NuHL4h59kYsLxJbP58QCtc0vA9r+CdkyniUcgZohaFtumOA==
dependencies:
"@cozy/minilog" "1.0.0"
"@types/jest" "^26.0.20"
Expand All @@ -6415,7 +6415,7 @@ cozy-client@^27.8.0:
cozy-device-helper "^1.12.0"
cozy-flags "2.7.1"
cozy-logger "^1.6.0"
cozy-stack-client "^27.6.5"
cozy-stack-client "^27.9.0"
json-stable-stringify "^1.0.1"
lodash "^4.17.13"
microee "^0.0.6"
Expand Down Expand Up @@ -6472,10 +6472,10 @@ cozy-logger@^1.6.0:
chalk "^2.4.2"
json-stringify-safe "5.0.1"

cozy-stack-client@^27.6.5:
version "27.6.5"
resolved "https://registry.yarnpkg.com/cozy-stack-client/-/cozy-stack-client-27.6.5.tgz#4b40ad59821b957f161a77132b5346e99be0bc2c"
integrity sha512-aGkchVfvVGfI38qt+R8/BKv8nFN6Ihhx1LFsDYDtV+mW6OxOqVYdd22sIg9iHkusaqJgxgkMYnB9NcnDlC8Ajg==
cozy-stack-client@^27.9.0:
version "27.9.0"
resolved "https://registry.yarnpkg.com/cozy-stack-client/-/cozy-stack-client-27.9.0.tgz#f73f41699218ffbc1eb8116aea2bcb97248d98e3"
integrity sha512-6wuk91Pt7PhmkENgyDAYXYDJlNMuWtsluhoZHQKJplF7tbWfuQPdWZq2OFwOUB7xzhwhmjcsF4JlRUlEqKVtJA==
dependencies:
cozy-flags "2.7.1"
detect-node "^2.0.4"
Expand Down

0 comments on commit dd3b769

Please sign in to comment.