|
| 1 | +import { auth, db } from '@/lib/firebase'; |
| 2 | +import { |
| 3 | + createUserWithEmailAndPassword, |
| 4 | + updateProfile, |
| 5 | + GithubAuthProvider, |
| 6 | + signInWithPopup, |
| 7 | + getAdditionalUserInfo, |
| 8 | +} from 'firebase/auth'; |
| 9 | +import { getDoc, doc, serverTimestamp, setDoc } from 'firebase/firestore'; |
| 10 | + |
| 11 | +export type SignupPayload = { |
| 12 | + nickname: string; |
| 13 | + email: string; |
| 14 | + password: string; |
| 15 | +}; |
| 16 | + |
| 17 | +export const signupWithEmail = async (p: SignupPayload) => { |
| 18 | + const cred = await createUserWithEmailAndPassword(auth, p.email, p.password); |
| 19 | + await updateProfile(cred.user, { displayName: p.nickname }); |
| 20 | + await setDoc(doc(db, 'users', cred.user.uid), { |
| 21 | + nickname: p.nickname, |
| 22 | + email: p.email, |
| 23 | + createdAt: serverTimestamp(), |
| 24 | + streakDays: 0, |
| 25 | + tilCount: 0, |
| 26 | + }); |
| 27 | + return cred.user; |
| 28 | +}; |
| 29 | + |
| 30 | +export const signupWithGithub = async () => { |
| 31 | + const provider = new GithubAuthProvider(); |
| 32 | + |
| 33 | + const result = await signInWithPopup(auth, provider); |
| 34 | + const user = result.user; |
| 35 | + |
| 36 | + const info = getAdditionalUserInfo(result); |
| 37 | + const githubUsername = info?.username ?? null; |
| 38 | + |
| 39 | + const userRef = doc(db, 'users', user.uid); |
| 40 | + const snap = await getDoc(userRef); |
| 41 | + |
| 42 | + if (!snap.exists()) { |
| 43 | + await setDoc(userRef, { |
| 44 | + userId: user.uid, |
| 45 | + nickname: user.displayName ?? githubUsername ?? '익명', |
| 46 | + email: user.email ?? '', |
| 47 | + provider: 'github.com', |
| 48 | + githubUsername, |
| 49 | + createdAt: serverTimestamp(), |
| 50 | + streakDays: 0, |
| 51 | + tilCount: 0, |
| 52 | + }); |
| 53 | + } |
| 54 | + return user; |
| 55 | +}; |
0 commit comments