Restrict actions for unauthorized users

This commit is contained in:
Lou 2021-04-13 16:24:08 +02:00
commit 7e3f9cdce2
4 changed files with 51 additions and 12 deletions

View file

@ -1,5 +1,6 @@
class Api::V1::UsersController < ApplicationController
before_action :set_user, only: %i[show update destroy]
before_action :check_owner, only: %i[update destroy]
def index
render json: User.all
@ -42,4 +43,8 @@ class Api::V1::UsersController < ApplicationController
def set_user
@user = User.find(params[:id])
end
def check_owner
head :forbidden unless @user.id == current_user&.id
end
end

View file

@ -1,2 +1,3 @@
class ApplicationController < ActionController::API
include Authenticable
end

View file

@ -38,27 +38,34 @@ class Api::V1::UsersControllerTest < ActionDispatch::IntegrationTest
#UPDATE
test "should update user" do
patch api_v1_user_url(@user), params: { user: { email: @user.email, username: @user.username, password: '123456' } }, as: :json
patch api_v1_user_url(@user),
params: { user: { email: @user.email, password: '123456' } },
headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
as: :json
assert_response :success
end
# test "should not update user when invalid params are sent" do
# patch api_v1_user_url(@user), params: { user: { email: 'bad_email', username: @user.username, password: '123456' } }, as: :json
# assert_response :unprocessable_entity
# end
test "should forbid update user" do
patch api_v1_user_url(@user),
params: { user: { email: @user.email, password: '123456' } },
as: :json
assert_response :forbidden
end
#DESTROY
test "should destroy user" do
assert_difference('User.count', -1) do
delete api_v1_user_url(@user), as: :json
delete api_v1_user_url(@user),
headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
as: :json
end
assert_response :no_content
end
# test "should forbid destroy user" do
# assert_no_difference('User.count') do
# delete api_v1_user_url(@user), as: :json
# end
# assert_response :forbidden
# end
test "should forbid destroy user" do
assert_no_difference('User.count') do
delete api_v1_user_url(@user), as: :json
end
assert_response :forbidden
end
end

View file

@ -0,0 +1,26 @@
class MockController
include Authenticable
attr_accessor :request
def initialize
mock_request = Struct.new(:headers)
self.request = mock_request.new({})
end
end
class AuthenticableTest < ActionDispatch::IntegrationTest
setup do
@user = users(:one)
@authentication = MockController.new
end
test 'should get user from Authorization token' do
@authentication.request.headers['Authorization'] = JsonWebToken.encode(user_id: @user.id)
assert_equal @user.id, @authentication.current_user.id
end
test 'should not get user from empty Authorization token' do
@authentication.request.headers['Authorization'] = nil
assert_nil @authentication.current_user
end
end