before filter issue in padrino - ruby

I'm trying to create a chain of before filter in padrino that look like this of which look like this
before do
set_current_user
track_order_ip
!current_user and pass
## don't allow the next filter other filter to run if no current user
customer_inactivity!
skip_enforce!
## so the theory is this if a users is is not enforced he should not be allowed to execute enforce! before filter
enforce!
end
Now all filter would execute in chain but if the current_user is not present I wish to drop(i.e pass) the filter chain processing which is taken care by this (!current_user and pass) code
But trying to do something like this in padrino cause the app to redirect the same route multiple time and then break with following error.
ArgumentError at /myaccount/users/authenticate
uncaught throw :pass
at
!current_customer and pass
What I'm find weird and what I'm not able to understand is , why? it not working in Padrino(since I know Padrino internally uses Sinatra) because I did wrote a proof of concept similar application in sinatra (can be found over here) and that just seem to work out of box without any issue
Lastly here the padrino code
Now any one can give me some pointer as too what I'm doing wrong in padrino that is implemented correctly in the proof of concept sinatra app
Thanks

Related

Using "helper" method in view

I made a helper in my rails project that makes a request in an external api and get a certain value from it.
def show_CoinPrice coin
begin
coinTicker = JSON.parse(HTTParty.get("https://www.mercadobitcoin.net/api/#{coin}/ticker/").body)
"R$ #{coinTicker["ticker"]["last"].to_number.round}"
rescue
"---"
end
end
However I have doubts if this was a good practice to do (this code caused slowness in my view), there is something I can do better, whether with a controller or something ?!
Thanks.
I think u should request to external API using client-side (JS). Cs fetching API with rails helper it's will run while your server is rendering view.

How do I programmatically set a content_security_policy?

I'm configuring the Content Security Policy for our Rails 5.2 app. I need to whitelist some domains in our CSP. I'd like to put the list of domains elsewhere so I can reference them in other places in the application, then generate the CSP headers programmatically from that list.
Looking at the source code for the Content Security Policy configuration mechanisms in Rails 5, it looks like there's some magic metaprogramming going on, so it's not clear to me how to accomplish what I need to do. It looks like the functions I need to call to set headers might be picky about how exactly they want to be called. In particular, it's not clear to me if I can pass them arrays or safely call them multiple times, or if they do some metaprogramming magic that only works if the domains are passed in as individual function arguments.
Can I pass in an array to the header I want to set, like this?
whitelisted_domains = ['https://example.com', 'self']
Rails.application.configure do
config.content_security_policy do |csp|
csp.child_src whitelisted_domains
end
end
Or can I call the same function multiple times, like this?
whitelisted_domains = ['https://example.com', 'self']
Rails.application.configure do
config.content_security_policy do |csp|
whitelisted_domains.each {|domain| csp.child_src domain}
end
end
If neither of those will work, what's the best way of accomplishing what I want to do?
From what I can tell from sourcecode and documentation, it takes an array. From the edgeguides at rails, posting following
Rails.application.config.content_security_policy do |policy|
policy.default_src :self, :https
...
end
and the sourcecode, using *sources as param; it believe it takes any number of arguments, meaning you could do something along the lines of;
whitelisted_domains = ['https://example.com', 'self']
Rails.application.configure do
config.content_security_policy do |csp|
csp.child_src(*whitelisted_domains)
end
end
https://blog.sqreen.io/integrating-content-security-policy-into-your-rails-applications-4f883eed8f45/
https://edgeguides.rubyonrails.org/security.html#content-security-policy
Sourcecode of define_method for each directive
https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/content_security_policy.rb#L151
(note: None of this has been tested in a Rails app, simple looking guides and source code of Rails)

checking groups at runtime with devise and devise_ldap_authenticatable

