home *** CD-ROM | disk | FTP | other *** search
Text File | 2010-07-12 | 34.4 KB | 1,152 lines |
- var gYaAuth = {
- get PasswordManager() {
- delete this.PasswordManager;
- return (this.PasswordManager = Cc["@mozilla.org/autocomplete/search;1?name=YasearchPassComplete"].getService().wrappedJSObject);
- },
-
- shutdown: function YaAuth_shutdown() {
- this.Users.clear();
- },
-
- normalizeUser: function(aUsername) {
- return new this.NormalizedUsernameData(aUsername);
- },
-
- Users: {
- _users: {},
-
- __iterator__: function YaAuthUsers___iterator__() {
- for (let [key, value] in Iterator(this._users))
- yield [key, value];
- },
-
- clear: function YaAuthUsers_clear() {
- for each (let [username, data] in Iterator(this))
- data.auth.destroy();
- },
-
- addUser: function YaAuthUsers_addUser(aUsername, aUsernameTyped) {
- if (!aUsername)
- return null;
-
- let normalizedUserData = gYaAuth.normalizeUser(aUsername);
- let username = normalizedUserData.name;
-
- let user = this._users[username] || (this._users[username] = {
- username: username,
- auth: new gYaAuth.AuthProcess(username),
- type: normalizedUserData.type,
-
- _usernameTyped: null,
- get usernameTyped() {
- return this._usernameTyped || this.username;
- }
- });
-
- if (aUsernameTyped)
- user._usernameTyped = aUsernameTyped;
-
- return user;
- },
-
- getUser: function YaAuthUsers_getUser(aUsername) {
- let username = gYaAuth.normalizeUser(aUsername).name;
- return username ? (this._users[username] || null) : null;
- }
- },
-
- isLogin: false,
-
- _sessionId: false,
- _sessionLogin: false,
-
- set session(aData) {
- if (aData.name == "Id")
- aData.val = this.Cookies.checkSessionCookieValue(aData.val);
-
- if (this.username && aData.name == "Login" &&
- aData.val && aData.val.replace(/\./g, "-") !== this.username &&
- this._sessionId)
- {
- aData.val = false;
- }
-
- this["_session" + aData.name] = aData.val;
-
- if (!aData.val) {
- this.fireAfterLogout();
- } else {
- if (this._sessionId && this._sessionLogin)
- this.fireAfterLogin();
- }
- },
-
- get session() {
- return {
- id: this._sessionId,
- login: this._sessionLogin
- };
- },
-
- _username: false,
-
- get username() {
- return this._username;
- },
-
- set username(val) {
- if (!val)
- val = false;
-
- this._username = val;
-
- if (val && "undefined" == typeof gYaSearchService.usersData[val])
- gYaSearchService.usersData[val] = {};
-
- return val;
- },
-
- fireAfterLogin: function YaAuth_fireAfterLogin() {
- if (this.isLogin)
- return;
-
- this._loginFailCounter = 0;
-
- this.isLogin = true;
-
- this.username = this.session.login.replace(/\./g, "-");
-
- let user = this.Users.addUser(this.username);
- user.auth.loginState = this.LOGIN_STATES.AUTH;
-
- let loginProcessData = user.auth.loginProcessData;
-
- if (loginProcessData.manualLogin) {
- this.PasswordManager.storeLoginDetails(user.usernameTyped,
- loginProcessData.password,
- loginProcessData.twoWeeks,
- "yandex");
- }
-
- if (loginProcessData.username)
- this.Cookies.getAuthDinamicData("login");
-
- if (this.Cookies.yaAuthStaticData.needRefresh)
- this.Cookies.getAuthStaticData();
-
- gYaSearchService.onYandexLogin();
- },
-
- fireAfterLogout: function YaAuth_fireAfterLogout(aClearCookies, aForgetLogin) {
- if (!this.isLogin)
- return;
-
- this.isLogin = false;
-
- if (aForgetLogin)
- this.PasswordManager.removeUserData(this.username);
-
- let username = this.username;
-
- this.username = false;
-
- this.session = {
- name: "Login",
- val: false
- };
-
- let user = gYaAuth.Users.getUser(username);
- if (user)
- user.auth.loginState = this.LOGIN_STATES.NO_AUTH;
-
- if (aClearCookies)
- new G_Timer(function() {
- let user = gYaAuth.Users.getUser(username);
- if (user)
- user.auth.cancel();
- }, 0);
-
- gYaSearchService.onYandexLogout();
-
- //OBSERVER_SERVICE.notifyObservers(null, "Ya-Refresh-Data", "login");
- },
-
- dropAllAuth: function() {
- gYaSearchService.yaMFD.dropAuthForAllLogins();
- this.fireAfterLogout(true, false);
- },
-
- dropAuth: function(aLogin, aClearCookies, aForgetLogin) {
- if (this.isLogin && aLogin == this.username)
- this.fireAfterLogout(aClearCookies, aForgetLogin);
- else
- gYaSearchService.yaMFD.dropAuthForLogin(aLogin, aForgetLogin);
-
- gYaSearchService.yaMFD.dropAuthForAllLogins();
- },
-
- LOGIN_STATES: {
- NO_AUTH: 0,
- ERROR: 1,
- CAPTCHA_ERROR: 2,
- NET_ERROR: 3,
- REQUEST: 4,
- AUTH: 5
- },
-
- _loginFailCounter: 0,
-
- get loginFail() {
- return (this._loginFailCounter >= 3);
- },
-
- _swapUsersData: null,
-
- get swapUsersData() {
- return this._swapUsersData || null;
- },
-
- initLoginSwapProcess: function(aNewUserLogin) {
- if (!aNewUserLogin ||
- this.normalizeUser(this.username).name == this.normalizeUser(aNewUserLogin).name ||
- gYaSearchService.yaMFD.isLoginHasAuth(aNewUserLogin))
- return;
-
- let loginSavedInfo = this.PasswordManager.getSavedLoginInfo(aNewUserLogin);
- if (!loginSavedInfo || !loginSavedInfo.password)
- return;
-
- this._swapUsersData = {
- login: aNewUserLogin,
- username: aNewUserLogin.split("@")[0],//.toLowerCase(),
- password: loginSavedInfo.password,
- type: (loginSavedInfo.type == "mfd" ? "mfd" : null)
- };
-
- if (gYaSearchService.yaMFD.dropAuthForDomain(aNewUserLogin, true))
- return;
-
- if (this.isLogin) {
- if (this._swapUsersData.type != "mfd") {
- this.fireAfterLogout(true, false);
- gYaSearchService.notifyBusyStateOfRequest(null, true, true, "yasearch-login");
- } else {
- this.checkSwapUsers();
- }
-
- } else {
- this.checkSwapUsers();
- }
- },
-
- checkSwapUsers: function() {
- let swapUsersData = this._swapUsersData;
- if (!swapUsersData)
- return;
-
- if (this.initLoginProcess(swapUsersData.login, swapUsersData.password, true, true)) {
- gYaSearchService.notifyBusyStateOfRequest(null, true, true, "yasearch-login");
- } else {
- this._swapUsersData = null;
- gYaSearchService.notifyBusyStateOfRequest(null, false, true, "yasearch-login");
- }
- },
-
- initLoginProcess: function(aName, aPassword, aTwoWeeks, aManualLogin) {
- if (!aName || !aPassword)
- return false;
-
- if ((this.isLogin && this.normalizeUser(this.username).name == this.normalizeUser(aName).name) ||
- gYaSearchService.yaMFD.isLoginHasAuth(aName))
- return false;
-
- let user = this.Users.addUser(aName, aManualLogin ? aName : null);
-
- if (user.type == "mfd")
- gYaSearchService.yaMFD.dropAuthForDomain(aName);
-
- user.auth.start(aPassword, aTwoWeeks, aManualLogin, user.type);
-
- return true;
- },
-
- onLogoutCallback: function() {
- this.checkSwapUsers();
- },
-
- Cookies: {
- get rootDomain() {
- return this.yaAuthStaticData.rootDomain;
- },
-
- __yaAuthStaticData: null,
-
- set yaAuthStaticData(aVal) {
- gYaSearchService.setCharPref("yasearch.auth.static", aVal);
- this.__yaAuthStaticData = null;
- return aVal;
- },
-
- get yaAuthStaticData() {
- if (this.__yaAuthStaticData === null) {
- let staticData = {
- ts: 0,
- get needRefresh() {
- let timeNow = Date.now();
- return ((timeNow - this.ts > 1 * DAY_SECS) || this.ts > timeNow) ? true : false;
- },
-
- rootDomain: false,
- rootPass: false,
- rootPasslogin: false,
- rootPasslogout: false,
- allHostsRegExp: false,
- hosts: {}
- };
-
- let data = (gYaSearchService.getCharPref("yasearch.auth.static") || "").split("~~~");
-
- if (data.length > 1 && /^\d+$/.test(data[0])) {
- let lastTime = +data[0];
- let uri;
-
- try {
- let hostStr = data[1];
- uri = hostStr && /^\/:/.test(hostStr) ? gYaSearchService.makeURI(hostStr.replace(/^\/:/,"")) : null;
- } catch(e){}
-
- if (uri && /https?/.test(uri.scheme)) {
- let allHostsRegExp = [];
-
- staticData.ts = lastTime;
-
- let passUrl = uri.spec;
- staticData.rootPass = passUrl;
-
- passUrl += (/\/$/.test(passUrl) ? "" : "/") + "xml/log";
-
- staticData.rootPasslogin = passUrl + "in";
- staticData.rootPasslogout = passUrl + "out";
-
- let domainArr = uri.host.split(".").reverse();
- staticData.rootDomain = domainArr.length > 1 ? ("." + domainArr[1] + "." + domainArr[0]) : false;
-
- let i = 2,
- cookies = data[i];
-
- while (cookies) {
- let hostIndx = cookies.indexOf(":");
-
- if (hostIndx > 2) {
- let host = cookies.substring(0, hostIndx);
-
- let hostReg = host.replace(/(\-|\.)/g,"\\\$1").replace(/^(\*\\\.)/,"(.*\\.)?");
- allHostsRegExp.push(hostReg);
- hostReg = new RegExp("^" + hostReg + "$", "i");
-
- let cookiesArr = [];
- for each (var cook in cookies.substring(++hostIndx).split(","))
- if (cook > "")
- cookiesArr.push(cook);
-
- if (cookiesArr.length)
- staticData.hosts[host] = {cookies: cookiesArr, hostReg: hostReg};
- }
-
- cookies = data[++i];
- }
-
- if (allHostsRegExp.length)
- staticData.allHostsRegExp = new RegExp("^(" + allHostsRegExp.join("|") + ")$", "i");
- }
- }
-
- this.__yaAuthStaticData = staticData;
- }
-
- return this.__yaAuthStaticData;
- },
-
- checkAuthOnStart: function YaAuthCookies_checkAuthOnStart(aSkipGettingStaticData) {
- if ((typeof aSkipGettingStaticData == "undefined") && !this.rootDomain)
- return this.getAuthStaticData(this.checkAuthOnStart.bind(this));
-
- if (this.rootDomain)
- gYaAuth.setSessionFromCookies(true);
- },
-
- getAuthStaticData: function YaAuthCookies_getAuthStaticData(aCallback) {
- gYaSearchService.xmlHttpRequest("https://passport.yandex.ru/bar.txt?" + getNCRndStr(),
- { callbackFunc: this.getAuthStaticDataCallback.bind(this, aCallback) });
- },
-
- getAuthStaticDataCallback: function YaAuthCookies_getAuthStaticDataCallback(aReq, aCallback) {
- let res = false;
-
- if (!gYaSearchService.isReqError(aReq)) {
- let staticDataArray = aReq.target.responseText.split(/\r?\n/);
- let rootPass = false;
- let resArray = [];
-
- for (let i = 0, len = staticDataArray.length; i < len; i++) {
- let item = staticDataArray[i].split("#")[0];
- if (/^\/:/.test(item)) {
- if (!rootPass)
- rootPass = item;
- } else if (item.indexOf(":") > 0) {
- resArray.push(item);
- }
- }
-
- if (rootPass) {
- resArray.unshift(Date.now(), rootPass);
- this.yaAuthStaticData = resArray.join("~~~");
- }
-
- res = !!this.rootDomain;
- }
-
- if (aCallback)
- aCallback(res);
- },
-
- getAuthDinamicData: function YaAuthCookies_getAuthDinamicData(aType) {
- let url = this.yaAuthStaticData["rootPass" + aType];
-
- if (url) {
- url = gYaSearchService.appendStatData2Url(url + "?" + getNCRndStr(), {});
- return gYaSearchService.xmlHttpRequest(url, {callbackFunc: this.getAuthDinamicDataCallback.bind(this, aType)});
- }
-
- if (aType === "logout")
- gYaAuth.onLogoutCallback();
- },
-
- getAuthDinamicDataCallback: function YaAuthCookies_getAuthDinamicDataCallback(aReq, aType) {
- let res = false;
-
- if ((aType === "logout" && !gYaAuth.isLogin) || (aType === "login" && gYaAuth.isLogin))
- res = this.manageCookies(gYaSearchService.isReqError(aReq) ?
- false : aReq.target.responseText.replace(/<\?xml .+\?>[\r\n]*/,""), aType);
-
- if (aType === "logout")
- gYaAuth.onLogoutCallback();
- },
-
- manageCookies: function YaAuthCookies_manageCookies(aXmlString, aType) {
- const cookieManager = gYaSearchService.cookieManager;
-
- let res = false;
- let presentHosts;
-
- let cookiesXml = gYaSearchService.safeE4Xml(aXmlString, "<mda/>", "mda");
-
- if (cookiesXml.domain.length()) {
- const cookieService = Cc["@mozilla.org/cookieService;1"].getService().QueryInterface(Ci.nsICookieService);
-
- presentHosts = this.getBrowserHostCookies();
-
- let timeNow = Date.now();
- let timeNowSec = parseInt(timeNow / 1000, 10);
-
- for (let i = 0, len_i = cookiesXml.domain.length(); i < len_i; i++) {
- let domain = cookiesXml.domain[i];
- let domainId = domain.@id.toString();
-
- for each (let actionTag in domain.*) {
- let action = actionTag.name().toString();
-
- for (let j = 0, len_j = actionTag.cookie.length(); j < len_j; j++) {
- let cookie = actionTag.cookie[j];
- let cookieName = cookie.@id.toString();
-
- if (cookieName > "") {
-
- let cookiePath = cookie.@path.toString() == "" ? "/" : cookie.@path.toString();
-
- switch (action) {
- case "remove":
- cookieManager.remove(domainId, cookieName, cookiePath, false);
- break;
-
- case "set":
- let maxAge = +(cookie["@max-age"].toString());
-
- if (cookie.@override.toString() != "yes" && presentHosts[domainId]) {
- for each (let existCookie in presentHosts[domainId]) {
- if (existCookie.name === cookieName) {
- if ((existCookie.expires == 0 && maxAge == 0) ||
- (existCookie.expires > 0 && maxAge > 0 && timeNowSec < existCookie.expires))
- cookieName = false;
- break;
- }
- }
- }
-
- if (cookieName) {
- let uri = Cc["@mozilla.org/network/standard-url;1"].createInstance(Ci.nsIURI);
- uri.spec = "http://" + domainId.replace(/^\./, "");
-
- let cookieStr = "" + cookieName + "=" + cookie.text().toString() + ";";
-
- if (domainId.charAt(0) == ".")
- cookieStr += "domain=" + domainId + ";";
-
- cookieStr += "path=" + cookiePath + ";";
-
- if (maxAge > 0)
- cookieStr += "expires=" + (new Date(timeNow + maxAge*1000).toGMTString()) + ";"
-
- cookieService.setCookieString(uri, null, cookieStr, null);
- }
-
- break;
-
- default:
- break;
- }
- }
- }
- }
- }
-
- res = true;
-
- } else if (aType == "logout") {
-
- presentHosts = this.getBrowserHostCookies(true);
-
- for each (let staticHost in this.yaAuthStaticData.hosts) {
- for (let presentHost in presentHosts) {
- if (staticHost.hostReg.test(presentHost)) {
- let presentCookies = presentHosts[presentHost];
- for each (let staticName in staticHost.cookies) {
- let i = presentCookies.length;
- while (--i > -1) {
- let presentCookie = presentCookies[i];
- if (staticName == presentCookie.name) {
- cookieManager.remove(presentCookie.host, presentCookie.name, presentCookie.path, false);
- presentCookies.splice(i,1);
- }
- }
- }
- }
- }
- }
-
- res = true;
-
- }
-
- return res;
- },
-
- checkSessionCookieValue: function YaAuthCookies_checkSessionCookieValue(aValue) {
- return (aValue && aValue.length) ? aValue : false;
- },
-
- getYandexCookie: function YaAuthCookies_getYandexCookie(aCookieName, aCheckExpired, aCookiePath) {
- let rootDomain = this.rootDomain;
- if (!rootDomain)
- return false;
-
- const nsICookie = Ci.nsICookie;
- let cookEnum = gYaSearchService.cookieManager.enumerator;
- let timeNow = parseInt(Date.now() / 1000, 10);
- let path = aCookiePath ? aCookiePath : "/";
-
- while (cookEnum.hasMoreElements()) {
- let cookie = cookEnum.getNext();
- if (cookie && cookie instanceof nsICookie && cookie.host == rootDomain &&
- cookie.name == aCookieName && cookie.path == path && cookie.value.toString() != "" &&
- (aCheckExpired ? !!(cookie.expires == 0 || timeNow < cookie.expires) : true))
- {
- let res = cookie.value.toString();
- return aCookieName == "Session_id" ? this.checkSessionCookieValue(res) : res;
- }
- }
-
- return false;
- },
-
- _getHostURIFromURL: function YaAuthCookies__getHostURIFromURL(aURL) {
- let host = aURL.replace(/^\s*([-\w]*:\/+)?/, "");
- return gYaSearchService.makeURI("http://" + host);
- },
-
- isCookiesAllowedForHost: function YaAuthCookies_isCookiesAllowedForHost(aURL) {
- let res = null;
-
- let uri = this._getHostURIFromURL(aURL);
- if (!uri)
- return res;
-
- const permissionManager = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager);
-
- switch (permissionManager.testPermission(uri, "cookie")) {
- case permissionManager.ALLOW_ACTION:
- res = true;
- break;
-
- case permissionManager.DENY_ACTION:
- res = null;
- break;
-
- case permissionManager.UNKNOWN_ACTION:
- default:
- let cookieBehaviorValue = gYaSearchService.getIntPref("network.cookie.cookieBehavior");
- res = (cookieBehaviorValue === 0);
- break;
- }
-
- return res;
- },
-
- allowCookiesForHost: function YaAuthCookies_allowCookiesForHost(aURL) {
- if (this.isCookiesAllowedForHost(aURL))
- return true;
-
- let uri = this._getHostURIFromURL(aURL);
- if (uri) {
- const permissionManager = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager);
- permissionManager.add(uri, "cookie", permissionManager.ALLOW_ACTION);
- }
-
- return this.isCookiesAllowedForHost(aURL);
- },
-
- getBrowserHostCookies: function YaAuthCookies_getBrowserHostCookies(aOnlyYandexList) {
- let res = {};
- let allHostsRegExp = aOnlyYandexList ? this.yaAuthStaticData.allHostsRegExp : false;
-
- if (!aOnlyYandexList || allHostsRegExp) {
- const nsICookie = Ci.nsICookie;
-
- let cookEnum = gYaSearchService.cookieManager.enumerator;
-
- while (cookEnum.hasMoreElements()) {
- let cookie = cookEnum.getNext();
-
- if (cookie && cookie instanceof nsICookie) {
- let host = cookie.host;
-
- if (!aOnlyYandexList || allHostsRegExp.test(host)) {
- let newCookie = {};
-
- for each (var prop in ["name", "value", "host", "path", "expires"])
- newCookie[prop] = cookie[prop];
-
- if (!res[host])
- res[host] = [];
-
- res[host].push(newCookie);
- }
-
- } else {
- break;
- }
- }
- }
-
- return res;
- }
- },
-
- onCookieChanged: function(aSubject, aTopic, aData) {
- let rootDomain = this.Cookies.rootDomain;
- if (!rootDomain)
- return;
-
- try {
- aSubject.QueryInterface(Ci.nsICookie);
- } catch(e) {}
-
- if (!(aSubject && aSubject instanceof Ci.nsICookie))
- return;
-
- if (aSubject.host == rootDomain) {
- if (aSubject.path == "/") {
- let name = aSubject.name;
-
- if (name == "Session_id" || name == "yandex_login") {
- let val = "";
- try {
- val = aSubject.value.toString();
- } catch(e) {}
-
- if (aData == "deleted" || !val)
- val = false;
-
- let needRecheckAuth = !!(aData == "changed" && !this.isLogin);
-
- this.session = {
- val: val,
- name: (name == "Session_id" ? "Id" : "Login")
- };
-
- if (needRecheckAuth && (this.session.id || this.session.login))
- this.setSessionFromCookies(false);
- }
-
- }
- }
- },
-
- setSessionFromCookies: function(aCheckExpired) {
- if (!this.isLogin) {
- let loginCookieValue = this.Cookies.getYandexCookie("yandex_login", aCheckExpired);
- let sessionCookieValue = this.Cookies.getYandexCookie("Session_id", aCheckExpired);
-
- if (loginCookieValue && sessionCookieValue) {
- this.session = {
- name: "Id",
- val: sessionCookieValue
- };
-
- this.session = {
- name: "Login",
- val: loginCookieValue
- };
-
- return true;
- }
- }
-
- return false;
- },
-
- getAllLoginsInfo: function() {
- let currentAuthUsername = this.isLogin ? this.username.split("@")[0].toLowerCase() : "";
-
- if (!currentAuthUsername && this._swapUsersData)
- currentAuthUsername = this._swapUsersData.login.split("@")[0].toLowerCase();
-
- let currentAuthMFDData = gYaSearchService.yaMFD.getAllAuthUsers()
- .map(function(aAuthUser) aAuthUser.boxname);
-
- let addYaAuthToList = !!currentAuthUsername;
- let loginsInfo = this.PasswordManager.getSavedLoginsInfo();
-
- for each (let [index, loginInfo] in Iterator(loginsInfo)) {
- let username = loginInfo.username;
-
- if (loginInfo.type == "yandex") {
- let hasAuth = !!(currentAuthUsername &&
- currentAuthUsername == username.split("@")[0].replace(/\./g, "-").toLowerCase())
-
- if (addYaAuthToList && hasAuth)
- addYaAuthToList = false;
-
- loginInfo.hasAuth = hasAuth;
-
- } else {
- let indx = currentAuthMFDData.indexOf(username);
- if (indx != -1) {
- loginInfo.hasAuth = true;
- currentAuthMFDData.splice(indx, 1);
- } else {
- loginInfo.hasAuth = false;
- }
- }
- }
-
- if (addYaAuthToList) {
- loginsInfo.push({
- username: this.session.login,
- password: null,
- hasAuth: true,
- type: "yandex"
- });
- }
-
- currentAuthMFDData.forEach(function(aMFDBoxname) {
- loginsInfo.push({
- username: aMFDBoxname,
- password: null,
- hasAuth: true,
- type: "mfd"
- });
- });
-
- return loginsInfo;
- }
- };
-
- (function() {
- function AuthProcess(aUsername) {
- this.userData = gYaAuth.normalizeUser(aUsername);
-
- this._username = aUsername;
-
- this._loginProcessData = {};
-
- this._connections = {
- login: null,
- logout: null
- };
-
- this._loginState = 0;
- }
-
- AuthProcess.prototype = {
- get mfdAppendString() {
- return this.userData.domain ? ("/for/" + this.userData.domain) : "";
- },
-
- getPassURL: function AuthProcess_getPassURL(aMode) {
- if (aMode == "auth" && this.userData.type == "mfd")
- aMode = "mdauth";
-
- let url = "https://passport.yandex.ru" + this.mfdAppendString + "/passport?mode=" + aMode + "&target=bar";
-
- if (aMode == "logout")
- url += "&yu=" + encodeURIComponent(gYaAuth.Cookies.getYandexCookie("yandexuid", false) || "");
-
- return url;
- },
-
- get loginProcessData() {
- return this._loginProcessData;
- },
-
- get loginState() {
- return this._loginState;
- },
-
- set loginState(val) {
- let newLoginStateValue = parseInt(val, 10);
-
- if (this._loginState !== newLoginStateValue) {
- if (newLoginStateValue < gYaAuth.LOGIN_STATES.NO_AUTH || newLoginStateValue > gYaAuth.LOGIN_STATES.AUTH) {
- gYaSearchService.log("loginState: bad value (" + val + ")");
- return this._loginState;
- }
-
- this._loginState = newLoginStateValue;
-
- OBSERVER_SERVICE.notifyObservers(null, "Ya-Login-State-Changed", this.userData.name);
-
- switch (newLoginStateValue) {
- case gYaAuth.LOGIN_STATES.AUTH:
- case gYaAuth.LOGIN_STATES.NO_AUTH:
- OBSERVER_SERVICE.notifyObservers(null, "Ya-Refresh-Login-Status", false);
- break;
-
- default:
- break;
- }
-
- OBSERVER_SERVICE.notifyObservers(null, "Ya-Refresh-Data", "login");
- }
-
- return this._loginState;
- },
-
- destroy: function AuthProcess_destroy() {
- this._abortConnection("login");
- this._abortConnection("logout");
- },
-
- start: function AuthProcess_start(aPassword, aTwoWeeks, aManualLogin, aAuthType) {
- this._abortConnection("logout");
-
- this.loginState = gYaAuth.LOGIN_STATES.REQUEST;
-
- this._loginProcessData = {
- username: this._username,
- password: aPassword,
- twoWeeks: aTwoWeeks,
- manualLogin: aManualLogin,
- type: aAuthType
- };
-
- if (!gYaAuth.Cookies.rootDomain)
- gYaAuth.Cookies.getAuthStaticData(this._startLoginProcess.bind(this));
- else
- this._startLoginProcess();
- },
-
- cancel: function AuthProcess_cancel() {
- this._startLogoutConnection();
- },
-
- _abortConnection: function AuthProcess__abortConnection(aConnectionType) {
- let connection = this._connections[aConnectionType];
-
- try {
- if (connection && connection.channel && connection.channel.isPending())
- connection.channel.cancel(Components.results.NS_BINDING_ABORTED);
- } catch (ex) {}
-
- this._connections[aConnectionType] = null;
- },
-
- _startLogoutConnection: function AuthProcess__startLogoutConnection() {
- this._abortConnection("logout");
-
- this._connections.logout =
- gYaSearchService.xmlHttpRequest(this.getPassURL("logout"), {
- callbackFunc: this._startLogoutConnectionCallback.bind(this)
- });
- },
-
- _startLogoutConnectionCallback: function AuthProcess__startLogoutConnectionCallback(aReq) {
- if (gYaSearchService.isReqError(aReq)) {
- this._abortConnection("logout");
-
- if (this.loginProcessData.type != "mfd") {
- gYaAuth.Cookies.manageCookies(false, "logout");
- gYaAuth.onLogoutCallback();
- }
-
- } else {
- if (this.loginProcessData.type != "mfd") {
- this._connections.logout = gYaAuth.Cookies.getAuthDinamicData("logout");
- }
- }
- },
-
- _startLoginProcess: function AuthProcess__startLoginProcess() {
- if (!gYaAuth.Cookies.rootDomain)
- this.loginState = gYaAuth.LOGIN_STATES.NET_ERROR;
- else
- this._startLoginConnection();
- },
-
- _startLoginConnection: function AuthProcess__startLoginConnection() {
- this._abortConnection("logout");
-
- let data = "login=" + encodeURIComponent(this.loginProcessData.username)
- + "&passwd=" + encodeURIComponent(this.loginProcessData.password)
- + "&retpath=https%3A%2F%2Fpassport.yandex.ru%2Fpassport%3Fmode%3Dpassport%26target%3Dbar"
- + "×tamp=" + Date.now();
-
- if (this.loginProcessData.twoWeeks)
- data += "&twoweeks=yes";
-
- this._talkToServer(this.getPassURL("auth"),
- data, null, "https://passport.yandex.ru/passport?mode=passport&target=bar",
- this._talkToServerCallback.bind(this));
- },
-
- _talkToServer: function AuthProcess__talkToServer(aURL, aPostData, aCookieData, aReferrer, aCallbackFunc) {
- let uri = gYaSearchService.makeURI(aURL);
-
- let uploadStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
- if (aPostData)
- uploadStream.setData(aPostData, aPostData.length);
-
- let channel = IO_SERVICE.newChannelFromURI(uri);
-
- this._connections.login = channel;
-
- let httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);
-
- if (aReferrer)
- httpChannel.referrer = gYaSearchService.makeURI(aReferrer);
-
- if (aPostData) {
- let uploadChannel = channel.QueryInterface(Ci.nsIUploadChannel);
- uploadChannel.setUploadStream(uploadStream, "application/x-www-form-urlencoded", -1);
- httpChannel.requestMethod = "POST";
- }
-
- if (aCookieData)
- for (let run = 0; run < aCookieData.length; run++)
- httpChannel.setRequestHeader("Cookie", aCookieData[run], true);
-
- let observer = new this._talkToServerObserver(aCallbackFunc);
- channel.notificationCallbacks = observer;
- channel.asyncOpen(observer, null);
- },
-
- _talkToServerCallback: function AuthProcess__talkToServerCallback(aData) {
- gYaAuth._swapUsersData = null;
-
- gYaSearchService.notifyBusyStateOfRequest(null, false, true, "yasearch-login");
-
- let aRequest = aData.request,
- status = null,
- warningText = "";
-
- try {
- aRequest.QueryInterface(Ci.nsIHttpChannel);
- status = aRequest.responseStatus;
- warningText = aRequest.getResponseHeader("Warning");
- } catch(e) {}
-
- if (!status || (status != 200 && status != 302)) {
- this.loginState = gYaAuth.LOGIN_STATES.NET_ERROR;
- } else {
-
- let successLogin = false;
-
- let loginProcessData = this.loginProcessData;
-
- if (this.loginProcessData.type == "mfd") {
- let mfdAuth = gYaSearchService.yaMFD.isLoginHasAuth(loginProcessData.username);
-
- if (mfdAuth) {
- if (loginProcessData.manualLogin)
- gYaAuth.PasswordManager.storeLoginDetails(loginProcessData.username,
- loginProcessData.password,
- loginProcessData.twoWeeks,
- "mfd");
-
- this.loginState = gYaAuth.LOGIN_STATES.AUTH;
- successLogin = true;
- }
-
- } else {
- successLogin = !!gYaAuth.isLogin;
- }
-
- if (!successLogin) {
- gYaAuth._loginFailCounter++;
-
- if (/showcaptcha/.test(warningText)) {
- gYaAuth._loginFailCounter += 3;
- this.loginState = gYaAuth.LOGIN_STATES.CAPTCHA_ERROR;
- } else {
- this.loginState = gYaAuth.LOGIN_STATES.ERROR;
- }
- }
-
- loginProcessData.manualLogin = false;
- }
-
- OBSERVER_SERVICE.notifyObservers(null, "Ya-Refresh-Data", "login");
- },
-
- _talkToServerObserver: function AuthProcess__talkToServerObserver(aCallbackFunc) {
- return ({
- data: "",
-
- onStartRequest: function (aRequest, aContext) {
- this.data = "";
- },
-
- onDataAvailable: function (aRequest, aContext, aStream, aSourceOffset, aLength) {
- let scriptableInputStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
- scriptableInputStream.init(aStream);
- this.data += scriptableInputStream.read(aLength);
- },
-
- onStopRequest: function (aRequest, aContext, aStatus) {
- aCallbackFunc({
- "data": this.data,
- "request": aRequest
- });
- },
-
- onStatus: function(aRequest, aContext, aStatus, aStatusArg) {},
- onProgress: function(aRequest, aContext, aProgress, aProgressMax) {},
- onChannelRedirect: function (aOldChannel, aNewChannel, aFlags) {},
- onRedirect : function (aOldChannel, aNewChannel) {},
-
- getAuthPrompt: function(aPromptReason, iid) {
- const ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher);
- return ww.getNewAuthPrompter(null);
- },
-
- interfaces: [ Ci.nsISupports,
- Ci.nsIStreamListener,
- Ci.nsISupportsWeakReference,
- Ci.nsIPrompt,
- Ci.nsIAuthPrompt,
- Ci.nsIAuthPromptProvider,
- Ci.nsIProgressEventSink,
- Ci.nsIInterfaceRequestor,
- Ci.nsIChannelEventSink,
- Ci.nsIHttpEventSink,
- Ci.nsIWebProgress ],
-
- QueryInterface: function(iid) {
- if (!this.interfaces.some( function(v) { return iid.equals(v) } ))
- throw Cr.NS_ERROR_NO_INTERFACE;
-
- if (iid.equals(Ci.nsIPrompt)) {
- let prompt = Cc["@mozilla.org/network/default-prompt;1"].createInstance();
- return prompt.QueryInterface(iid);
- }
-
- if (iid.equals(Ci.nsIAuthPrompt)) {
- let prompt = Cc["@mozilla.org/network/default-auth-prompt;1"].createInstance();
- return prompt.QueryInterface(iid);
- }
-
- return this;
- },
-
- getInterface: function(iid) {
- try {
- return this.QueryInterface(iid);
- } catch(e) {
- return null;
- }
- }
- });
- },
- };
-
-
- gYaAuth.AuthProcess = AuthProcess;
-
- function NormalizedUsernameData(aUsername) {
- this._type = "yandex";
- this._username = aUsername || "";
- this._domain = null;
-
- this._init();
- }
-
- NormalizedUsernameData.prototype = {
- _init: function NUData__init() {
- let username = this._username;
-
- if (!username)
- return;
-
- if (this.domain) {
- this._type = "mfd";
- } else {
- username = username.split("@")[0].replace(/\./g, "-");
- }
-
- this._username = username.toLowerCase();
- },
-
- get name() {
- return this._username;
- },
-
- get type() {
- return this._type;
- },
-
- get domain() {
- if (this._domain === null) {
- let domain = false;
-
- let chkString = this._username.split("@")[1];
-
- if (chkString &&
- /.+\.[a-z]+$/i.test(chkString) &&
- !(/^(yandex|narod|ya)\.[a-z]{2,5}$/i.test(chkString)))
- domain = chkString;
-
- this._domain = domain || false;
- }
-
- return this._domain;
- },
-
- toString: function NUData_toString() {
- return this.name;
- }
- }
-
- gYaAuth.NormalizedUsernameData = NormalizedUsernameData;
-
- }());
-