我可以让 Firebase 使用用户名登录过程吗? [英] Can I make Firebase use a username login process?

查看:23
本文介绍了我可以让 Firebase 使用用户名登录过程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个允许用户名登录的系统.此过程需要以下内容:

  1. 用户必须使用电子邮件/密码进行注册
  2. 用户可以设置唯一的用户名
  3. 用户可以使用电子邮件或用户名登录
  4. 用户可以通过电子邮件或用户名找回密码
  5. 该功能必须适用于启用持久性的数据库

这个问题之前已经回答过,但它禁用了用户使用密码恢复的功能.他们也没有解决区分大小写的问题,一个人可以注册为史酷比",另一个人可以注册为史酷比".

解决方案

免责声明:这段代码现在已经两年多了.虽然这并不意味着它已被弃用,但我强烈建议在假设这是最佳方法之前调查替代方法.我个人不希望 Firebase 的标准登录过程由我最初解决问题的方法决定,而 Firebase 的采用率没有现在这么高.

<小时><小时>

经过多次迭代开发,我想出了以下设计来解决这个问题.我将在 Swift 中发布我的代码片段,但它们通常可以轻松地直接翻译成 Android.

<小时>

  1. 为电子邮件/密码创建 Firebase 注册流程.

这是用户登录体验的支柱所必需的.这可以完全从需要注意的几点:

  • 用户名存储两次,一次在 usernames 中,另一次在 details/[uid]/username 中.我建议这样做,因为它允许您对用户名区分大小写(请参阅下一点),它还允许您知道确切的数据库引用以检查用户名(usernames/scooby),而不必查询或检查 details 的子级以找到匹配的用户名(当您必须考虑区分大小写时,这只会变得更加复杂)
  • usernames 引用以小写形式存储.当我检查此引用中的值或保存到此引用时,我确保只以小写形式保存数据.这意味着如果有人想检查用户名scoobY"是否存在,它将失败,因为在小写时它与现有用户Scooby"的用户名相同.
  • details/[uid]/username 字段包含大写.这允许在用户偏好的情况下显示用户名,而不是强制使用小写或大写单词,用户可以将他们的名字指定为NASA Fan"而不是转换为Nasa Fan",同时也防止注册用户名NASA FAN"(或任何其他案例迭代)的任何其他人
  • 电子邮件存储在用户详细信息中.这可能看起来很奇怪,因为您可以通过 Firebase.auth().currentUser.email? 检索当前用户的电子邮件.这样做是必要的,因为我们需要在以用户身份登录之前引用电子邮件.
<小时>

  1. 使用电子邮件或用户名登录

为了使其无缝运行,您需要在登录时进行一些检查.

因为我不允许在用户名中使用@ 字符,所以我可以假设包含@ 的登录请求是电子邮件请求.这些请求会正常处理,使用 Firebase 的 FIRAuth.auth().signInWithEmail(email, password, completion) 方法.

对于所有其他请求,我们将假定它是用户名请求.注意:强制转换为小写.

let ref = FIRDatabase.database().reference()让 usernameRef = ref.child("users/usernames/(username.lowercaseString)")

执行此检索时,您应该考虑是否启用了持久性,以及是否有可能撤销用户名.如果用户名可以被撤销并且您启用了持久性,您将需要确保在事务块中检索用户名值,以确保您不会获得缓存值.

当这个检索成功时,你从username[username]中得到值,它是用户的uid.使用此值,您现在可以对用户的电子邮件值执行检索:

let ref = FIRDatabase.database().reference()let usernameRef = ref.child("users/details/[uid]/email")

此请求成功后,您就可以使用刚刚检索到的电子邮件字符串执行标准 Firebase 电子邮件登录.

完全相同的检索方法可用于从用户名中检索电子邮件以恢复密码.

高级功能需要注意的几点:- 如果您允许用户使用 FIRUserProfileChangeRequest 更新他们的电子邮件, 确保在 auth 和 details[uid]email 字段上更新它,否则您将破坏用户名登录功能- 通过使用成功和失败块,您可以显着减少处理检索方法中所有不同失败情况所需的代码.这是我的获取电子邮件方法的示例:

static func getEmail(username:String, success:(email:String) -> Void, failure:(error:String!) -> Void) {让 usernameRef = FIRDatabase.database().reference().child("users/usernames/(username.lowercaseString)")usernameRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in如果让 userId = snapshot.value 作为?细绳 {让 emailRef = FIRDatabase.database().reference().child("users/details/(userId)/email")emailRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in如果让电子邮件 = snapshot.value 作为?细绳 {成功(电子邮件:电子邮件)} 别的 {失败(错误:找不到用户名'(用户名)'的电子邮件.")}}) {(错误)在失败(错误:找不到电子邮件.")}} 别的 {失败(错误:找不到用户名'(用户名)'的帐户.")}}) {(错误)在失败(错误:找不到用户名.")}}

这个成功/失败块的实现让我在我的 ViewControllers 中调用的代码更加清晰.Å login 调用如下方法:

