Skip to content

Commit af5548d

Browse files
authored
cache token (#476)
<!--変更したい場合は、`/.github/pull_request_template.md` を修正して下さい。--> # PRの概要 close #475 <!-- 変更の目的 もしくは 関連する Issue 番号 --> <!-- 以下のように書くと Issue にリンクでき、マージ時に自動で Issue を閉じられる--> <!-- closes #1 --> ## 具体的な変更内容 <!-- ビューの変更がある場合はスクショによる比較などがあるとわかりやすい --> ## 影響範囲 <!-- この関数を変更したのでこの機能にも影響がある、など --> ## 動作要件 <!-- 動作に必要な 環境変数 / 依存関係 / DBの更新 など --> ## 補足 <!-- レビューをする際に見てほしい点、ローカル環境で試す際の注意点、など --> ## レビューリクエストを出す前にチェック! - [ ] 改めてセルフレビューしたか - [ ] 手動での動作検証を行ったか - [ ] server の機能追加ならば、テストを書いたか - 理由: 書いた | server の機能追加ではない - [ ] 間違った使い方が存在するならば、それのドキュメントをコメントで書いたか - 理由: 書いた | 間違った使い方は存在しない - [ ] わかりやすいPRになっているか <!-- レビューリクエスト後は、Slackでもメンションしてお願いすることを推奨します。 -->
1 parent e57bac5 commit af5548d

File tree

1 file changed

+23
-21
lines changed

1 file changed

+23
-21
lines changed

web/src/firebase/auth/lib.ts

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
11
import { getAuth, onAuthStateChanged } from "firebase/auth";
22
import type { User } from "firebase/auth";
33
import type { IDToken } from "../../common/types";
4+
import { app } from "../config";
45

56
export class ErrUnauthorized extends Error {}
67

7-
export async function getIdToken(): Promise<IDToken> {
8-
const auth = getAuth();
9-
const user = await new Promise<User>((resolve) => {
10-
const unsubscribe = onAuthStateChanged(auth, (user: User | null) => {
11-
if (user != null) {
12-
resolve(user);
13-
unsubscribe();
14-
} else {
15-
console.error("getIdToken: user is null");
16-
}
17-
});
18-
});
19-
20-
if (user == null) {
21-
throw new Error(
22-
"Client Error: firebase/auth/lib.ts: current user not found",
23-
);
8+
let user: User;
9+
let token: string;
10+
11+
const auth = getAuth(app);
12+
onAuthStateChanged(auth, async (u: User | null) => {
13+
if (u != null) {
14+
user = u;
15+
token = await user.getIdToken();
2416
}
17+
});
18+
19+
async function refreshToken() {
20+
token = await user.getIdToken(true);
21+
}
2522

26-
return await user.getIdToken(true);
23+
export async function getIdToken(): Promise<IDToken> {
24+
if (token) return token;
25+
await refreshToken();
26+
return token;
2727
}
2828

2929
type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -48,9 +48,11 @@ export async function credFetch(
4848
};
4949
}
5050

51-
const res = await fetch(`${path}?token=${idToken}`, init);
51+
let res = await fetch(`${path}?token=${idToken}`, init);
52+
if (res.status === 401) {
53+
await refreshToken();
54+
res = await fetch(`${path}?token=${idToken}`);
55+
}
5256

53-
// if (res.status === 401) throw new ErrUnauthorized();
54-
// if (!res.ok) throw new Error("response was not ok");
5557
return res;
5658
}

0 commit comments

Comments
 (0)