Devise with Simple Token Authentication - ruby-on-rails

i am using the following gem and devise now, since devise remove the support for token authentication.
https://github.com/gonzalo-bulnes/simple_token_authentication
What i am missing here is that, I have all the configuration setup but when i hit http://localhost:3000/user/sign_in.json using the RestConsole Tester on Google.
I am getting the following error:
ActionController::InvalidAuthenticityToken at /users/sign_in.json
ActionController::InvalidAuthenticityToken
actionpack (4.0.2)
lib/action_controller/metal/request_forgery_protection.rb, line 163
def initialize(controller)
#controller = controller
end
def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
end
end
protected
Any ideas?

Your POST is failing a CSRF token check. You can validate this is the case by temporarily removing protect_from_forgery from your application_controller.rb which should make this work.
This article provides a solution for overriding that check on a specific controller, which should be safe for login requests.

You could try this
Authenticate:
curl -H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-X POST http://localhost:3000/users/sign_in \
-d '{"user" : { "email" : "test#example.com", "password" : "password"}}' \
-c cookie
Show:
curl -H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-X GET http://localhost:3000/pages/1.xml \
-b cookie
That works for me.

Related

rspec API data with files upload

I want to create RSpec case for the post-API. in which data (JSON format + pdf files) are passing as form. e.g
curl --location --request POST 'http://localhost:3000/api/v1/books' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer eyJra...' \
--form 'book="{ \"book\": {
\"info\":{
\"reference_id\": \"43999\"
}
}
}"' \
--form 'book_content=#"/home/bookcontent.pdf"' \
--form 'book_booksummery=#"/home/booksummery.pdf"'
similarly, I can also create from postman too. How can I create the same form data in rspec and attached files in params? I tried it but the controller is unable to receive params.
it 'updates inquiry' do
post '/api/v1/books', params: book="{ \"book\": {
\"info\":{
\"reference_id\": \"43999\"
}
}
}".merge(book_content: fixture_file_upload('spec/fixtures/files/book_content.pdf', 'application/pdf'))
.merge(book_booksummery: fixture_file_upload('spec/fixtures/files/book_booksummery.pdf', 'application/pdf'))
, headers: headers_data
Rails.logger.info response
expect(response).to have_http_status(201) # giving 422 status error code
expect(json['reference_id']).to eq '43999'
end

Rails ActionController ignores request headers

I have a simple controller method that logs headers via ActionController's #headers method:
class ThingsController < ActionController::Base
def show
Rails.logger.info headers
render json: {response: 'success'}
end
end
However, when I call this controller method via curl with headers, they are not logged:
curl "http://localhost:3000/things/1” \
-H "access-token XXX" \
-H "token-type Bearer" \
-H "client YYY" \
-H "expiry 1234" \
-H "uid test#test" \
Instead, the following headers are logged:
{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}
I thought my Rails 5 app's CORS policy might be to blame, so I installed the rack-cors gem and configured it in the initializer below. Unfortunately, it did not change the result.
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: %i(get post put patch delete options head)
end
end
I don't think this has anything to do with CORS.
In Rails 5.2, the ActionController instance method #headers is delegated to the response object.
https://github.com/rails/rails/blob/v5.2.0/actionpack/lib/action_controller/metal.rb#L150
delegate :headers, :status=, :location=, :content_type=,
:status, :location, :content_type, to: "#_response"
To access the request headers, you can do so via the request object. http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-headers
Additionally, your cURL syntax needs to change to delimit the key from the value.
curl "http://localhost:3000/things/1” \
-H "access-token: XXX" \
-H "token-type: Bearer" \
-H "client: YYY" \
-H "expiry: 1234" \
-H "uid: test#test" \
Per the Rack spec (and RFC 3875), headers sent by the client are prefixed with HTTP_ and all occurrences of - are replaced with _.
To log the headers you specified via cURL:
class ThingsController < ActionController::Base
def show
Rails.logger.info {
request.headers.env.slice(
"HTTP_ACCESS_TOKEN",
"HTTP_TOKEN_TYPE",
"HTTP_CLIENT",
"HTTP_EXPIRY",
"HTTP_UID"
)
}
render json: {response: 'success'}
end
end

No route matches?

