Ruby, Sinatra , omniauth-github Authentication Failure Callback Error - ruby

ok it has been over 5 hours and I am still getting no where. What I am trying to do is setup omniauth-gihub gem in one of my Ruby-Sinatra based applications. Following is What I have done yet.
Added the Gems to the Gemfile (& Ran bundler update command ofcourse):
source 'https://rubygems.org'
gem 'sinatra'
gem 'haml'
gem 'shotgun'
gem 'omniauth', :git => 'git://github.com/intridea/omniauth.git'
gem 'omniauth-github', :git => 'git://github.com/intridea/omniauth-github.git'
Under my app.rb file I have the following code:
#imports
require 'rubygems'
require 'bundler'
require 'sinatra'
require 'omniauth'
require 'omniauth-github'
require 'haml'
require './helpers.rb'
#Configure OmniAuth
use OmniAuth::Builder do
provider :github, ENV['api_key'], ENV['secret'], # Removing the key and secret for security reasons
scope: "user,repo,gist"
end
#Application Settings
set :sessions, true
set :views, 'templates'
#Get Method for Application Root
get '/' do
haml :index
end
#Get/Post Methods For Authentication
%w(get post).each do |method|
send(method, "/auth/:provider/callback") do
env['omniauth.auth']
end
end
The Github application's settings are as follows:
URL = http://127.0.0.1:4567
Callback URL = http://127.0.0.1:4567/auth/github/callback
Now whenever I visit 127.0.0.1:4567/auth/github/callback I get the following error:
I, [2012-07-26T07:05:23.540462 #30458] INFO -- omniauth: (github) Callback phase initiated.
E, [2012-07-26T07:05:23.540700 #30458] ERROR -- omniauth: (github) Authentication failure! invalid_credentials: OmniAuth::Strategies::OAuth2::CallbackError, OmniAuth::Strategies::OAuth2::CallbackError
localhost - - [26/Jul/2012:07:05:23 IST] "GET /auth/github/callback HTTP/1.1" 302 9
- -> /auth/github/callback
localhost - - [26/Jul/2012:07:05:23 IST] "GET /auth/failure?message=invalid_credentials&strategy=github HTTP/1.1" 404 448
- -> /auth/failure?message=invalid_credentials&strategy=github
localhost - - [26/Jul/2012:07:05:23 IST] "GET /favicon.ico HTTP/1.1" 404 447
- -> /favicon.ico
it seems it's not even trying to connect to github, I thought I was already logged in so I logged out of github and try visiting 127.0.0.4567/auth/github/callback again and yes it is not even connecting or sending any information to github.
I have check my api key and the secret and they are correct. I can't really figure out what am I missing and am really tired. Any help or suggestion will be much appreciated.
EDIT::
Okay I found that the code raising the error is as follows in oauth2.rb
def callback_phase
if request.params['error'] || request.params['error_reason']
raise CallbackError.new(request.params['error'], request.params['error_description'] || request.params['error_reason'], request.params['error_uri'])
end
if request.params['state'].to_s.empty? || request.params['state'] != session.delete('omniauth.state')
raise CallbackError.new(nil, :csrf_detected)
end
I feel it is something to do with CSRF.

This might be of interest:
https://github.com/intridea/omniauth-github/issues/12
I was getting the same error as you, and adding scope: 'user' fixed it for me.
I see you're already using scope, but the link might put you on the right track.

Had the same issue - downgrading omniauth-facebook to 1.4.0 fixed it for me. https://github.com/mkdynamic/omniauth-facebook/issues/73

Related

Prevent phantomjs from raising Capybara::Poltergeist::StatusFailError when requesting never ending assets

I am having some issues with Capybara::Poltergeist::Driver
When I visit the the following url with poltergeist, I am exerpiencing an issue where an asset that seemingly doesn't exist takes for ever to load and eventually an error gets raised: https://www.feinstein.senate.gov/public/index.cfm/e-mail-me
$ brew install phantomjs
$ gem install capybara -v 2.17.0
$ gem install poltergeist -v 1.7.0
$ gem install selenium-webdriver -v 2.53.4
Then in irb:
require 'capybara/poltergeist'
module Drivers
class Poltergeist < Capybara::Poltergeist::Driver
def needs_server?
false
end
end
end
Capybara.register_driver :poltergeist_errorless do |app|
options = ['--load-images=no', '--ignore-ssl-errors=yes', '--ssl-protocol=any', '--disk-cache=true', '--max-disk-cache-size=500000']
Drivers::Poltergeist.new(app, js_errors: false, phantomjs_options: options)
end
session = Capybara::Session.new(:poltergeist_errorless)
session.visit('https://www.feinstein.senate.gov/public/index.cfm/e-mail-me')
After 10-20 seconds, the request fails, and I get back a Capybara::Poltergeist::StatusFailError exception with a message that says:
Request to 'https://www.feinstein.senate.gov/public/index.cfm/e-mail-me' failed to reach server, check DNS and/or server status - Timed out with the following resources still waiting https://sdc1.senate.gov/NEED_VALUE/wtid.js
But if I then call:
session.save_screenshot('/tmp/sc.png', full: true)
the outputted screenshot is shows that the rest of the page loaded just fine. If this were any other browser, it would just continue to function happily without worrying about an asset that is taking forever to load.
Is there anyway to configure phantomjs to not wait for this asset and to not raise this exception?
The easiest way to deal with that is to use Poltergeists blacklist to block the url - https://github.com/teampoltergeist/poltergeist#customization -
and/or - https://github.com/teampoltergeist/poltergeist#url-blacklisting--whitelisting
If your situation is more dynamic you could rescue the exception, parse out the URL, add it to the blacklist, and then retry the visit.
Additionally, there is no need to override needs_server?. If you don't pass a second parameter (the app to run) to Session#new (which you aren't doing) then needs_server? is irrelevant.
I'll play around with the session timeout params:
session = Capybara::Session.new(:poltergeist_errorless, :timeout=>ASSET_LOAD_TIME)

route giving 404 in sinatra

I have just started working on sinatra, now my application is not able to navigate upto route and get data from db, I am always getting 404. This is what I am doing.
File Structure
app
|---->helpers
|----->models
|----->public
|----->routes
| |------->candidate.rb
| |------->init.rb
|----->app.rb
|----->config.ru
config.ru
require './app'
run MyApp
app.rb
require 'json'
require 'sinatra'
require 'data_mapper'
require 'dm-migrations'
require 'sinatra/cross_origin'
require 'logger'
require './models/init'
require './helpers/init'
require './routes/init'
class MyApp < Sinatra::Base
configure :development do
enable :cross_origin
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(
:default,
'mysql://root:#localhost/hackerrank'
)
end
get '/' do
File.read(File.join('public', 'index.html'))
end
DataMapper.finalize
end
Command
bundle exec rackup -p 4567 config.ru
api in candidate.rb are correct but if i try to access the resource as http://localhost:4567/#/recruiter I am getting 404 .
I am not able to figure out what is wrong I am doing here.
You're getting a 404, since GET '/' only works for the root page and you're trying to load /recruiter. You can change it to GET '/:pagename' and that would fix the 404 problem instantly.
Your codebase looks fine. When you're running your Sinatra app from the terminal, each request shows a log line such as
127.0.0.1 - - [02/Jan/2016 00:43:53] "GET / HTTP/1.1" 200 - 0.0033
Ensure that the HTTP verb and or endpoint/route you see is the one you are expecting (perhaps you are making a POST request when accessing the resource?)

Sinatra logging outside request

I believe I'm missing something with the way Sinatra does logging. I'd like to define a custom logger but also use it outside Sinatra's routes.
My app.rb looks like this:
require 'sinatra'
require 'logger'
logger = Logger.new(STDOUT)
configure do
use Rack::CommonLogger, logger
end
get '/' do
logger.info 'In request'
'Hello, world!'
end
logger.info 'Outside request'
The config.ru like so:
require 'sinatra'
require_relative 'app'
configure do
enable :logging
end
run Sinatra::Application
But when I run the application and curl the URL, I only see the log out during the request, not logger.info 'Outside request' when the application loads.
$ bundle exec rackup
I, [2015-06-22T23:09:32.789802 #6122] INFO -- : Outside request
[2015-06-22 23:09:32] INFO WEBrick 1.3.1
[2015-06-22 23:09:32] INFO ruby 2.1.4 (2014-10-27) [x86_64-linux]
[2015-06-22 23:09:32] INFO WEBrick::HTTPServer#start: pid=6122 port=9292
::1 - - [22/Jun/2015:23:09:48 -0400] "GET / HTTP/1.1" 200 13 0.0059
::1 - - [22/Jun/2015:23:09:48 -0400] "GET / HTTP/1.1" 200 13 0.0124
Hello, world!%
I know I'm missing something fundamental here, any help would be appreciated. Thank you.

Sinatra - Error Handling

I'm trying to make my sinatra app show a custom error page when an error is raised on the server (e.g. an IOError or ArgumentError).
Currently I'm using AJAX to load the results into a certain #results div, but if and when an error arises on the server, I would like an error page to open up on a new page.
Currently, the IOError is shown on the server and a error is seen in the console (the server responded with a status of 500 (Internal Server Error)). Other than that, nothing happens.
I think that I have to play about with the Javascript (as well as the Sinatra::Base class) but I've spent the whole of yesterday and this morning not getting anywhere.
I would be very grateful for any help. I've created an oversimplified version of my app which I have shown below...
Sinatra_app.rb
require 'sinatra/base'
require9 'sinatra'
require 'slim'
# A helper module
module GVhelpers
def create_results(name)
# raise IOError, "There's a problem..."
return "<p>The Server Says 'Hey #{name}'</p>"
end
end
class GVapp < Sinatra::Base
helpers GVhelpers
set :root, File.dirname(__FILE__)
error do
#error = env['sinatra.error']
slim :"500", :locals => {:error => error}
end
get '/' do
slim :index
end
post '/form' do
name = params[:personName]
create_results(name)
end
end
GVapp.run!
index.slim (in views folder)
script src="/jquery.min.js"
script src="/Gvapp.js"
form#sayHey action="/form" method="post"
| Name:
input type="text" name="personName"
br
input type="submit"
#output
500.slim (in views folder)
h1 Oops! Something went Wonky!
p Apologies, there was an error with your request:
strong request.env['sinatra.error'].message
p If the error persists, please contact the administrator.
Gvapp.js (in public folder)
$(document).ready(function() {
$('#sayHey').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/form',
data: $('#sayHey').serialize(),
success: function(response){
$('#output').html(response);
}
})
})
})
Sinatra swallows exceptions when run in the development environment by default and shows its debugging error page instead. So, to trigger your custom error handlers, you have to either run the application inside a Rack environment other than development (probably production), or preferably, tell Sinatra to not use its default error handlers in development mode.
Consider the following, standalone Sinatra application example:
require "sinatra"
#disable :show_exceptions
get "/" do
raise RuntimeError.new("boom")
end
error RuntimeError do
"A RuntimeError occured"
end
If you run this application using the default development environment like this:
$ ruby foo.rb
Then you will get Sinatra’s default error page. If you uncomment the disable line in the example, the error handler will be triggered instead, displaying a page containing "A RuntimeError occured". Alternatively, you can, as explained, run the application in an environment other than development as only that one pre-sets the show_exception setting. You can do that by setting the RACK_ENV environment variable:
$ RACK_ENV=production ruby foo.rb
For development purposes, setting RACK_ENV to production is not the correct way of course. Use disable :show_exceptions instead. You can use a configure block as outlined in the Sinatra README to conditionally disable the setting for the development environment.
configure :development do
disable :show_exceptions
end
That behaviour is documented in Sinatra’s documentation on configuration, along with several other useful settings.

