summaryrefslogtreecommitdiff
path: root/app/models/local_email.rb
blob: 2b4c65ee3630d488c8a18b71a0910590a8bc61b4 (plain)
1
2
3
4
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
56
57
58
59
60
61
62
63
64
65
66
67
68
class LocalEmail < Email

  BLACKLIST_FROM_RFC2142 = [
    'postmaster', 'hostmaster', 'domainadmin', 'webmaster', 'www',
    'abuse', 'noc', 'security', 'usenet', 'news', 'uucp',
    'ftp', 'sales', 'marketing', 'support', 'info'
  ]

  def self.domain
    APP_CONFIG[:domain]
  end

  validates :email,
    :format => {
      :with => /@#{domain}\Z/i,
      :message => "needs to end in @#{domain}"
    }

  validate :handle_allowed

  def initialize(s)
    super
    append_domain_if_needed
  end

  def to_key
    [handle]
  end

  def domain
    LocalEmail.domain
  end

  protected

  def append_domain_if_needed
    unless self.index('@')
      self << '@' + domain
    end
  end

  def handle_allowed
    errors.add(:handle, "is reserved.") if handle_reserved?
  end

  def handle_reserved?
    # *ARRAY in a case statement tests if ARRAY includes the handle.
    case handle
    when *APP_CONFIG[:handle_blacklist]
      true
    when *APP_CONFIG[:handle_whitelist]
      false
    when *BLACKLIST_FROM_RFC2142
      true
    else
      handle_in_passwd?
    end
  end

  def handle_in_passwd?
    begin
      !!Etc.getpwnam(handle)
    rescue ArgumentError
      # handle was not found
      return false
    end
  end
end