Skip to content

Commit

Permalink
Oauth (#24)
Browse files Browse the repository at this point in the history
* starting push notifications. problems

* chat push notifications logic.

* add handler for different types. TODO: add more types.

* add accepted request notification type.

* remove comments

* oauth init.

* add endpoint of oauth.

* ups.

* add logout in google.

* remove sensible files.

* remove comment.
  • Loading branch information
olifer97 authored Jul 21, 2020
1 parent 5e019da commit c747511
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 9 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"expo-av": "~8.2.1",
"expo-constants": "~9.1.1",
"expo-font": "~8.2.1",
"expo-google-sign-in": "~8.2.1",
"expo-image-picker": "~8.3.0",
"expo-notifications": "~0.3.3",
"expo-permissions": "~9.0.1",
Expand Down
11 changes: 10 additions & 1 deletion src/app/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'react-native-gesture-handler';
import React from 'react';
import React, { useEffect } from 'react';
import { Image } from 'react-native';
import { useSelector } from 'react-redux';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
Expand Down Expand Up @@ -33,6 +34,14 @@ Notifications.setNotificationHandler({
})
});

Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false
})
});

const Stack = createStackNavigator();
const WallStack = createStackNavigator();
const Tab = createBottomTabNavigator();
Expand Down
44 changes: 43 additions & 1 deletion src/app/screens/LoginScreen/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
TouchableOpacity
} from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import * as GoogleSignIn from 'expo-google-sign-in';

