Ask A Question

Notifications

You’re not receiving notifications from this thread.

Edit user profile with devise if user signed up with facebook omniauth

Camilla asked in Rails

Hello.

I use 2 gems (gem 'devise' and gem 'omniauth-facebook').
The user is able both to sign_in ou sign_up with facebook. If a User did a regular sign up in the past, he's found by email, and if not he is created in the database.

My question now is how a User can update his account including password if he doesn't know the actual password because it's generated as a random number? I saw the Devise article https://github.com/heartcombo/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password but I also want users to update their passwords. Any thoughts?

MODEL:

class User < ApplicationRecord
def self.find_for_facebook_oauth(auth)
user_params = auth.slice("provider", "uid")
user_params.merge! auth.info.slice("email", "first_name", "last_name")
user_params[:facebook_picture_url] = auth.info.image
user_params = user_params.to_h

user = User.find_by(provider: auth.provider, uid: auth.uid)
user ||= User.find_by(email: auth.info.email) # User did a regular sign up in the past.
if user
  user.update(user_params)
else
  user = User.new(user_params)
  user.password = Devise.friendly_token[0, 20]  # Fake password for validation
  user.save(validate: false)
end

return user

end

CONTROLLER

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
user = User.find_for_facebook_oauth(request.env['omniauth.auth'])

if user.persisted?
  sign_in_and_redirect user, event: :authentication
  set_flash_message(:notice, :success, kind: 'Facebook') if is_navigational_format?
else
  session['devise.facebook_data'] = request.env['omniauth.auth']
  redirect_to new_user_registration_url
end

end

def failure
redirect_to root_path
end
end

Reply

Hey Camilla,

I almost always use the Devise wiki page to not require the current password to update their account. That would make it so the user wouldn't have to know their password to update.

Reply

Thanks!

Reply

Updating a user profile when they signed up with Facebook omniauth and don't have a traditional password can be a bit tricky. To enable users to update their passwords, you can consider adding a separate "Change Password" functionality within your app. Users can go to their account settings and initiate a password change by entering a new password.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.