Custom Access Token functions & Constant URL

Constant URL for the auth server
This commit is contained in:
Arnab Chakraborty
2024-09-17 23:16:46 -04:00
parent 117c1a1860
commit 4e4e964d48
7 changed files with 112 additions and 87 deletions

View File

@@ -40,6 +40,7 @@ import { changeTwTheme, tw } from './lib/tailwind';
import RootNavigator from './navigation';
import OnboardingNavigator from './navigation/OnboardingNavigator';
import { P2P } from './screens/p2p/P2P';
import { AUTH_SERVER_URL } from './utils';
import { currentLibraryStore } from './utils/nav';
LogBox.ignoreLogs(['Sending `onAnimatedValueUpdate` with no listeners registered.']);
@@ -158,7 +159,7 @@ export default function App() {
global.Intl = require('intl');
require('intl/locale-data/jsonp/en'); //TODO(@Rocky43007): Setup a way to import all the languages we support, once we add localization on mobile.
SuperTokens.init({
apiDomain: 'http://localhost:9420',
apiDomain: AUTH_SERVER_URL,
apiBasePath: '/api/auth'
});
SplashScreen.hideAsync();

View File

@@ -92,7 +92,7 @@ const Devices = ({ node, stats }: Props) => {
}, [node]);
return (
<OverviewSection title="Devices" count={node ? 1 : 0}>
<OverviewSection title="Devices" count={node ? 1 + (devices.data?.length ?? 0) : 0}>
<View>
<Fade height={'100%'} width={30} color="black">
<ScrollView
@@ -111,7 +111,7 @@ const Devices = ({ node, stats }: Props) => {
connectionType={null}
/>
)}
{/* {devices.data?.map((device) => (
{devices.data?.map((device) => (
<StatCard
key={device.pub_id}
name={device.name}
@@ -122,7 +122,7 @@ const Devices = ({ node, stats }: Props) => {
color="#0362FF"
connectionType={'cloud'}
/>
))} */}
))}
<NewCard
icons={['Laptop', 'Server', 'SilverBox', 'Tablet']}
text="Spacedrive works best on all your devices."

View File