if fieldText.containsString("@") {loginWithEmail(fieldText)} 别的 {//尝试获取用户名的电子邮件.LoginHelper.getEmail(fieldText, success: { (email) inself.loginWithEmail(email)}, 失败: { 错误在HUD.flash(.Error, delay: 0.5)})}

I want to make a system which allows for username login. This process requires the following:

  1. User must register with an email/password
  2. The user can set a unique username
  3. The user can sign in with either email or username
  4. The user can recover their password via email or username
  5. The functionality must work on a persistence enabled database

This question has been answered previously, but it disabled the functionality for the user to use password recovery. They also didn't address case-sensitivity, one person could register as "scooby" and another as "Scooby".

解决方案

DISCLAIMER: This code is now over two years old. While this doesn't mean it's deprecated, I would strongly recommend investigating alternative methods before assuming this is the best approach. I personally wouldn't want the standard login process for Firebase to be dictated by my initial approach to a problem while Firebase wasn't as heavily adopted as it is now.



After multiple iterations of development I've come up with the following design to address this. I will post my code snippets in Swift, but they will typically be translatable directly into Android with ease.


  1. Create a Firebase registration process for email/password.

This is required as the backbone of the user's sign-in experience. This can be implemented completely from the stock Firebase API documentation provided here


  1. Prompt the user to enter their username

The username entry should be completed at registration, I'd recommend an additional field in the registration flow. I also recommend checking if the user has a username whenever they log in. If they don't, then display a SetUsername interface that prompts them to set a username before progressing further into the UI. A user might not have a username for a few reasons; it could be revoked for being rude or reserved, or they might have signed up prior to the username being required at registration.

Make sure that if you're using a persistence-enabled Firebase build that you use Firebase Transactions. The transactions are necessary, otherwise your app can make assumptions about the data in the username table, even though a username might have been set for a user only seconds earlier.

I would also advise enforcing the username to be nearly alphanumeric (I allow for some harmless punctuation). In Swift I can achieve this with the following code:

static var invalidCharacters:NSCharacterSet {
    let chars = NSMutableCharacterSet.alphanumericCharacterSet()

    // I add _ - and . to the valid characters.
    chars.addCharactersInString("_-.")

    return chars.invertedSet
}

if username.rangeOfCharacterFromSet(invalidCharacters) != nil {
    // The username is valid
}


  1. Saving the user data

The next important step is knowing how to save the user's data in a way that we can access it in the future. Below is a screenshot of the way I store my user data: A few things to note:

  • The usernames are stored twice, once in usernames and again in details/[uid]/username. I recommend this as it allows you to be case sensitive with usernames (see the next point) and it also allows you to know the exact database reference to check a username (usernames/scooby) rather than having to query or check through the children of details to find a username that matches (which would only become more complicated when you have to factor in case-sensitivity)
  • the usernames reference is stored in lowercase. When I check the values in this reference, or when I save to this reference, I ensure that I only save data in lowercase. This means if anyone wants to check if the username 'scoobY' exists, it will fail because in lowercase it's the same username as the existing user "Scooby".
  • The details/[uid]/username field contains capitals. This allows for the username to display in the case of preference for the user, rather than enforcing a lowercase or Capitalised word, the user can specify their name as "NASA Fan" and not be converted over to "Nasa Fan", while also preventing anyone else from registering the username "NASA FAN" (or any other case iterations)
  • The emails are being stored in the user details. This might seem peculiar because you can retrieve the current user's email via Firebase.auth().currentUser.email?. The reason this is necessary is because we need references to the emails prior to logging in as the user.

  1. Logging in with email or username

For this to work seamlessly, you need to incorporate a few checks at login.

Since I've disallowed the @ character in usernames, I can assume that a login request containing an @ is an email request. These requests get processed as normal, using Firebase's FIRAuth.auth().signInWithEmail(email, password, completion) method.

For all other requests, we will assume it's a username request. Note: The cast to lowercase.

let ref = FIRDatabase.database().reference()
let usernameRef = ref.child("users/usernames/(username.lowercaseString)")

When you perform this retrieval, you should consider if you have persistence-enabled, and if there's a possibility that a username could be revoked. If a username could be revoked and you have persistence-enabled, you will want to ensure you retrieve the username value within a Transaction block, to make sure you don't get a cached value back.

When this retrieval succeeds, you get the value from username[username], which is the user's uid. With this value, you can now perform a retrieval on the user's email value:

let ref = FIRDatabase.database().reference()
let usernameRef = ref.child("users/details/[uid]/email")

Once this request succeeds, you can then perform the standard Firebase email login with the email string you just retrieved.

The exact same retrieval methods can be used to retrieve an email from a username to allow for password recovery.

A few points to be wary of for advanced functionality: - If you allow the user to update their email using FIRUserProfileChangeRequest, make sure you update it both on the auth AND the details[uid]email field, otherwise you will break the username login functionality - You can significantly reduce the code required to handle all the different failure cases in the retrieval methods by using success and failure blocks. Here's an example of my get email method:

static func getEmail(username:String, success:(email:String) -> Void, failure:(error:String!) -> Void) {
    let usernameRef = FIRDatabase.database().reference().child("users/usernames/(username.lowercaseString)")

    usernameRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
        if let userId = snapshot.value as? String {
            let emailRef = FIRDatabase.database().reference().child("users/details/(userId)/email")

            emailRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
                if let email = snapshot.value as? String {
                    success(email: email)
                } else {
                    failure(error: "No email found for username '(username)'.")
                }
            }) { (error) in
                failure(error: "Email could not be found.")
            }
        } else {
            failure(error: "No account found with username '(username)'.")
        }
    }) { (error) in
        failure(error: "Username could not be found.")
    }
}

This success/failure block implementation allows the code I call in my ViewControllers to be much cleaner. Å login calls the following method:

if fieldText.containsString("@") {
    loginWithEmail(fieldText)
} else {
    // Attempt to get email for username.
    LoginHelper.getEmail(fieldText, success: { (email) in
        self.loginWithEmail(email)
    }, failure: { error in
        HUD.flash(.Error, delay: 0.5)
    })
}

这篇关于我可以让 Firebase 使用用户名登录过程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