fanadewi

authentication API

Sep 27th, 2018
670
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # This is how I improve this rails action
  2. # authentication API
  3. def auth
  4.   # find is a method to search by id use find_by if we use other field as parameter
  5.   # declare user as a class method
  6.   @user = User.find_by(username: params[:username])
  7.  
  8.   # Before we check the password,
  9.   # We need to check if the user with that username is present
  10.   if @user.present? && @user.check_password(params[:password])
  11.     # json response should always including status
  12.     # give status ok (200) for successful auth
  13.     render json: @user, status: :ok
  14.   else
  15.     # The errors message is not needed to be in an array
  16.     # Use single-quoted if we don't use string interpolation.
  17.     render json: { errors: 'wrong username or password' }, status: :unauthorized
  18.   end
  19. end
RAW Paste Data