2 * (C) Copyright 2011 John J. Foerch
4 * Use, modification, and distribution are subject to the terms specified in the
9 * Find and return a login (an nsILoginInfo) matching the given host. The
10 * host can be given as a string (for an exact match) or as a RegExp.
12 function login_find (host) {
13 var lm = Cc["@mozilla.org/login-manager;1"]
14 .getService(Ci.nsILoginManager);
15 var logins = lm.getAllLogins({});
16 for (var i = 0, n = logins.length; i < n; ++i) {
17 if (host instanceof RegExp) {
18 if (host.test(logins[i].hostname))
20 } else if (logins[i].hostname == host)
28 * Return an array of all logins (nsILoginInfo objects) that match the
29 * given host. Host may be given as a string (for an exact match) or as a
32 function login_find_all (host) {
34 var lm = Cc["@mozilla.org/login-manager;1"]
35 .getService(Ci.nsILoginManager);
36 var logins = lm.getAllLogins({});
37 for (var i = 0, n = logins.length; i < n; ++i) {
38 if (host instanceof RegExp) {
39 if (host.test(logins[i].hostname))
40 result.push(logins[i]);
41 } else if (logins[i].hostname == host)
42 result.push(logins[i]);
49 * Remove the given login. The login must be an nsILoginInfo object,
50 * which can be gotten from login_find or login_find_all.
52 function login_remove (login_info) {
53 var lm = Cc["@mozilla.org/login-manager;1"]
54 .getService(Ci.nsILoginManager);
55 lm.removeLogin(login_info);
60 * Remove all logins from the login manager.
62 function login_remove_all () {
63 var lm = Cc["@mozilla.org/login-manager;1"]
64 .getService(Ci.nsILoginManager);
70 * host, username, and password are mandatory arguments. one or the other
71 * of form_submit_url and httprealm is also mandatory, but if neither is
72 * given, the host will be used for form_submit_url. httprealm
73 * corresponds to the value of the http header in a 401 Authorization
74 * Required, 'WWW-Authenticate: Basic realm="foo"'.
76 function login_add (host, username, password,
77 httprealm, form_submit_url,
78 username_field, password_field) {
79 if (form_submit_url == null && httprealm == null)
80 form_submit_url = host;
81 var lm = Cc["@mozilla.org/login-manager;1"]
82 .getService(Ci.nsILoginManager);
83 var login_info = new Components.Constructor(
84 "@mozilla.org/login-manager/loginInfo;1",
85 Ci.nsILoginInfo, "init");
86 var info = new login_info(host,
87 (form_submit_url || null),
90 (username_field || ""),
91 (password_field || ""));
97 * login_set first removes all existing logins for the given host, then
98 * passes all of its arguments to login_add.
100 function login_set (host, username, password,
101 httprealm, form_submit_url,
102 username_field, password_field) {
103 login_find_all(host).map(login_remove);
104 login_add(host, username, password,
105 httprealm, form_submit_url,
106 username_field, password_field);