Implement the basic interface for the Authentication endpoint

* Handle errors as 422
* Require parameters through strong_parameters
* Use a custom rescue_from
This commit is contained in:
Maciej Szlosarczyk 2018-07-19 11:50:40 +03:00
parent 1c6b838b2b
commit dad57ba528
No known key found for this signature in database
GPG key ID: 41D62D42D3B0D765
4 changed files with 35 additions and 11 deletions

View file

@ -5,21 +5,30 @@ module Api
module V1
module Registrant
class AuthController < ActionController::API
rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception|
error = {}
error[parameter_missing_exception.param] = ['parameter is required']
response = { errors: [error] }
render json: response, status: :unprocessable_entity
end
def eid
login_params = set_eid_params
user = RegistrantUser.find_or_create_by_api_data(eid_params)
token = create_token(user)
user = RegistrantUser.find_or_create_by_api_data(login_params)
unless user.valid?
render json: user.errors, status: :bad_request
else
token = create_token(user)
if token
render json: token
else
render json: { error: 'Cannot create generate session token'}
end
end
def set_eid_params
params.permit(:ident, :first_name, :last_name)
private
def eid_params
[:ident, :first_name, :last_name].each_with_object(params) do |key, obj|
obj.require(key)
end
end
def create_token(user)

View file

@ -53,10 +53,14 @@ class RegistrantUser < User
end
def find_or_create_by_api_data(api_data = {})
return false unless api_data[:ident]
return false unless api_data[:first_name]
return false unless api_data[:last_name]
estonian_ident = "EE-#{api_data[:ident]}"
user = find_or_create_by(registrant_ident: estonian_ident)
user.username = "#{api_data[:first_name]}, #{api_data[:last_name]}"
user.username = "#{api_data[:first_name]} #{api_data[:last_name]}"
user.save
user

View file

@ -28,6 +28,17 @@ class RegistrantApiAuthenticationTest < ApplicationSystemTestCase
end
def test_request_returns_existing_user
assert_no_changes User.count do
post '/api/v1/registrant/auth/eid', @user_hash
end
end
def test_request_documented_parameters_are_required
params = { foo: :bar, test: :test }
post '/api/v1/registrant/auth/eid', params
json = JSON.parse(response.body, symbolize_names: true)
assert_equal({errors: [{ident: ['parameter is required']}]}, json)
assert_equal(422, response.status)
end
end

View file

@ -11,7 +11,7 @@ require 'minitest/mock'
require 'capybara/rails'
require 'capybara/minitest'
require 'webmock/minitest'
require 'support/rails5_assertions' # Remove once upgraded to Rails 5
require 'support/rails5_assetions' # Remove once upgraded to Rails 5
require 'application_system_test_case'