authentication - How to use Google Oauth2 for both signing in users and creating new user accounts in a rails app? -


i'm working on google authentication rails app. using omniauth-google-oauth2 gem implement google auth. i've managed have users sign in using google. however, i'd users able sign using google. problem i've matched google callback url particular controller action (sessions#create). possible choose between 2 redirect uris based on whether users signing in or signing up? currently, idea create new google client credentials used sign up, hope there better way.

you don't need have 2 redirect uris, need more work when receiving callback. instance:

class sessionscontroller < applicationcontroller    ...    def create     email = auth_hash['info']['email'] # assuming omniauth hash auth_hash , you're requiring email scope     @user = user.find_by(email: email) if !email.blank? # assuming user model user      if @user       login_user(@user) # use login method     elsif !email.blank?       @user = user.new(name: auth_hash['info']['name'], email: email)        unless @user.save!(validate: false) # validate false because i'm enforcing passwords on devise - hence need allow passwordless register here)           # deal error on saving       end     else       # deal no found user , no email     end   end    protected      def auth_hash         request.env['omniauth.auth']     end  end 

i've written steps creation process can shortened to:

@user = user.create_with(name: auth_hash['info']['name']).find_or_initialize_by(email: email) @user.save! if @user.new_record? if @user    login_user(@user) else    # deal no user end 

nonetheless, can't sure user going give scope access email, think first version, if bit lengthier more robust. on shorter version there's problem of, if @user false, why so? , require add more logic figure out why that, whereas in first 1 it's easier apply correct response each situation.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -