Omniauth for provider authentication in Rails API - ruby-on-rails

I've got omniauth working flawlessly for my rails app on the web. I've also created an API for our iPhone app to interact and I'm trying to get omniauth to work.
Is there a way to pass an access token (received from the integrated iOS integration with the Facebook.app) to omniauth to create the provider entry in the database?
Right now in my web app I have an authentications controller with the following code
def create
omniauth = request.env["omniauth.auth"]
user = User.where("authentications.provider" => omniauth['provider'], "authentications.uid" => omniauth['uid']).first
if user
session[:user_id] = user.id
flash[:notice] = t(:signed_in)
redirect_to root_path
elsif current_user
user = User.find(current_user.id)
user.apply_omniauth(omniauth)
user.save
flash[:notice] = t(:success)
redirect_to root_path
else
session[:omniauth] = omniauth.except('extra')
flash[:notice] = "user not found, please signup, or login. Authorization will be applied to new account"
redirect_to register_path
end
end

In my user controller for the API I created the following:
def create
#user = User.new(params[:user])
#user.save
# Generate data for omni auth if they're a facebook user
if params[:fb_access_token]
graph = Koala::Facebook::API.new(params[:fb_access_token])
profile = graph.get_object('me')
#user['fb_id'] = profile['id']
#user['fb_token'] = params[:fb_access_token]
#user['gender'] = profile['gender']
# Generate omnihash
omnihash = Hash.new
omnihash['provider'] = 'facebook'
omnihash['uid'] = profile['id']
omnihash['info'] = Hash.new
omnihash['info']['nickname'] = profile['username']
omnihash['info']['name'] = profile['name']
omnihash['info']['email'] = profile['email']
omnihash['info']['first_name'] = profile['first_name']
omnihash['info']['last_name'] = profile['last_name']
omnihash['info']['verified'] = profile['verified']
omnihash['info']['urls'] = Hash.new
omnihash['info']['urls']['Facebook'] = profile['link']
omnihash['credentials'] = Hash.new
omnihash['credentials']['token'] = params[:fb_access_token]
omnihash['extra'] = Hash.new
omnihash['extra']['raw_info'] = Hash.new
puts omnihash
# Save the new data
#user.apply_omniauth(omnihash)
#user.save
end

Related

Save to database post,but before check http request in Ruby on Rails

I am trying save hashes to my database but before I want check request
I am using
require 'net/http'
gem 'http'
This is my controller (hashes I call :hammer)
class PaymentsController < ApplicationController
before_action :logged_in_user, only: [:create]
def create
#payment = current_user.payments.build(payment_params)
aza = ''
uri = URI("https://blockexplorer.com/api/tx/#{:hammer}")
res = Net::HTTP::Post.new(uri)
res1 = res.class.name
aza += Net::HTTP.get(uri)
#go = aza
if aza.include?( '3MGeicHK6P2pUpepsXyTiuA7omMbRZbZx3') #'"addresses":["3MGeicHK6P2pUpepsXyTiuA7omMbRZbZx3"]'
if aza.include? '"value":"0.03072025"'
if aza.include? '"confirmations":0'
flash[:info] = "Wait 15 minutes for confirm"
else
if #payment.save
flash[:success] = "You paid"
redirect_to root_url
else
render 'welcome/index'
end
end
else
flash[:danger] = "You paid less"
end
else
flash[:danger] = "#{res1}"
redirect_to root_url
end
end
def destroy
end
private
def payment_params
params.require(:payment).permit(:hammer)
end
end
When I was try to save it is not check, it is just show error 400
But If I use console it is work
uri = URI("https://blockexplorer.com/api/tx/f484f14ebf9726ab2ab46ffc491786db50fc69ceff737620122e51559a3ea379")
irb(main):003:0> Net::HTTP.get(uri)
I find want can to do
#test = payment_params[:hammer]
# hammer = ''
# hammer += params[:hammer].to_s
aza = ''
uri = URI("https://blockexplorer.com/api/tx/#{#test}")
I think the bug is there:
uri = URI("https://blockexplorer.com/api/tx/#{:hammer}")
in PaymentsController.
Try that instead:
uri = URI("https://blockexplorer.com/api/tx/#{params[:hammer]}")
You missed params[] in your interpolation.

