Advertisement
luckymeerzaa

Untitled

Feb 15th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.27 KB | None | 0 0
  1. # please improve this rails action,
  2. # if you'd like to put some code in another file please state so:
  3. # authentication API
  4. before_action :set_user, only [:show, :edit, :update, :destroy]
  5. def auth
  6.   success = ->(user) { render json: user }
  7.   error = -> { render json: { errors: ["wrong username or password"] }, status: :unauthorized }
  8.  
  9.   UseCase::User::CheckPassword.new.call(user, params, success: success, failure: error)
  10. end
  11. private
  12. def set_user
  13.   @user = repo.find(params[:username])
  14. end
  15.  
  16. def repo
  17.   @repo ||= UserRepository.new(params)
  18. end
  19.  
  20. #app/repositories/user_repository.rb
  21. class UserRepository
  22.   def new_entity(attrs = nil)
  23.     User.new(attrs)
  24.   end
  25.   def find(attr)
  26.     (attr.is_a?(String)) ? User.find_by_username(attr) : User.find(attr)
  27.   end
  28.   def check_password(attr)
  29.   end
  30. end
  31.  
  32. # app/use_cases/use_case/base.rb
  33. module UseCase
  34.   class Base
  35.     attr_reader :repository
  36.  
  37.     def initialize(repo=nil)
  38.       @repository = repo
  39.     end
  40.   end
  41. end
  42.  
  43. # app/use_cases/use_case/user/check_password.rb
  44. module UseCase
  45.   module User
  46.     class CheckPassword < UseCase::Base
  47.       def call(user, attrs, callbacks)
  48.         user.check_password(attrs[:password]) ? callbacks[:success].call(user) : callbacks[:failure].call()
  49.       end
  50.     end
  51.   end
  52. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement