about summary refs log tree commit diff
path: root/src/platform/auth-flow.native.ts
blob: 596632f1754c155769c8bdeea0d94fca34dd9ac4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import {Linking} from 'react-native'
import * as auth from '@adxp/auth'
import * as ucan from 'ucans'
import {InAppBrowser} from 'react-native-inappbrowser-reborn'
import {isWeb} from '../platform/detection'
import {extractHashFragment, makeAppUrl} from '../platform/urls'
import {ReactNativeStore, parseUrlForUcan} from '../state/auth'
import * as env from '../env'

export async function requestAppUcan(
  authStore: ReactNativeStore,
  scope: ucan.Capability,
) {
  const did = await authStore.getDid()
  const returnUrl = makeAppUrl()
  const fragment = auth.requestAppUcanHashFragment(did, scope, returnUrl)
  const url = `${env.AUTH_LOBBY}#${fragment}`

  if (isWeb) {
    // @ts-ignore window is defined -prf
    window.location.href = url
    return false
  }

  if (await InAppBrowser.isAvailable()) {
    // use in-app browser
    const res = await InAppBrowser.openAuth(url, returnUrl, {
      // iOS Properties
      ephemeralWebSession: false,
      // Android Properties
      showTitle: false,
      enableUrlBarHiding: true,
      enableDefaultShare: false,
    })
    if (res.type === 'success' && res.url) {
      const fragment = extractHashFragment(res.url)
      if (fragment) {
        const ucan = await parseUrlForUcan(fragment)
        if (ucan) {
          await authStore.addUcan(ucan)
          return true
        }
      }
    } else {
      console.log('Not completed', res)
      return false
    }
  } else {
    // use system browser
    Linking.openURL(url)
  }
  return true
}