서버/1.(Firebase) Authentication

[4]_1_3. (Firebase) 비밀번호 변경 / 탈퇴

skyotter84 2022. 7. 24. 16:29

 

 

 

 

 


비밀번호 변경 

 

비밀번호 변경은 이메일/패스워드 로그인 방식에만 해당하며 탈퇴를 전체를 포괄한다.

 

우선 로그인이 완료된 화면에서 비밀번호 버튼을 만들고 구글을 이용해 로그인을 할 경우는 안 보이게 하는 코드를 작성한다.

 

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let email = Auth.auth().currentUser?.email ?? "고객"
        lblWelcome.text = """
        환영합니다.
        \(email)님
        """
        
        let isEmailSignIn = Auth.auth().currentUser?.providerData[0].providerID == "password"
        btnChangePassword.isHidden = !isEmailSignIn
        
    }

 

print로 콘솔창에 Auth.auth().currentUser?.providerData[0].providerID를 찍어보면

 

구글로 로그인 시 "google.com"

 

이메일/패스워드 로그인 시 "password"로 나타난다.

 

따라서 패스워드로 로그인 하지 않은 경우는 비밀번호 변경 버튼을 hidden 처리하도록 코드를 작성한다.

 

 

 

 

 

이제 비밀번호 변경 버튼을 눌렀을 때의 코드를 작성하면

  @IBAction func tabBtnChangePassword(_ sender: UIButton) {
        let email = Auth.auth().currentUser?.email ?? ""
        Auth.auth().sendPasswordReset(withEmail: email, completion: nil)
    }

꽤 간단하다.

 

user 정보에서 이메일을 가져오고sendPasswordReset 명령어에 그 이메일만 주면

 

Firebase에서 알아서 해당 이메일로 reset을 진행할 수 있는 이메일을 보내주고 처리해준다. 정말 똑똑한 집사님이다.

 

 

 

 

 


탈퇴

 

강의에서 구현한 기능은 여기까지인데 로그인 / 로그아웃 / 비밀번호 변경이 있는데 탈퇴가 없으니까 섭하다.

 

위 기능들이 모두 Auth.auth()에 있으니 탈퇴도 있을 것이라 생각했고, 탈퇴가 영어로 뭐더라...하고 검색하니

 

delete users account라고 문장으로 쓴다더라.

 

그래서 Auth.auth().delete를 찍어보니 currentUser 뒤에 나타난다.

작성 후 실행해보니 유저가 체감하지 못할 정도로 진행되서 경고알럿완료알럿 및 화면 이동을 추가했다.

 

  @IBAction func tabBtnDeleteUser(_ sender: UIButton) {
        let deleteAlert = UIAlertController(title: "탈퇴", message: "탈퇴를 할 경우, 모든 데이터가 소멸됩니다.", preferredStyle: .alert)
        deleteAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
            Auth.auth().currentUser?.delete()
            self.deleteUserDone()
        }))
        deleteAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        present(deleteAlert, animated: true)
        
    }
    
    private func deleteUserDone() {
        let deleteDoneAlert = UIAlertController(title: "탈퇴가 완료되었습니다.", message: nil, preferredStyle: .alert)
        deleteDoneAlert.addAction(UIAlertAction(title: "확인", style: .default, handler: { _ in
            self.navigationController?.popToRootViewController(animated: true)
        }))
        self.present(deleteDoneAlert, animated: true)
        
    }

지금 보니 완료 알럿 및 화면 이동 코드는 currentUser.delete 핸들러 안에 작성하면 됐을 것 같다.

 

 

 

 

 

그동안 애를 먹던 구글 로그인을 그래도 일단 구현할 수 있었다. 

 

며칠을 깊이 있게 고민하고 파서 안 되도, 다음날 얕은 고민으로 해결될 때가 많다.

 

허무하긴 하지만 그렇게만이도 되면 어디냐. 빠샤!