I'm getting a "No route matches" exception in one of my tests (and using curl from the command line) one of my routes (POST /users/confirm). The curl's I've tried are as follows, neither of them work and receive the same exceptions outlined in the below notes:
curl -X POST -H "Content-Type: application/json; version=1" \
-d '{ user: { "token":"1deb36b4e6a7ba6d9203" } }' \
http://localhost:3000/appname/users/confirm
curl -X POST -H "Content-Type: application/json; version=1" \
-d '{ "token":"1deb36b4e6a7ba6d9203" }' \
http://localhost:3000/appname/users/confirm
My test is as follows. I have config.wrap_parameters = true in my /config/application.rb file...
Here is my User UsersController#confirm action along with my strong params. I params.require(:user).permit(:token) as opposed to simply params.permit(:token) because, as stated above, I have config.wrap_parameters = true in my /config/application.rb file...
This is my route entry...
Here is the output from rails routes (app name removed)...
I have config.wrap_parameters = true in my /config/application.rb file...
Oddly enough, if I change my params in my test to post :confirm, params: { token: #user.confirmation_token }, I get the following error instead:
At a loss. Any thoughts?
It turns out I didn't need :token in my route after all. Changed it to this, and all is well:
post '/appname/users/confirm/', to: 'users#confirm', as: 'appname_users_confirm'

How to reading and Output [FILTERED] value from parameters in Ruby

I am using curl to post json to my example service. I am posting json to the service as shown below
curl \
> -i \
> -H "Accept: application/json" \
> -H "Content-type: application/json" \
> -X POST \
> -d '{"email":"micky#minn.com","full_names":"Inisne Dats", "password": "oasswn"}' http://localhost:3000/api/admin_users
Below is my method thats responsible for creating and saving the new Active record Object
def create
user = AdminUser.new(white_list)
if user.save
head 200
else
puts user.errors.full_messages
head 500
end
end
My Whitelist method below
private
def white_list
params.require(:admin_user).permit(:email,:full_names,:password)
end
The problem is that this code never saves because the password is FILTERED, I have inspected the parameters and this is the output;
{"email"=>"micky#minn.com", "full_names"=>"Inisne Dats", "password"=>"[FILTERED]", "admin_user"=>{"email"=>"micky#minn.com", "full_names"=>"Inisne Dats"}}
Can anyone help show me how to retrieve the filtered password and use it once the parameters reach the controller method create. Or I'm I using whitelisting feature wrong?
#j-dexx gave me this answer. I had to wrap the parameters with a root "admin_user" key like so:
{ "admin_user":
{ "email": "micky#minn.com",
"full_names": "Inisne Dats",
"password": "oasswn",
"password_confirmation": "oasswn"
}
}
...so I changed my post request to:
curl \
> -i \
> -H "Accept: application/json" \
> -H "Content-type: application/json" \
> -X POST \
> -d '{"admin_user":{"email":"micky#minn.com","full_names":"Inisne Dats","password":"oasswn","password_confirmation":"oasswn"}}' http://localhost:3000/api/admin_users
That did the trick!

Error occurred while parsing request parameters JSON::ParserError - 795: unexpected token at

I am trying to write the API methods for user to sign up on spree app. It's working properly on my local machine but not on server. here is my code of user_decorator_controller.rb
def sign_up
#user = Spree::User.find_by_email(params[:user][:email])
if #user.present?
render "spree/api/users/user_exists", :status => 401 and return
end
#user = Spree::User.new(user_params)
if !#user.save
unauthorized
return
end
#user.generate_spree_api_key!
end
and sign_up.v1.rabl is
object #user
attributes :id, :spree_api_key, :email, :firstname, :lastname, :mobile
child(:bill_address => :bill_address) do
extends "spree/api/addresses/show"
end
child(:ship_address => :ship_address) do
extends "spree/api/addresses/show"
end
when I CURL the server with below request
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d {"user":{"email":"ml5698#gmail.com","password":"12345678", "firstname":"M", "lastname":"L", "mobile":"9999888877"}} http://localhost:3000/api/users/sign_up
It gives me above error below is extracts from web server log
Started POST "/api/users/sign_up" for 127.0.0.1 at 2015-10-15 11:23:36 +0530
ActiveRecord::SchemaMigration Load (0.3ms) SELECT `schema_migrations`.* FROM `schema_migrations`
Error occurred while parsing request parameters.
Contents:
{user:{email:ml5698#gmail.com,password:12345678,
JSON::ParserError - 795: unexpected token at '{user:{email:ml5698#gmail.com,password:12345678,':
json (1.8.3) lib/json/common.rb:155:in `parse'
activesupport (4.2.4) lib/active_support/json/decoding.rb:26:in `decode'
I am using Ruby 2.2 , rails 4, json 1.8.3 , what could be the issue, please help me resolve it.
Your error is actually in your use of your command line curl. You use the -d switch, and pass parameters to it. The parameters are only parsed until the next space, so your parameters being passed in are
{user:{email:ml5698#gmail.com,password:12345678,
This is what you're seeing in the error message, and is obviously not well formed JSON, so you get the parsing error.
Try quoting your -d parameters like so:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d '{"user":{"email":"ml5698#gmail.com","password":"12345678","firstname":"M","lastname":"L","mobile":"9999888877"}}' http://localhost:3000/api/users/sign_up

Resources