Where to put auth information - ruby

So I'm making a small program in VisualRuby that can tweet. So here's what my main.rb looks like:
#!/usr/bin/ruby
require 'vrlib'
require 'twitter_oauth'
#make program output in real time so errors visible in VR.
STDOUT.sync = true
STDERR.sync = true
#everything in these directories will be included
my_path = File.expand_path(File.dirname(__FILE__))
require_all Dir.glob(my_path + "/bin/**/*.rb")
LoginWindow.new.show
and my LoginWindow.rb looks like this
require 'twitter_oauth'
class LoginWindow #(change name)
include GladeGUI
client = TwitterOAuth::Client.new(
:consumer_key => '****',
:consumer_secret => '****',
:token => '****-****',
:secret => '****'
)
def show()
load_glade(__FILE__) #loads file, glade/MyClass.glade into #builder
set_glade_all() #populates glade controls with insance variables (i.e. Myclass.label1)
show_window()
end
def button1__clicked(*argv)
if client.authorized?
puts "true"
end
end
end
And finally my window looks like this:
Now when I run this and click the login button, VR spits this out
C:/Users/*/visualruby/Test/bin/LoginWindow.rb:22:in `button1__clicked': undefined local variable or method `client' for #<LoginWindow:0x3f56aa8>
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:146:in `call'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:146:in `block (3 levels) in parse_signals'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:331:in `call'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:331:in `main'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:331:in `show_window'
from C:/Users/*/visualruby/Test/bin/LoginWindow.rb:17:in `show'
from main.rb:14:in `<main>'
I don't think I'm supposed to put the client = Twitter.... stuff inside the LoginWindow class but I can't think of anywhere else to put it. Any ideas on how to fix this issue?

This is a quick solution for what you need.
in your LoginWindow.rb
def initialize
#client = TwitterOAuth::Client.new(
:consumer_key => '****',
:consumer_secret => '****',
:token => '****-****',
:secret => '****'
)
end
def button1__clicked(*argv)
if #client.authorized?
puts "true"
end
end
The problem with this solution is now you can't call button1_clicked without initializing LogginWindow before, so be careful.

Related

undefined method for calling methode in class

i try to call my methode check_table_exists for check my table. This methode is on my module, and i dont understand why i get this error .
i know #connexion is a Mysql2::Client instance, which doesn't include the module Sgbd. but i dont see how to include my methode ?
./yamlReadFile.rb:44:in `mysql_connection': undefined method `check_table_exists' for #<Mysql2::Client:0x000000033a7750> (NoMethodError)
$LOAD_PATH << '.'
require 'yaml'
require 'rubygems'
require 'mysql2'
require 'creatDatabase'
#binding.pry
class StreamMysql
include Sgbd
def mysql_connection(conf)
#connexion = Mysql2::Client.new(:host => conf['ost'], :username => conf['user'], :password => conf['password'], :table => conf['table'], :port => conf['port'])
if #connexion
puts check_table_exists
#connexion.check_table_exists
puts "connexion etablie"
else
puts "error connexion"
end
rescue Mysql2::Error => e
puts e.errno
puts e.error
#connexion.close
end
def read_config_file
config = YAML::load_file(File.join(__dir__, 'config.yml'))
conf = config['database']
mysql_connection(conf)
end
end
my module file with the mehode check_table_exists
module Sgbd
# class ModuleCreateDatabase
def create_database
end
def check_table_exists
query=("SHOW TABLES;")
end
end
It’s unclear why would you want to include your module in the foreign class, but it’s doable:
Mysql2::Client.include Sgbd
The line above should be put e. g. before class StreamMysql declaration.

