ashchan / gmail-notifr

A RubyCocoa Gmail Notifier for Mac OS X

This URL has Read+Write access

gmail-notifr / GNKeychain.rb
100644 82 lines (73 sloc) 1.693 kb
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#
# GNKeychain.rb
# Gmail Notifr
#
# Created by james on 10/4/08.
# Copyright (c) 2008 ashchan.com. All rights reserved.
#
 
require 'osx/cocoa'
OSX.require_framework 'Security'
 
class GNKeychain < OSX::NSObject
  include OSX
  SERVICE = "GmailNotifr"
  
    
  def self.sharedInstance
    @instance ||= self.alloc.init
  end
  
  def set_account(username, password)
    return if username.nil? || password.nil?
    pass = "#{password}"
    error = SecKeychainAddGenericPassword(
      nil,
      SERVICE.length,
      SERVICE,
      username.length,
      username,
      pass.length,
      pass,
      nil)
      
    #already set
    if error == OSX::ErrSecDuplicateItem
      status, *data = SecKeychainFindGenericPassword(
        nil,
        SERVICE.length,
        SERVICE,
        username.length,
        username)
      data.shift
      data.shift
      item = data.shift #SecKeychainItemRef
      SecKeychainItemModifyContent(item, nil, pass.length, pass)
    end
  end
  
  def delete_account(username)
    return if username.nil?
    status, *data = SecKeychainFindGenericPassword(
      nil,
      SERVICE.length,
      SERVICE,
      username.length,
      username)
    if status == 0
      data.shift
      data.shift
      item = data.shift
      SecKeychainItemDelete(item)
    end
  end
  
  def get_password(username)
    return "" if username.nil?
    status, *data = SecKeychainFindGenericPassword(
      nil,
      SERVICE.length,
      SERVICE,
      username.length,
      username)
    if status == 0
      password_length = data.shift
      password_data = data.shift
      password = password_data.bytestr(password_length)
    else
      ""
    end
  end
end