Rails DirectUploadsController: override #create method to add custom headers values - ruby-on-rails-5

I wonder if it is possible to override DirectUploadsController#create method that calls a private direct_upload_json method:
class ActiveStorage::DirectUploadsController < ActiveStorage::BaseController
def create
blob = ActiveStorage::Blob.create_before_direct_upload!(blob_args)
render json: direct_upload_json(blob)
end
private
...
def direct_upload_json(blob)
blob.as_json(root: false, methods: :signed_id).merge(direct_upload: {
url: blob.service_url_for_direct_upload,
headers: blob.service_headers_for_direct_upload
})
end
I need it to set a Authorization Bearer <token> as well another key/value to the request header.
Any idea? Thank you.

#config/routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
post '/rails/active_storage/direct_uploads', to: 'image_uploads#create'
end
override your DirectUploadsController
#app/controllerss/image_uploads_controler.rb
class ImageUploadsController < ActiveStorage::DirectUploadsController
def create
super
end
private
def direct_upload_json(blob)
headers = blob.service_headers_for_direct_upload
headers[:custom_header] = "TEST HEADER"
blob.as_json(root: false, methods: :signed_id).merge(direct_upload: {
url: blob.service_url_for_direct_upload,
headers: headers
})
end
end

Related

Chef InSpec check an http request is failing [successfully]

I am writing some infrastructure testing in Chef InSpec & am not sure how to go about testing that a url is not accessible publicly. I have the following code snippet which I am currently using
environments = {
:ops => "ops",
}
control "verify-not-accessible-publicly" do
impact 1.0
title "verify we are not publicly accessible"
environments.each do |_, env|
uri = "http://#{env}.internal.example.com"
begin
result = http(uri, ssl_verify: true, open_timeout: 2, read_timeout: 5, max_redirects: 0)
rescue => e
unless e.class == Faraday::ConnectionFailed
raise e
end
end
end
end
This isn't working quite like I expect. I don't think the http(uri,...) block is actually executed until it is passed into a describe function.
Thanks
you should use http resource with a describe block and matchers
describe http('url', auth: {user: 'user', pass: 'test'}, params: {params}, method: 'method', headers: {headers}, data: data, open_timeout: 60, read_timeout: 60, ssl_verify: true, max_redirects: 3) do
its('status') { should eq number }
its('body') { should eq 'body' }
its('headers.name') { should eq 'header' }
end

Invalid signature Open Bank Project Oauth1.0a

I'm developing a React-Native App with Open Bank Project and I can't use suggested SDKs, not even the nodeJS one as Oauth1.0 is not available in RN.
And I'm stuck with a Bad Signature error on Access Token request '/oauth/token' after passed '/oauth/initiate' and '/oauth/authorize' without any problem.
As specified in docs here before accessing to a Protected Resource we need an Access Token via a POST Request, which gives me the Bad Signature answer.
Here is my code for the request:
getAccessToken(verifier){
let request = {
url: 'https://api.openbankproject.com/oauth/token',
method: 'POST',
data: {
oauth_verifier: verifier,
oauth_token: this.auth.oauth_token,
oauth_token_secret: this.auth.oauth_token_secret
}
}
return fetch(this.url_login, {
method: request.method, //POST
form: request.data,
headers: this.oauth.toHeader(this.oauth.authorize(request))
})
.then((res) => {return res.text()})
.then((txt) => {
console.log('setUID', txt, this.url_login, {
method: request.method,
form: request.data,
headers: this.oauth.toHeader(this.oauth.authorize(request))
})
})
Here is the signed request:
Object {method: "POST", form: Object, headers: Object}
form:
oauth_token:"..."
oauth_token_secret:"..."
oauth_verifier:"71531"
headers:
Authorization:
"OAuth oauth_consumer_key="...", oauth_nonce="3UlQ5dx958tibf6lSg0RUGPQFZeV7b8V", oauth_signature="weyE1lFkoIjAErYLKdSi9SDlCZsNBi7%2BuAkLV2PWePo%3D", oauth_signature_method="HMAC-SHA256", oauth_timestamp="1464248944", oauth_token="...", oauth_token_secret="...", oauth_verifier="71531", oauth_version="1.0""
I've tried with and without Oauth_token_secret, also moving oauth_verifier from body to query but with the same Bad Signature result.
Any idea? thx
You can use oauth module https://github.com/ciaranj/node-oauth
var oauth=require('oauth');
var consumer = new oauth.OAuth(
"https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token",
_twitterConsumerKey, _twitterConsumerSecret, "1.0A", "http://127.0.0.1:8080/sessions/callback", "HMAC-SHA1");
then generating signature like this :
var parameters = consumer._prepareParameters("user_access_token", "user_access_token_secret", "http_method", "request_url");
var headers = consumer._buildAuthorizationHeaders(parameters);
parameters array contains signature, also you can build authorization headers if needed. Hope it helps :)