deploy a sinatra app with passenger gives only 404, page not founds. Yet a simple rack app works

I have correctly (or prbably not) installed passenger on apache 2. Rack works, but sinatra keeps giving 404's.
Here is what works:
config.ru:
#app = proc do |env|
return [200, { "Content-Type" => "text/html" }, "hello <b>world</b>"]
end
run app
Here is what works too:
Running the app.rb (see below) with ruby app.rb and then looking at localhost:4567/about and /
restarting the app, gives me a correct hello world. w00t.
But then there is the sinatra entering the building:
config.ru
require 'rubygems'
require 'sinatra'
root_dir = File.dirname(__FILE__)
set :environment, ENV['RACK_ENV'].to_sym
set :root, root_dir
set :app_file, File.join(root_dir, 'app.rb')
disable :run
run Sinatra::Application
and an app.rb
require 'rubygems'
require 'sinatra'
get '/' do
"Hallo wereld!"
end
get '/about' do
"Hello world, it's #{Time.now} at the server!"
end
This keeps giving 404s.
/var/logs/apache2/error.log lists these correctly as "404" with something that worries me:
83.XXXXXXXXX - - [30/May/2010 16:06:52] "GET /about " 404 18 0.0007
83.XXXXXXXXX - - [30/May/2010 16:06:56] "GET / " 404 18 0.0007
The thing that worried me, is the space after the / and the /about. Would apache or sinatra go looking for /[space], like /%20?
If anyone knows what this problem relates to, maybe a known bug (that I could not find) or a known gotcha?
Maybe I am just being stupid and getting "it all wrong?"
Otherwise any hints on where to get, read or log more developers data on a running rack, sinatra or passenger app would be helpfull too: to see what sinatra is looking for, for example.
Some other information:
Running ubuntu 9.04, apache2-mm-prefork (deb), mod_php5, ruby 1.8.7, passenger 2.2.11, sinatra 1.0
You are not loading the routes in app.rb. To do this, replace require 'sinatra' with require File.join(File.dirname(__FILE__), 'app.rb') in config.ru.
root_dir = File.dirname(__FILE__)
app_file = File.join(root_dir, 'app.rb')
require app_file
set :environment, ENV['RACK_ENV'].to_sym
set :root, root_dir
set :app_file, app_file
disable :run
run Sinatra::Application
set :app_file won't load them for you.
Just substitute the require sinatra with a require 'app' and you're set to go.

Resources