summaryrefslogtreecommitdiffstats
path: root/src/features/auth/services/authService.ts
blob: 54ff58f7792587a70e44ef63bd7a35e2fbcc3f3f (plain)
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
import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signOut,
  updateProfile,
  User,
} from 'firebase/auth';
import { doc, serverTimestamp, setDoc } from 'firebase/firestore';
import { auth, db } from '@/shared/lib/firebase/config';

type RegisterParams = {
  email: string;
  password: string;
  displayName: string;
};

type LoginParams = {
  email: string;
  password: string;
};

export const authService = {
  async register({ email, password, displayName }: RegisterParams): Promise<User> {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    const user = userCredential.user;

    if (displayName.trim()) {
      await updateProfile(user, { displayName });
    }

    await setDoc(doc(db, 'users', user.uid), {
      email: user.email,
      displayName: displayName.trim(),
      createdAt: serverTimestamp(),
    });

    return user;
  },

  async login({ email, password }: LoginParams): Promise<User> {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  },

  async logout(): Promise<void> {
    await signOut(auth);
  },
};