Firebase에서 사용자 관리하기

사용자 생성

Firebase 프로젝트에서 신규 사용자를 생성할 때는 createUserWithEmailAndPassword 메서드를 호출하는 방법과 Google 로그인 또는 Facebook 로그인과 같은 제휴 ID 공급업체를 이용해 사용자의 최초 로그인을 처리하는 방법이 있습니다.

또한 Firebase Console '인증' 섹션의 '사용자' 페이지에서 또는 Admin SDK를 활용하여 비밀번호 인증을 사용하는 신규 사용자를 생성할 수 있습니다.

현재 로그인한 사용자 가져오기

현재 사용자를 가져올 때 권장하는 방법은 다음과 같이 Auth 객체에 관찰자를 설정하는 것입니다.

웹 모듈식 API

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/auth.user
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

웹 네임스페이스화된 API

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/v8/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

관찰자를 사용하면 현재 사용자를 가져올 때 Auth 객체가 중간 단계(초기화 등)에 있지 않도록 할 수 있습니다. signInWithRedirect를 사용하면 onAuthStateChanged 관찰자는 getRedirectResult가 해결될 때까지 기다린 후에 트리거됩니다.

currentUser 속성을 사용하여 현재 로그인한 사용자를 가져올 수도 있습니다. 사용자가 로그인 상태가 아니라면 currentUser 값이 null입니다.

웹 모듈식 API

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/auth.user
  // ...
} else {
  // No user is signed in.
}

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/v8/firebase.User
  // ...
} else {
  // No user is signed in.
}

사용자 프로필 가져오기

사용자의 프로필 정보를 가져오려면 User 인스턴스의 속성을 사용합니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // The user's ID, unique to the Firebase project. Do NOT use
  // this value to authenticate with your backend server, if
  // you have one. Use User.getToken() instead.
  const uid = user.uid;
}

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // The user's ID, unique to the Firebase project. Do NOT use
  // this value to authenticate with your backend server, if
  // you have one. Use User.getIdToken() instead.
  const uid = user.uid;
}

제공업체별 사용자 프로필 정보 가져오기

사용자에게 연결된 로그인 제공업체로부터 프로필 정보를 가져오려면 providerData 속성을 사용합니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

사용자 프로필 업데이트

사용자의 표시 이름 및 프로필 사진 URL 등의 기본 프로필 정보를 업데이트할 때는 updateProfile 메서드를 사용합니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
  displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Profile updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});  

사용자 이메일 주소 설정

updateEmail 메서드로 사용자의 이메일 주소를 설정할 수 있습니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth, updateEmail } from "firebase/auth";
const auth = getAuth();
updateEmail(auth.currentUser, "user@example.com").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;

user.updateEmail("user@example.com").then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

사용자에게 인증 메일 보내기

sendEmailVerification 메서드로 사용자에게 주소 인증 메일을 보낼 수 있습니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth, sendEmailVerification } from "firebase/auth";

const auth = getAuth();
sendEmailVerification(auth.currentUser)
  .then(() => {
    // Email verification sent!
    // ...
  });

웹 네임스페이스화된 API

firebase.auth().currentUser.sendEmailVerification()
  .then(() => {
    // Email verification sent!
    // ...
  });

또한 Firebase Console '인증' 섹션의 '이메일 템플릿' 페이지에서 이메일 템플릿을 맞춤설정할 수 있습니다. Firebase 고객센터의 이메일 템플릿 항목을 참조하세요.

인증 메일을 보낼 때 연결 URL을 통해 상태를 전달하여 앱으로 다시 리디렉션할 수도 있습니다.

또한 이메일을 보내기 전에 인증 인스턴스의 언어 코드를 업데이트하면 인증 메일을 현지화할 수 있습니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

웹 네임스페이스화된 API

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

사용자 비밀번호 설정

updatePassword 메서드로 사용자의 비밀번호를 설정할 수 있습니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth, updatePassword } from "firebase/auth";

const auth = getAuth();

const user = auth.currentUser;
const newPassword = getASecureRandomPassword();

updatePassword(user, newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;
const newPassword = getASecureRandomPassword();

user.updatePassword(newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

비밀번호 재설정 이메일 보내기

sendPasswordResetEmail 메서드로 사용자에게 비밀번호 재설정 이메일을 보낼 수 있습니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth, sendPasswordResetEmail } from "firebase/auth";

const auth = getAuth();
sendPasswordResetEmail(auth, email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

웹 네임스페이스화된 API

firebase.auth().sendPasswordResetEmail(email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ..
  });

또한 Firebase Console '인증' 섹션의 '이메일 템플릿' 페이지에서 이메일 템플릿을 맞춤설정할 수 있습니다. Firebase 고객센터의 이메일 템플릿 항목을 참조하세요.

비밀번호 재설정 이메일을 보낼 때 연결 URL을 통해 상태를 전달하여 앱으로 다시 리디렉션할 수도 있습니다.

또한 이메일을 보내기 전에 인증 인스턴스의 언어 코드를 업데이트하면 비밀번호 재설정 이메일을 현지화할 수 있습니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

웹 네임스페이스화된 API

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

또한 Firebase Console에서 비밀번호 재설정 이메일을 보낼 수도 있습니다.

사용자 삭제하기

delete 메서드로 사용자 계정을 삭제할 수 있습니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth, deleteUser } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

deleteUser(user).then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;

user.delete().then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

또한 Firebase Console '인증' 섹션의 '사용자' 페이지에서 사용자를 삭제할 수도 있습니다.

사용자 재인증

계정 삭제, 기본 이메일 주소 설정, 비밀번호 변경과 같이 보안에 민감한 작업을 하려면 사용자가 최근에 로그인한 적이 있어야 합니다. 이런 작업을 할 때 사용자가 너무 오래 전에 로그인했다면 오류가 발생하면서 작업이 실패합니다. 이때에는 사용자에게 새로운 로그인 인증 정보를 받은 다음 이 정보를 reauthenticateWithCredential에 전달하여 사용자를 재인증해야 합니다. 예를 들면 다음과 같습니다.

웹 모듈식 API

import { getAuth, reauthenticateWithCredential } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

reauthenticateWithCredential(user, credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error ocurred
  // ...
});

웹 네임스페이스화된 API

const user = firebase.auth().currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

user.reauthenticateWithCredential(credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error occurred
  // ...
});

사용자 계정 가져오기

Firebase CLI의 auth:import 명령어를 사용하여 파일에서 Firebase 프로젝트로 사용자 계정을 가져올 수 있습니다. 예를 들면 다음과 같습니다.

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14