updating user record when associating providers with omniauth - ruby-on-rails-3

When I create a new account through google, the email gets stored in my user record. When I create a user through twitter, the email column is blank. I'd like to update that entry if a user associates their current twitter account with google.
in my User model:
def self.create_from_hash!(hash)
create! do |user|
user.name = hash['user_info']['name']
user.email = hash['user_info']['email']
end
end
In sessions controller:
def create
auth = request.env['rack.auth']
unless #auth = Authorization.find_from_hash(auth)
#auth = Authorization.create_from_hash(auth, current_user)
end
self.current_user = #auth.user
flash[:notice] = "Welcome, #{current_user.name}."
redirect_to '/'
end
and in the Authorization model:
def self.create_from_hash(hash, user = nil)
user ||= User.create_from_hash!(hash)
Authorization.create(:user => user, :uid => hash['uid'], :provider => hash['provider'])
end
How can I update that column when I am adding an authorization method?

I added the following line into my sessionscontroller create action, which seems to solve the issue:
if #user && (#user.email.blank? || #user.email.nil?)
#user.update_attribute(:email, request.env['rack.auth']['user_info']['email']) unless request.env['rack.auth']['user_info']['email'].nil? || #user.nil?
end

Related

NoMethodError (undefined method `info' for nil:NilClass) `find_for_google_oauth2'

! am trying to allow co-workers and students to sign up using their google project accounts. I have gotten as far as the token being passed but then i get an error.
app/models/user.rb:70:in `find_for_google_oauth2'
app/controllers/authentications_controller.rb:5:in `create'
my authentication controller create method
def create
auth = request.env[":google_oauth2"]
#user = User.find_for_google_oauth2(request.env["omniauth.auth"])
redirect_to root_url, :notice => "Signed in!"
end
my user model
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.first_name = auth.info.first_name
user.last_name = auth.info.last_name # assuming the user model has a name
user.image = auth.info.image # assuming the user model has an image
end
end
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(name: data["name"],
email: data["email"],
uid: access_token.uid,
provider: access_token.provider,
password: Devise.friendly_token[0,20]
)
end
user
end
and my config/omniauth.rd
require 'omniauth-google-oauth2'
OmniAuth.config.logger = Rails.logger
OmniAuth.logger.progname = "omniauth"
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, '***********petnk.apps.googleusercontent.com',
google_client_secret: '***********',
prompt: "consent",
select_account: true,
scope: 'userinfo.email',
image_aspect_ratio: 'square',
image_size: 50
on_failure { |env|AuthenticationsController.action(:failure).call(env) }
end
Not sure what to include to help y'all help me. I am new to rails and have been trying to learn for the past year so any help is appreciated.
thanks
I had to move my create function from my authentication controller to my omnicontroller. not really sure why this solved the problem but for now it did.

find_by_* method is not returning the object

I am trying to set up a simple authentication for my rails application. I have a security_users scaffold and have created some users.
When, I am trying to log in using some of these accounts it seams that the "find_by_*" method is not able to detect the current one.
This is how my session controller looks like (I have comment the password check in purpose in order to debug the issue):
class SessionsController < ApplicationController
def new
end
def create
#security_user = SecurityUser.find_by_email(params[:email])
if #security_user #&& #security_user.authenticate(params[:password])
session[:security_user_id] = #security_user.id
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Email or password is invalid"
render 'new'
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Logged out!"
end
end
So, when I try to create a session (to log in) I am redirect to the session 'new' template. This is the debug information:
which seems to be all right. Why the following statement could not find the record:
SecurityUser.find_by_email(params[:email])
EDIT:
When I entered the line above in the console it is returning the record:
First off, unless this is a simple exercise in Rails authentication, you should use Devise or AuthLogic at this stage.
Second, are you sure that params[:email] contains the email you are looking for? From your params, it looks to me like you want to use params[:session][:email].
Third, you should move this down into the model. For example:
class SecurityUser < ActiveRecord::Base
def self.authenticate(params)
user = where(email: params[:email]).first
(user && user.password == params[:password]) ? user : false
end
end
And in the controller:
#user = SecurityUser.authenticate params[:session]
session[:user_id] = user.id if #user
Note above that the password is not hashed - you should not save a plain text password - but that's not what this is about.
Also note that now you should use where().first instead of find_by.

How can I automatically assign extra params to my User with omniauth?

I have omniauth and devise successfully set-up for LinkedIn and Twitter.
When authenticating with LinkedIn, I am able to get the users name and email passed into the sign-up form automatically - but then it still gives an error and ask's the user to 'check the errors' which is bad UX given there technically are no errors.
How can I get them automatically assigned to the user during the create process, but only when they are present? Here's the relevant code:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def all
user = User.from_omniauth(request.env["omniauth.auth"])
if user.persisted?
flash.notice = "Signed in!"
sign_in_and_redirect user
else
session["devise.user_attributes"] = user.attributes
flash.notice = "Please confirm your name and email"
redirect_to sign_up_path
end
end
alias_method :linkedin, :all
alias_method :twitter, :all
end
From the User model:
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
end
end

How to create current user method without using any gem or plugin?

i know it's a silly one but i want to know how can we create a current_user method to get access throughout the app without using any gem or plugin ? To test it i created an app that make a user able to share files and folders.How to create such method that a user can only access his folder and files?Here is my code sample:
Login controller:
class LoginController < ApplicationController
layout 'signup'
#to skip checking the authentication and authorization.
skip_before_filter :check_authentication, :check_authorization
def index
end
def authenticate
if request.post?
user = User.authenticate(params[:username],params[:password])
if user
session[:current_user_id]=user.id
session[:name]= user.first_name
puts "session name #{session[:name]}"
redirect_to(:subdomain => user.company.subdomain, :controller => :dashboard)
else
flash.now[:notice] = "Invalid user/password combination"
end
end
end
def destroy
session[:current_user_id] = nil
reset_session
flash[:notice] = "You have been successfully logged out."
redirect_to root_url
end
end
User model:
require 'digest/sha1'
class User < ActiveRecord::Base
#sharering method start
after_create :check_and_assign_shared_ids_to_shared_folders
#this is to make sure the new user ,of which the email addresses already used to share folders by others, to have access to those folders
def check_and_assign_shared_ids_to_shared_folders
#First checking if the new user's email exists in any of ShareFolder records
shared_folders_with_same_email = SharedFolder.find_all_by_shared_email(self.email)
if shared_folders_with_same_email
#loop and update the shared user id with this new user id
shared_folders_with_same_email.each do |shared_folder|
shared_folder.shared_user_id = self.id
shared_folder.save
end
end
end
#to check if a user has acess to this specific folder
def has_share_access?(folder)
#has share access if the folder is one of one of his own
return true if self.folders.include?(folder)
#has share access if the folder is one of the shared_folders_by_others
return true if self.shared_folders_by_others.include?(folder)
#for checking sub folders under one of the being_shared_folders
return_value = false
folder.ancestors.each do |ancestor_folder|
return_value = self.being_shared_folders.include?(ancestor_folder)
if return_value #if it's true
return true
end
end
return false
end
#sharing method end
def self.authenticate(name, password)
user = self.find_by_username(name)
if user
expected_password = encrypt_password(password, user.salt)
if user.hashed_password != expected_password
user = nil
end
end
user
end
#'password' is a virtual attribute
def password
#password
end
def password= (pwd)
#password =pwd
return if pwd.blank?
create_new_salt
self.hashed_password = User.encrypt_password( self.password, self.salt)
end
def self.users_in_company(user_id)
User.find(user_id).company.users
end
private
def password_non_blank
errors.add(:password, "Missing password, please enter your password") if hashed_password.blank?
end
def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end
def self.encrypt_password(password, salt)
string_to_hash = password +"prftnxt" + salt
Digest::SHA1.hexdigest(string_to_hash)
end
end
i want to access all files as "current_user.files" is it possible without any gem?
Application helper:
module ApplicationHelper
#for current user to use through out the app
def current_user
#current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) # Use find_by_id to get nil instead of an error if user doesn't exist
end
end
Application controller:
class ApplicationController < ActionController::Base
include UrlHelper
#include ApplicationHelper
helper_method :current_user #make this method available in views
protect_from_forgery
# def current_user
# #current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) # Use find_by_id to get nil instead of an error if user doesn't exist
# end
end
and in task controller:
class TasksController < ApplicationController
# GET /tasks
# GET /tasks.xml
def index
#menu = "Timesheet"
#page_name = "Manage Task"
company_id = Company.find_by_subdomain(request.subdomain)
#users = User.find_all_by_company_id(company_id)
#tasks = current_user.tasks.all#Task.all
#task = Task.new
respond_to do |format|
format.html # index.html.erb
format.html # new.html.erb
format.xml { render :xml => #tasks }
end
end
end
and my error message i got:
NameError in TasksController#index
undefined local variable or method `current_user' for #<TasksController:0xfa7e638>
that's not so hard ;) just define the method you need:
class ApplicationController < ...
def current_user
#current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) # Use find_by_id to get nil instead of an error if user doesn't exist
end
helper_method :current_user #make this method available in views
end
Hi friends i have found the way to create current_user method without using any gem or plugin:
In my application_helper.rb i did this :
module ApplicationHelper
def current_user
User.find(session[:current_user_id])
end
end
and at the end in my application controller.rb i called this, because from here i can access it through the application:
class ApplicationController < ActionController::Base
include UrlHelper
include ApplicationHelper
helper_method :current_user
end
and now i can access any data related to current user:
like :
#tasks = current_user.tasks
Thanks to all my friends for their valuable answers.

Rails 3: updating user attributes when authentications are created

I followed Railscasts #235 and #236 to setup creating user authentications with omniauth.
http://railscasts.com/episodes/235-omniauth-part-1
http://railscasts.com/episodes/236-omniauth-part-2
I have a 2 boolean attributes on the user model called :facebok_share and :twitter_share that I want to set to true when a new authentication is created.
I have this working for me when I create a new user, but if an existing user adds an authentication I cannot get the boolean to update to true.
When apply_omniauth(omniauth) is called it sets self.facebook_share = true or self.twitter_share = true in my user model.
I've tried to add a new method called apply_share which changes the booleans depending on provider, and I'm trying to call current_user.apply_share(omniauth) but nothing is happening in the database.
What am I doing wrong? Thanks!
## authentications controller
class AuthenticationsController < ApplicationController
def index
#title = "Authentications"
#authentications = current_user.authentications if current_user
end
def create
# creates omniauth hash and looks for an previously established authentication
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
# if previous authentication found, sign in user
if authentication
flash[:notice] = "Signed in successfully"
sign_in_and_redirect(:user, authentication.user)
# for users already signed in (current_user), create a new authentication for the user
elsif current_user
current_user.apply_share(omniauth)
current_user.authentications.create(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => (omniauth['credentials']['token'] rescue nil),
:secret => (omniauth['credentials']['secret'] rescue nil))
flash[:notice] = "authentications successful"
redirect_to authentications_url
# new user is created and authentications are built through apply_omniauth(omniauth)
else
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully"
sign_in_and_redirect(:user, user)
# if validations fail to save user, redirects to new user registration page
# new twitter authentications redirect so user can enter their password
else
session[:omniauth] = omniauth
redirect_to new_user_registration_url
end
end
end
def destroy
#authentication = current_user.authentications.find(params[:id])
#authentication.destroy
flash[:notice] = "Successfully destroyed authentication."
redirect_to authentications_url
end
end
## user model
# set share booleans to true depending on 'provider' type
def apply_share(omniauth)
case omniauth['provider']
when 'facebook'
self.facebook_share = true
when 'twitter'
self.twitter_share = true
end
end
# from authentications controller, new user split into type of provider
def apply_omniauth(omniauth)
case omniauth['provider']
when 'facebook'
self.apply_facebook(omniauth)
when 'twitter'
self.apply_twitter(omniauth)
end
# builds authentication with provider, uid, token, and secret
authentications.build(hash_from_omniauth(omniauth))
end
protected
# sets new user attributes from facebook
def apply_facebook(omniauth)
self.name = omniauth['user_info']['name']
self.email = omniauth['user_info']['email'] if email.blank?
self.facebook_share = true
end
# sets new user attributes from twitter
def apply_twitter(omniauth)
if (extra = omniauth['extra']['user_hash'] rescue false)
# Example fetching extra data. Needs migration to User model:
# self.firstname = (extra['name'] rescue '')
self.name = (extra['name'] rescue '')
self.bio = (extra['description'] rescue '')
end
self.twitter_share = true
end
# set authentication attributes to those from 'omniauth' hash
def hash_from_omniauth(omniauth)
{
:provider => omniauth['provider'],
:uid => omniauth['uid'],
:token => (omniauth['credentials']['token'] rescue nil),
:secret => (omniauth['credentials']['secret'] rescue nil)
}
end
end
## new methid with :before add => :apply_share
def apply_share(authentication)
case authentication['provider']
when 'facebook'
self.facebook_share = true
when 'twitter'
self.twitter_share = true
end
self.save
end
I believe your never actually saving current_user. So your setting your attributes to true, and then redirecting. The association is stored in the authentication model, so Rails, trying to be helpful, doesn't update current_user, just the new instance of authentication
try:
current_user.apply_share(omniauth)
current_user.save
and see if that fixes it. Now if it does, I would strongly recommend using a callback instead. Take a look here:
http://guides.rubyonrails.org/association_basics.html
Section 4.5 about association callbacks. You can do a before_add callback on your has_many authentications assocation to remove that code from your controller as its getting pretty bloated as is.
class User < ActiveRecord::Base
has_many :authentications, :before_add => :apply_share
def apply_share(authentication)
#update attributes
#save model
end
end
You need to call #save on the User object after setting the *_share attributes.
Adding new items to a has_many collection automatically saves the collection item, but does not trigger a save operation on the parent (belongs_to).