220 lines
8.6 KiB
JavaScript
220 lines
8.6 KiB
JavaScript
import React, {useEffect, useState} from 'react';
|
|
import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform, KeyboardAvoidingView} from 'react-native';
|
|
import {useAuthStore} from '@/store/authStore';
|
|
import {useRouter} from 'expo-router';
|
|
|
|
import {Box} from "@/components/ui/box"
|
|
import {Button, ButtonText, ButtonIcon} from "@/components/ui/button"
|
|
import {Center} from "@/components/ui/center"
|
|
import {Heading} from "@/components/ui/heading"
|
|
import {Input, InputField, InputIcon, InputSlot} from "@/components/ui/input"
|
|
import {Text} from "@/components/ui/text"
|
|
import {VStack} from "@/components/ui/vstack"
|
|
import {HStack} from "@/components/ui/hstack"
|
|
import {ArrowRightIcon, EyeIcon, EyeOffIcon} from "@/components/ui/icon"
|
|
import {Divider} from '@/components/ui/divider';
|
|
import {Ionicons} from "@expo/vector-icons";
|
|
|
|
import * as WebBrowser from 'expo-web-browser';
|
|
import * as Google from "expo-auth-session/providers/google";
|
|
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
import {makeRedirectUri} from "expo-auth-session";
|
|
|
|
import Constants from 'expo-constants';
|
|
|
|
WebBrowser.maybeCompleteAuthSession();
|
|
|
|
// client_id ios 936418008320-ohefdfcebd41f6oa2o8phh1mgj9s49sl.apps.googleusercontent.com
|
|
// android 936418008320-d8dfjph5e4r28fcm1rbdfbh5phmbg03d.apps.googleusercontent.com
|
|
|
|
export default function Login() {
|
|
const [email, setEmail] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [emailError, setEmailError] = useState('');
|
|
const [showPassword, setShowPassword] = useState(false)
|
|
const {signIn, isLoading, signInWithGoogle} = useAuthStore();
|
|
const router = useRouter();
|
|
|
|
const [request, response, promptAsync] = Google.useAuthRequest({
|
|
androidClientId: "936418008320-d8dfjph5e4r28fcm1rbdfbh5phmbg03d.apps.googleusercontent.com",
|
|
iosClientId: "936418008320-ohefdfcebd41f6oa2o8phh1mgj9s49sl.apps.googleusercontent.com",
|
|
webClientId: "936418008320-btdngtlfnjac1p67guje72m9el5q59a7.apps.googleusercontent.com",
|
|
redirectUri:
|
|
Platform.OS === 'android'
|
|
? makeRedirectUri({
|
|
scheme: Constants.expoConfig.android.package,
|
|
path: '/',
|
|
})
|
|
: undefined,
|
|
})
|
|
|
|
const handleInternalLogin = async () => {
|
|
if (!email || !password) {
|
|
alert('Proszę wprowadzić email i hasło.');
|
|
return;
|
|
}
|
|
|
|
if (!validateEmail(email)) {
|
|
setEmailError('Nieprawidłowy format adresu email');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await signIn(email, password);
|
|
alert(`Zalogowano jako ${email}`);
|
|
router.replace('/');
|
|
} catch (e) {
|
|
alert("Błąd logowania: " + (e.response?.data?.message || e.message));
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
handleGoogleLogin();
|
|
}, [response]);
|
|
|
|
const handleGoogleLogin = async () => {
|
|
// const user = await AsyncStorage.getItem("@user");
|
|
let user = null;
|
|
if (!user) {
|
|
if (response.type === "success") {
|
|
user = await getUserInfo(response.authentication.accessToken)
|
|
await signInWithGoogle(response.authentication.accessToken);
|
|
alert(`Zalogowano jako ${user.email}`);
|
|
router.replace('/');
|
|
}
|
|
|
|
} else {
|
|
console.info("Pobrano użytkownika z AsyncStorage:", JSON.parse(user));
|
|
alert(`Zalogowano jako ${user.email}`);
|
|
}
|
|
};
|
|
|
|
const getUserInfo = async (token) => {
|
|
if (!token) {
|
|
return
|
|
}
|
|
try {
|
|
const response = await fetch("https://www.googleapis.com/userinfo/v2/me",
|
|
{
|
|
headers: {
|
|
Authorization: `Bearer ${token}`
|
|
},
|
|
}
|
|
);
|
|
const user = await response.json();
|
|
await AsyncStorage.setItem("@user", JSON.stringify(user));
|
|
return user;
|
|
} catch (error) {
|
|
console.error("Błąd podczas pobierania informacji o użytkowniku:", error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
const validateEmail = (email) => {
|
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
return emailRegex.test(email);
|
|
};
|
|
|
|
const handleShowPassword = () => {
|
|
setShowPassword((showState) => {
|
|
return !showState
|
|
})
|
|
}
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<View style={styles.container}>
|
|
<ActivityIndicator size="large"/>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<KeyboardAvoidingView
|
|
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
|
style={{flex: 1}}
|
|
keyboardVerticalOffset={Platform.OS === "ios" ? 64 : 0}
|
|
>
|
|
<SafeAreaView style={styles.container}>
|
|
<Center>
|
|
<Box className="p-5 max-w-96 border border-background-300 rounded-lg">
|
|
<VStack className="pb-4" space="xs">
|
|
<Heading className="leading-[30px]">Logowanie</Heading>
|
|
<Box className="flex flex-row">
|
|
{/* <Link href="/registration" asChild> */}
|
|
<Button variant="link" size="sm" className="p-0"
|
|
onPress={() => router.replace("/registration")}>
|
|
<ButtonText style={styles.signupbutton}>Nie masz jeszcze konta? Załóz je
|
|
tutaj!</ButtonText>
|
|
<ButtonIcon className="mr-1" size="md" as={ArrowRightIcon}/>
|
|
</Button>
|
|
{/* </Link> */}
|
|
</Box>
|
|
</VStack>
|
|
<VStack space="xl" className="py-2">
|
|
{emailError ? <Text style={styles.errorText}>{emailError}</Text> : null}
|
|
<Input isRequired={true} isInvalid={!!emailError}>
|
|
<InputField className="py-2" inputMode="email" placeholder="Login"
|
|
onChangeText={(text) => {
|
|
setEmail(text);
|
|
if (text && !validateEmail(text)) {
|
|
setEmailError('Nieprawidłowy format adresu email');
|
|
} else {
|
|
setEmailError('');
|
|
}
|
|
}}
|
|
/>
|
|
</Input>
|
|
<Input isRequired={true}>
|
|
<InputField type={showPassword ? "text" : "password"} className="py-2"
|
|
placeholder="Hasło"
|
|
onChangeText={setPassword}/>
|
|
<InputSlot className="pr-3" onPress={handleShowPassword}>
|
|
<InputIcon as={showPassword ? EyeIcon : EyeOffIcon}/>
|
|
</InputSlot>
|
|
</Input>
|
|
</VStack>
|
|
<VStack space="lg" className="pt-4">
|
|
<Button size="sm" onPress={handleInternalLogin}>
|
|
<ButtonText>Zaloguj się</ButtonText>
|
|
</Button>
|
|
</VStack>
|
|
|
|
<HStack alignItems="center" space="sm" className="pt-6 pb-6">
|
|
<Divider flex={1}/>
|
|
<Text fontSize="$sm" className="text-gray-300">
|
|
lub
|
|
</Text>
|
|
<Divider flex={1}/>
|
|
</HStack>
|
|
<Button size="sm" onPress={() => promptAsync()}>
|
|
<Ionicons name="logo-google" color="#fff"/>
|
|
</Button>
|
|
</Box>
|
|
</Center>
|
|
</SafeAreaView>
|
|
</KeyboardAvoidingView>
|
|
);
|
|
}
|
|
|
|
const styles = StyleSheet.create({
|
|
container: {
|
|
flex: 1,
|
|
justifyContent: 'center',
|
|
padding: 20,
|
|
},
|
|
input: {
|
|
borderWidth: 1,
|
|
borderColor: '#ddd',
|
|
borderRadius: 5,
|
|
marginBottom: 15,
|
|
padding: 10,
|
|
},
|
|
errorText: {
|
|
color: 'red',
|
|
fontSize: 12,
|
|
},
|
|
signupbutton: {
|
|
fontWeight: '300',
|
|
},
|
|
}); |