我将GitHub OAuth集成到我的rails应用程序,用户可以通过github帐户登录我的rails应用程序,我不想使用第三方宝石,如OmniAuth,warden-github等。
if !authenticated?
authenticate!
else
access_token = session[:access_token]
scopes = []
begin
auth_result = RestClient.get('https://api.github.com/user',
{:params => {:access_token => access_token},
:accept => :json})
rescue => e
session[:access_token] = nil
return authenticate!
end
auth_result = JSON.parse(auth_result)
user = User.find_by(github_id: auth_result["id"])
if not user
user_attr = {user_name: auth_result["login"],
email: auth_result["email"],
github_id: auth_result["id"],
avatar_url: auth_result["avatar_url"],
location: auth_result["location"],
}
user = User.create!(user_attr)
session[:user_id] = user.id
end
if scopes.include? 'user:email'
auth_result['private_emails'] =
JSON.parse(RestClient.get('https://api.github.com/user/emails',
{:params => {:access_token => access_token},
:accept => :json}))
end
redirect_to user_path(user)
如果用户通过github帐户登录我的应用程序,我将在数据库中创建用户记录。我有两个问题:
答案 0 :(得分:0)
我使用SecureRandom
库生成随机字符串作为密码。
http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html