Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ApplicationRecord
- # Attributes to control password reset
- attr_accessor :remember_token, :activation_token, :reset_token
- has_secure_password
- has_many :messages
- has_one :profile, inverse_of: :user, autosave: true
- has_one :chatrooms, through: :messages
- accepts_nested_attributes_for :profile, allow_destroy: true
- # validates :email, format: { with: /\A[^@\s]+@([^@.\s]+\.)+[^@.\s]+\z/ }, uniqueness: { case_sensitive: false }
- after_create :initialize_user
- def User.new_token
- SecureRandom.urlsafe_base64
- end
- def User.digest(string)
- cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
- BCrypt::Engine.cost
- BCrypt::Password.create(string, cost: cost)
- end
- def generate_json_api_error
- json_error = {"errors": []}
- errors.messages.each do |err_type, messages|
- messages.each do |msg|
- json_error[:errors] << {"detail": "#{err_type} #{msg}", "source": {"pointer": "user/err_type"}}
- end
- end
- json_error
- end
- def initialize_user
- welcome_message
- create_profile
- end
- def welcome_message
- pp self.attributes.deep_symbolize_keys
- welcome = ChatbotManager.talk(intent: 'Greeting', session: {
- user: self.attributes.deep_symbolize_keys,
- current_language: :english
- })
- Message.create(welcome.merge(user_id: self.id))
- next_message = ChatbotManager.talk(intent: 'Options', session: {
- user: self.attributes.deep_symbolize_keys,
- current_language: :english
- })
- Message.create(next_message.merge(user_id: self.id))
- end
- # Creates temporal token for allowing password reset
- def create_reset_digest
- self.reset_token = User.new_token
- update_attribute(:reset_digest, User.digest(reset_token))
- update_attribute(:reset_sent_at, Time.zone.now)
- end
- # TODO: maybe this logic should be moved to a service!
- def send_password_reset_mail
- UserMailer.password_reset(self).deliver_now
- end
- # Checks whether reset password token did expire or not
- def password_reset_expired?
- reset_sent_at < 1.hours.ago
- end
- # If user was created with no profile, add a default profile
- def create_profile
- return if !self.profile.nil?
- new_profile = Profile.create({ language: "EN" })
- self.profile = new_profile
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement