/
app.js
100 lines (90 loc) · 3.55 KB
/
app.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
// FirebaseのSDKをインポート
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.0/firebase-app.js";
import { getAuth, connectAuthEmulator, sendPasswordResetEmail, signInWithEmailAndPassword, onAuthStateChanged, signOut, initializeAuth, browserLocalPersistence } from "https://www.gstatic.com/firebasejs/10.7.0/firebase-auth.js";
// Firebaseの設定
const firebaseConfig = {
apiKey: "AIzaSyAp_2RtaVDeWhNEnmfy0A7o2Gq_7DUTKN0",
authDomain: "authentication-basic-400a6.firebaseapp.com",
projectId: "authentication-basic-400a6",
storageBucket: "authentication-basic-400a6.appspot.com",
messagingSenderId: "393706331983",
appId: "1:393706331983:web:e54c1fecffec8586ce6f3a",
measurementId: "G-K6DHS6MYLK"
};
// Firebaseの初期化
const app = initializeApp(firebaseConfig);
// iOSを判定する関数
const isIos = () => {
const userAgent = navigator.userAgent;
return /iPad|iPhone|iPod/i.test(userAgent);
}
// Authenticationのインスタンスを取得
let auth;
if (isIos()) {
auth = initializeAuth(app, {
persistence: browserLocalPersistence,
})
} else {
auth = getAuth(app);
}
auth.languageCode = 'ja'; // パスワードリセットメールやパスワードリセット画面の言語設定
// connectAuthEmulator(auth, "http://127.0.0.1:9099"); // Emulatorを起動する場合、コメントを外す
// パスワード再設定メールを送信ボタンがクリックされたときの処理
const onClickSendPasswordResetEmail = () => {
const email = document.getElementById("emailForPasswordReset").value;
sendPasswordResetEmail(auth, email)
.then(() => {
alert("パスワードリセットメールを送信しました");
})
.catch((error) => {
alert("パスワードリセットメールを送信に失敗しました");
console.error(error);
});
};
// ログインボタンがクリックされたときの処理
const onClickLogin = () => {
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// ログイン成功
alert("ログインしました");
const user = userCredential.user;
console.log(user);
})
.catch((error) => {
alert("ログインエラーです");
console.error(error);
});
};
// ログイン状態が変わった時に実行される処理
onAuthStateChanged(auth, (user) => {
renderLoginStatus(user);
});
// ログイン状態を画面に反映させる関数
const renderLoginStatus = (user) => {
const loginStatus = document.getElementById("loginStatus");
let html = `<p>未ログイン</p>`;
if (user) {
html = `
<p>ログイン中</p>
<p>ユーザー名:${user.displayName}</p>
<p>メールアドレス:${user.email}</p>
<p>ユーザーID:${user.uid}</p>
<button class="button" id="logoutButton">ログアウト</button>
`;
}
loginStatus.innerHTML = html;
if (user) {
document.getElementById('logoutButton').addEventListener('click', onClickLogout);
}
}
// ログアウトボタンがクリックされたときの処理
const onClickLogout = () => {
signOut(auth).then(() => {
alert("ログアウトしました");
}).catch((error) => {
console.error(error);
});
};
export { onClickSendPasswordResetEmail, onClickLogin };