How to use Rails 5.2 credentials in another .yml file? - ruby-on-rails

I'm using the Cloudinary gem to allow a user to upload their avatar. In the docs, they offer a few ways to supply your api_key and api_secret, however I'm unable to get it work correctly with Rails credentials.
I've tried with the cloudinary.yml:
---
development:
cloud_name: test_cloud
api_key: <%= Rails.application.credentials.cloudinary[:api_key] %>
api_secret: <%= Rails.application.credentials.cloudinary[:api_secret] %>
enhance_image_tag: true
static_file_support: false
production:
cloud_name: test_cloud
api_key: <%= Rails.application.credentials.cloudinary[:api_key] %>
api_secret: <%= Rails.application.credentials.cloudinary[:api_secret] %>
enhance_image_tag: true
static_file_support: true
test:
cloud_name: test_cloud
api_key: <%= Rails.application.credentials.cloudinary[:api_key] %>
api_secret: <%= Rails.application.credentials.cloudinary[:api_secret] %>
enhance_image_tag: true
static_file_support: false
And I've also tried using a cloudinary.rb initializer:
Cloudinary.config do |config|
config.cloud_name = "test_cloud"
config.api_key = Rails.application.credentials.cloudinary[:api_key]
config.api_secret = Rails.application.credentials.cloudinary[:api_secret]
config.enhance_image_tag = true
config.static_file_support = false
end
When I attempt to upload the image, I receive a 500 error CloudinaryException (Must supply api_key). I know that the actual upload itself works because I hard-coded the values into the cloudinary.yml file to test it.
I've also tried using the .fetch function mentioned below, however I receive a key not found: :api_secret (KeyError)
How can I use Rails credentials within either of these files?

Related

Rails ActiveStorage / Cloudinary Not Redirecting Image Request to HTTPS

