[英]Logging in a pre-existing user with new Omniauth method
If a user has registered on my website using the "native" email registration, and then later, being logged out, wants to use their Facebook to log in, I want this to be just fine, and to "combine" the info into one user. 如果用户使用“本机”电子邮件注册在我的网站上注册,然后注销,然后希望使用其Facebook登录,我希望这很好,并将信息“组合”为一个用户。 Here is my method for doing so:
这是我这样做的方法:
def self.from_omniauth(auth)
if user = User.find_by(email: auth.info.email)
user.provider ||= auth.provider
user.uid ||= auth.uid
user.first_name ||= auth.info.first_name
user.last_name ||= auth.info.last_name
user.save
user
elsif user = User.create(provider: auth.provider, uid: auth.uid)
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.save
user
end
end
It appears to work fine, though my tests are pretty simple. 尽管我的测试非常简单,但它似乎工作正常。 I just have a few questions, being a relatively amateur programmer and appreciating the wisdom of those with the experience to know not just "how to" but "how best to.
我只是有几个问题,是一个相对业余的程序员,并且赞赏那些有经验的人的智慧,他们不仅知道“如何”,而且知道“如何最好”。
Is this a common and "legit" practice? 这是常见的“合法”做法吗? Is there maybe some privacy or "best practice" concern I'm not thinking of?
我可能没有想到某些隐私或“最佳实践”问题?
Is there a way to combine the find_by
and create
calls, the two branches of my if/elsif
statement? 有没有一种方法可以组合
find_by
和create
调用,这是我的if/elsif
语句的两个分支? Actually, this post has a great answer in using tap
. 实际上, 这篇文章在使用
tap
方面有很好的答案。 Is there any reason not to do that? 有什么理由不这样做吗?
What is the usual way to do this with more than one provider (like if the user we're talking about who has registered with email, then logged in with Facebook, then logs in with Google)? 与多个提供者进行此操作的通常方法是什么(例如,如果我们正在谈论的用户是谁注册了电子邮件,然后使用Facebook登录,然后使用Google登录)? My best guess is either a hash or a whole other ActiveRecord object.
我最好的猜测是哈希或整个其他ActiveRecord对象。 (can you even store a hash as a property of an ActiveRecord object?)
(您甚至可以将散列存储为ActiveRecord对象的属性吗?)
I hope it's okay to post a question that isn't exactly a problem. 我希望可以发布并非完全是问题的问题。 Thanks for the advice!
谢谢你的建议!
1 )I have done what you did and don't think it's a problem subjectly. 1 )我已经做了您所做的事情,从主题上看这不成问题。 Having two users with same email can be a hassle to manage as user base grows.
随着用户群的增长,让两个用户使用同一封电子邮件可能会很麻烦。
2 )You can use find_or_create_by
ie: 2 )您可以使用
find_or_create_by
即:
def self.from_omniauth(auth)
user = User.find_or_create_by(email: auth.info.email) do |u|
u.provider = auth.provider
u.uid = auth.uid
...
end
end
3 ) ActiveRecord supports storing hash
in column. 3 )ActiveRecord支持在列中存储
hash
。 https://api.rubyonrails.org/classes/ActiveRecord/Store.html provides good details how you can achieve it. https://api.rubyonrails.org/classes/ActiveRecord/Store.html提供了有关如何实现此目标的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.