Facebook Auth log out with Rails and Parse

I am having trouble finding a way to log out from facebook. We are logging in using window.location = '/auth/facebook' which redirects the user to a facebook login page, and calls a callback route /auth/facebook/callback(declared in developers.facebook.com) to a method in my session_controller/create.
The session_controller/create method looks like this
def create
#get auth hash from omniauth
auth = auth_hash
#data = {}
#session_data = {}
#data['id'] = auth['uid']
#data['access_token'] = auth['credentials']['token']
#time must be in iso format, see parse rest api for details under linking
#expiry = Time.at(auth['credentials']['expires_at']).iso8601
#data['expiration_date'] = #expiry
#create new linking user object
user = Parse::User::Facebook.new(#data)
# add other user information to body of PARSE::USER::FACEBOOK instance
user.body['email'] = auth['info']['email']
user.body['auth'] = true
user.body['fullname'] = auth['info']['name']
user.body['ip'] = request.remote_ip
user.body['image'] = auth['info']['image'] if auth['info']['image']
user.body['admin'] = false
user.body['facebookId'] = auth['uid']
user.body['facebookToken'] = auth['credentials']['token']
user.body['has_seen_web_tutorial'] = false
#current_user = user.save
#save necessary session information
session['name'] = #current_user['fullname']
session['points'] = #current_user['points']
session['objectId'] = #current_user['objectId']
session['sessionToken'] = #current_user['sessionToken']
session['image'] = #current_user['image']
session['location'] = #current_user['location']
#session_data['name'] = session['name']
#session_data['fullname'] = #current_user['fullname']
#session_data['points'] = session['points']
#session_data['objectId'] = session['objectId']
#session_data['image'] = session['image']
if auth['info']['image']
File.open('temp_face.png', 'wb') do |file|
file << open(auth['info']['image'], :allow_redirections => :safe).read
end
photo = Parse::File.new({
:body => IO.read("temp_face.png"),
:local_filename => "temp_face.png",
:content_type => "image/png"
})
photo.save
#user.body['image'] = photo
end
image = Parse::Object.new("ImageUploads")
image['fileKey'] = photo
image['owner'] = Parse::Pointer.new({"className" => "_User", "objectId" => session['objectId']})
image['type'] = 'profile'
#image['location']
saved_image = image.save
redirect_to listing_index_path
end
I am having trouble trying to log out. Very new to rails. Any help please?
Thank you

How to get OpenStreetMap access token with devise omniauth-osm

In my controller, I'm trying to get an access token to OSM.
class Auth::OauthController < Devise::OmniauthCallbacksController
def osm
#user = AppUser.from_omniauth(request.env["omniauth.auth"])
token_req = request.env["omniauth.auth"]['extra']['access_token'].consumer.get_request_token(:oauth_verifier => params['oauth_verifier'])
#user.token = token_req.token
#user.token_secret = token_req.secret
sign_in_and_redirect #user
end
end
When I get the access token and writes it to the database.
Next, I try to use the OSM API through oauth gem.
#consumer=OAuth::Consumer.new Settings.osm.consumer_key,
Settings.osm.consumer_secret,
{site: osm_uri}
#access_token = OAuth::AccessToken.new(#consumer, current_user.token, current_user.token_secret)
puts #access_token.get('/api/0.6/user/preferences').body
However, this code does not work in the console I see the authorization error
the error in this code:
token_req = request.env["omniauth.auth"]['extra']['access_token'].consumer.get_request_token(:oauth_verifier => params['oauth_verifier'])
#user.token = token_req.token
#user.token_secret = token_req.secret
correct code
#app_user.token = request.env["omniauth.auth"]['credentials']['token']
#app_user.token_secret = request.env["omniauth.auth"]['credentials']['secret']

Request Error Twitter-API Rails 4

I'm wondering how to limit the number of followers returned via the twitter api, or if there's a better way of returning the twitter followers of a user.
We've been challenged to create a twitter manager, and I've done most of the stuff, but I keep getting a request error when someone has a large amount of followers, as we're supposed to get the users from the twitter api and store them in a database, and the page usually times out or gives a twitter get error too many requests and locks me out for an hour. It's very hard to develop when this keeps happening, I was just wondering if there's a better way to do it?
Here is my code for the dashboard which is where the user details are returned and saved, and also where the followers are returned and save:
class DashboardController < ApplicationController
helper_method :logged_in?
def new
#just_updated = ""
Twitter.configure do |config|
# Test Account
config.consumer_key = "none-of-your-business"
config.consumer_secret = "none-of-your-business"
config.oauth_token = "none-of-your-business"
config.oauth_token_secret = "none-of-your-business"
end
#user = User.find(session[:user_id])
if #user.twitter_username.present? && #user.twitter_details_present == false
#twitter_user = Twitter.user(#user.twitter_username)
#user.no_of_followers = #twitter_user[:followers_count]
#user.profile_picture_url = #twitter_user[:profile_image_url]
#user.following = #twitter_user[:friends_count]
#user.twitter_nationality = #twitter_user[:location]
#user.no_of_tweets = #twitter_user[:statuses_count]
#user.twitter_details_present = true
#user.updated_at = Time.now
if #user.save
#just_updated = "We have just updated your follower details"
else
#just_updated = "There was a problem with your save1"
end
end
if (Time.now - #user.updated_at) < 10.minute && (#user.updated_at - #user.created_at) > 1.hour
Follower.where("owner = #{#user.id}").destroy_all
end
if #user.twitter_username.present?
if (#followers = Follower.where("owner = #{#user.id}")).count > 0
i = Follower.first.id
#followers.each do |follower|
if (Time.now - Follower.where("owner = #{#user.id}").first.updated_at) > 1.hour
if (follower_to_save = Follower.where(follower_id: follower[:id])).present?
follower_to_save[0].follower_username = follower[:screen_name].to_s
follower_to_save[0].owner = #user.id
follower_to_save[0].follower_nationality = follower[:location]
follower_to_save[0].no_of_followers = follower[:followers_count]
follower_to_save[0].following= follower[:friends_count]
follower_to_save[0].no_of_tweets = follower[:statuses_count]
follower_to_save[0].profile_picture_url = follower[:profile_image_url]
follower_to_save[0].updated_at = Time.now
if follower_to_save[0].save
#just_updated = "We have just updated your follower details"
else
#just_updated = "There was a problem with your save1"
break;
end
else
follower_to_save = Follower.new
follower_to_save.follower_id = follower[:id]
follower_to_save.owner = #user.id
follower_to_save.follower_username = follower[:screen_name]
follower_to_save.follower_nationality = follower[:location]
follower_to_save.no_of_followers = follower[:followers_count]
follower_to_save.following= follower[:friends_count]
follower_to_save.no_of_tweets = follower[:statuses_count]
follower_to_save.profile_picture_url = follower[:profile_image_url]
follower_to_save.updated_at = Time.now
if follower_to_save.save
#just_updated = "We have just updated your follower details"
else
#just_updated = "There was a problem with your save2"
break;
end
end
else
next
end
i=i+1
#sleep(1)
end
else
#followers = Twitter.followers(#user.twitter_username)
#followers.each do |follower|
follower_to_save = Follower.new
follower_to_save.follower_id = follower[:id]
follower_to_save.owner = #user.id
follower_to_save.follower_username = follower[:screen_name]
follower_to_save.follower_nationality = follower[:location]
follower_to_save.no_of_followers = follower[:followers_count]
follower_to_save.following= follower[:friends_count]
follower_to_save.no_of_tweets = follower[:statuses_count]
follower_to_save.profile_picture_url = follower[:profile_image_url]
follower_to_save.updated_at = Time.now
if follower_to_save.save
#just_updated = "We have just compiled your followers"
else
#just_updated = "There was a problem with your save3"
break;
end
#sleep(1)
end
end
else
#no_twitter_username = "Please go into settings and add your twitter username to start."
end
#followers = Follower.all.where("owner = #{#user.id}")
#follower_count = #followers.count
end
def logged_in?
if session[:user_id].present?
true
else
false
end
end
end
The code is pretty inefficient right now, but I'm just trying to get it working.

rails redirect after create problem

Could anyone help with this problem:
Upon "create", the user is redirected to the url: model/model_id (eg post/1), instead I am redirected to models/url_encoding_object (eg posts/.%23) and there is an "406 Not Acceptable" message in the console.
Typically, upon create, the console's message is "Processing PostsController#create (for 000.0.0.0 at 2009-11-23 12:32:52) [POST]", but with this error, the message is "Processing PostsController#create to # (for 000.0.0.0 at 2009-11-23 12:32:52) [POST]"
I've seen austinfromboston's response and tried his "old fashioned but effective" solution to that similar problem, but it doesn't work for me.
Any help would be greatly appreciated
Controller Code:
# POST /groups
# POST /groups.xml
def create
#group = Group.new(params[:group])
#group.category = params[:category]
#group.user = current_user
#here we add the current user to the membership collection of the group
#membership = #group.memberships.build(params[:membership])
#membership.group = #group
#membership.user = current_user
#membership.initiator = false
#membership.membership_status_id = 2
#and here we set the current_user as the owner of the group
#group_permission = #group.group_permissions.build(params[:group_permission])
#group_permission.membership = #membership
#group_permission.group_role = GroupRole.find_by_name('Owner')
unless params[:metro_area_id].blank?
#group.metro_area = MetroArea.find(params[:metro_area_id])
#group.state = (#group.metro_area && #group.metro_area.state) ?
#group.metro_area.state : nil
#group.country = #group.metro_area.country if (#group.metro_area &&
#group.metro_area.country)
else
#group.metro_area = #group.state = #group.country = nil
end
#group.tag_list = params[:tag_list] || ''
# unless #user.is_in_group?(#group)
# #user.memberships << #group
# end
respond_to do |format|
if #group.save
flash[:notice] = :group_was_successfully_created.l
format.html { redirect_to(group_path(#group.id)) }
else
format.html {
#metro_areas, #states = setup_metro_area_choices_for(#group)
if params[:metro_area_id]
#metro_area_id = params[:metro_area_id].to_i
#state_id = params[:state_id].to_i
#country_id = params[:country_id].to_i
end
render :action => "new"
}
end
end
end
Looks like either your routes are off somewhere or your model_id parameter is not what you are expecting. Might want to check to see what that parameter is being set to.
It's also really hard to give any suggestions without seeing controller code. Can you post the method making this call?
There's a lot of superfluous code, in your controller. It still works, but you're doing a lot of things the hard way.
Your problem is this line:
format.html { redirect_to(groups_path(#group.id)) }
Which redirects to the collective groups url adding the parameter #group.id.
What it should be is
format.html { redirect_to(group_path(#group.id)) }
# POST /groups
# POST /groups.xml
def create
#group = Group.new(params[:group])
#group.category = params[:category]
#group.user = current_user
#here we add the current user to the membership collection of the group
#membership = #group.memberships.build(params[:membership])
#membership.group = #group
#membership.user = current_user
#membership.initiator = false
#membership.membership_status_id = 2
#and here we set the current_user as the owner of the group
#group_permission = #group.group_permissions.build(params[:group_permission])
#group_permission.membership = #membership
#group_permission.group_role = GroupRole.find_by_name('Owner')
unless params[:metro_area_id].blank?
#group.metro_area = MetroArea.find(params[:metro_area_id])
#group.state = (#group.metro_area && #group.metro_area.state) ? #group.metro_area.state : nil
#group.country = #group.metro_area.country if (#group.metro_area && #group.metro_area.country)
else
#group.metro_area = #group.state = #group.country = nil
end
#group.tag_list = params[:tag_list] || ''
unless #user.is_in_group?(#group)
#user.memberships << #group
end
respond_to do |format|
if #group.save
flash[:notice] = :group_was_successfully_created.l
format.html { redirect_to(groups_path(#group.id)) }
else
format.html {
#metro_areas, #states = setup_metro_area_choices_for(#group)
if params[:metro_area_id]
#metro_area_id = params[:metro_area_id].to_i
#state_id = params[:state_id].to_i
#country_id = params[:country_id].to_i
end
render :action => "new"
}
end
end
end
What is this .1 doing at the end of the line??
flash[:notice] = :group_was_successfully_created.l
I tried to run similar code in my environment and it choked on that.
It should also reference:
group_path(id)
not
groups_path(id)

Resources