Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. class User < ApplicationRecord
  2. # Attributes to control password reset
  3. attr_accessor :remember_token, :activation_token, :reset_token
  4.  
  5. has_secure_password
  6. has_many :messages
  7. has_one :profile, inverse_of: :user, autosave: true
  8. has_one :chatrooms, through: :messages
  9. accepts_nested_attributes_for :profile, allow_destroy: true
  10. # validates :email, format: { with: /\A[^@\s]+@([^@.\s]+\.)+[^@.\s]+\z/ }, uniqueness: { case_sensitive: false }
  11.  
  12. after_create :initialize_user
  13.  
  14. def User.new_token
  15. SecureRandom.urlsafe_base64
  16. end
  17.  
  18. def User.digest(string)
  19. cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
  20. BCrypt::Engine.cost
  21. BCrypt::Password.create(string, cost: cost)
  22. end
  23.  
  24. def generate_json_api_error
  25. json_error = {"errors": []}
  26. errors.messages.each do |err_type, messages|
  27. messages.each do |msg|
  28. json_error[:errors] << {"detail": "#{err_type} #{msg}", "source": {"pointer": "user/err_type"}}
  29. end
  30. end
  31. json_error
  32. end
  33.  
  34. def initialize_user
  35. welcome_message
  36. create_profile
  37. end
  38.  
  39. def welcome_message
  40. pp self.attributes.deep_symbolize_keys
  41. welcome = ChatbotManager.talk(intent: 'Greeting', session: {
  42. user: self.attributes.deep_symbolize_keys,
  43. current_language: :english
  44. })
  45. Message.create(welcome.merge(user_id: self.id))
  46.  
  47. next_message = ChatbotManager.talk(intent: 'Options', session: {
  48. user: self.attributes.deep_symbolize_keys,
  49. current_language: :english
  50. })
  51. Message.create(next_message.merge(user_id: self.id))
  52. end
  53.  
  54. # Creates temporal token for allowing password reset
  55. def create_reset_digest
  56. self.reset_token = User.new_token
  57. update_attribute(:reset_digest, User.digest(reset_token))
  58. update_attribute(:reset_sent_at, Time.zone.now)
  59. end
  60.  
  61. # TODO: maybe this logic should be moved to a service!
  62. def send_password_reset_mail
  63. UserMailer.password_reset(self).deliver_now
  64. end
  65.  
  66. # Checks whether reset password token did expire or not
  67. def password_reset_expired?
  68. reset_sent_at < 1.hours.ago
  69. end
  70.  
  71. # If user was created with no profile, add a default profile
  72. def create_profile
  73. return if !self.profile.nil?
  74. new_profile = Profile.create({ language: "EN" })
  75. self.profile = new_profile
  76. end
  77. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement