如何使用Google用户预先填充我的Rails 4应用程序?

Dav*_*ave 6 seed omniauth ruby-on-rails-4

我正在使用Rails 4.2.5和"omniauth-google-oauth2"gem.在我的应用程序中,用户可以登录的唯一方法是通过他们的Google或Facebook登录.我想要的是使用管理员角色向初始用户my(email ='davea@gmail.com")预先填充我的应用程序.以编程方式执行此操作会很好,这样当我将其推送到其他环境时,我可以使用相同的代码.

我的角色表(通过db/seeds.rb)具有角色

Admin
User
Run Code Online (Sandbox Code Playgroud)

和我的app/model/user.rb文件有

def self.from_omniauth(auth)
  where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.name = auth.info.name
    user.oauth_token = auth.credentials.token
    user.oauth_expires_at = Time.at(auth.credentials.expires_at)
    user.save!
  end
end
Run Code Online (Sandbox Code Playgroud)

但是,我不确定如何做我想做的事情,因此会重视一些忠告.

Jam*_*hen 2

现在假设您有 Google uid。只需从您的种子创建一个用户,例如:

user = User.new(
  provider: "google",
  uid: "your-google-id",
  email: "davea@gmail.com",
  name: "Your name"
)
user.roles << admin_role # Replace this line with your role assignment
user.save # Perhaps use save(validate: false) if there're validations for other fields
Run Code Online (Sandbox Code Playgroud)

这样,当您使用 Google 登录时,omniauth 逻辑应该能够找到种子用户,这意味着您将能够充当管理员。

请注意,这假设您不需要 Google oauth 令牌来执行任何进一步的操作,因为您没有保存该令牌,并且from_omniauth如果用户记录已存在,则不会保存它。

PS 从您的示例代码中,Oauth 信息直接保存到User模型(provideruid)。这样,我担心用户将无法同时使用 Facebook 和 Google 登录,因为两者都想保存到这两个字段。

更新:从我的代码库粘贴一个模型,该模型是一个单独的模型User,允许多个提供者登录。当然,控制器需要更新才能使用Authorization而不是User. 以防万一有帮助。

class Authorization < ActiveRecord::Base
  belongs_to :user

  def self.from_omniauth(auth)
    authorization = where(auth.slice(:provider, :uid)).first_or_create
    return authorization if authorization.user

    if user = User.where(email: auth.info.email).first
      authorization.bind_user(user)
    else
      user = authorization.create_user(auth.info)
    end

    authorization
  end

  def bind_user(user)
    self.user = user
    save
  end

  def create_user(info)
    user = User.new(
      email:      info.email,
      password:   Devise.friendly_token[0, 20],
      first_name: info.first_name,
      last_name:  info.last_name,
    )
    user.save(validate: false)

    bind_user(user)

    user
  end
end
Run Code Online (Sandbox Code Playgroud)