Module: AuthThree::Generators::OrmHelpers

Included in:
InstallGenerator
Defined in:
lib/generators/orm_helpers.rb

Instance Method Summary collapse

Instance Method Details

#migration_dataObject



57
58
59
60
61
62
63
64
65
66
# File 'lib/generators/orm_helpers.rb', line 57

def migration_data
<<RUBY
t.string :username, null: false

t.string :email, null: false

t.string :password_digest, null: false
t.string :session_token, null: false
RUBY
end

#migration_index_dataObject



68
69
70
71
72
73
74
75
# File 'lib/generators/orm_helpers.rb', line 68

def migration_index_data
<<RUBY

    add_index :users, :username, unique: true
    add_index :users, :email, unique: true
    add_index :users, :session_token, unique: true
RUBY
end

#model_contentsObject



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
# File 'lib/generators/orm_helpers.rb', line 5

def model_contents
<<RUBY
  validates :username, :email, :session_token, presence: true
  validates :username, uniqueness: true
  validates :password_digest, presence: { message: "Password can't be blank."}
  validates :password, length: { minimum: 6, allow_nil: true }

  after_initialize :ensure_session_token

  def self.token
    SecureRandom::urlsafe_base64(16)
  end

  def self.find_by_credentials(username, password)
    user = User.find_by(username: username)
    return nil if user.nil?
    if user.is_password?(password)
return user
    else
return nil
    end
  end

  attr_reader :password

  def password=(password)
    @password = password
    self.password_digest = digest(password)
  end

  def digest(string)
    string_digest = BCrypt::Password.create(string)
  end

  def is_password?(password)
    BCrypt::Password.new(self.password_digest).is_password?(password)
  end

  def reset_session_token!
    self.session_token = User.token
    self.save
    self.session_token
  end

  private

  def ensure_session_token
    self.session_token ||= User.token
  end
RUBY
end