How use authorized user to make requests to another project with the same ldap authorization? - ruby-on-rails-4

I can't make request to another project with the same auth
I've tried to make
req.basic_auth curent_user.username, current_user.encrypted_password
But it said currnet_user is not defined
I've tried to set in project2
skip_before_filter :authenticate_user!, only: :get_data
Bit it returns
{"status":"422","error":"Unprocessable Entity"}
The code is
uri = URI(["#{request.protocol}#{request.host_with_port}", 'clients', Rails.configuration.system_client_name, 'project1', 'get_data'].join('/'))
res = nil
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https'
) do |http|
req = Net::HTTP::Post.new(uri.request_uri)
# ??? req.basic_auth curent_user.username, current_user.encrypted_password
res = http.request(req)
end
data = res.body
Project1
def get_data
render json: {q: 1}, status: 200
end
Gems are the same in both projects
devise_ldap_authenticatable (0.8.1)
devise (>= 3.0)
net-ldap (>= 0.3.1, < 0.6.0)

I've made no auth
In project2:
skip_before_action :verify_authenticity_token, only: : get_data
skip_before_action :authenticate_user!, only: : get_data
In project1:
uri = URI(["#{request.protocol}#{request.host_with_port}", 'clients', Rails.configuration.system_client_name, get_data, 'get_num_of_synonyms'].join('/'))
res = nil
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https'
) do |http|
req = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/json')
res = http.request(req)
end

Related

error in fetching mail using griddler(mandrill)

