-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGithubAuth.js
72 lines (61 loc) · 1.76 KB
/
GithubAuth.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
import * as firebase from 'firebase';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/toPromise';
import { getAuthenticatedUser } from './Github';
let _accessToken;
let _userInfo;
export function startAuth() {
const provider = new firebase.auth.GithubAuthProvider();
provider.addScope('repo');
provider.setCustomParameters({
'allow_signup': 'false'
});
firebase.auth().signInWithRedirect(provider);
}
export function signOut() {
const auth = firebase.auth();
localStorage.removeItem(tokenLocalStorageKey(auth.currentUser.uid));
auth.signOut();
window.location.reload(); // TODO: without refresh
}
function firebaseAuthStateChanges() {
return Observable.create(obs => {
const unsubscribe = firebase.auth().onAuthStateChanged(
user => obs.next(user),
err => obs.error(err),
() => obs.complete()
);
return unsubscribe;
});
}
function tokenLocalStorageKey(uid) {
return `githubTokens/${uid}`;
}
export async function initialize() {
const result = await firebase.auth().getRedirectResult();
let accessToken;
if (result.user) {
// Redirected
localStorage.setItem(tokenLocalStorageKey(result.user.uid), result.credential.accessToken);
accessToken = result.credential.accessToken;
} else {
const user = await firebaseAuthStateChanges().first().toPromise();
if (user) {
accessToken = localStorage.getItem(tokenLocalStorageKey(user.uid));
}
}
if (accessToken) {
_accessToken = accessToken;
_userInfo = await getAuthenticatedUser().toPromise();
}
}
export function getAccessToken() {
return _accessToken;
}
export function getUserInfo() {
return _userInfo;
}
export function isAuthenticated() {
return Boolean(_userInfo);
}