Class: Murlsh::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/murlsh/auth.rb

Overview

Interface to authentication file. Format of authentication file:

username,MD5 hash of email address,bcrypted password

Authentication is done using password only to make adding easier and because there will be a small number of trusted users.

See Rakefile for user maintenance tasks.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Auth

Returns a new instance of Auth.



18
# File 'lib/murlsh/auth.rb', line 18

def initialize(file); @file = file; end

Class Method Details

.csv_iter(csv_file, &block) ⇒ Object

Handle differences in csv interface between ruby 1.8 and 1.9.



21
22
23
24
25
26
27
28
29
# File 'lib/murlsh/auth.rb', line 21

def self.csv_iter(csv_file, &block)
  if defined?(CSV::Reader)
    # ruby 1.8
    CSV::Reader.parse(open(csv_file), &block)
  else
    # ruby 1.9
    CSV.foreach(csv_file, &block)
  end
end

Instance Method Details

#add_user(username, email, password) ⇒ Object

Add a user to the authentication file.



40
41
42
43
44
45
# File 'lib/murlsh/auth.rb', line 40

def add_user(username, email, password)
  Murlsh::openlock(@file, 'a') do |f|
    f.write "#{[username, Digest::MD5.hexdigest(email),
      BCrypt::Password.create(password)].join(',')}\n"
  end
end

#auth(password) ⇒ Object

Authenticate a user by password. Return their name and email if correct.



32
33
34
35
36
37
# File 'lib/murlsh/auth.rb', line 32

def auth(password)
  self.class.csv_iter(@file) do |row|
    return { :name => row[0], :email => row[1] }  if
      BCrypt::Password.new(row[2]) == password
  end
end

#by_email(email) ⇒ Object

Look up a user by email address.

Return nil if not found.



50
51
52
53
54
55
56
57
# File 'lib/murlsh/auth.rb', line 50

def by_email(email)
  hash = Digest::MD5.hexdigest(email)

  self.class.csv_iter(@file) do |row|
    return { :name => row[0], :email => row[1] }  if hash == row[1]
  end

end