I can get this devise_ldap_authenticatable working just fine when I don't care about what groups they are, it either connects to ldap and authenticates the user signing in under devise or doesn't. But I want to let only certain members that are apart of one or several specific groups in. I had a post on this question here:
Checking group membership in rails devise ldap gem, is it in the yaml?
(the gem for completeness sake is this one: https://github.com/cschiewek/devise_ldap_authenticatable)
Got to thinking I am asking the wrong question. I think I want to know how in devise (and the devise_ldap_authenticatable is the data stored where perhaps I can peek at my array of memberOf's myself and check the groups for myself in code, and then at that time don't let them in. Is there anywhere on the net that's hows this? My googling has turned up nothing but not being a ldap or devise pro I am guessing my terms suck.
I am sure I just might of missed the how to do this, closest I can see that might help (Though in its form as I read it makes little sense to me is the part on the readme here:
https://github.com/cschiewek/devise_ldap_authenticatable/blob/master/README.md
about querying ldap, is this the case?)
You could do this with a callback or validation on the User (or equivalent) model.
before_create :user_is_not_member_of_specified_group?
private
def user_is_not_member_of_specified_group?
member_of = Devise::LdapAdapter.get_ldap_param(self.username,"memberOf")
test member_of
end
where test is a method that returns true/false based on your conditions for the member groups.
The Devise::LdapAdapter.get_ldap_param(self.username,"memberOf") is a method from devise_ldap_authenticatable that will return an array of member groups. You'll want to run your group testing on this array.
If you use a validation you could specify an error message for users that failed the test. Hope this helps.
EDIT
Another way to handle this would be to let your gem handle the redirection and error messages by monkeypatching the authorized? method in Devise::LdapAdapter::LdapConnect (https://github.com/cschiewek/devise_ldap_authenticatable/blob/master/lib/devise_ldap_authenticatable/ldap_adapter.rb). It would look like:
Devise::LdapAdapter::LdapConnect.class_eval do
def user_group_test
member_of = self.ldap_param_value("memberOf")
test member_of # your group test method
end
def authorized?
DeviseLdapAuthenticatable::Logger.send("Authorizing user #{dn}")
if !user_group_test
DeviseLdapAuthenticatable::Logger.send("Not authorized because custom authentication failed.")
return false
elsif !authenticated?
DeviseLdapAuthenticatable::Logger.send("Not authorized because not authenticated.")
return false
elsif !in_required_groups?
DeviseLdapAuthenticatable::Logger.send("Not authorized because not in required groups.")
return false
elsif !has_required_attribute?
DeviseLdapAuthenticatable::Logger.send("Not authorized because does not have required attribute.")
return false
else
return true
end
end
end
You would want to put this in a custom initializer file in config/initializers.

Splunk-client (with Nokogiri) giving Undefined Namespace Prefix

I'm using splunk-client to extract results from splunk. Here's the code:
query = "sourcetype=collection #{order_id}"
search = #splunk_client.search(query)
search.wait
The search is happening fine, and it seems like I'm doing everything according to the example (https://github.com/cbrito/splunk-client), but I get this error on the 'search.wait' line:
Undefined namespace prefix: //s:key[#name='isDone']
Any ideas what could be going wrong? Running these commands in irb works fine. Is there some sort of blocking issue?
There is currently very little error checking which occurs within the gem itself. The reason for the error is that wait looks for the status of the isDone key to change to true.
Since your credentials were not properly setup in the first place, the gem creates a search object with an invalid session. The search does not initially fail, because enough response came back from Splunk that Nokogiri processes it into an object without a Splunk search sid.
In the future I should likely raise an exception if a proper sid is not returned to avoid confusion.
Source: I wrote the gem.
I found out the issue -- the splunk client wasn't authenticating properly, and so search was actually a broken SplunkJob object (with a nil username and authentication key). It's strange that there was no error raised until the wait command, but upon inspecting the search object, one of the fields stated that the object was malformed.

rails session_store odd behaviour

I am using active_record_store in a rails application which is storing this in session session[:email] = "email#address.com"
now this works fine in the action. but when this action gets over and is redirected to another page, which also accesses the same session[:email] I get an error
undefined method `eq' for nil:NilClass
this should probably mean that i am trying to compare values at some place i am not allowed to. but i cannot see anything like that in the code.
This looks like an old question, but I was just having the same problem and had to figure it out on my own, and thought I would post the solution up here for anyone else that runs into this. It's not very well documented, but to get this to work you have to add:
config.action_dispatch.session_store = :active_record_store
to application.rb, and
Application.config.session_store :active_record_store
to config/initializers/session_store.rb. Then, you have to do:
rake db:sessions:create
and:
rake db:migrate
Then, you have to restart your rails server. I think it was the db:sessions:create step that tripped up the original poster. Not only does that database table have to be laid out the way rails is expecting (that is, with an 'id' column, which is the actual cause of this error, I think), but also the current session has to have a valid ID. Hence the need to create the table and re-start the server, or potentially empty the table if it exists.

Resources