I've been using Devise + OmniAuth Twitter to authenticate the user to my portal. I am currently facing two issues.
When the user is accessing /users/sign_up, the form is publicly visible. Instead, I want to redirect him to the Twitter authentication page.
When the user is accessing /users/sign_up, the email form is visible. I'm using this form to get the email address of the users after he signs up successfully from Twitter.
Can someone please help me solve this issue from people accessing the forms directly?
Adding Code Snippets:
#config/routes.rb
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
devise_scope :user do
get "skcript1625" => "devise/sessions#new", as: :login
get "logout", to: "devise/sessions#destroy", as: :logout
end
# app/models/user.rb
devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name # assuming the user model has a name
user.profileimg = auth.info.profileimg # assuming the user model has an image
end
end
You have to redirect the user with the following link
<%= link_to "Sign in with Twitter", user_omniauth_authorize_path(:twitter) %>
Make sure you told your model (usually 'user') that it is 'omniauthable'
devise :omniauthable, :omniauth_providers => [:twitter]
When the user authorized twitter to share your info with the app, all the user's information is available in a hash request.env["omniauth.auth"].
See the documentation for more detail about this hash.
Edit: Everything is well explained here
Related
I'm building an app using Devise.
The problem I have is about the password reset process.
If the user forgets their password, enter the registered email address and send a password reset notice to that address.
So far it works as expected.
problem
The password reset token received in the email does not match the password reset token generated by the application.
So, when I try to reset the password from the email I received, I get the error "Token is invalid".
=========================
Show my code.
Gemfile
gem 'devise'
gem 'omniauth'
gem 'omniauth-google-oauth2'
gem 'omniauth-facebook'
gem 'devise-i18n'
routes.rb
devise_for :users, controllers: {
registrations: 'users/registrations',
sessions: 'users/sessions',
confirmations: 'users/confirmations',
omniauth_callbacks: 'users/omniauth_callbacks'
}
model/user.rb
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable,
:omniauthable, omniauth_providers: %i[google_oauth2]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.skip_confirmation!
end
end
def update_without_current_password(params, *options)
params.delete(:current_password)
if params[:password].blank? && params[:password_confirmation].blank?
params.delete(:password)
params.delete(:password_confirmation)
end
result = update_attributes(params, *options)
clean_up_passwords
result
end
views/users/mailer/reset_password_instructions.html.erb
<%= link_to 'パスワードの変更を行う', edit_password_url(#resource,reset_password_token: #token) %>
=========================================
I searched many times, but I couldn't find much new information because it was only old information.
Why don't the tokens match?
How can I email the generated tokens?
Please help someone.
※I'm not good at English. There may be mistakes.
You have to create a new table for reset tokens.
schema can be like
password_reset_tokens
---------------------
id pk
reset_token unique string
user_id integer
is_active boolean
created_at datetime
updated_at datetime
whenever a user is going to request for a change password. Create an entry in this password_reset_tokens with a random reset_token string and assign a user_id to it.
send this token in the email with a link and when user is going to click on it the reset token. Open the form with new password fields and when password is updated through that link then mark is_active as false.
Additional step:
You can also write a cron to expire the reset_tokens after x hours. whenever a new reset_passsword_token is generated then you can schedule a cron to expire it after x hours.
I'm getting this error:
The action 'github' could not be found for Users::OmniauthCallbacksController
I've looked everywhere and tried the other suggestions on other peoples posts.
This was the post on stack overflow but they had a typo and I didn't have that same error.
Devise OmniauthsController not being used
This recommendation said to check rake routes but my routes match what I'm pointing to.
https://github.com/plataformatec/devise/issues/1566
Most of the other links were all similar issues and I double checked the info with mine, changed stuff and still getting errors.
Info about my code.
gemfile:
gem 'omniauth-github'
config/routes.rb:
devise_for :users, :controllers => { :omniauth_callbacks => 'users/omniauth_callbacks' }
Users::OmniauthCallbacksController:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def github
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, event: :authentication
set_flash_message(:notice, :success, kind: "Github") if is_navigational_format?
else
redirect_to root_path
end
end
end
User Model:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:github]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.uid = auth.uid
user.provider = auth.provider
user.password = Devise.friendly_token[0, 20]
user.name = auth.info.name #assuming the user model has a name
user.oauth_token = auth.credentials.token
user.image = auth.info.image #assuming the user model has an image
user.save!
end
end
Devise initializer:
config.omniauth :github, Rails.application.secrets.github_client_id, Rails.application.secrets.github_client_secret, scope: 'user:email'
Not sure what to do since I have the method in the Users::OmniauthCallBacks controller? Am I missing something? I've been combing through for an entire day.
Update: somehow I had 2 users folders in the controller but one was hidden? It must have gotten messed up when I reverted to a previous repo last night. Once I removed the folder all was good!
I'm playing around with the omniauth-facebook gem to log into a devise session through a facebook account. When I click the "Sign in with facebook" link, everything goes well: a new account is created, I'm signed in and bounce back to the homepage with a message confirming my new session (very good!).
Problem: However when an account already exists, upon clicking the link I am redirected to the user/sign_up page. I've been following this documentation from the Devise wiki. There is a good deal of documentation on similar errors here, here, here and here. Each of the solutions, however, are already implemented in my app (as far as I can tell) OR (in the case of the last link) seem to be based on an older configuration model that seems sufficiently different from the wiki that I'm not sure it's applicable.
My best guess is that it has something to do with the callbacks controller, as #user.persisted? seems to be coming up false.This leads me to believe that my definition of #user is not correct. See below:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
logger.debug "Inside facebook"
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.from_omniauth(request.env["omniauth.auth"])
logger.debug "User is #{#user}"
if #user.persisted?
logger.debug "#user.persisted?"
debugger
sign_in_and_redirect #user, :event => :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
logger.debug "user exists"
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
def failure
redirect_to root_path, alert: "Login failed"
end
end
Additionally, my user model is as follows:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = Devise.friendly_token[0,20]
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.fname = auth.info.first_name
user.lname = auth.info.last_name
end
end
end
Any suggestions would be certainly welcome! Thanks in advance.
Try Something Like This
class Authentication < ActiveRecord::Base
belongs_to :user
# validates :provider, :uid, :presence => true
def self.from_omniauth(auth)
authenticate = where(provider: auth[:provider], :uid=>auth[:uid]).first_or_initialize
if authenticate.user
authenticate.provider = auth[:provider]
authenticate.uid =auth[:uid]
else
user = User.find_or_initialize_by(:email => email)
authenticate.provider = auth[:provider]
user.email = email
user.first_name = first_name
user.last_name = last_name
user.social_image = image
user.password = Devise.friendly_token.first(8)
user.save(validate: false)
if user.errors.any?
return user
else
authenticate.user_id = user.id
end
end
authenticate.save
authenticate.user
end
end
Try this
def after_sign_in_path_for(resource)
super resource
end
From what i perceived that you are not going to your landing page
from_omniauth never finds an existing facebook user because you are overwriting the provider attribute:
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
searches for a user with provider 'facebook' in this case, but none can be found:
user.provider = Devise.friendly_token[0,20]
changes the provider to some random token
just remove that line and it should work properly
I'm trying to do OmniAuth in rails 4 for spotify. I almost have it but for some reason, the redirect URI isn't working. I am using Devise with omniauth These are my files:
User.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :omniauth_providers => [:spotify]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
end
My Callbacks controller to handle callbacks
class CallbacksController < Devise::OmniauthCallbacksController
def spotify
#user = User.from_omniauth(request.env["omniauth.auth"])
sign_in_and_redirect #user
end
end
My Devise.rb snippet:
config.omniauth :spotify, client_id, client_secret,scope: 'playlist-read-private user-read-private user-read-email'
My Routes.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => 'callbacks' }
get '/users/auth/callback', to: 'callbacks#spotify'
end
And lastly, the link leading up to the login:
<%= link_to 'Sign in with Spotify', user_omniauth_authorize_path(:spotify) %>
But for some reason, whenever I try to log into spotify, it says invalid redirect URI
OK, I figured out a solution to my particular problem:
When it was giving me the error of "invalid redirect URI", I looked at the URI it was trying to go to and I simply used that.
Then I got a second error which gave me a SSL Cert error so I used "gem certified" to fix that. THEN, it gave me a third problem of unauthorized access (the callback returned a failed request). What was happening was that I was trying to use OmniAuth twice. I had two files:
A) OmniAuth.rb
and B) Devise.rb
Both of these files were making API calls and it was messing it up. So to anyone having this problem- don't use both omniauth and devise. Honestly, after the first initial hiccup, I found devise to be way more useful than making your own User model and applying omniauth to that. Devise is more comprehensive!
I have problem with authentication through devise + google. I have local application written in Ruby on Rails 3.2. I was following devise docs to make this authentication to works:
https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
So here is my users omniauth controller located in app/controllers/users
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
#user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
if #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect #user, :event => :authentication
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
My routes:
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
in my devise.rb initializer:
require "omniauth-google-oauth2"
config.omniauth :google_oauth2, "ClientID", "SecretId", { access_type: "offline", approval_prompt: "" }
My user model:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:email => data["email"]).first
unless user
user = User.create(email: data["email"], password: Devise.friendly_token[0,20])
end
user
end
I don't know why this is not working. Maybe I'm doing something wrong with generating oauth clientid in google?
I generate my google app clientid and secret like in the following tutorial:
http://richonrails.com/articles/google-authentication-in-ruby-on-rails
Edit: I forgot to show what error I have:
when i click my link:
<%= link_to "Login via Google account", user_omniauth_authorize_path(:google_oauth2), :class => "btn btn-inverse btn-large" %>
i have the following addres in browser :
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=487629202871.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fusers%2Fauth%2Fgoogle_oauth2%2Fcallback&state=68a65048cca9ccb61a31d2a048bf9ef03d25ebe4a11d77ca&access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile
and my error looks like this: