Class: Eksa::User

Inherits:
Model
  • Object
show all
Defined in:
lib/eksa/user.rb

Class Method Summary collapse

Methods inherited from Model

db, ensure_schema

Class Method Details

.allObject



16
17
18
# File 'lib/eksa/user.rb', line 16

def self.all
  db.execute("SELECT id, username FROM eksa_users")
end

.authenticate(username, password) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/eksa/user.rb', line 30

def self.authenticate(username, password)
  user_data = db.execute("SELECT id, username, password_hash FROM eksa_users WHERE username = ? LIMIT 1", [username]).first
  return nil unless user_data

  stored_hash = BCrypt::Password.new(user_data[2])
  if stored_hash == password
    { id: user_data[0], username: user_data[1] }
  else
    nil
  end
end

.create(username, password) ⇒ Object



20
21
22
23
# File 'lib/eksa/user.rb', line 20

def self.create(username, password)
  hash = BCrypt::Password.create(password)
  db.execute("INSERT INTO eksa_users (username, password_hash) VALUES (?, ?)", [username, hash])
end

.find(id) ⇒ Object



42
43
44
45
# File 'lib/eksa/user.rb', line 42

def self.find(id)
  user_data = db.execute("SELECT id, username FROM eksa_users WHERE id = ? LIMIT 1", [id]).first
  user_data ? { id: user_data[0], username: user_data[1] } : nil
end

.setup_schemaObject



5
6
7
8
9
10
11
12
13
14
# File 'lib/eksa/user.rb', line 5

def self.setup_schema
  db.execute <<~SQL
    CREATE TABLE IF NOT EXISTS eksa_users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      username TEXT UNIQUE,
      password_hash TEXT,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  SQL
end

.update_password(username, new_password) ⇒ Object



25
26
27
28
# File 'lib/eksa/user.rb', line 25

def self.update_password(username, new_password)
  hash = BCrypt::Password.create(new_password)
  db.execute("UPDATE eksa_users SET password_hash = ? WHERE username = ?", [hash, username])
end