undefined local variable or method `res' for main:Object (NameError)

I have the following little script that connects to a host, and gets some output.
#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'timeout'
serverurl = "http://www.google.com/"
uri = URI(serverurl)
res = Net::HTTP.post_form(uri, 'method' => 'login', 'username' => 'admin', 'password' => 'MySup3rDup3rp#55w0rd')
cookie = res['set-cookie']
if cookie.nil?
puts "No cookie"
end
I want to use some timeout so I do:
#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'timeout'
serverurl = "http://www.google.com/"
uri = URI(serverurl)
begin
timeout(10) do
res = Net::HTTP.post_form(uri, 'method' => 'login', 'username' => 'admin', 'password' => 'MySup3rDup3rp#55w0rd')
end
rescue StandardError,Timeout::Error
puts "#{server} Timeout"
exit(1)
end
cookie = res['set-cookie']
if cookie.nil?
puts "No cookie"
end
Now I get some error:
test.rb:20:in `<main>': undefined local variable or method `res' for main:Object (NameError)
I don't know why, because a similar test code works without error:
require "timeout"
begin
timeout(6) do
sleep
end
#rescue # under ruby >= 1.9 is ok
rescue StandardError,Timeout::Error # workaround for ruby < 1.9
p "I'm sorry, Sir. We couldn't make it, Sir."
end
Any idea what am I doing wrong?
This is about scope. In Ruby, variables are only visible within the same scope where they are defined (exceptions are instance-, class-, and global variables as well as constants).
So in your example, res is only visible within the timeout-block. Add res = nil before the begin-block to make sure res is defined in the scope you actually need the value.

Daemonizing Mailman app

Starting my mailman app by running rails runner lib/daemons/mailman_server.rb works fine.
When starting with my daemon script and command bundle exec rails runner script/daemon run mailman_server.rb, the script generates an error:
.rvm/gems/ruby-1.9.3-p194/gems/mailman-0.5.3/lib/mailman/route/conditions.rb:21:in `match': undefined method `each' for nil:NilClass (NoMethodError)
My code is as follows:
lib/daemons/mailman_server.rb
require 'mailman'
# Config Mailman
Mailman.config.ignore_stdin = false
Mailman.config.graceful_death = true
Mailman.config.poll_interval = 15
Mailman.config.logger = Logger.new File.expand_path("../../../log/mailman.log", __FILE__)
Mailman.config.pop3 = {
:username => 'alias#mygoogleapp.com',
:password => 'password',
:server => 'pop.gmail.com',
:port => 995,
:ssl => true
}
# Run the mailman
Mailman::Application.run do
from('%email%').to('alias+q%id%#mygoogleapp.com') do |email, id|
begin
# Get message without headers to pass to add_answer_from_email
if message.multipart?
reply = message.text_part.body.decoded
else
reply = message.body.decoded
end
# Call upon the question to add answer to his set
Question.find(id).add_answer_from_email(email, reply)
rescue Exception => e
Mailman.logger.error "Exception occured while receiving message:\n#{message}"
Mailman.logger.error [e, *e.backtrace].join("\n")
end
end
end
and my script/daemon file is:
#!/usr/bin/env ruby
require 'rubygems'
require "bundler/setup"
require 'daemons'
ENV["APP_ROOT"] ||= File.expand_path("#{File.dirname(__FILE__)}/..")
script = "#{ENV["APP_ROOT"]}/lib/daemons/#{ARGV[1]}"
Daemons.run(script, dir_mode: :normal, dir: "#{ENV["APP_ROOT"]}/tmp/pids")
Any insight as to why it fails as a daemon?

How do I use omniauth in rspec for sinatra?