The ActiveStorage image_url helper generates a URL to the image on the Rails web server. When that request is received on the web server it is redirected to a URL on Cloudinary to request the image. ActiveStorage is generating an image URL with the https protocol but the Rails web server is generating an image URL to Cloudinary with the http (no ssl) protocol. I have not been able to determine why.
The Log of the request:
Started GET "/rails/active_storage/blobs/really_long_hash/user-2.png"
Processing by ActiveStorage::BlobsController#show as JPEG
Parameters: {"signed_id"=>"really_long_hash", "filename"=>"nsi-site-bg"}
ActiveStorage::Blob Load (0.8ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2 [["id", 48], ["LIMIT", 1]]
Cloudinary Storage (4.3ms) Generated URL for file at key: cloudinary_file_name (http://res-4.cloudinary.com/hcfhlrdjg/image/upload/cloudinary_file_name.jpg)
Redirected to http://res-4.cloudinary.com/hcfhlrdjg/image/upload/cloudinary_file_name.jpg
Completed 302 Found in 48ms (ActiveRecord: 13.8ms)
cloudinary.yml
development:
cloud_name: <%= ENV['CLOUDINARY_CLOUD_NAME'] %>
api_key: <%= ENV['CLOUDINARY_API_KEY'] %>
api_secret: <%= ENV['CLOUDINARY_API_SECRET'] %>
secure: true
cdn_subdomain: true
production:
cloud_name: <%= ENV['CLOUDINARY_CLOUD_NAME'] %>
api_key: <%= ENV['CLOUDINARY_API_KEY'] %>
api_secret: <%= ENV['CLOUDINARY_API_SECRET'] %>
secure: true
cdn_subdomain: true
test:
cloud_name: <%= ENV['CLOUDINARY_CLOUD_NAME'] %>
api_key: <%= ENV['CLOUDINARY_API_KEY'] %>
api_secret: <%= ENV['CLOUDINARY_API_SECRET'] %>
secure: true
cdn_subdomain: true
I just updated the cloudinary gem to 1.13.0 and didn't see a change. If you need anything else let me know.
Cloudinary gem provides a cl_image_tag helper which generates a HTML img tag that links directly to the image on the Cloudinary server
You should prefer to use this helper as opposed to ActiveStorage url helpers as this helper tag generates a direct link to the image and not a link to your server. You get the full benefits of using a CDN by hitting the image directly from Cloudinary. To have https, just specify secure: true in the tag.
E.g: If you have a User record that has_one_attached :file. You can use the cl_image_tag like this:
cl_image_tag(user.file.key, secure: true)

How to change watir chrome pref default_directory to amazon s3?

storage.yml
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
local:
service: Disk
root: <%= Rails.root.join("storage") %>
amazon:
service: S3
access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
region: <%= ENV['AWS_REGION'] %>
bucket: <%= ENV['S3_BUCKET_NAME'] %>
confi/enviroments/development.rb
-----------------------------------------------
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :amazon
Watir Chrome Downaload
-----------------------------------------
prefs = {
download: {
prompt_for_download: false,
default_directory: '/path/to/dir'
}
}
b = Watir::Browser.new :chrome, options: {prefs: prefs}
**My query how to do i set default_directory ro amazon in pref for watir chrom download
**
is this correct --
prefs = {
download: {
prompt_for_download: false,
default_directory: amazon
}
}
Need help :)
enter link description here
If you specify the directory name then it will create the directory in your current directory. Give the full path there. It will work perfectly. I am using this and it's working perfectly for me.

Devise LDAP can't find user, but logs in fine

So when I authorize a user with the devise_ldap_authenticatable gem, I get the following logged information:
LDAP: LDAP dn lookup: sAMAccountName=john.smith
LDAP: LDAP search for login: sAMAccountName=john.smith
LDAP: LDAP search yielded 0 matches
LDAP: Authorizing user lt\john.smith
As I understand it, the search fails to return a user, which I would like to find so I could set other attributes based off of LDAP fields (mainly department).
I've checked that this search should work with the following rake task:
desc "LDAP Test"
task ldap: :environment do
ldap = Net::LDAP.new :host => ENV['LDAP_IP'],
:port => ENV['LDAP_PORT'],
:encryption => :simple_tls,
:base => ENV['LDAP_BASE'],
:auth => {
:method => :simple,
:username => ENV['LDAP_LOGIN'],
:password => ENV['LDAP_PASSWORD']
}
if ldap.bind
ldap.search(:base => ENV['LDAP_BASE'], :filter => Net::LDAP::Filter.eq("sAMAccountName", "john.smith"), :attributes => ["sAMAccountName", "department"], :return_result => false) do |entry|
entry.each do |attr, values|
puts "#{attr}: #{values.first}"
end
end
else
puts "Connection failed! Code: #{ldap.get_operation_result.code}, message: #{ldap.get_operation_result.message}"
end
end
Which returns:
dn: CN=John Smith,OU=Temporary Staff,OU=Users,DC=lt,DC=local
department: Bioinformatics
samaccountname: Johh.Smith
Does anyone know why the login search could be failing? My config files are as follows:
devise.rb:
# ==> LDAP Configuration
config.ldap_logger = true
config.ldap_create_user = true
config.ldap_update_password = false
# config.ldap_config = "#{Rails.root}/config/ldap.yml"
config.ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| "lt\\#{login}"}
# config.ldap_check_group_membership = false
# config.ldap_check_attributes = false
config.ldap_use_admin_to_bind = true
ldap.yml:
development:
host: <%= ENV['LDAP_IP'] %>
port: <%= ENV['LDAP_PORT'] %>
attribute: sAMAccountName
base: <%= ENV['LDAP_BASE'] %>
admin_user: <%= ENV['LDAP_LOGIN'] %>
admin_password: <%= ENV['LDAP_PASSWORD'] %>
ssl: true
# <<: *AUTHORIZATIONS
I would use a packet sniffer like Wireshark to see the difference between the LDAP requests in the rake task vs. devise. The UnboundID LDAP SDK for Java also ships with a tool called LDAPDebugger that you can use as a proxy between your app and Active Directory to decode the traffic.
I hope this helps.

LDAP groups authentication fails: Invalid Binding Information

