tooot/src/components/Instance/Auth.tsx

83 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-01-07 19:13:09 +01:00
import { useNavigation } from '@react-navigation/native'
import { InstanceLocal, localAddInstance } from '@utils/slices/instancesSlice'
import * as AuthSession from 'expo-auth-session'
import React, { useEffect } from 'react'
import { useQueryClient } from 'react-query'
import { useDispatch } from 'react-redux'
export interface Props {
instanceDomain: string
2021-01-17 22:37:05 +01:00
// Domain can be different than uri
instanceUri: Mastodon.Instance['uri']
2021-01-07 19:13:09 +01:00
appData: InstanceLocal['appData']
goBack?: boolean
}
const InstanceAuth = React.memo(
2021-01-17 22:37:05 +01:00
({ instanceDomain, instanceUri, appData, goBack }: Props) => {
2021-01-28 00:41:53 +01:00
const redirectUri = AuthSession.makeRedirectUri({
native: 'tooot://instance-auth',
useProxy: false
})
2021-01-27 00:35:34 +01:00
2021-01-07 19:13:09 +01:00
const navigation = useNavigation()
const queryClient = useQueryClient()
const dispatch = useDispatch()
const [request, response, promptAsync] = AuthSession.useAuthRequest(
{
clientId: appData.clientId,
clientSecret: appData.clientSecret,
scopes: ['read', 'write', 'follow', 'push'],
2021-01-16 14:16:58 +01:00
redirectUri
2021-01-07 19:13:09 +01:00
},
{
authorizationEndpoint: `https://${instanceDomain}/oauth/authorize`
}
)
useEffect(() => {
;(async () => {
if (request?.clientId) {
await promptAsync()
}
})()
}, [request])
useEffect(() => {
;(async () => {
if (response?.type === 'success') {
const { accessToken } = await AuthSession.exchangeCodeAsync(
{
clientId: appData.clientId,
clientSecret: appData.clientSecret,
scopes: ['read', 'write', 'follow', 'push'],
2021-01-16 14:16:58 +01:00
redirectUri,
2021-01-07 19:13:09 +01:00
code: response.params.code,
extraParams: {
grant_type: 'authorization_code'
}
},
{
tokenEndpoint: `https://${instanceDomain}/oauth/token`
}
)
queryClient.clear()
dispatch(
localAddInstance({
url: instanceDomain,
token: accessToken,
2021-01-17 22:37:05 +01:00
uri: instanceUri,
2021-01-07 19:13:09 +01:00
appData
})
)
goBack && navigation.goBack()
}
})()
}, [response])
return <></>
},
() => true
)
export default InstanceAuth