forked from firebase/quickstart-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanon.ts
68 lines (61 loc) · 1.76 KB
/
anon.ts
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
import { firebaseConfig } from './config';
import { initializeApp } from 'firebase/app';
import {
getAuth,
signInAnonymously,
connectAuthEmulator,
signOut,
onAuthStateChanged,
} from 'firebase/auth';
initializeApp(firebaseConfig);
const auth = getAuth();
if (window.location.hostname === 'localhost') {
connectAuthEmulator(auth, 'http://127.0.0.1:9099');
}
const signInButton = document.getElementById(
'quickstart-sign-in',
)! as HTMLButtonElement;
const signInStatus = document.getElementById(
'quickstart-sign-in-status',
)! as HTMLSpanElement;
const accountDetails = document.getElementById(
'quickstart-account-details',
)! as HTMLDivElement;
/**
* Handles the sign in button press.
*/
function toggleSignIn() {
if (auth.currentUser) {
signOut(auth);
} else {
signInAnonymously(auth).catch(function (error) {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
if (errorCode === 'auth/operation-not-allowed') {
alert('You must enable Anonymous auth in the Firebase Console.');
} else {
console.error(error);
}
});
}
signInButton.disabled = true;
}
// Listening for auth state changes.
onAuthStateChanged(auth, function (user) {
if (user) {
// User is signed in.
const isAnonymous = user.isAnonymous;
const uid = user.uid;
signInStatus.textContent = 'Signed in';
signInButton.textContent = 'Sign out';
accountDetails.textContent = JSON.stringify(user, null, ' ');
} else {
// User is signed out.
signInStatus.textContent = 'Signed out';
signInButton.textContent = 'Sign in';
accountDetails.textContent = 'null';
}
signInButton.disabled = false;
});
signInButton.addEventListener('click', toggleSignIn, false);