Rails 3 Flash with jquery - ruby-on-rails-3

I use flash to tell the user if they logged in correctly or not, is there a way to put in the jquery code to fade after so many seconds or is there a way to do it with just the flash command?
Here is what im talking about
def login
#title = "Log in to Connect my Friends"
if param_posted?(:user)
#user = User.new(params[:user])
user = User.find_by_screen_name_and_password(#user.screen_name,
#user.password)
if user
user.login!(session)
flash[:notice] = "User #{user.screen_name} logged in!"
redirect_to_forwarding_url
else
#user.clear_password!
flash[:notice] = "Invalid screen name/password combination"
end
end
end

See http://snippets.dzone.com/posts/show/5271 for several examples of how to accomplish this.
Another example here: http://bjhess.com/blog/fading-flash-message/

Related

How can I access to Google Drive from a Rails 3 app using omniauth + omniauth-google-apps

I'm trying to access to google drive using the google-drive-ruby gem but I haven't had success. That gem has an option to login with auth but I don't know how to get the access token from omniauth. The schema returned is here.
This is my code.
in models/user.rb
def self.create_with_omniauth(auth, role = 'user')
create! do |user|
user.email = auth['info']['email']
user.first_name = auth['info']['first_name']
user.last_name = auth['info']['last_name']
user.google_token = auth['credential']['token']
user.google_secret = auth['credential']['secret']
user.role = Role.where(:account_type => role).first_or_create
end
end
in controllers/sessions_coontroller.rb
auth = request.env["omniauth.auth"]
email = auth['info']['email']
user = User.find_by_email(email) || User.create_with_omniauth(auth)
and in controllers/documents_controller.rb
def index
session = GoogleDrive.login_with_oauth(current_user.google_tocken)
for file in session.files
#docs << file
end
end
I really hope someone can help me.
Thanks in advance

Rails OAuthException :: An active access token must be used to query information about the current user

Iam using fb_graph in my rails application to get and set the access token if it authenticates with facebook. I have an Invites controller where a user will have to authenticate to invite friends. My code looks like this:
def facebook
if params[:code]
set_oauth_token(params[:code])
elsif params[:error]
redirect_to landing_path, :alert => "Access Denied"
return
end
if current_user.oauth_token.nil?
redirect_to client.authorization_uri(
:scope => "user_about_me, email, publish_stream, user_location, user_interests, user_birthday, user_likes, user_hometown, offline_access"
)
end
private
def set_oauth_token(token)
client.authorization_code = params[:code]
access_token = client.access_token! :client_auth_body
user = FbGraph::User.me(access_token).fetch
current_user.oauth_token = access_token
current_user.save(:validate => false)
end
def client
FbGraph::Auth.new(ENV["FACEBOOK_KEY"], ENV["FACEBOOK_SECRET"], :redirect_uri => invites_facebook_url).client
end
But Iam getting the error:
FbGraph::InvalidRequest at /invites/facebook
OAuthException :: An active access token must be used to query information about the current user.
The error is at the following line:
user = FbGraph::User.me(access_token).fetch
I tried to look for a solution and modified the code but still couldn't able to resolve the problem. Its all that the oauth token is not valid.
Please help me find a solution. Many thanks!!
Finally I got the error wchich was that after the callback you have to hit the facebook again to get the oauth token. I have modified my code and it worked.
User model
def self.auth(redirect_url)
FbGraph::Auth.new(ENV["FACEBOOK_KEY"], ENV["FACEBOOK_SECRET"], :redirect_uri => redirect_url)
end
User controller
def facebook
if params[:code]
set_oauth_token(params[:code])
elsif params[:error]
redirect_to landing_path, :alert => "Access Denied"
return
end
if current_user.oauth_token.nil?
client = User.auth(invites_facebook_url).client
redirect_to client.authorization_uri(
:scope => "user_about_me, email, publish_stream, user_location, user_interests, user_birthday, user_likes, user_hometown, offline_access"
)
end
end
private
def set_oauth_token(token)
client = User.auth(invites_facebook_url).client
client.authorization_code = params[:code]
access_token = client.access_token! :client_auth_body
user = FbGraph::User.me(access_token).fetch
current_user.oauth_token = access_token
current_user.save(:validate => false)
end

How to give option for resend verification email to user?

i am working on rails3 application. In my application when a user registered first time, an email has been sent to user with a verification link, after clicking that link i update the status_id and redirect user to login page. Here is my code :
code for token generation:
require 'digest/sha2'
class Subscription < ActiveRecord::Base
validate :ids_must_be_present, :on => :create
def ids_must_be_present
if status_id==0
generate_token
else
errors.add('Something gone wrong')
end
end
def generate_token
self.token = encrypt_string(id, generate_salt)
end
def encrypt_string(id, salt)
Digest::SHA2.hexdigest(id.to_s + "prftnxt" + salt)
end
private
def generate_salt
self.object_id.to_s + rand.to_s + company_id.to_s + Time.now.to_i.to_s
end
end
code to send email with link:
def email_verify
if subscription = Subscription.find_by_id_and_token(params[:id], params[:token])
subscription.update_attribute(:status_id, 1)
redirect_to("/login/index", :notice => "Thanks, email successfully verified")
else
flash.now[:notice] = "Your email has not verified yet. Please verify your email by clicking the link we have sent you."
end
end
Email template with verification link:
Hello <b><%= #user.username %></b>,
<br/>
<br/>
Thank you for signing up .
<b> Please Verify your email</b>
<%= link_to "verify", "http://localhost:3000/login/email_verify?token=#{#subscription.token}&id=#{#subscription.id}"%>
</br></br>
</br>
Now everything is fine, now my client want if user did not get verification email, then we some where give the option or link to request to resend verification mail.
i am thinking on to display flash msg on login attempt with a link to request for email.
but i am confused how do i do this any example or help would be helpful thanks.
Hi friends i got a solution, i have used a method in login controller that check the email is verified or not and if not verified a flash message displayed. The message contains the link .
When a user click on that link i resend the verification mail.
Here is my code:
subscription = Subscription.find_by_company_id_and_plan_id(current_company.id, current_company.plan.id)
link = "<a href= '/login/resend_verification_email'>Click</a>"
if subscription.status_id == 0
flash[:error] = "Your email is not verified. Please verify before login. <br/> #{link} here to resend verification email.".html_safe
redirect_to :back
end
and in login controller:
def resend_verification_email
subscription = Subscription.find_by_company_id_and_plan_id(current_company.id, current_company.plan.id)
Email.verify_email(current_user, subscription).deliver
redirect_to :back
flash[:success] = 'Verification email has been resend successfully, please check your inbox.'
end

Rails Sorcery Bug? Creates Duplicate User Accounts

The example sorcery code shown on github appears to me to create duplicate accounts if it is extended to allow for multiple sign in methods (which is the whole point of oauth). You can see in the snipit here that create_from() will be called if login_from() does not succeed.
GITHUB AT at https://github.com/NoamB/sorcery-example-app/blob/master/app/controllers/oauths_controller.rb
def callback
provider = params[:provider]
begin
if #user = login_from(provider)
redirect_to root_path, :notice => "Logged in from #{provider.titleize}!"
else
begin
#user = create_from(provider)
Investigating the source code for create_from in all cases a new User Account record will be created. This would not be correct, if a User account record already exists.
My question: What sorcery methods should be called on the first facebook connect, if a User account has been created by some means other than facebook. login_from will fail, and create_from will generate a duplicate usser record?
You can use def create_and_validate_from(provider).
It will validate if the users email/username already exist. If its true, that he will store infos into a session and can be rendered into registration form.
And if you wish to add some provider to your account you can use def add_provider_to_user(provider).
Several requests have come through for an answer to this question, so I am providing the answer that Andy Mejia part of my team eventually arrived at for this question. We used the source within sorcery to adapt the following functions:
# Returns the hash that contains the information that was passed back from Facebook.
# It only makes sense to call this method on the callback action.
#
# Example hash:
# {:user_info=>{:id=>"562515238", :name=>"Andrés Mejía-Posada", :first_name=>"Andrés", :last_name=>"Mejía-Posada", :link=>"http://www.facebook.com/andmej", :username=>"andmej", :gender=>"male", :email=>"andmej#gmail.com", :timezone=>-5, :locale=>"en_US", :verified=>true, :updated_time=>"2011-12-31T21:39:24+0000"}, :uid=>"562515238"}
def get_facebook_hash
provider = Rails.application.config.sorcery.facebook
access_token = provider.process_callback(params, session)
hash = provider.get_user_hash
hash.merge!(:access_token => access_token.token)
hash.each { |k, v| v.symbolize_keys! if v.is_a?(Hash) }
end
# Method added to the User Account model class
def update_attributes_from_facebook!(facebook_hash)
self.first_name = facebook_hash[:user_info][:first_name] if self.first_name.blank?
self.last_name = facebook_hash[:user_info][:last_name] if self.last_name.blank?
self.facebook_access_token = facebook_hash[:access_token]
self.email ||= facebook_hash[:user_info][:email]
unless facebook_authentication?
authentications.create!(:provider => "facebook", :uid => facebook_hash[:uid])
end
self.build_facebook_profile if facebook_profile.blank?
save!
self.facebook_profile.delay.fetch_from_facebook! # Get API data
end
To show these code in context, I am also including logic from our controller:
def callback
provider = params[:provider]
old_session = session.clone # The session gets reset when we login, so let's backup the data we need
begin
if #user = login_from(provider) # User had already logged in through Facebook before
restore_session(old_session) # Cleared during login
else
# If there's already an user with this email, just hook this Facebook account into it.
#user = UserAccount.with_insensitive_email(get_facebook_hash[:user_info][:email]).first
# If there's no existing user, let's create a new account from scratch.
#user ||= create_from(provider) # Be careful, validation is turned off because Sorcery is a bitch!
login_without_authentication(#user)
end
#user.update_attributes_from_facebook!(get_facebook_hash)
rescue ::OAuth2::Error => e
p e
puts e.message
puts e.backtrace
redirect_to after_login_url_for(#user), :alert => "Failed to login from #{provider.titleize}!"
return
end
redirect_to after_login_url_for(#user)
end
I hope this solution is helpful to others.
I came across the same problem. While I have not found a direct solution via Sorcery, I did the following which seems to work:
#user = create_from(params[:provider]) do |user|
User.where(:twitter_id => user.twitter_id).first.blank?
end
This teqnique requires that you have twitter_id in the User model. You can also do it the other way around with the Authentication model instead. Such as:
#user = create_from(params[:provider]) do |user|
Authentication.where(:uid => user.twitter_id).first.blank?
end
If the block returns false, then it doesn't create the user. Avoiding any duplicates.
Note, the block for create_from does not work with 0.7.12. It works with 0.7.13.

railstutorial.org NoMethodError in SessionsController#create

undefined method `current_user=' for #<SessionsController:0x1044926b8>
Rails.root: /Users/Bulow/ruby/sample_app
Application Trace | Framework Trace | Full Trace
app/helpers/sessions_helper.rb:4:in `sign_in'
app/controllers/sessions_controller.rb:20:in `create'
Request
Parameters:
{"commit"=>"Sign in",
"session"=>{"password"=>"[FILTERED]",
"email"=>"kennyvonbulow#gmail.com"},
"authenticity_token"=>"/fWZncGEWuhQLIYMxRPXBcBJ37vzLoVrIz1QHU28u6w=",
"utf8"=>"✓"}
Show session dump
Show env dump
Response
Headers:
None
unable to log in simply - and i have no clue how to correct it. been all over the guide back and forth and can't seem to find the error that's causeing this
The online tutorial has the following definitions in sessions_helper.rb
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user = user
end
.
.
.
def sign_out
cookies.delete(:remember_token)
self.current_user = nil
end
I changed them to the following and was able to login/logout without any errors.
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
#current_user = user
end
.
.
.
def sign_out
cookies.delete(:remember_token)
#current_user = nil
end
Also, to confirm it's you that's logged in, change the URL localhost:3000/users/(your user ID) to another user ID. It'll show that users info. Click on the profile link at the top and it'll go back to your profile. The app is set up so that this link will got to the logged in user's profile.
Where I found the solution.
http://getsatisfaction.com/railstutorial/topics/undefined_method_current_user_for_sessionscontroller