Advertisement
zainalmustofa

Untitled

Dec 11th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.21 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. def auth
  5.   user = User.find(params[:username])
  6.   if user.check_password(params[:password])
  7.     render json: user
  8.   else
  9.     render json: { errors: ["wrong username or password"] }, status: :unauthorized
  10.   end
  11. end
  12.  
  13. ######################################
  14. #
  15. # my Code
  16. #
  17.  
  18. before_action :find_user, only: :auth
  19.  
  20.  
  21. def auth
  22.   user_valid = @user.check_password(params[:password])
  23.  
  24.   if user_valid
  25.     render json: @user
  26.   else
  27.     render json: { errors: @user.errors }, status: 401
  28.   end
  29. end
  30.  
  31. private
  32.  
  33. def find_user
  34.   @user = User.find(params[:username])
  35.  
  36.   render json: { errors: ["User not found, please check your username"] }, status: 401 unless @user  
  37. end
  38.  
  39.  
  40.  
  41. ######################################
  42. #
  43. # this is user.rb model
  44. #
  45.  
  46. def check_password password_from_params
  47.   #
  48.   # if we use devise we can do this
  49.   #
  50.  
  51.   # if valid_password?(password_from_params)
  52.   #   true
  53.   # else
  54.   #   self.errors.add(:password, "wrong password")
  55.   # end
  56.  
  57.   if password.eql? password_from_params
  58.     true
  59.   else
  60.     self.errors.add(:password, "wrong password")
  61.   end
  62. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement