10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Firebase Authentication 個人的メモ

Last updated at Posted at 2018-03-02

Qiita初投稿で、書き方も良い構成も全然わからないですが、個人的に今後の開発で使うだろうなぁと思った物をメモしていきます。間違いなどあるかと思いますので、指摘していただけるとありがたいです。

Firebase Authentication

https://firebase.google.com/docs/auth/
firebaseコンソールで使う認証方法を有効にしたりする。

Sign Up

Mail And Password

signup_mail.kt
  private lateinit var mAuth: FirebaseAuth
  private var currentUser: FirebaseUser? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    mAuth = FirebaseAuth.getInstance()
    //ボタンリスナー
    sign_up_btn.setOnClickListener {  it: View!
      signUp()
    }
  }

  private fun signUp(){
    val emailStr = input_email.text.toString()  //editTextとか。
    val passwordStr = input_password.text.toString()

    mAuth.createUserWithEmailAndPassword(emailStr, passwordStr)
         .addOnCompleteListener { task: Task<AuthResult> ->
               if(task.isSuccessful){
                    makeToast(this@SignInActivity, "Create Account Success!")
                    updateUI(mAuth.currentUser)  //activity移るとか、ボタン消すとか。
               }else{
                    makeToast(this@SignInActivity, "Sign Up Failed.")
               }
          }
  }

Sign In

Mail And Password

signin_mail.kt
  private lateinit var mAuth: FirebaseAuth
  private var currentUser: FirebaseUser? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    mAuth = FirebaseAuth.getInstance()

    sign_in_btn.setOnClickListener {  it: View!
      signIn()
    }
  }

  private fun signIn(){
    val emailStr = input_email.text.toString()
    val passwordStr = input_password.text.toString()

    mAuth.signInWithEmailAndPassword(emailStr, passStr)
                .addOnCompleteListener { task: Task<AuthResult> ->
                    if (!task.isSuccessful) {
                        makeToast(this@SignInActivity, "Sign In Failed.")
                        return@addOnCompleteListener
                    }
                    makeToast(this@SignInActivity, "Sign In is success.")
                    updateUI(mAuth.currentUser)
                }
  }

Google

signin_google.kt
  private lateinit var mAuth: FirebaseAuth
  private var currentUser: FirebaseUser? = null
  private var mGoogleSignInClient? = null  //追加

  override fun onCreate(savedInstanceState: Bundle?) {
    mAuth = FirebaseAuth.getInstance()

    val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()  //Email情報取りたい場合
                .build()
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso)

    sign_in_btn.setOnClickListener {  it: View!
      signIn()
    }
  }

  private fun signIn(){
    val signInIntent = mGoogleSignInClient?.signInIntent
    startActivityForResult(signInIntent, RC_SIGN_IN)
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == RC_SIGN_IN) {
            val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
            if (result.isSuccess) {
                // Google Sign In was successful, authenticate with Firebase
                val account = result.signInAccount
                firebaseAuthWithGoogle(account!!)
            } else {
                makeToast(this@SignInActivity, "Google Auth is Failed.")
            }
        }
  }

  //Googleサインインを元にfirebaseへサインイン
  private fun firebaseAuthWithGoogle(account: GoogleSignInAccount) {
        val credential = GoogleAuthProvider.getCredential(account.idToken, null)
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener { task: Task<AuthResult> ->
                    if(!task.isSuccessful){
                        makeToast(this@SignInActivity, "firebase auth with credential is failed.")
                        return@addOnCompleteListener
                    }
                    updateUI(mAuth.currentUser)
                }
    }

Sign Out

Mail And Password

sign_out_mail.kt
  mAuth.signOut()  //firebaseのSignOut
  updateUI(currentUser = null)

GoogleアカウントでFirebase認証した場合

sign_out_google.kt
  mAuth.signOut()
  //GoogleからもSignOutする
  mGoogleSignInClient!!.signOut()
                    .addOnCompleteListener { task: Task<Void> ->
                        if(!task.isSuccessful){
                            makeToast(this@MainActivity, "Sign Out Failed.")
                            return@addOnCompleteListener
                        }
                        makeToast(this@MainActivity, "Google Sign Out.")
                    }
  updateUI(currentUser = null)

どの認証方法でSignInしたか。(Provider)

  if(currentUser!!.providers.toString() == "[google.com]"){
      //Googleで認証した場合の処理
  }else{
      //その他
    }

プロバイダの判定はこれであっているのでしょうか…。一応動いているので良しとします。
providerIdを取得してみると、Google認証を使っていても"firebase"と返ってきました。

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?