Shortened version:
Using the omniauth gem for sinatra, I can't get rspec log in to work and keep my session for subsequent requests.
Based on suggestions from http://benprew.posterous.com/testing-sessions-with-sinatra, and turning off sessions, I've isolated the problem to this:
app.send(:set, :sessions, false) # From http://benprew.posterous.com/testing-sessions-with-sinatra
get '/auth/google_oauth2/callback', nil, {"omniauth.auth" => OmniAuth.config.mock_auth[:google_oauth2] }
# last_request.session => {"uid"=>"222222222222222222222", :flash=>{:success=>"Welcome"}}
# last_response.body => ""
follow_redirect!
# last_request.session => {:flash=>{}}
# last_response.body => Html for the homepage, which is what I want
How do I get rspec to follow the redirect and retain the session variables? Is this possible in Sinatra?
From http://benprew.posterous.com/testing-sessions-with-sinatra, it seems like I'd have to send the session variables on each get/post request that I require login for, but this wouldn't work in the case of redirects.
The details:
I'm trying to use the omniauth gem in sinatra with the following setup:
spec_helper.rb
ENV['RACK_ENV'] = 'test'
# Include web.rb file
require_relative '../web'
# Include factories.rb file
require_relative '../test/factories.rb'
require 'rspec'
require 'rack/test'
require 'factory_girl'
require 'ruby-debug'
# Include Rack::Test in all rspec tests
RSpec.configure do |conf|
conf.include Rack::Test::Methods
conf.mock_with :rspec
end
web_spec.rb
describe "Authentication:" do
before do
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:google_oauth2, {
:uid => '222222222222222222222',
:info => {
:email => "someone#example.com",
:name => 'Someone'
}
})
end
describe "Logging in as a new user" do
it "should work" do
get '/auth/google_oauth2/'
last_response.body.should include("Welcome")
end
end
end
When trying to authenticate, I get a <h1>Not Found</h1> response. What am I missing?
On the Integration testing page of the omniauth docs, it mentions adding two environment variables:
before do
request.env["devise.mapping"] = Devise.mappings[:user]
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
end
But seems to be for rails only, as I added
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:google_oauth2]
to my before block in my spec and I get this error:
Failure/Error: request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:google_oauth2]
ArgumentError:
wrong number of arguments (0 for 1)
Edit:
Calling get with
get '/auth/google_oauth2/', nil, {"omniauth.auth" => OmniAuth.config.mock_auth[:google_oauth2]}
seems to give me last_request.env["omniauth.auth"] equal to
{"provider"=>"google_oauth2", "uid"=>"222222222222222222222", "info"=>{"email"=>"someone#example.com", "name"=>"Someone"}}
which seems right, but last_response.body still returns
<h1>Not Found</h1>
A partial answer...
The callback url works better, with the added request environment variables:
get '/auth/google_oauth2/callback', nil, {"omniauth.auth" => OmniAuth.config.mock_auth[:google_oauth2]}
follow_redirect!
last_response.body.should include("Welcome")
However, this doesn't work with sessions after the redirect, which is required for my app to know someone is logged in. Updated the question to reflect this.
Using this gist (originating from https://stackoverflow.com/a/3892401/111884) to store session data, I got my tests to store the session, allowing me to pass the session to further requests.
There might be an easier way though.
Setup code:
# Omniauth settings
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:google_oauth2, {
:uid => '222222222222222222222',
:info => {
:email => "someone#example.com",
:name => 'Someone'
}
})
# Based on https://gist.github.com/375973 (from https://stackoverflow.com/a/3892401/111884)
class SessionData
def initialize(cookies)
#cookies = cookies
#data = cookies['rack.session']
if #data
#data = #data.unpack("m*").first
#data = Marshal.load(#data)
else
#data = {}
end
end
def [](key)
#data[key]
end
def []=(key, value)
#data[key] = value
session_data = Marshal.dump(#data)
session_data = [session_data].pack("m*")
#cookies.merge("rack.session=#{Rack::Utils.escape(session_data)}", URI.parse("//example.org//"))
raise "session variable not set" unless #cookies['rack.session'] == session_data
end
end
def login!(session)
get '/auth/google_oauth2/callback', nil, { "omniauth.auth" => OmniAuth.config.mock_auth[:google_oauth2] }
session['uid'] = last_request.session['uid']
# Logged in user should have the same uid as login credentials
session['uid'].should == OmniAuth.config.mock_auth[:google_oauth2]['uid']
end
# Based on Rack::Test::Session::follow_redirect!
def follow_redirect_with_session_login!(session)
unless last_response.redirect?
raise Error.new("Last response was not a redirect. Cannot follow_redirect!")
end
get(last_response["Location"], {}, { "HTTP_REFERER" => last_request.url, "rack.session" => {"uid" => session['uid']} })
end
def get_with_session_login(path)
get path, nil, {"rack.session" => {"uid" => session['uid']}}
end
Sample rspec code:
describe "Authentication:" do
def session
SessionData.new(rack_test_session.instance_variable_get(:#rack_mock_session).cookie_jar)
end
describe "Logging in as a new user" do
it "should create a new account with the user's name" do
login!(session)
last_request.session[:flash][:success].should include("Welcome")
get_with_session_login "/"
follow_redirect_with_session_login!(session)
last_response.body.should include("Someone")
end
end
end

Is there a way with test::unit Ruby to load gems

I am trying to use test::unit for testing and the framework I am trying to test requires a particular gem (rhodes)
Can anyone suggest how I can get the gem loaded when I run my tests
Update :: Error Message
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- rho (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from ../../app/Settings/controller.rb:1
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from ../test_helper.rb:4
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from test_settings.rb:4
My unit test uses require to include test_helper.rb which contains following
$: << "../../app"
require 'rubygems'
require 'rhodes'
require 'test/unit'
require 'Settings/controller'
Settings/controller lives in app and contains
require 'rho'
require 'rho/rhocontroller'
require 'rho/rhoerror'
require 'helpers/browser_helper'
class SettingsController < Rho::RhoController
include BrowserHelper
def index
#msg = #params['msg']
render
end
def login
#msg = #params['msg']
render :action => :login, :back => '/app'
end
def login_callback
errCode = #params['error_code'].to_i
if errCode == 0
# run sync if we were successful
WebView.navigate Rho::RhoConfig.options_path
SyncEngine.dosync
else
if errCode == Rho::RhoError::ERR_CUSTOMSYNCSERVER
#msg = #params['error_message']
end
if !#msg || #msg.length == 0
#msg = Rho::RhoError.new(errCode).message
end
WebView.navigate ( url_for :action => :login, :query => {:msg => #msg} )
end
end
def do_login
if #params['login'] and #params['password']
begin
SyncEngine.login(#params['login'], #params['password'], (url_for :action => :login_callback) )
render :action => :wait
rescue Rho::RhoError => e
#msg = e.message
render :action => :login
end
else
#msg = Rho::RhoError.err_message(Rho::RhoError::ERR_UNATHORIZED) unless #msg && #msg.length > 0
render :action => :login
end
end
def logout
SyncEngine.logout
#msg = "You have been logged out."
render :action => :login
end
def reset
render :action => :reset
end
def do_reset
Rhom::Rhom.database_full_reset
SyncEngine.dosync
#msg = "Database has been reset."
redirect :action => :index, :query => {:msg => #msg}
end
def do_sync
SyncEngine.dosync
#msg = "Sync has been triggered."
redirect :action => :index, :query => {:msg => #msg}
end
end
Edit 2: after looking at your code, I believe the following should work:
Move the lines from test_helper
require 'rubygems'
require 'rhodes'
to the very top of Settings/controller
Or are you thinking of loading it dynamically during setup/teardown (possibly to avoid conflicting dependencies etc.)?
Edit: I wrote up a quick example of testing a simple wrapper around a Watir class (UI manipulator for IE browser).
require 'rubygems'
require 'watir'
require 'test/unit'
class WatirWrapper
def initialize()
#browser = Watir::IE.new()
end
def method_missing(sym, *args, &block)
#browser.send(sym, *args, &block)
end
end
class WatirWrapperTest < Test::Unit::TestCase
def test_goto
#ww = WatirWrapper.new()
#ww.goto('http://www.google.com/')
assert_equal('http://www.google.com/', #ww.url())
end
end

Resources