import logo from '@assets/tutubo-03.png';
import CustomButton from '@components/CustomButton';
Expand All @@ -22,6 +23,7 @@ import styles from './styles';
function LoginScreen({ navigation }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [googleLoading, setGoogleLoading] = useState(false);

const emailValid = validateEmail(email);
const passwordValid = password.length > 0;
Expand All @@ -44,6 +46,7 @@ function LoginScreen({ navigation }) {

useEffect(() => {
if (token) {
setGoogleLoading(false);
navigation.reset({
index: 0,
routes: [{ name: ROUTES.Home }]
Expand All @@ -52,6 +55,36 @@ function LoginScreen({ navigation }) {
}
}, [token, cleanLogin, navigation]);

useEffect(() => {
initAsync();
}, [initAsync]);

const initAsync = useCallback(async () => {
await GoogleSignIn.initAsync();
}, []);

const _syncUserWithStateAsync = useCallback(async () => {
const user = await GoogleSignIn.signInSilentlyAsync();
dispatch(actionCreator.oauth(user.auth.idToken, user.photoURL));
}, [dispatch]);

const signInAsync = useCallback(async () => {
try {
setGoogleLoading(true);
const { type } = await GoogleSignIn.signInAsync();
if (type === 'success') {
await _syncUserWithStateAsync();
}
} catch ({ message }) {
alert('login: Error:' + message);
setGoogleLoading(false);
}
}, [_syncUserWithStateAsync]);

const onPressLoginGoogle = useCallback(() => {
signInAsync();
}, [signInAsync]);

const onNavigateToRegister = useCallback(() => {
cleanLogin();
navigation.navigate(ROUTES.SignUp);
Expand Down Expand Up @@ -88,7 +121,7 @@ function LoginScreen({ navigation }) {
textStyle={disable ? styles.textDisable : styles.loginButtonText}
onPress={onSubmit}
disable={disable}
loading={authLoading}
loading={authLoading && !googleLoading}
loaderColor={COLORS.white}
/>
<CustomButton
Expand All @@ -98,6 +131,15 @@ function LoginScreen({ navigation }) {
onPress={onNavigateToRegister}
disable={authLoading}
/>
<CustomButton
text="INGRESAR CON GOOGLE"
style={[styles.loginButton]}
textStyle={disable ? styles.textDisable : styles.loginButtonText}
onPress={onPressLoginGoogle}
disable={authLoading && !googleLoading}
loading={googleLoading}
loaderColor={COLORS.white}
/>
<TouchableOpacity onPress={onNavigateToResetPassword}>
<Text style={styles.forgotPassword}>Olvidaste tu contraseña?</Text>
</TouchableOpacity>
Expand Down
24 changes: 20 additions & 4 deletions src/redux/auth/actions.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import * as GoogleSignIn from 'expo-google-sign-in';

import {
login,
register,
oauth,
setSession,
removeSession
} from '@services/AuthService';
Expand All @@ -15,7 +18,8 @@ export const actions = {
REGISTER: '@@AUTH/REGISTER',
REGISTER_SUCCESS: '@@AUTH/REGISTER_SUCCESS',
REGISTER_FAILURE: '@@AUTH/REGISTER_FAILURE',
CLEAN_STATE: '@@AUTH/CLEAN_STATE'
CLEAN_STATE: '@@AUTH/CLEAN_STATE',
OAUTH: '@@AUTH/OAUTH'
};

export const actionCreator = {
Expand All @@ -39,9 +43,13 @@ export const actionCreator = {
api.setHeader('access-token', session.token);
return { type: actions.SAVE_CURRENT_SESSION, payload: session };
},
logout: () => {
logout: () => async (dispatch, getState) => {
dispatch({ type: actions.LOGOUT });
const { googleUser } = getState().auth;
if (googleUser) {
await GoogleSignIn.signOutAsync();
}
removeSession();
return { type: actions.LOGOUT };
},
register: (info) => async (dispatch) => {
dispatch({ type: actions.REGISTER });
Expand All @@ -59,7 +67,15 @@ export const actionCreator = {
}),
cleanState: () => ({
type: actions.CLEAN_STATE
})
}),
oauth: (idToken, photoURL) => async (dispatch) => {
dispatch({ type: actions.OAUTH });
const response = await oauth(idToken, photoURL);
if (response?.ok) {
setSession(response.data);
dispatch(actionCreator.loginSuccess(response.data));
} else dispatch(actionCreator.loginFailure(response?.data.reason));
}
};

export default actionCreator;
11 changes: 10 additions & 1 deletion src/redux/auth/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const initialState = {
token: '',
error: null,
registered: false,
currentUser: {}
currentUser: {},
googleUser: false
};

function reducer(state = initialState, action) {
Expand Down Expand Up @@ -67,6 +68,14 @@ function reducer(state = initialState, action) {
error: null,
loading: false
};
case actions.OAUTH:
return {
...state,
loading: true,
token: '',
error: null,
googleUser: true
};
default:
return state;
}
Expand Down
7 changes: 5 additions & 2 deletions src/services/AuthService.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import api from '@config/api';
export const login = (username, password) =>
api.post('/login', { email: username, password });

export const oauth = (idToken, photoURL) =>
api.post('/oauth2login', { idToken, photoURL });

export const register = (info) => api.post('/register', info);

export const resetPassword = (email) => api.post(`/reset_password`, { email });
Expand All @@ -22,8 +25,8 @@ export const getSession = async () => {
return { token, user: { id: parseInt(id, 10), username } };
};

export const removeSession = () => {
AsyncStorage.removeItem('access-token');
export const removeSession = async () => {
await AsyncStorage.removeItem('access-token');
AsyncStorage.removeItem('userid');
AsyncStorage.removeItem('username');
api.deleteHeader('access-token');
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4260,6 +4260,13 @@ expo-font@~8.2.1:
fbjs "1.0.0"
fontfaceobserver "^2.1.0"

expo-google-sign-in@~8.2.1:
version "8.2.1"
resolved "https://registry.yarnpkg.com/expo-google-sign-in/-/expo-google-sign-in-8.2.1.tgz#eae43b7c8ea890eed03e47ae28d25cf896b9efce"
integrity sha512-rWBbL5+/xMyzAzDxjtEoeBP/E35aJoRDijlU+AWvkHlxtqxLDqAVbNC/eWGnW/erTEpJrSj1Lt/arhPFiBQrLA==
dependencies:
invariant "^2.2.4"

expo-image-picker@~8.3.0:
version "8.3.0"
resolved "https://registry.yarnpkg.com/expo-image-picker/-/expo-image-picker-8.3.0.tgz#5a9daacbc1afa7fdbfd31edb22818524ad0b85e2"
Expand Down

0 comments on commit c747511

Please sign in to comment.