|
1 | 1 | class User < ApplicationRecord |
2 | | - attr_accessor :remember_token |
3 | | - before_save { self.email = email.downcase } |
| 2 | + attr_accessor :remember_token, :activation_token |
| 3 | + before_save :downcase_email |
| 4 | + before_create :create_activation_digest |
4 | 5 | validates :name, presence: true, length: { maximum: 50 } |
5 | 6 | VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i |
6 | 7 | validates :email, presence: true, length: { maximum: 255 }, |
@@ -32,13 +33,39 @@ def session_token |
32 | 33 | end |
33 | 34 |
|
34 | 35 | # Returns true if the given token matches the digest. |
35 | | - def authenticated?(remember_token) |
36 | | - return false if remember_digest.nil? |
37 | | - BCrypt::Password.new(remember_digest).is_password?(remember_token) |
| 36 | + def authenticated?(attribute, token) |
| 37 | + digest = send("#{attribute}_digest") |
| 38 | + return false if digest.nil? |
| 39 | + BCrypt::Password.new(digest).is_password?(token) |
38 | 40 | end |
39 | 41 |
|
40 | 42 | # Forgets a user. |
41 | 43 | def forget |
42 | 44 | update_attribute(:remember_digest, nil) |
43 | 45 | end |
| 46 | + |
| 47 | + # Activates an account. |
| 48 | + def activate |
| 49 | + update_attribute(:activated, |
| 50 | + true) |
| 51 | + update_attribute(:activated_at, Time.zone.now) |
| 52 | + end |
| 53 | + |
| 54 | + # Sends activation email. |
| 55 | + def send_activation_email |
| 56 | + UserMailer.account_activation(self).deliver_now |
| 57 | + end |
| 58 | + |
| 59 | + private |
| 60 | + |
| 61 | + # Converts email to all lowercase. |
| 62 | + def downcase_email |
| 63 | + self.email = email.downcase |
| 64 | + end |
| 65 | + |
| 66 | + # Creates and assigns the activation token and digest. |
| 67 | + def create_activation_digest |
| 68 | + self.activation_token = User.new_token |
| 69 | + self.activation_digest = User.digest(activation_token) |
| 70 | + end |
44 | 71 | end |
0 commit comments