I am implementing griddler(using Mandrill) to fetch e-mail in my app.
This is my class to receive mail
#app/email_receivers/incoming.rb
class EmailReceiver < Incoming::Strategies::Mandrill
def receive(mail)
%(Got message from #{mail.to.first} with subject "#{mail.subject}")
end
end
req = Rack::Request.new(Rails.env)
result = EmailReceiver.receive(req)
This is my rails controller that calls receive method of EmailReceiver class.
#emails_controller.rb
class EmailsController < ActionController::Base
def create
if EmailReceiver.receive(request)
render :json => { :status => 'ok' }
else
render :json => { :status => 'rejected' }, :status => 403
end
end
end
Routes for calling create method of EmailsController
#routes.rb
Rails.application.routes.draw do
post '/emails' => 'emails#create'
end
Note:- After running server in production environment
rails s -e production
I got this error
/home/bvc-2/.rvm/gems/ruby-2.2.1/gems/rack-1.6.4/lib/rack/request.rb:192:in `[]=': string not matched (IndexError)
Where "puts req" in
req = Rack::Request.new(Rails.env)
turns out to be:
#<Rack::Request:0xc3bace8 #env="production">
And my config/application.rb file is:-
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
ActionMailer::Base.smtp_settings = {
:address =>"smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "***#gmail.com",
:password => "pass*******",
:authentication => 'plain',
:enable_starttls_auto => true
}
module ComplaintSystem
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
config.active_job.queue_adapter = :delayed_job
config.time_zone = 'Mumbai'
config.active_record.default_timezone = :local
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
This type of error happens when you try to access a string variable as a Hash by mistake.
s = "hello world"
s["position"] = "programming is fun"
# > IndexError: string not matched
# > from (irb):5:in `[]='
# > from (irb):5
Look at your full stack trace and see where you are trying to do such operation.

Omniauth devise Authentication failure! csrf_detected:

I got the Authentication failure! csrf_detected: so that I couldn't login with omniauth.
I followed this tutorial
and I found similar issue here,
But there are no luck for my problem till now.
Any idea for fixing the error ? Thanks
E, [2015-06-27T10:40:06.028200 #18798] ERROR -- omniauth: (facebook) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
Gems
* devise (3.5.0)
* omniauth (1.2.2)
* omniauth-facebook (2.0.0)
* omniauth-oauth2 (1.3.1)
/app/controllers/application_controller.rb
protect_from_forgery with: :exception
-
+ before_action :authenticate_user!
/app/models/user.rb
devise :database_authenticatable, :registerable,
+ :omniauthable, :omniauth_providers => [:facebook]
+ def self.from_omniauth(auth)
+ where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
+ binding.pry
+ user.provider = auth.provider
+ user.uid = auth.uid
+ user.email = auth.info.email
+ user.password = Devise.friendly_token[0,20]
+ end
+ end
+
/config/initializers/omniauth.rb
+Rails.application.config.middleware.use OmniAuth::Builder do
+ provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'],
+ :scope => 'email'
+end
Error log from console (how to trace it?)
Started GET "/users/auth/facebook/callback?code=AQDZC-Ny2PI-UwunCNi29mx4YGKT&state=cf896d3decffe2a7a664315e050a1165a290477542ff7d33" for 127.0.0.1 at 2015-06-27 10:40:05 +0800
I, [2015-06-27T10:40:05.255832 #18798] INFO -- omniauth: (facebook) Callback phase initiated.
I, [2015-06-27T10:40:06.028051 #18798] INFO -- omniauth: (facebook) Callback phase initiated.
E, [2015-06-27T10:40:06.028200 #18798] ERROR -- omniauth: (facebook) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
Processing by CallbacksController#failure as HTML
Parameters: {"code"=>"AQDZC-Ny2PI-UwunCNi29mx4YGKTuHDeP2X2X-leywO14gr_iHLvXxX1LpV5WteUrQHpX-uc0Z01wcjy4XHA9CBkZeSo4qRb7jXdvPLfQl6mgwbMrFuQb1_55KughvtMWMlZ_7YEhtiLoEZH_2EvGXLbuKkUq", "state"=>"cf896d3decffe2a7a663"}
routes
+ devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }
It looks like you also asked this question on the Omniauth Facebook Github Repo. It didn't look like there was a solid answer there either.
#dmcbrayer did suggest changing your initializer to look like:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'],
:scope => 'email',
:info_fields => 'email'
end
This was due to an API change on facebook side which required you to explicitly ask for info_fields.
The maintainer #mkdynamic also wanted you to verify whether it was fixed in a newer version (3.0.0 at the time).

rails renders fast but view slow

Using rails 4.1 & 4.1.0rc2
We're having this weird issue with rendering:
I, [2014-04-13T07:45:28.856574 #5695] INFO -- : Started GET "/xpto" for xxx.xxx.xxx.xxx at 2014-04-13 07:45:28 +0000
I, [2014-04-13T07:45:28.916947 #5695] INFO -- : Processing by XptoController#index as HTML
D, [2014-04-13T07:45:28.952666 #5695] DEBUG -- : Cart Load (2.5ms) sql
D, [2014-04-13T07:45:29.000582 #5695] DEBUG -- : SQL (2.5ms) sql
D, [2014-04-13T07:45:29.004601 #5695] DEBUG -- : SQL (2.6ms) sql
I, [2014-04-13T07:45:29.026042 #5695] INFO -- : Rendered xpto/index.html.erb within layouts/application (58.4ms)
I, [2014-04-13T07:45:29.719445 #5695] INFO -- : Completed 200 OK in 802ms (Views: 735.2ms | ActiveRecord: 31.4ms)
As you can see in the log the render took 58.4ms but the "View" took 735.2ms. Every data is being preloaded and the view consists only of:
<h1>xptos</h1>
<% #xptos.each do |xpto| %>
<p>link: <%= link_to xpto.name, xptos_path(xpto) %> (ID: <%= xpto.id %>)</p>
<% end %>
The configurations used:
Rails.application.configure do
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = true
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.assets.version = '1.0'
config.force_ssl = false
config.log_level = :debug
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
config.paperclip_defaults = {
storage: :fog,
fog_credentials: { provider: 'aws',
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
},
fog_directory: 'xpto-bucket'
}
end
Requests are being served directly by Unicorn with config:
log_path = 'log/unicorn.log'
pid_path = 'tmp/pids/unicorn.pid'
pid pid_path
worker_processes 8
timeout 15
preload_app true
listen 3000, backlog: 1025
stderr_path log_path
stdout_path log_path
before_fork do |server, worker|
ActiveRecord::Base.connection.disconnect! if defined?(ActiveRecord)
end
after_fork do |server, worker|
ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
end
Is there any way to debug what is taking so long after render but before returning the response?

ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

My ruby on rails action mailer runs all good in development environment, but in production environment, it keeps throw:
ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
My development config is
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:port => xxx,
:address => 'smtp.example.org',
:user_name => 'xxx#example.com',
:password => 'xxxxxxxx',
:domain => 'xxxxxx.example',
:authentication => :plain,
}
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
My production config is
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:port => 587,
:address => 'smtp.example.org',
:user_name => 'xxx#example.com',
:password => 'xxxxxx',
:domain => 'example.com',
:authentication => :plain,
}
config.action_mailer.default_url_options = { :host => 'example.com' }
My other environments are:
ruby 2.1.1
rails 4.0.3
sidekiq
devise
devise-async
I have tried:
Add the following in a initializer file
ActionMailer::Base.default_url_options[:host] = "example.com"
This answer here
Neither of them works.
In the end I added the following with the correct value to each environment file:
test.rb / development.rb / production.rb
Devise 3.2.x - 4.x.x
Rails 4.1.x && Rails 4.2.x && Rails 5.x.x
Thanks to maudulus
# Default Mailer Host
Rails.application.routes.default_url_options[:host] = 'domain.example'
Try restarting the server. Even in Rails 4.1 the config is not reparsed without a restart.

lighttpd + mod_fastcgi + django

I am having trouble deploying my django app to a server that uses lighttpd (on which I'm root.)
Here's my lighttpd.conf:
server.modules = (
# "mod_access",
# "mod_alias",
# "mod_compress",
# "mod_redirect",
"mod_status",
#"mod_rewrite",
# "mod_fastcgi",
# "mod_accesslog",
)
status.status-url = "/server-status"
status.config-url = "/server-config"
$HTTP["host"] == "myurl.com" {
server.document-root = "/var/www/myurl"
server.errorlog = "/var/log/lighttpd/myurl/error.log"
accesslog.filename = "var/log/lighttpd/nixcraft/access.log"
server.error-handler-404 = "/e404.html"
fastcgi.server = (
"/myurl/nonorientable.fcgi" => (
"main" => (
# Use host / port instead of socket for TCP fastcgi
# "host" => "127.0.0.1",
# "port" => 3033,
"socket" => "/tmp/myurl.sock",
"check-local" => "disable",
)
),
)
}
server.pid-file = "/var/run/lighttpd.pid"
server.username = "www-data"
server.groupname = "www-data"
index-file.names = ( "index.php", "index.html",
"index.htm", "default.htm")
url.access-deny = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )
## Use ipv6 if available
#include_shell "/usr/share/lighttpd/use-ipv6.pl"
dir-listing.encoding = "utf-8"
server.dir-listing = "enable"
compress.cache-dir = "/var/cache/lighttpd/compress/"
compress.filetype = ( "application/x-javascript", "text/css", "text/html", "text/plain" )
include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl"
server.modules += ( "mod_auth" )
auth.debug = 2
auth.backend = "plain"
auth.backend.plain.userfile = "/etc/lighttpd/.lighttpdpassword"
auth.require = ( "/" =>
("method" => "basic",
"realm" => "",
"require" => "user=john"))
And then I ran this on my server (from the folder /var/www/myurl):
sudo python manage.py runfcgi daemonize=false socket=/tmp/myurl.sock maxrequests=1
At this point, when I try to load myurl.com, all I get is the directory listing: my django app is not executed. I thought that the problem was that mod_fastcgi is commented in my conf, it actually appears on myurl.com/server-config. If I uncomment it, lighttpd complains that I'm trying to load the same module twice and exits, so my guess is that it is imported by default.
I'm using django1.4 (latest stable) and lighttpd 1.4.28 on ubuntu 12.04, and I'm pretty stuck. I followed the official doc (https://docs.djangoproject.com/en/1.4/howto/deployment/fastcgi/)
It looks like your missing the rewrite directive given in the docs:
url.rewrite-once = (
"^(/media.*)$" => "$1",
"^/favicon\.ico$" => "/media/favicon.ico",
"^(/.*)$" => "/mysite.fcgi$1",
)
Update: You need to change the fastcgi.server section from /myurl/nonorientable.fcgi to /mysite.fcgi so that it matches the rewrite above.