File size: 1,558 Bytes
f5071ca |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# == Schema Information
#
# Table name: users
#
# id :bigint not null, primary key
# username :string not null
# password_digest :string not null
# session_token :string not null
# created_at :datetime not null
# updated_at :datetime not null
# fname :string
# bio :text
#
class User < ApplicationRecord
attr_reader :password
validates :username, :password_digest, :session_token, presence: true
validates :username, uniqueness: true
validates :password, length: { minimum: 6 }, allow_nil: true
after_initialize :ensure_session_token
has_one_attached :photo
has_many :spots,
foreign_key: :host_id,
class_name: :Spot
has_many :bookings,
foreign_key: :guest_id,
class_name: :Booking
has_many :booked_spots,
through: :bookings,
source: :spot
def self.find_by_credentials(username, password)
user = User.find_by(username: username)
return nil unless user
user.is_password?(password) ? user : nil
end
def password=(password)
@password = password
self.password_digest = BCrypt::Password.create(password)
end
def is_password?(password)
BCrypt::Password.new(self.password_digest).is_password?(password)
end
def reset_session_token!
self.session_token = SecureRandom.urlsafe_base64
save!
self.session_token
end
private
def ensure_session_token
self.session_token ||= SecureRandom.urlsafe_base64
end
end
|