Skip to content

Commit

Permalink
アカウント登録をした時にバックエンドでアカウントを作成するように変更
Browse files Browse the repository at this point in the history
  • Loading branch information
MurakawaTakuya committed Jan 14, 2025
1 parent bfde582 commit 9eb0be3
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 53 deletions.
32 changes: 31 additions & 1 deletion functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import express from "express";
import { rateLimit } from "express-rate-limit";
import admin from "firebase-admin";
import { logger } from "firebase-functions";
import { onRequest } from "firebase-functions/v2/https";
import { HttpsError, onRequest } from "firebase-functions/v2/https";
import { beforeUserCreated } from "firebase-functions/v2/identity";
import helmet from "helmet";
import serviceAccount from "./serviceAccountKey.json";

Expand Down Expand Up @@ -138,3 +139,32 @@ export const helloWorld = onRequest({ region: region }, (req, res) => {
logger.info("Hello log!", { structuredData: true });
res.send("Hello World!");
});

const db = admin.firestore();

// アカウント作成時に実行される処理
export const beforecreated = beforeUserCreated(
{ region: region },
async (event) => {
const user = event.data;

if (!user) {
throw new HttpsError("invalid-argument", "No user data provided.");
}
const userId = user?.uid;
const name = user?.displayName || "No Name";

try {
await db.collection("user").doc(userId).set({
name: name,
streak: 0,
fcmToken: "",
});
} catch (error) {
logger.error(error);
throw new HttpsError("internal", "Error creating user data.");
}

return;
}
);
2 changes: 1 addition & 1 deletion src/app/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ if (typeof window !== "undefined") {
isTokenAutoRefreshEnabled: true,
});

getToken(appCheck)
await getToken(appCheck)
.then((token) => {
console.log("App Check: Success");
appCheckToken = token.token;
Expand Down
1 change: 1 addition & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export default function RootLayout({
<link rel="icon" type="image/svg+xml" href="/appIcon.svg" />
<link rel="apple-touch-icon" href="/icon512_maskable.png"></link>
<meta name="theme-color" content="#2EC6FE" />
<meta name="description" content={description} />

{/* Open Graph */}
<meta property="og:title" content="TODO REAL" />
Expand Down
25 changes: 0 additions & 25 deletions src/utils/API/User/createUser.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/utils/API/User/fetchUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const fetchUserById = async (userId: string): Promise<User> => {
* @return {*}
*/
export const handleFetchUserError = (error: unknown) => {
let snackBarMessage = "初回ログインかユーザーデータが見つかりません";
let snackBarMessage = "ユーザーデータが見つかりません";

if (error instanceof Error) {
if (error.message.includes("404")) {
Expand Down
20 changes: 3 additions & 17 deletions src/utils/Auth/signInWithGoogleAccount.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,15 @@
import { auth, googleProvider } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { createUser } from "@/utils/API/User/createUser";
import { updateUser } from "@/utils/UserContext";
import { getAdditionalUserInfo, signInWithPopup } from "firebase/auth";
import { signInWithPopup } from "firebase/auth";

/**
* Firebase Authenticationを使ってGoogleアカウントでログインする
* 初回ログインの時のみデータベースにユーザー情報を登録する
*
*
*/
export const signInWithGoogleAccount = async () => {
try {
const result = await signInWithPopup(auth, googleProvider);

// 初めての時だけユーザー情報を登録する
if (getAdditionalUserInfo(result)?.isNewUser) {
// uidとdocument IDを一致させる
await createUser(result.user.displayName ?? "no name", result.user.uid);
updateUser({
userId: result.user.uid,
name: result.user.displayName ?? "no name",
loginType: "Google",
isMailVerified: result.user.emailVerified,
});
}
await signInWithPopup(auth, googleProvider);

showSnackBar({
message: "Googleアカウントでログインしました",
Expand Down
25 changes: 19 additions & 6 deletions src/utils/Auth/signUpWithMail.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { auth } from "@/app/firebase";
import { appCheckToken, auth, functionsEndpoint } from "@/app/firebase";
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { createUser } from "@/utils/API/User/createUser";
import { updateUser } from "@/utils/UserContext";
import {
createUserWithEmailAndPassword,
sendEmailVerification,
updateProfile,
} from "firebase/auth";
import { updateUser } from "../UserContext";

/**
* Firebase Authenticationを使ってメールでユーザーを作成し、生成されたuserIdをドキュメントIDとしてFirestoreにユーザー情報を登録する
Expand All @@ -33,8 +32,22 @@ export const signUpWithMail = async (
console.error("プロファイル更新に失敗しました:", profileUpdateError);
}

// userIdとdocument IDを一致させる
await createUser(name, user.uid);
// displayNameをFirestoreに登録
const response = await fetch(`${functionsEndpoint}/user/${user.uid}`, {
method: "PUT",
headers: {
"X-Firebase-AppCheck": appCheckToken,
"Content-Type": "application/json",
},
body: JSON.stringify({ name }),
});

if (!response.ok) {
const status = response.status;
const data = await response.json();
throw new Error(`Error ${status}: ${data.message}`);
}

updateUser({
userId: user.uid,
name: name,
Expand All @@ -46,7 +59,7 @@ export const signUpWithMail = async (
try {
await sendEmailVerification(user);
} catch (verificationError) {
console.error("failed to send email verification:", verificationError);
console.error("Failed to send email verification:", verificationError);
}

showSnackBar({
Expand Down
2 changes: 0 additions & 2 deletions src/utils/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,6 @@ export const UserProvider = ({ children }: Props) => {

try {
const userData = await fetchUserById(firebaseUser.uid);
// ユーザーデータを作成する前にfetchしようとして"User not found"になるので、postした場所でsetさせている
// "User not found"ではない(= 初回ログイン直後ではない)場合のみsetする
if (userData.userId) {
setUser({
...userData,
Expand Down

0 comments on commit 9eb0be3

Please sign in to comment.