I'm using devise_ldap_authenticatable to log in into my Rails app via LDAP. Log in works for user (with username), but does not work for groups: when I try to check if user is in a particular group I get:
'Net::LDAP::BindingInformationInvalidError in
Devise::SessionsController#create
Invalid binding information
Extracted source (around line #244):
raise Net::LDAP::BindingInformationInvalidError, "Invalid binding information" unless (user && psw)
I tried several suggested solutions but they all failed with the error mentioned above.
First attempted solution
I tried changing config.ldap_check_group_membership=false to config.ldap_check_group_membership=true in devise.rb:
config.ldap_create_user = true
config.ldap_check_group_membership = true
config.ldap_check_attributes = false
config.ldap_use_admin_to_bind = false
config.ldap_ad_group_check = true (also tried false with this one)
and setting groups in ldap.yml file like this:
authorizations: &AUTHORIZATIONS
group_base: OU=US,DC=um,DC=com #also tried without group_base, with group_base DC=um,DC=com
required_groups:
- CN=D US Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com
- CN=B US Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com
later like that:
authorizations: &AUTHORIZATIONS
#also tried without group_base, with group_base DC=um,DC=com
group_base: OU=US,DC=um,DC=com
required_groups:
["memberOf", "CN=D US Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com;CN=B US Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com"]
Second attempted solution
After this failed, I also tried changing ldap_check_attributes=false to ldap_check_attributes=true in devise.rb:
config.ldap_create_user = true
config.ldap_check_group_membership = false
config.ldap_check_attributes = true
config.ldap_use_admin_to_bind = false
and setting attribute in ldap.yml file like this:
authorizations: &AUTHORIZATIONS
require_attribute:
memberOf: CN=D US Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com
development:
host: <%= ENV["LDAP_HOST"] %>
port: <%= ENV["LDAP_PORT"] %>
attribute: 'userprincipalname'
base: 'DC=um,DC=com'
ssl: <%= ENV["LDAP_SSL"] %>
<<: *AUTHORIZATIONS
I have access to AD, I know, that group is correct. When I look at my account there, I see something like this:
memberOf: CN=D US Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com;CN=B US
Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com
What am I doing wrong?
Today I managed to find one solution that worked. I've changed devise.rb file like this:
config.ldap_create_user = true
config.ldap_check_group_membership = false
config.ldap_check_attributes = true
config.ldap_use_admin_to_bind = false
and ldap.yml like that:
authorizations: &AUTHORIZATIONS
#group_base:
#required_groups:
require_attribute:
memberOf: CN=D US Workers,OU=Workers,OU=abc,OU=US,DC=um,DC=com
development:
host: <%= ENV["LDAP_HOST"] %>
port: <%= ENV["LDAP_PORT"] %>
attribute: sAMAccountName
base: DC=um,DC=com
ssl: <%= ENV["LDAP_SSL"] %>
admin_user: <%= ENV["LDAP_ADMIN_USER"] %> # currently my own: CN=name surname,OU=Workers,OU=abc,OU=US,DC=um,DC=com
admin_password: <%= ENV["LDAP_ADMIN_PASSWORD"] %> currently my own password
<<: *AUTHORIZATIONS
If I find better solution, I'll post it. Feel free to suggest your way too.

s3_direct_upload is not working in production server

In Rails 4.0.2, I am using s3_direct_upload and aws-sdk gems for file uploads for s3 bucket directly. In development environment it is working fine but in production environment it is throwing an error like below,
ActionView::Template::Error (no implicit conversion of nil into String)
In views,
<%= s3_uploader_form :callback_url=>create_cv_url, :id=> "s3_uploader", :key=> "cv_uploads/{unique_id}/${filename}",
:key_starts_with=> "cv_uploads/", :callback_param=> "cv[direct_upload_url]", :max_file_size=> 1.megabytes,
:expiration=> 24.hours.from_now.utc.iso8601 do %>
<%= file_field_tag :file, multiple: true, :max_file_size => 1.megabytes, accept: 'application/pdf application/msword application/rtf application/doc application/docx' %>
<% end %>
<script id="template-upload" type="text/x-tmpl">
<div id="upload_{%=o.unique_id%}" class="upload">
<h5 class="mt1">Please Wait. <span style="color: #5f6fa0;"> {%=o.name%} </span>is processing...</h5>
<div class="progress"><div class="progress-bar progress-bar-striped active" style="width: 0%;"></div></div>
</div>
Here, the issue is mainly pointing to s3_uploader_form line(in views).
This feature is fully referred from http://blog.littleblimp.com/post/53942611764/direct-uploads-to-s3-with-rails-paperclip-and
In paperclip.rb
Paperclip::Attachment.default_options.merge!(
url: :s3_domain_url,
path: ':class/:attachment/:id/:style/:filename',
storage: :s3,
s3_credentials: Rails.configuration.aws,
s3_permissions: :private,
s3_protocol: 'http'
)
require 'paperclip/media_type_spoof_detector'
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
In aws.rb
require 'aws-sdk'
# Rails.configuration.aws is used by AWS, Paperclip, and S3DirectUpload
Rails.configuration.aws = YAML.load(ERB.new(File.read("# {Rails.root}/config/aws.yml")).result)[Rails.env].symbolize_keys!
AWS.config(:logger=> Rails.logger)
AWS.config(Rails.configuration.aws)
In s3_direct_upload.rb
S3DirectUpload.config do |c|
c.access_key_id = Rails.configuration.aws[:access_key_id]
c.secret_access_key = Rails.configuration.aws[:secret_access_key]
c.bucket = Rails.configuration.aws[:bucket]
c.region = "s3"
end
Is it because of configuration issue in production environment? Please help me to solve this issue.
I had the same problem and I solve it adding the file config.yml with my S3 credentials:
RailsApp/config.yml
# Fill in your AWS Access Key ID and Secret Access Key
# http://aws.amazon.com/security-credentials
access_key_id: xxxxxx
secret_access_key: xxxxxxx
More info: https://docs.aws.amazon.com/AWSSdkDocsRuby/latest/DeveloperGuide/ruby-dg-setup.html
The code seems ok. As skozz mentioned, one of the issue may be with your configuration keys that may be not assigned properly. Please check aws production keys in "/config/aws.yml".
I was suffering the same, by following this link. The thing is that I've added the initializers, but I needed to restart rails (it was running but not refreshed).
Executing this command worked for me. figaro heroku:set -e production

Resources