1 /* ***** BEGIN LICENSE BLOCK *****
  2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3  *
  4  * The contents of this file are subject to the Mozilla Public License Version
  5  * 1.1 (the "License"); you may not use this file except in compliance with
  6  * the License. You may obtain a copy of the License at
  7  * http://www.mozilla.org/MPL/
  8  *
  9  * Software distributed under the License is distributed on an "AS IS" basis,
 10  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 11  * for the specific language governing rights and limitations under the
 12  * License.
 13  *
 14  * The Original Code is gContactSync.
 15  *
 16  * The Initial Developer of the Original Code is
 17  * Josh Geenen <gcontactsync@pirules.org>.
 18  * Portions created by the Initial Developer are Copyright (C) 2008-2009
 19  * the Initial Developer. All Rights Reserved.
 20  *
 21  * Contributor(s):
 22  *
 23  * Alternatively, the contents of this file may be used under the terms of
 24  * either the GNU General Public License Version 2 or later (the "GPL"), or
 25  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 26  * in which case the provisions of the GPL or the LGPL are applicable instead
 27  * of those above. If you wish to allow use of your version of this file only
 28  * under the terms of either the GPL or the LGPL, and not to allow others to
 29  * use your version of this file under the terms of the MPL, indicate your
 30  * decision by deleting the provisions above and replace them with the notice
 31  * and other provisions required by the GPL or the LGPL. If you do not delete
 32  * the provisions above, a recipient may use your version of this file under
 33  * the terms of any one of the MPL, the GPL or the LGPL.
 34  *
 35  * ***** END LICENSE BLOCK ***** */
 36 
 37 if (!com) var com = {}; // A generic wrapper variable
 38 // A wrapper for all GCS functions and variables
 39 if (!com.gContactSync) com.gContactSync = {};
 40 
 41 /**
 42  * Stores and retrieves the authentication token from the login manager.
 43  * Does NOT store the password and username.
 44  * @class
 45  */
 46 com.gContactSync.LoginManager = {
 47   /** The hostname used in the login manager */
 48   mHostname:      "chrome://gContactSync",
 49   /** The URL in the login manager */
 50   mSubmitURL:     "User Auth Token",
 51   /** The HTTP realm */
 52   mHttpRealm:     null,
 53   /** The username field */
 54   mUsernameField: "",
 55   /** The password field */
 56   mPasswordField: "",
 57   /** An object with authentication tokens keyed by username */
 58   mAuthTokens:    {},
 59   /** The number of authentication tokens found */
 60   mNumAuthTokens: 0,
 61   /**
 62    * Stores the token in the Login Manager.
 63    * @param aUsername {string} The username (e-mail address).
 64    * @param aToken    {string} The authentication token from Google.
 65    */
 66   addAuthToken: function LoginManager_addAuthToken(aUsername, aToken) {
 67     if (this.mNumAuthTokens === 0) {
 68       this.getAuthTokens();
 69     }
 70     // Thunderbird 2
 71     if ("@mozilla.org/passwordmanager;1" in Components.classes) {
 72       var passwordManager =  Components.classes["@mozilla.org/passwordmanager;1"]
 73                                        .getService(Components.interfaces.nsIPasswordManager);
 74       passwordManager.addUser(this.mHostname, aUsername, aToken);
 75       this.mAuthTokens[aUsername] = aToken;
 76       this.mNumAuthTokens++;
 77     }
 78     // Thunderbird 3, Seamonkey 2
 79     else if ("@mozilla.org/login-manager;1" in Components.classes) {
 80       var loginManager =  Components.classes["@mozilla.org/login-manager;1"]
 81                                     .getService(Components.interfaces.nsILoginManager),
 82           nsLoginInfo  = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
 83                                                     Components.interfaces.nsILoginInfo,
 84                                                     "init"),
 85           extLoginInfo = new nsLoginInfo(this.mHostname, this.mSubmitURL,
 86                                          this.mHttpRealm, aUsername, aToken,
 87                                          this.mUsernameField, this.mPasswordField);
 88       loginManager.addLogin(extLoginInfo);
 89       this.mAuthTokens[aUsername] = aToken;
 90       this.mNumAuthTokens++;
 91     }
 92   },
 93   /**
 94    * Gets the tokens in the Login Manager.
 95    * @returns {object} The auth tokens, if any, null otherwise.
 96    */
 97   getAuthTokens: function LoginManager_getAuthTokens() {
 98     this.mAuthTokens = {};
 99     this.mNumAuthTokens = 0;
100     // Thunderbird 2
101     if ("@mozilla.org/passwordmanager;1" in Components.classes) {
102       var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"]
103                                       .getService(Components.interfaces.nsIPasswordManager),
104           iter = passwordManager.enumerator;
105       while (iter.hasMoreElements()) {
106         try {
107           var pass = iter.getNext().QueryInterface(Components.interfaces.nsIPassword);
108           if (pass.host === this.mHostname) {
109             this.mAuthTokens[pass.user] = pass.password;
110             this.mNumAuthTokens++;
111           }
112         } catch (e) {}
113       }
114     }
115     // Thunderbird 3, Seamonkey 2
116     else if ("@mozilla.org/login-manager;1" in Components.classes) {
117       var loginManager =  Components.classes["@mozilla.org/login-manager;1"]
118                                     .getService(Components.interfaces.nsILoginManager);
119       // Find users for the given parameters
120       var logins = loginManager.findLogins({}, this.mHostname, this.mSubmitURL,
121                                            this.mHttpRealm);
122       // Find user from returned array of nsILoginInfo objects
123       for (var i = 0; i < logins.length; i++) {
124         this.mAuthTokens[logins[i].username] = logins[i].password;
125         this.mNumAuthTokens++;
126       }
127     }
128     return this.mAuthTokens;
129   },
130   /**
131    * Gets the token in the Login Manager.
132    * @returns {string} The auth token, if present, null otherwise.
133    */
134   getAuthToken: function LoginManager_getAuthToken(aUsername) {
135     if  (this.mNumAuthTokens === 0) {
136       this.getAuthTokens();
137     }
138     return this.mAuthTokens ? this.mAuthTokens[aUsername] : null;
139   },
140   /**
141    * Removes the auth token from the Login Manager.
142    * @returns {boolean} True if the auth token was successfully removed.
143    */
144   removeAuthToken: function LoginManager_removeAuthToken(aUsername) {
145     // Thunderbird 2
146     if ("@mozilla.org/passwordmanager;1" in Components.classes) {
147       var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"]
148                                       .getService(Components.interfaces.nsIPasswordManager);
149       try {
150         passwordManager.removeUser(this.mHostname, aUsername);
151         this.mAuthTokens[aUsername] = null;
152         this.mNumAuthTokens--;
153       }
154       catch (e) {
155         com.gContactSync.alertError(com.gContactSync.StringBundle.getStr("removeLoginFailure") + "\n\n" + e);
156       }
157     }
158     // Thunderbird 3, Seamonkey 2
159     else if ("@mozilla.org/login-manager;1" in Components.classes) {
160       var loginManager = Components.classes["@mozilla.org/login-manager;1"]
161                                    .getService(Components.interfaces.nsILoginManager);
162       // Find logins for the given parameters
163       var logins = loginManager.findLogins({}, this.mHostname, this.mSubmitURL,
164                                             this.mHttpRealm);
165       aUsername = aUsername.toLowerCase();
166       // Find user from returned array of nsILoginInfo objects
167       for (var i = 0; i < logins.length; i++) {
168         if (logins[i].username.toLowerCase() == aUsername) {
169           try {
170             com.gContactSync.LOGGER.VERBOSE_LOG("Found the login to remove");
171             loginManager.removeLogin(logins[i]);
172             this.mAuthTokens[aUsername] = null;
173             this.mNumAuthTokens--;
174             return;
175           }
176           catch (ex) {
177             com.gContactSync.alertError(com.gContactSync.StringBundle.getStr("removeLoginFailure") + "\n\n" + ex);
178           }
179         }
180       }
181       // Could not find the login...
182       com.gContactSync.alertError(com.gContactSync.StringBundle.getStr("removeLoginFailure"));
183     }
184   },
185   /**
186    * Returns an array of all e-mail account usernames matching an optional
187    * pattern.
188    *
189    * @param aPattern {RegExp} A RegExp to match against.  If not provided all
190    *                          IMAP & mailbox usernames are returned.
191    */
192   getAllEmailAccts: function LoginManager_getAllEmailAccts(aPattern) {
193     var arr = [];
194     // Thunderbird 2
195     if ("@mozilla.org/passwordmanager;1" in Components.classes) {
196       var passwordManager = Components.classes["@mozilla.org/passwordmanager;1"]
197                                       .getService(Components.interfaces.nsIPasswordManager),
198           iter = passwordManager.enumerator;
199       while (iter.hasMoreElements()) {
200         try {
201           var pass = iter.getNext().QueryInterface(Components.interfaces.nsIPassword);
202           if (pass.host.indexOf("imap://") === 0 || pass.host.indexOf("mailbox://") === 0) {
203             if (!aPattern || aPattern.test(pass.user)) {
204               arr.push(pass.user);
205             }
206           }
207         } catch (e) {}
208       }
209     }
210     // Thunderbird 3, Seamonkey 2
211     else if ("@mozilla.org/login-manager;1" in Components.classes) {
212       var loginManager =  Components.classes["@mozilla.org/login-manager;1"]
213                                     .getService(Components.interfaces.nsILoginManager),
214       // Find users for the given parameters
215           count  = {},
216           out    = {},
217           logins = loginManager.getAllLogins(count, out),
218           i      = 0,
219           hostname;
220       // Find user from returned array of nsILoginInfo objects
221       for (; i < logins.length; i++) {
222         hostname = logins[i].hostname;
223         if (hostname.indexOf("imap://") === 0 || hostname.indexOf("mailbox://") === 0) {
224           if (!aPattern || aPattern.test(logins[i].username)) {
225             arr.push(logins[i].username);
226           }
227         }
228       }
229     }
230     return arr;
231   }
232 };
233