I need to upload external directory references (json file) to my users data. It's a good opportunity to learn how to create an API and use cURL, but I still meet at least one issue.
I start with a single element, but I plan to pass a json data file at the end of the story. Typical elements to load look like this:
{"name": "Test", "id": "35", "external_id": "X-001"}
I went through the cURL manual and several StackOverflow posts to finally build this API:
Created a dedicated route in routes.rb
match '/API/user_directory', to: "users#set_external_reference", via: :post
Added a method to the users controller
def set_external_reference
puts "Loaded parameters:"
puts params
if target_user = User.find(params[:id])
target_user.update_attributes(external_directory_id: params[:external_id])
render json: {"Response": "OK"}, status: 200
else
render json: {"Response": "not OK"}, status: 500
end
end
Workaround Devise authentication requirement and CanCanCan authorisation in the users controller
class UsersController < ApplicationController
# Check for active session
before_action :authenticate_user! unless ->{:action == 'set_external_reference'}
load_and_authorize_resource except: :set_external_reference
Workaround CSRF in the application controller
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception unless -> { request.format.json? }
I'd be glad to hear from you if this is a good approach, or if it exposes the web site to security threards.
But the issue raises when I try to run the cURL request:
curl --noproxy localhost -d "{"name": "Test", "id": "35", "external_id": "X-001"}" -H "Accept: application/json" -H "Content-type: application/json" http://localhost/API/user_directory > error.html
The following error is raised when trying to parse request parameters:
ActionDispatch::Http::Parameters::ParseError in UsersController#set_external_reference
767: unexpected token at '{name: Test, id: 35, external_id: X-001}'
At this point, I can't find a clue to this issue. Can you provide some help? Thanks a lot!