Advertisement
Guest User

Untitled

a guest
Apr 6th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. class Session
  2. include ActiveModel::Validations
  3.  
  4. attr_reader :email, :password, :user
  5.  
  6. def initialize params
  7. params = params.try(:symbolize_keys) || {}
  8.  
  9. @user = params[:user]
  10.  
  11. @email = params[:email]
  12.  
  13. @password = params[:password]
  14. end
  15.  
  16. validate do |model|
  17. if user
  18. model.errors.add :password, 'is invalid' unless user.authenticate password
  19. else
  20. model.errors.add :email, 'not found'
  21. end
  22. end
  23.  
  24. def save!
  25. raise ActiveModel::StrictValidationFailed unless valid?
  26.  
  27. user.create_auth_token value: SecureRandom.uuid
  28. end
  29.  
  30. def destroy!
  31. user.auth_token.destroy!
  32. end
  33.  
  34. def auth_token
  35. user.try(:auth_token).try(:value)
  36. end
  37.  
  38. def as_json *args
  39. { auth_token: auth_token }
  40. end
  41.  
  42. def decorate
  43. self
  44. end
  45.  
  46. private
  47. def user
  48. @user ||= User.find_by email: email
  49. end
  50. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement