Skip to content
This repository has been archived by the owner on Apr 9, 2019. It is now read-only.

Commit

Permalink
make the settings object support encryption for any value. not sure o…
Browse files Browse the repository at this point in the history
…f the worth of this but meh
  • Loading branch information
timriley committed Jun 23, 2008
1 parent 7b13bb4 commit 39d93b5
Showing 1 changed file with 29 additions and 19 deletions.
48 changes: 29 additions & 19 deletions app/models/settings.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,29 @@ class Settings

# this allows us to read and write settings of any name
def method_missing(method_id, *arguments)
if /=$/ =~ method_id.to_s
write_setting(method_id.to_s.gsub(/=$/,''), arguments.first)
case method_id.to_s
when /^crypted_.*\?$/:
match_crypted_setting(method_id.to_s.gsub(/\?$/, ''), arguments.first)
when /^crypted_.*=$/:
write_crypted_setting(method_id.to_s.gsub(/=$/, ''), arguments.first)
when /\?$/:
match_setting(method_id.to_s.gsub(/\?$/, ''), arguments.first)
when /=$/:
write_setting(method_id.to_s.gsub(/=$/, ''), arguments.first)
else
read_setting(method_id.to_s)
end
end

# the password setting is special, we need to encrypt its contents
def password=(value)
salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--")
write_setting('password_salt', salt)
write_setting('password', self.class.encrypt(value, salt))
end

def password?(password)
self.password == self.class.encrypt(password, self.password_salt)
end

def save
File.open("#{Rails.root}/config/config.yml", 'w') { |f| YAML.dump(@raw_tree, f) }
end

def self.encrypt(string, salt)
Digest::SHA1.hexdigest("--#{salt}--#{string}--")
end

private

def tree
@raw_tree ||= YAML.load_file("#{Rails.root}/config/config.yml")
end

private

def read_setting(key)
tree[Rails.env][key]
Expand All @@ -42,4 +34,22 @@ def read_setting(key)
def write_setting(key, val)
tree[Rails.env][key] = val
end

def write_crypted_setting(key, val)
salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--")
write_setting("#{key}_salt", salt)
write_setting(key, encrypt(val, salt))
end

def match_setting(key, val)
read_setting(key) == val
end

def match_crypted_setting(key, val)
read_setting(key) == encrypt(val, read_setting("#{key}_salt"))
end

def encrypt(string, salt)
Digest::SHA1.hexdigest("--#{salt}--#{string}--")
end
end

0 comments on commit 39d93b5

Please sign in to comment.