Rspec to mock my call to external api from my function and return custom response back to the function

So i have written a module which has a function. And now i am trying to test the function.
My question here is that how do i use mocking or stub etc. to test that for a random userid we grab the request to github from the function and return a custom json back to the function.?
Module being tested:
require 'json'
require 'httparty'
module util
GITHUB_URL = 'http://github.com/'
def get_name(id)
begin
response = HTTParty.get("#{GITHUB_URL}#{id}.json")
data = JSON.parse(response.body)
return data.first['actor_attributes']['name']
rescue Exception => e
return nil
end
end
end
My Rspec file:
# coding: UTF-8
require 'spec_helper'
class DummyClass
end
describe 'GET_NAME' do
before(:each) do
#dummy_class = DummyClass.new
#dummy_class.extend(util)
end
context 'for invalid Github ID' do
it 'return nil' do
expect(#dummy_class.getName('invalid')).to be_nil
end
end
end
Thank you all for your help.
Checkout https://github.com/bblimke/webmock or http://fakeweb.rubyforge.org/
Then you do something like:
stub_request(
:post, "#{GITHUB_URL}1.json"
).to_return(
body: { actor_attributes: {name: "Bill"} }.to_json
)
I'm a bigger fan of Webmock than Fakeweb (it's got a few more features), but they'll both do for you, and it's pretty easy to switch between them.

rails 3.1 mountable engines HTTP 404 Error on ajax post call

I am building my first Rails 3.1 engines plugin in which i have controller called initiatives_controller and have a action know as upload whenever i try to make a call to upload action via jquery ajax "post" call its returning me 404 error I feel there is some issue in routes.rb because it used work in Rails 3.0
My routes.rb looks like
Marcal::Engine.routes.draw do
resources :media
resources :initiatives
post "initiatives/upload"
end
My initiatives_controller.rb
class InitiativesController < ApplicationController
def upload
puts "hiiiii"
#medium = Medium.new(params[:medium])
if #medium.save
render :json => { 'status' => 'success' }
else
render :json => { 'status' => 'error' }
end
end
end
end
And i used do ajax call as below
$.ajax({
url: "/initiatives/upload",
type: "POST",
data: "medium=something"
dataType: "json",
success: function(sucessdata)
{
alert("success");
}
});
end
Your dummy app is probably mounted on "/marcal" which is the default when you create a mountable engine. You're ajax probably doesn't simple because it sends the POST on "/initiatives/upload" instead of the desired "/marcal/initiatives/upload".
You might want to rename your javascript file from "name.js" to "name.js.erb" and change it's content to:
$.ajax({
url: "<%= root_path %>initiatives/upload",
type: "POST",
data: "medium=something"
dataType: "json",
success: function(sucessdata)
{
alert("success");
}
});
root_path is the key here.

Rails + Devise: redirect to a specific url upon public page Facebook Login

I have a public assessable page
"http://www.example.com/gift/5"
There is a Facebook connect button on it.
I want the user to click the Facebook connect button and then be redirected to
"http://www.example.com/gift/5/coupon"
Currently Devise/Omniauth seems to lose the session as it's authenticating the user.
I've tried sending an ajax request before I do a FB.api
FB.login(function(response) {
if (response.session) {
$.ajax({
url : '/ajax/facebook/url',
type : 'post',
data : {push_to: "/gift/5/coupon"},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});
window.location = "https://graph.facebook.com/oauth/authorize?client_id=..........";
} else {
}
});
Ajax request hits
class AjaxController < ApplicationController
def ajax_facebook_url_redirect
session[:"fb_redirect_to"] = params[:push_to]
end
But I can't find the variable in either
application_controller.rb
def after_sign_in_path_for(resource)
print session[:"fb_redirect_to"]
(session[:"user.return_to"].nil?) ? "/" : session[:"user.return_to"].to_s
end
Any advice on sending the user to a specific url from a public page?
There is a new section recently added to the OmniAuth Overview docs on the Devise website that addresses this issue: https://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview
Here is the gist:
def authenticate_user!
if !current_user
# This should work, but session is lost. See https://github.com/plataformatec/devise/issues/1357
# session[:return_to] = request.fullpath
redirect_to user_omniauth_authorize_path(:google_apps, :origin => request.fullpath)
end
end
def after_sign_in_path_for(resource)
# This should work, but session is lost. See https://github.com/plataformatec/devise/issues/1357
# return_to = session[:return_to]
# session[:return_to] = nil
return_to = request.env['omniauth.origin']
stored_location_for(resource) || return_to || root_path
end