-
Notifications
You must be signed in to change notification settings - Fork 65
/
authService.js
executable file
·117 lines (96 loc) · 2.71 KB
/
authService.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import jwtDecode from 'jwt-decode';
import axios from 'src/utils/axios';
import firebase from 'firebase';
class AuthService {
// Configure Firebase.
config = {
apiKey: 'AIzaSyBogaqI7q74Wml7AD90VVm_89o1cgFFQCo',
authDomain: 'code-for-cause-leaders.firebaseapp.com',
projectId: 'code-for-cause-leaders',
storageBucket: 'code-for-cause-leaders.appspot.com',
messagingSenderId: '58409560329',
appId: '1:58409560329:web:60ffc3c128d3b155a18bd8',
measurementId: 'G-49RJ8QM95E'
// ...
};
// Configure FirebaseUI.
uiConfig = {
// Popup signin flow rather than redirect flow.
signInFlow: 'popup',
signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
callbacks: {
// Avoid redirects after sign-in.
signInSuccessWithAuthResult: () => false
}
};
firebase = firebase;
user = {};
setAxiosInterceptors = ({ onLogout }) => {
axios.interceptors.response.use(
response => response,
error => {
if (error.response && error.response.status === 401) {
this.setSession(null);
if (onLogout) {
onLogout();
}
}
return Promise.reject(error);
}
);
};
handleAuthentication() {
this.firebase.initializeApp(this.config);
}
signInWithEmailAndPassword(email, password) {
return this.firebase.auth().signInWithEmailAndPassword(email, password);
}
login = () => {
this.keycloak.init().then(authenticated => {
if (!authenticated) {
this.keycloak.login();
}
});
};
loginInWithToken = () =>
new Promise((resolve, reject) => {
axios
.get('/api/account/me')
.then(response => {
if (response.data.user) {
resolve(response.data.user);
} else {
reject(response.data.error);
}
})
.catch(error => {
reject(error);
});
});
logout = () => {
this.firebase.auth().signOut();
this.setSession(null);
};
setSession = accessToken => {
if (accessToken) {
localStorage.setItem('accessToken', accessToken);
axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
} else {
localStorage.removeItem('accessToken');
delete axios.defaults.headers.common.Authorization;
}
};
getAccessToken = () => localStorage.getItem('accessToken');
isValidToken = accessToken => {
if (!accessToken) {
return false;
}
const decoded = jwtDecode(accessToken);
const currentTime = Date.now() / 1000;
return decoded.exp > currentTime;
};
isAuthenticated = () => !!this.keycloak.authenticated;
}
const authService = new AuthService();
export default authService;
export { firebase };