@@ -26,6 +26,7 @@ import {
SettingsStackScreenProps,
User
} from '~/navigation/tabs/SettingsStack';
import { AUTH_SERVER_URL } from '~/utils';
type SectionType = {
title: string;
@@ -183,7 +184,7 @@ export default function SettingsScreen({ navigation }: SettingsStackScreenProps<
const [userInfo, setUserInfo] = useState<User | null>(null);
useEffect(() => {
async function _() {
const user_data = await fetch('http://localhost:9420/api/user', {
const user_data = await fetch(`${AUTH_SERVER_URL}/api/user`, {
method: 'GET'
});
const data = await user_data.json();

View File

@@ -32,75 +32,75 @@ const AccountLogin = () => {
const [activeTab, setActiveTab] = useState<'Login' | 'Register'>('Login');
// FIXME: Currently opens in App.
const socialLoginHandlers = (name: SocialLogin['name']) => {
return {
Github: async () => {
try {
const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({
thirdPartyId: 'github',
// const socialLoginHandlers = (name: SocialLogin['name']) => {
// return {
// Github: async () => {
// try {
// const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({
// thirdPartyId: 'github',
// This is where Github should redirect the user back after login or error.
frontendRedirectURI: 'http://localhost:9420/api/auth/callback/github'
});
// // This is where Github should redirect the user back after login or error.
// frontendRedirectURI: 'http://localhost:9420/api/auth/callback/github'
// });
// we redirect the user to Github for auth.
window.location.assign(authUrl);
} catch (err: any) {
if (err.isSuperTokensGeneralError === true) {
// this may be a custom error message sent from the API by you.
toast.error(err.message);
} else {
toast.error('Oops! Something went wrong.');
}
}
},
Google: async () => {
try {
const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({
thirdPartyId: 'google',
// // we redirect the user to Github for auth.
// window.location.assign(authUrl);
// } catch (err: any) {
// if (err.isSuperTokensGeneralError === true) {
// // this may be a custom error message sent from the API by you.
// toast.error(err.message);
// } else {
// toast.error('Oops! Something went wrong.');
// }
// }
// },
// Google: async () => {
// try {
// const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({
// thirdPartyId: 'google',
// This is where Google should redirect the user back after login or error.
// This URL goes on the Google's dashboard as well.
frontendRedirectURI: 'http://localhost:9420/api/auth/callback/google'
});
// // This is where Google should redirect the user back after login or error.
// // This URL goes on the Google's dashboard as well.
// frontendRedirectURI: 'http://localhost:9420/api/auth/callback/google'
// });
/*
Example value of authUrl: https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&access_type=offline&include_granted_scopes=true&response_type=code&client_id=1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com&state=5a489996a28cafc83ddff&redirect_uri=https%3A%2F%2Fsupertokens.io%2Fdev%2Foauth%2Fredirect-to-app&flowName=GeneralOAuthFlow
*/
// /*
// Example value of authUrl: https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&access_type=offline&include_granted_scopes=true&response_type=code&client_id=1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com&state=5a489996a28cafc83ddff&redirect_uri=https%3A%2F%2Fsupertokens.io%2Fdev%2Foauth%2Fredirect-to-app&flowName=GeneralOAuthFlow
// */
// we redirect the user to google for auth.
window.location.assign(authUrl);
} catch (err: any) {
if (err.isSuperTokensGeneralError === true) {
// this may be a custom error message sent from the API by you.
toast.error(err.message);
} else {
toast.error('Oops! Something went wrong.');
}
}
},
Apple: async () => {
try {
const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({
thirdPartyId: 'apple',
// // we redirect the user to google for auth.
// window.location.assign(authUrl);
// } catch (err: any) {
// if (err.isSuperTokensGeneralError === true) {
// // this may be a custom error message sent from the API by you.
// toast.error(err.message);
// } else {
// toast.error('Oops! Something went wrong.');
// }
// }
// },
// Apple: async () => {
// try {
// const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({
// thirdPartyId: 'apple',
// This is where Apple should redirect the user back after login or error.
frontendRedirectURI: 'http://localhost:9420/api/auth/callback/apple'
});
// // This is where Apple should redirect the user back after login or error.
// frontendRedirectURI: 'http://localhost:9420/api/auth/callback/apple'
// });
// we redirect the user to Apple for auth.
window.location.assign(authUrl);
} catch (err: any) {
if (err.isSuperTokensGeneralError === true) {
// this may be a custom error message sent from the API by you.
toast.error(err.message);
} else {
toast.error('Oops! Something went wrong.');
}
}
}
}[name]();
};
// // we redirect the user to Apple for auth.
// window.location.assign(authUrl);
// } catch (err: any) {
// if (err.isSuperTokensGeneralError === true) {
// // this may be a custom error message sent from the API by you.
// toast.error(err.message);
// } else {
// toast.error('Oops! Something went wrong.');
// }
// }
// }
// }[name]();
// };
return (
<ScreenContainer scrollview={false} style={tw`gap-2 px-6`}>

View File

@@ -1,16 +1,19 @@
import { useNavigation } from '@react-navigation/native';
import { Envelope } from 'phosphor-react-native';
import { useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import Card from '~/components/layout/Card';
import ScreenContainer from '~/components/layout/ScreenContainer';
import { Button } from '~/components/primitive/Button';
import { tw } from '~/lib/tailwind';
import { User } from '~/navigation/tabs/SettingsStack';
import { SettingsStackScreenProps, User } from '~/navigation/tabs/SettingsStack';
import { AUTH_SERVER_URL } from '~/utils';
const AccountProfile = () => {
const [userInfo, setUserInfo] = useState<User | null>(null);
useEffect(() => {
async function _() {
const user_data = await fetch('http://localhost:9420/api/user', {
const user_data = await fetch(`${AUTH_SERVER_URL}/api/user`, {
method: 'GET'
});
const data = await user_data.json();
@@ -26,6 +29,14 @@ const AccountProfile = () => {
const emailName = userInfo ? userInfo.email.split('@')[0] : '';
const capitalizedEmailName = (emailName?.charAt(0).toUpperCase() ?? '') + emailName?.slice(1);
const navigator = useNavigation<SettingsStackScreenProps<'AccountLogin'>['navigation']>();
function signOut() {
fetch(`${AUTH_SERVER_URL}/api/auth/signout`, {
method: 'POST'
}).then(() => {
navigator.navigate('AccountLogin');
});
}
return (
<ScreenContainer scrollview={false} style={tw`gap-2 px-6`}>
@@ -48,6 +59,10 @@ const AccountProfile = () => {
<Text style={tw`text-white`}>{userInfo ? userInfo.email : ''}</Text>
</Card>
</View>
<Button variant="danger" style={tw`mt-4`} onPress={signOut}>
<Text style={tw`text-white`}>Sign Out</Text>
</Button>
</View>
</Card>
</View>

View File

@@ -1,3 +1,4 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
import { useState } from 'react';
import { Controller } from 'react-hook-form';
@@ -9,6 +10,7 @@ import { Input } from '~/components/primitive/Input';
import { toast } from '~/components/primitive/Toast';
import { tw } from '~/lib/tailwind';
import { SettingsStackScreenProps } from '~/navigation/tabs/SettingsStack';
import { AUTH_SERVER_URL } from '~/utils';
import ShowPassword from './ShowPassword';
@@ -18,7 +20,7 @@ async function signInClicked(
navigator: SettingsStackScreenProps<'AccountProfile'>['navigation']
) {
try {
const req = await fetch('http://localhost:9420/api/auth/signin', {
const req = await fetch(`${AUTH_SERVER_URL}/api/auth/signin`, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
@@ -67,6 +69,8 @@ async function signInClicked(
// sign in successful. The session tokens are automatically handled by
// the frontend SDK.
toast.success('Sign in successful');
// Save the access token to AsyncStorage, because SuperTokens doesn't store it correctly. Thanks to the React Native SDK.
await AsyncStorage.setItem('access_token', req.headers.get('st-access-token')!);
// Refresh the page to show the user is logged in
navigator.navigate('AccountProfile');
}
@@ -104,19 +108,21 @@ const Login = () => {
control={form.control}
name="email"
render={({ field }) => (
<Input
{...field}
placeholder="Email"
style={tw`w-full`}
onChangeText={field.onChange}
/>
<View style={tw`relative flex items-center justify-end`}>
<Input
{...field}
placeholder="Email"
style={tw`w-full`}
onChangeText={field.onChange}
/>
{form.formState.errors.email && (
<Text style={tw`text-xs text-red-500`}>
{form.formState.errors.email.message}
</Text>
)}
</View>
)}
/>
{form.formState.errors.email && (
<Text style={tw`text-xs text-red-500`}>
{form.formState.errors.email.message}
</Text>
)}
<Controller
control={form.control}
name="password"
@@ -129,6 +135,11 @@ const Login = () => {
onChangeText={field.onChange}
secureTextEntry={!showPassword}
/>
{form.formState.errors.password && (
<Text style={tw`text-xs text-red-500`}>
{form.formState.errors.password.message}
</Text>
)}
<ShowPassword
showPassword={showPassword}
setShowPassword={setShowPassword}
@@ -136,11 +147,6 @@ const Login = () => {
</View>
)}
/>
{form.formState.errors.password && (
<Text style={tw`text-xs text-red-500`}>
{form.formState.errors.password.message}
</Text>
)}
<Button
style={tw`mx-auto mt-2 w-full`}
variant="accent"

View File

@@ -1,6 +1,8 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
export async function getAccessToken() {
const fetched = await AsyncStorage.getItem('supertokens-rn-front-token-key');
const fetched = await AsyncStorage.getItem('access_token');
return fetched;
}
export const AUTH_SERVER_URL = __DEV__ ? 'http://localhost:9420' : 'https://auth.spacedrive.com';