"use strict";
const EXPORTED_SYMBOLS = ["yauth", "dauth", "mfdauth", "authdefs"];
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu, manager: Cm} = Components;
var utils;
var pwdMgr;
const dauth = {
get authorized() {
return ! ! (yauth.user || mfdauth.getTopUser());
}
,
get users() {
return [].concat(mfdauth.users).concat(yauth.users).reverse();
}
,
get user() {
return yauth.user || mfdauth.user;
}
,
get yauth() {
return yauth;
}
,
get mfdauth() {
return mfdauth;
}
,
get liveUsers() {
return [].concat(yauth.liveUsers).concat(mfdauth.liveUsers);
}
,
isLoginHasAuth: function dauth_isLoginHasAuth(strUsername) {
return yauth.isLoginHasAuth(strUsername) || mfdauth.isLoginHasAuth(strUsername);
}
,
init: function dauth_init(api) {
if (this._initialized)
return;
this._api = api;
Cu.import(this._api.Package.resolvePath("/native/fx/modules/utils.jsm"));
this.__proto__ = new utils.NotificationSource();
yauth.init(api);
mfdauth.init(api);
mfdauth.addListener(mfdauth.EVENTS.AUTH_STATE_CHANGED,this);
mfdauth.addListener(mfdauth.EVENTS.LOGIN_STATE_CHANGED,this);
yauth.addListener(yauth.EVENTS.AUTH_STATE_CHANGED,this);
yauth.addListener(yauth.EVENTS.LOGIN_STATE_CHANGED,this);
this._initialized = true;
}
,
initLoginProcess: function dauth_initLoginProcess(strUsername, strPwd, isStorePwd) {
if (yauth.isNativeUser(strUsername))
return yauth.initLoginProcess(strUsername,strPwd,isStorePwd);
return mfdauth.initLoginProcess(strUsername,strPwd,isStorePwd);
}
,
initLogoutProcess: function dauth_initLogoutProcess(strUsername, forgetLoginInfo) {
if (yauth.isNativeUser(strUsername))
return yauth.initLogoutProcess(strUsername,forgetLoginInfo);
return mfdauth.initLogoutProcess(strUsername,forgetLoginInfo);
}
,
initLogoutAll: function dauth_initLogoutAll() {
yauth.initLogoutAll();
mfdauth.initLogoutAll();
}
,
observe: function dauth_observe(subject, topic, data) {
switch (topic) {
case yauth.EVENTS.AUTH_STATE_CHANGED:

case mfdauth.EVENTS.AUTH_STATE_CHANGED:
this._notifyListeners(this.EVENTS.AUTH_STATE_CHANGED,data);
break;
case this.EVENTS.LOGIN_STATE_CHANGED:
this._notifyListeners(topic,data);
break;
}

}
,
openAuthDialog: function dauth_openAuthDialog(event, dialogParams, isForceLogin, onAuthedCallback, onDlgEventCallback) {
_openAuthDialog.call(this,event,dialogParams,isForceLogin,onAuthedCallback,onDlgEventCallback);
}
,
getUserForDomain: function dauth_getUserNameForDomain(strDomain) {
if (yauth.isNativeDomain(strDomain))
return yauth.user;
for(let [, user] in Iterator(mfdauth.users)) if (user.domain == strDomain)
return user;
return null;
}
,
get pwdmng() {
return pwdMgr;
}
,
get authdefs() {
return authdefs;
}
,
_getModule: function dauth__getModule(moduleName, modulePath) {
var mScope = {
};
Cu.import(this._api.Package.resolvePath(modulePath),mScope);
var module = mScope[moduleName];
if (! module)
throw new Error("No module '" + moduleName + "' in " + modulePath);
if (typeof module.init == "function")
module.init(this._api);
return module;
}
,
EVENTS: {
AUTH_STATE_CHANGED: "dauth-state-changed",
LOGIN_STATE_CHANGED: "login-state-changed"}};
const authdefs = {
USER_TYPES: {
USER_MFD: "pdd",
USER_YANDEX: "yandex",
USER_FOREIGN: "foreign"},
LOGIN_STATES: {
NO_AUTH: 0,
LOGIN_FAIL: 1,
CAPTCHA_ERROR: 2,
NET_ERROR: 3,
REQUEST: 4,
AUTH: 5},
DOMAINS: {
MAIN_DOMAIN: "yandex.ru"},
LINKS: {
AUTH_PASSPORT_URL: "https://passport.yandex.ru",
PASS_ROOT_URL: "http://pass.yandex.ru"}};
function _auth() {
this._users = [];
this._loginCookies = [];
this._sessionCookies = [];
}

_auth.prototype = {
clearUsers: function auth_clearUsers() {
for(let [, user] in Iterator(this._users)) {
user.authorized = false;
user.auth.destroy();
}

this._users.length = 0;
}
,
addUser: function auth_addUser(user) {
if (user)
{
user.authorized = true;
this._users.push(user);
}

}
,
removeUser: function auth_removeUser(user) {
if (user)
{
user.authorized = false;
let ind = this._users.indexOf(user);
this._users.splice(ind,1);
}

}
,
getTopUser: function auth_getTopUser() {
if (this._users.length)
{
return this._users[this._users.length - 1];
}

return null;
}
,
isNativeUser: function auth_isNativeUser(strUsername) {

}
,
_getUserForDomain: function auth__getUserForDomain() {

}
,
_addCookie: function auth__addCookie(cookie, collection) {
if (! cookie)
return;
for(let [, item] in Iterator(collection)) {
if (item.name === cookie.name && item.uri.path === cookie.uri.path)
{
return;
}

}

cookie.addListener(cookie.EVENTS.COOKIE_VALUE_CHANGED,this);
collection.push(cookie);
}
,
_addLoginCookie: function auth__addLoginCookie(cookie) {
this._addCookie(cookie,this._loginCookies);
}
,
_addSessionCookie: function auth__addSessionCookie(cookie) {
this._addCookie(cookie,this._sessionCookies);
}
,
_removeLoginCookie: function auth__removeLoginCookie(cookie) {
this._removeCookie(cookie,this._loginCookies);
}
,
_removeSessionCookie: function auth__removeSessionCookie(cookie) {
this._removeCookie(cookie,this._sessionCookies);
}
,
_removeCookie: function auth__removeCookie(sessionCookie, collection) {
if (! sessionCookie)
return;
var ind = collection.indexOf(sessionCookie);
collection.splice(ind,1);
sessionCookie.removeAllListeners();
}
,
_getLoginCookie: function auth__getLoginCookie(pathOrDomain) {

}
,
_getSessionCookie: function auth__getSessionCookie(pathOrDomain) {

}
,
_clearCookies: function auth__clearCookies() {
for(let [, cookie] in Iterator(this._loginCookies)) {
cookie.removeAllListeners();
}

for(let [, cookie] in Iterator(this._sessionCookies)) {
cookie.removeAllListeners();
}

}
,
get _isPasswordManagerRegistered() {
return Cm.QueryInterface(Ci.nsIComponentRegistrar).isCIDRegistered(pwdMgr.classID);
}
,
_registerPasswordManager: function auth__registerPasswordManager() {
if (this._isPasswordManagerRegistered)
return;
Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory(pwdMgr.classID,pwdMgr.classDescription,pwdMgr.contractID,pwdMgr);
}
,
get users() {
return this._users;
}
,
get liveUsers() {

}
,
get user() {
return this.getTopUser();
}
,
get authorized() {
return ! ! this.user;
}
,
get branding() {
return this._branding;
}
,
getUser: function auth_getUser(strUsername) {
if (strUsername)
{
let lowered = strUsername.toLowerCase();
let normalizedName = lowered.split("@")[0].replace(/\./g,"-");
for(let [, user] in Iterator(this._users)) {
if (user.type == authdefs.USER_TYPES.USER_YANDEX && user.name == normalizedName || user.fullName == lowered)
{
return user;
}

}

}

return null;
}
,
isLoginHasAuth: function auth_isLoginHasAuth(strLogin) {
var user = this.getUser(strLogin);
return ! ! user && ! ! user.sessionId;
}
,
init: function auth_init(api) {
if (this._initialized)
return;
this._api = api;
this._branding = this._api.Services.obtainService("ru.yandex.custombar.branding","package",this);
Cu.import(this._api.Package.resolvePath("/native/fx/modules/utils.jsm"));
Cu.import(this._api.Package.resolvePath("/native/fx/modules/user.jsm"));
User.init(this._api);
this._prefSrv = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
this._initialized = true;
this.__proto__.__proto__.__proto__ = utils.NotificationSource.prototype;
utils.NotificationSource.apply(this);
pwdMgr = this._getModule("pwdmng","/native/fx/modules/pwdmng.jsm");
this._registerPasswordManager();
const observer = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
observer.addObserver(this,"cookie-changed",false);
observer.addObserver(this,"quit-application-granted",false);
if (! this.passportConfig.rootPassportURL && ! this._activePassConfigRequest)
{
this._refreshPassportConfig();
}

}
,
observeServiceEvent: function auth_observeServiceEvent(providerID, serviceName, topic, data) {

}
,
initLoginProcess: function auth_initLoginProcess(strUserName, strPassword, isStorePwd) {
if (! this._checkLoginConditions(strUserName))
{
return false;
}

this._checkCookiesReset(strUserName);
var user = this.createUser(strUserName,strPassword,isStorePwd);
user.auth.addListener("login-state-changed",this);
this._onInitLoginProcess(user);
this._loginUser = user;
user.auth.start(strPassword,isStorePwd,user.type);
return true;
}
,
_checkLoginConditions: function auth_checkLoginConditions(strUserName) {
if (this.isLoginHasAuth(strUserName))
{
return false;
}

if (! this._checkIfCookiesAllowed())
{
let dialogTextAppend = "";
let cookieBehaviorValue = this._api.Settings.PrefsModule.get("network.cookie.cookieBehavior",3);
let needResetPreference = false;
switch (cookieBehaviorValue) {
case 1:
dialogTextAppend = " " + this.branding.expandBrandTemplates(this._stringBundle.get("Cookies3PartyDisabledText"));
needResetPreference = true;
break;
case 2:
needResetPreference = true;
break;
default:
dialogTextAppend = " " + this.branding.expandBrandTemplates(this._stringBundle.get("Cookies3PartyDisabledYandexText"));
break;
}

let dialogText = this.branding.expandBrandTemplates(this._stringBundle.get("CookiesDisabledText",[dialogTextAppend]));
if (utils.showPromptExWithYesNo(null,null,dialogText) == 1)
{
throw new Error("Cookies is not allowed (user rejected dialog). Impossible to authenticate.");
}

if (needResetPreference)
this._api.Settings.PrefsModule.reset("network.cookie.cookieBehavior");
if (! this._checkIfCookiesAllowed())
throw new Error("Cookies is not allowed (can not set cookies preferences). Impossible to authenticate.");
this._followRequiredCookies();
}

return true;
}
,
_onInitLoginProcess: function auth__onInitLoginProcess(user) {
if (this._logoutUser)
{
if (this._logoutUser.domain == user.domain)
{
this._logoutUser.auth.destroy();
}

}

}
,
initLogoutProcess: function auth_initLogoutProcess(strUsername, forgetLoginInfo) {
var user = this.getUser(strUsername);
if (! user)
return;
this._onInitLogoutProcess(user);
this._logoutUser = user;
if (forgetLoginInfo)
{
pwdMgr.removeUserData(user.name);
}

user.auth.addListener("login-state-changed",this);
user.auth.cancel((function () {
this._onLogoutError(user.domain);
var cookie = this._getSessionCookie(user.domain);
this._setSession(cookie);
}
).bind(this));
}
,
_onInitLogoutProcess: function auth__onInitLogoutProcess(user) {
if (this._loginUser && this._loginUser.domain == user.domain)
this._loginUser.auth.destroy();
}
,
initLogoutAll: function auth_initLogoutAll() {
for(let [, user] in Iterator(this.users)) user.auth.destroy();
this._logoutUser = this.getTopUser();
for(let [, user] in Iterator(this.users)) {
user.auth.addListener("login-state-changed",this);
user.auth.cancel((function () {
this._onLogoutError.bind(this);
var cookie = this._getSessionCookie(user.domain);
this._setSession(cookie);
}
).bind(this));
}

}
,
_onLogoutError: function auth__onLogoutError(strDomain) {
this._manualResetUsedCookies(strDomain);
}
,
openAuthDialog: function auth_openAuthDialog(event, dialogParams, isForceLogin, onAuthedCallback, onDlgEventCallback) {
_openAuthDialog.call(this,event,dialogParams,isForceLogin,onAuthedCallback,onDlgEventCallback);
}
,
_authdefs: null,
get authdefs() {
if (! this._authdefs)
{
let passportConfig = this.passportConfig;
if (! passportConfig.mainDomain)
return authdefs;
this._authdefs = Object.create(authdefs);
this._authdefs.DOMAINS.MAIN_DOMAIN = passportConfig.mainDomain;
this._authdefs.LINKS.PASS_ROOT_URL = passportConfig.rootPassportURL;
this._authdefs.LINKS.AUTH_PASSPORT_URL = "https://passport." + passportConfig.mainDomain;
}

return this._authdefs;
}
,
get pwdmng() {
return pwdMgr;
}
,
get api() {
return this._api;
}
,
get _counters() {
var counters = this._getModule("counters","/native/fx/modules/counters.jsm");
delete this._counters;
this.__defineGetter__("_counters",function () counters);
return counters;
}
,
__stringBundle: null,
get _stringBundle() {
return this.__stringBundle || (this.__stringBundle = this._api.Localization.createStringBundle("/native/fx/yauth.properties"));
}
,
setPref: function auth_setPref(strPrefName, strPrefValue) {
var prefFullName = this.api.Settings.getPackageBranchPath() + strPrefName;
var prefsModule = this.api.Settings.PrefsModule;
return prefsModule.set(prefFullName,strPrefValue);
}
,
getPref: function auth_getPref(strPrefName, defaultValue) {
var prefFullName = this.api.Settings.getPackageBranchPath() + strPrefName;
var prefsModule = this.api.Settings.PrefsModule;
return prefsModule.get(prefFullName,defaultValue);
}
,
_initialized: false,
_api: null,
_active: false,
EVENTS: {
AUTH_STATE_CHANGED: "yauth-state-changed",
LOGIN_STATE_CHANGED: "login-state-changed"},
onCountersChange: function auth_onCountersChange(flags, responseDoc) {
if (flags && flags.noAuth)
{
this.initLogoutProcess(this.user.name);
}

}
,
observe: function auth_observe(subject, topic, data) {
if (! this._loginUser && ! this._logoutUser)
{
if (this._sessionCookies.indexOf(subject) != - 1)
{
this._setSession(subject);
}
 else
{
if (this._loginCookies.indexOf(subject) != - 1)
{
this._setSessionByLogin(subject);
}

}

}

if (topic == "login-state-changed")
{
let user = subject.user;
if (data.state == this.authdefs.LOGIN_STATES.AUTH)
{
this._trySetSessionFromCookies(user.domain);
}

if (data.state == this.authdefs.LOGIN_STATES.NO_AUTH)
{
let cookie = this._getSessionCookie(user.domain);
this._setSession(cookie);
}

if (data.state != this.authdefs.LOGIN_STATES.REQUEST)
{
user.auth.removeListener("login-state-changed",this);
this._loginUser = this._logoutUser = null;
}

this._notifyListeners("login-state-changed",data);
}

if (topic == "quit-application-granted")
{
try {
User._db.close();
}
catch (e) {

}

}

}
,
_listenerAdded: function auth__listenerAdded(topic, listener) {
this._watchAuth();
}
,
_listenerRemoved: function auth_listenerRemoved(topic, listener) {
if (! this._hasListeners)
this._stopWatching();
}
,
_watchAuth: function auth__watchAuth() {
if (this._active)
return;
try {
this._trySetSessionFromCookies();
this._counters.listenResponses(this);
}
 finally {
this._active = true;
}

}
,
_stopWatching: function auth__stopWatching() {
if (! this._active)
return;
try {
this._counters.ignoreResponses(this);
this._clearCookies();
}
 finally {
this._active = false;
}

}
,
_afterLogin: function auth__afterLogin(strLogin, sessionCookie) {
var user = this._loginUser;
if (user)
{
try {
if (user.isStorePwd)
{
if (this._api.Settings.PrefsModule.get("signon.rememberSignons",false) === true)
{
pwdMgr.storeLoginDetails(user.fullNameForPassManager,user.password,user.isStorePwd,user.type);
}

}
 else
{
pwdMgr.removeUserData(user.fullNameForPassManager,user.type);
}

}
catch (e) {
this._api.logger.debug("User canceled master-password request.");
}

}
 else
{
user = this.createUser(strLogin,"",false);
}

this.addUser(user);
this._loginUser = null;
return user;
}
,
_afterLogout: function auth__afterLogout(user) {
user.auth.destroy();
this.removeUser(user);
this._logoutUser = null;
}
,
_getModule: function auth__getModule(moduleName, modulePath) {
var mScope = {
};
Cu.import(this._api.Package.resolvePath(modulePath),mScope);
var module = mScope[moduleName];
if (! module)
throw new Error("No module '" + moduleName + "' in " + modulePath);
if (typeof module.init == "function")
module.init(this._api);
return module;
}
,
_trySetSessionFromCookies: function auth__trySetSessionFromCookies() {

}
,
_setSessionByLogin: function auth__setSessionByLogin(loginCookie) {
this._debug("_setSessionByLogin:\n" + "    value: " + (loginCookie && loginCookie.value) + "," + "    uri.path: " + (loginCookie && loginCookie.uri.path) + "," + "    name: " + (loginCookie && loginCookie.name));
if (loginCookie && loginCookie.value)
{
let sessionCookie = this._getSessionCookie(loginCookie.uri.path);
if (sessionCookie && sessionCookie.value)
{
this._setSession(sessionCookie);
}

}

}
,
_setSession: function auth__setSession(sessionCookie) {
this._debug("_setSession:\n" + "    value: " + (sessionCookie && sessionCookie.value) + "," + "    uri.path: " + (sessionCookie && sessionCookie.uri.path) + "," + "    name: " + (sessionCookie && sessionCookie.name));
if (sessionCookie && sessionCookie.value)
{
let loginCookie = this._getLoginCookie(sessionCookie.uri.path);
if (loginCookie && loginCookie.value)
{
let strLogin = loginCookie.value;
let user = this._getUserForDomain(sessionCookie.uri.path);
if (! user && sessionCookie.value)
{
this._afterLogin(strLogin,sessionCookie);
this._onStateChanged(this.getTopUser(),sessionCookie);
}

}

}
 else
{
let user = sessionCookie && this._getUserForDomain(sessionCookie.uri.path);
this._debug("_logout:" + user);
if (user)
{
this._afterLogout(user);
this._onStateChanged(user,sessionCookie);
}

}

}
,
_onStateChanged: function auth__onStateChanged(user, sessionCookie) {
this._notifyListeners(this.EVENTS.AUTH_STATE_CHANGED,{
user: user,
hasAuth: ! ! (sessionCookie && sessionCookie.value)});
}
,
_getEmptyPassConfig: function auth__getEmptyPassConfig() {
return {
rootPassportURL: undefined,
mainDomain: undefined,
servedDomains: []};
}
,
get _passConfigPrefName() {
return this._api.Settings.getPackageBranchPath() + "yauth.passport.config";
}
,
__passportConfig: null,
get passportConfig() {
if (! this.__passportConfig)
{
let savedConfig = this._api.Settings.PrefsModule.get(this._passConfigPrefName,"");
if (! savedConfig)
{
let barTxtFile = this._branding.findFile("/passport/bar.txt");
if (barTxtFile)
this._passportConfig = this._createPassConfig(this._api.Files.readTextFile(barTxtFile));
}

if (! this.__passportConfig)
{
try {
this.__passportConfig = JSON.parse(savedConfig);
}
catch (e) {
this.__passportConfig = this._getEmptyPassConfig();
this._api.Settings.PrefsModule.reset(this._passConfigPrefName);
}

}

if (Math.abs(Date.now() - (this.__passportConfig.lastUpdate || 0)) > 7 * 24 * 60 * 60 * 1000)
this._refreshPassportConfig();
}

return this.__passportConfig;
}
,
set _passportConfig(config) {
if (typeof config != "object" || ! config.rootPassportURL || ! config.mainDomain || ! config.servedDomains)
throw new TypeError("Invalig passport config object");
this.__passportConfig = config;
this._api.Settings.PrefsModule.set(this._passConfigPrefName,JSON.stringify(config));
}
,
get _barTxtData() {
var barTxtURL = this.authdefs.LINKS.AUTH_PASSPORT_URL + "/bar.txt";
var ignorePass = false;
var barTxtFile = this._branding.findFile("/passport/bar.txt");
if (barTxtFile)
{
let passportDoc = this._branding.getXMLDocument("/passport/passport.xml");
if (passportDoc)
{
let barTxtNode = passportDoc.querySelector("Passport > BarTxt[url]");
barTxtURL = barTxtNode && barTxtNode.getAttribute("url") || null;
ignorePass = ! ! passportDoc.querySelector("Passport > IgnorePassXml");
}

}

this.__defineGetter__("_barTxtData",function () {
return {
url: barTxtURL,
ignorePass: ignorePass};
}
);
return this._barTxtData;
}
,
_activePassConfigRequest: null,
_refreshPassportConfig: function auth__refreshPassportConfig() {
var barTxtURL = this._barTxtData.url;
if (! barTxtURL)
return;
var reqConfig = {
bypassCache: true,
callbackFunc: this._passConfigReceiver.bind(this)};
this._activePassConfigRequest = utils.sendRequest(barTxtURL,reqConfig);
}
,
_passConfigReceiver: function auth__passConfigReceiver(reqEvent) {
var request = reqEvent.target;
if (reqEvent.type == "error" || request.status != 200)
{
let reqTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
reqTimer.initWithCallback({
notify: this._refreshPassportConfig.bind(this)},10 * 60 * 1000,reqTimer.TYPE_ONE_SHOT);
return;
}

var config = this._createPassConfig(request.responseText);
if (config.rootPassportURL)
config.lastUpdate = Date.now();
this._passportConfig = config;
this._activePassConfigRequest = null;
}
,
_createPassConfig: function auth__createPassConfig(configText) {
var config = this._getEmptyPassConfig();
try {
let configLines = configText.split(/\r?\n/);
let specialStmtPattern = /^\/:(.*)$/;
let domainToCookiesPattern = /^(.+):(.*)$/;
for (let i = 0, len = configLines.length;i < len;i++) {
let statement = configLines[i].split("#")[0];
let spStmtMatch = statement.match(specialStmtPattern);
if (spStmtMatch && ! config.rootPassportURL)
{
let uri = utils.tryCreateFixupURI(spStmtMatch[1]);
if (uri)
{
const eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"].getService(Ci.nsIEffectiveTLDService);
config.mainDomain = eTLDService.getBaseDomain(uri);
config.rootPassportURL = uri.spec.replace(/^http:/,"https:");
}

}
 else
{
let domToCookiesMatch = statement.match(domainToCookiesPattern);
if (domToCookiesMatch)
{
let cookieNames = domToCookiesMatch[2].split(",");
config.servedDomains.push({
domain: domToCookiesMatch[1],
cookieNames: cookieNames});
}

}

}

}
catch (e) {

}

return config;
}
,
_followRequiredCookies: function auth__followRequiredCookies() {

}
,
_checkIfCookiesAllowed: function auth_checkIfCookiesAllowed() {
const cookiePermission = Cc["@mozilla.org/cookie/permission;1"].getService(Ci.nsICookiePermission);
var authMainDomainURI = utils.newURI("http://" + this.authdefs.DOMAINS.MAIN_DOMAIN);
cookiePermission.setAccess(authMainDomainURI,1);
var cookieBehaviorValue = this._prefSrv.getIntPref("network.cookie.cookieBehavior");
return ! (cookieBehaviorValue === 1 || cookieBehaviorValue === 2);
}
,
getYandexCookie: function auth_getYandexCookie(aCookieName, aCheckExpired, aCookiePath) {
return this.findCookieValue(aCookieName,aCheckExpired,aCookiePath,false);
}
,
findCookieValue: function auth__findCookieValue(strCookieName, bCheckExpired, strCookiePath, bStrictMatch) {
var mainYandexDomain = this.authdefs.DOMAINS.MAIN_DOMAIN;
if (! mainYandexDomain)
return undefined;
if (! strCookiePath)
strCookiePath = "/";
return this._api.Network.findCookieValue("http://" + mainYandexDomain + strCookiePath,strCookieName,true,bCheckExpired,bStrictMatch);
}
,
_debug: function auth__debug(message) {
if (this._api)
{
this._api.logger.debug(message);
}
 else
{
Cu.reportError("yAuth can't log message through native API!\n" + message);
}

}
};
const mfdauth = {
__proto__: new _auth(),
isNativeUser: function mfdauth_isNativeUser(strUsername) {
if (strUsername)
{
let domain = strUsername.split("@")[1];
return this.isNativeDomain(domain);
}

return false;
}
,
isNativeDomain: function mfdauth_isNativeDomain(strDomain) {
return strDomain && /.+\.[a-z]+$/i.test(strDomain);
}
,
get liveUsers() {
var logins = pwdMgr.getSavedLogins([this.authdefs.USER_TYPES.USER_MFD]);
var savedUsers = [];
logins.forEach((function (login) {
if (! this.getUser(login))
savedUsers.push(this.createUser(login,pwdMgr.getStoredPassword(login)));
}
).bind(this));
var userNames = this._users.map(function (u) u.fullNameForPassManager);
return this._users.reverse().concat(savedUsers.filter(function (u) userNames.indexOf(u.fullNameForPassManager) == - 1)).sort(function (a, b) a.displayName > b.displayName);
}
,
_getLoginCookie: function mfdauth__getLoginCookie(pathOrDomain) {
var path = "/for/" + encodeURIComponent(decodeURIComponent(pathOrDomain.replace("/for/","")));
for(let [, item] in Iterator(this._loginCookies)) {
if (item.uri.path === path)
{
return item;
}

}

return null;
}
,
_getSessionCookie: function mfdauth__getSessionCookie(pathOrDomain) {
var path = "/for/" + encodeURIComponent(decodeURIComponent(pathOrDomain.replace("/for/","")));
for(let [, item] in Iterator(this._sessionCookies)) {
if (item.uri.path === path)
{
return item;
}

}

return null;
}
,
_getUserForDomain: function mfdauth__getUserForDomain(strPathOrDomain) {
var domain = decodeURIComponent(strPathOrDomain.replace("/for/",""));
for each(let user in this._users) {
if (user.domain === domain)
{
return user;
}

}

return null;
}
,
EVENTS: {
AUTH_STATE_CHANGED: "mfdauth-state-changed",
LOGIN_STATE_CHANGED: "login-state-changed"},
get authdefsUserType() {
return this.authdefs.USER_TYPES.USER_MFD;
}
,
createUser: function mfdauth_createUser(strUsername, strPassword, isStorePwd) {
return new _MFDUser(strUsername, strPassword, isStorePwd);
}
,
onMailCountersChange: function mfdauth_onCountersChange(flags, arrDomains) {
if (! flags || ! flags.noAuth || ! arrDomains)
return;
arrDomains.forEach((function (strDomain) {
var user = this._getUserForDomain(strDomain);
if (user)
{
this.initLogoutProcess(user.name);
}

}
).bind(this));
}
,
_onInitLoginProcess: function mfdauth__onInitLoginProcess(user) {
this.__proto__._onInitLoginProcess.apply(this,arguments);
var domainURI = utils.newURI("http://" + this.authdefs.DOMAINS.MAIN_DOMAIN + "/for/" + user.domain,null,null);
var sessionCookie = new this._api.Network.Cookie(this.COOKIE_SESSION_ID, domainURI, true);
this._addSessionCookie(sessionCookie);
var loginCookie = new this._api.Network.Cookie(this.COOKIE_LOGIN, domainURI, true);
this._addLoginCookie(loginCookie);
}
,
initLogoutAll: function mfdauth_initLogoutAll() {
for(let [, user] in Iterator(this.users)) user.auth.destroy();
this._manualResetUsedCookies();
}
,
_manualResetUsedCookies: function mfdauth__manualResetUsedCookies(strDomain) {
const cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
var pathRegex = new RegExp("^/for" + (strDomain ? "/" + strDomain : ""));
var arrCookies = this._getCookies({
path: pathRegex,
name: this.COOKIE_SESSION_ID});
this._debug("_manualResetUsedCookies:" + arrCookies.length + "," + strDomain);
for(let [, cookie] in Iterator(arrCookies)) {
cookieManager.remove(cookie.host,cookie.name,cookie.path,false);
}

}
,
_onStateChanged: function mfdauth__onStateChanged(user, sessionCookie) {
this._notifyListeners(this.EVENTS.AUTH_STATE_CHANGED,{
user: user,
hasAuth: ! ! sessionCookie.value});
}
,
_afterLogin: function mfdauth__afterLogin(strLogin, sessionCookie) {
var user = this.__proto__._afterLogin.apply(this,arguments);
user.update({
sessionId: sessionCookie.value});
var loginCookie = this._getLoginCookie(user.domain);
if (loginCookie)
{
this._removeLoginCookie(loginCookie);
}

}
,
_afterLogout: function mfdauth__afterLogout(user, sessionCookie) {
this.__proto__._afterLogout.apply(this,arguments);
var sessionCookie = this._getSessionCookie(user.domain);
this._removeSessionCookie(sessionCookie);
}
,
COOKIE_LOGIN: "yandex_login",
COOKIE_SESSION_ID: "Eda_id",
_trySetSessionFromCookies: function mfdauth__trySetSessionFromCookies(strDomain) {
if (! this._checkIfCookiesAllowed())
return;
var pathRegex = new RegExp("^/for" + (strDomain ? "/" + strDomain : ""));
var cookies = this._getCookies({
path: pathRegex,
name: this.COOKIE_SESSION_ID});
cookies.forEach(function (cookie) {
var domainURI = utils.newURI("http://" + this.authdefs.DOMAINS.MAIN_DOMAIN + cookie.path,null,null);
var sessionCookie = new this._api.Network.Cookie(this.COOKIE_SESSION_ID, domainURI, true);
this._addSessionCookie(sessionCookie);
var loginCookie = new this._api.Network.Cookie(this.COOKIE_LOGIN, domainURI, true);
this._addLoginCookie(loginCookie);
this._setSession(sessionCookie);
}
,this);
}
,
_getCookies: function mfdauth__getCookies(cookiesProps) {
var timeNow = parseInt(Date.now() / 1000,10);
var arrCookies = [];
var cookies = this._api.Network.getCookiesFromHost("." + this.authdefs.DOMAINS.MAIN_DOMAIN);
for(let cookie in cookies) {
if (cookie.expires == 0 || timeNow < cookie.expires)
{
let result = true;
for(let [propName, propValue] in Iterator(cookiesProps)) {
result = result && (propValue instanceof RegExp && propValue.test(cookie[propName]) || cookie[propName] == propValue);
}

if (result)
{
arrCookies.push(cookie);
}

}

}

return arrCookies;
}
,
_checkCookiesReset: function mfdauth__checkCookiesReset(strUserName) {
var existedUser = this._getUserForDomain(strUserName.split("@")[1]);
if (existedUser)
{
this._manualResetUsedCookies(existedUser.domain);
}

}
,
_counters: {
listenResponses: function () {

}
,
ignoreResponses: function () {

}
},
observe: function mfdauth_observe(subject, topic, data) {
this.__proto__.observe.apply(this,arguments);
if (topic != "cookie-changed")
return;
try {
subject.QueryInterface(Ci.nsICookie2);
}
catch (e) {

}

if (! (subject && subject instanceof Ci.nsICookie2))
return;
if (! subject.value)
return;
if (subject.path.indexOf("/for/") == - 1)
return;
var user = this._getUserForDomain(subject.path);
if (user)
return;
if (subject.name == this.COOKIE_SESSION_ID)
{
let domainURI = utils.newURI("http://" + this.authdefs.DOMAINS.MAIN_DOMAIN + subject.path,null,null);
let sessionCookie = new this._api.Network.Cookie(this.COOKIE_SESSION_ID, domainURI, true);
this._addSessionCookie(sessionCookie);
this._setSession(sessionCookie);
}

if (subject.name == this.COOKIE_LOGIN)
{
let domainURI = utils.newURI("http://" + this.authdefs.DOMAINS.MAIN_DOMAIN + subject.path,null,null);
let loginCookie = new this._api.Network.Cookie(this.COOKIE_LOGIN, domainURI, true, true);
this._addLoginCookie(loginCookie);
this._setSessionByLogin(loginCookie);
}

}
};
const yauth = {
__proto__: new _auth(),
isNativeUser: function yauth_isNativeUser(strUsername) {
if (strUsername)
{
let domain = strUsername.split("@")[1];
return this.isNativeDomain(domain);
}

return false;
}
,
isNativeDomain: function yauth_isNativeDomain(strDomain) {
return ! strDomain || /^(yandex\.(ru|ua|by|kz|net|com(\.tr)?)|(ya|narod)\.ru)$/i.test(strDomain);
}
,
get liveUsers() {
var logins = pwdMgr.getSavedLogins([this.authdefs.USER_TYPES.USER_YANDEX]);
var savedUsers = [];
logins.forEach((function (login) {
if (! this.getUser(login))
{
savedUsers.push(this.createUser(login,pwdMgr.getStoredPassword(login)));
}

}
).bind(this));
return this._users.concat(savedUsers).sort(function (a, b) a.displayName > b.displayName);
}
,
_getLoginCookie: function yauth__getLoginCookie() {
return this._loginCookies[0];
}
,
_getSessionCookie: function yauth__getSessionCookie() {
return this._sessionCookies[0];
}
,
_getUserForDomain: function yauth__getUserForDomain() {
return this.getTopUser();
}
,
createUser: function yauth_createUser(strUsername, strPassword, isStorePwd) {
return new _User(strUsername, strPassword, isStorePwd);
}
,
get username() {
if (this.user)
{
return this.user.name;
}

return null;
}
,
get displayName() {
if (this.user)
{
return this.user.displayName;
}

return null;
}
,
initLoginProcess: function yauth_initLoginProcess(strUserName) {
if (this._checkLoginConditions(strUserName))
{
this._resetAuthDynamicRequests();
if (this.authorized)
{
let args = arguments;
this._sendAuthDynamicDataLogout((function () {
this.__proto__.initLoginProcess.apply(this,args);
}
).bind(this));
return true;
}

return this.__proto__.initLoginProcess.apply(this,arguments);
}

;
return false;
}
,
_afterLogin: function yauth__afterLogin(strLogin, sessionCookie) {
this.clearUsers();
var displayName = "";
var authType = this.authdefs.USER_TYPES.USER_YANDEX;
var authProvider = "";
var udn = this._getUDNValue();
if (udn)
{
let match;
if (match = udn.match(/^p:(.+)$/))
{
displayName = match[1];
}
 else
if (match = udn.match(/^s:.+:(.+):(.+)$/))
{
authType = this.authdefs.USER_TYPES.USER_FOREIGN;
authProvider = match[1];
displayName = match[2];
}
 else
{
displayName = udn;
}

}

var loginUser = this._loginUser;
var user = this.__proto__._afterLogin.apply(this,arguments);
user.update({
displayName: displayName || user.displayName,
type: authType,
authProvider: authProvider,
sessionId: sessionCookie.value});
if (loginUser && loginUser.domain == user.domain)
this._sendAuthDynamicDataLogin();
}
,
_afterLogout: function yauth__afterLogout(user) {
if (this._logoutUser && this._logoutUser.domain == user.domain)
this._sendAuthDynamicDataLogout();
this.__proto__._afterLogout.apply(this,arguments);
}
,
COOKIE_SESSION_ID: "Session_id",
COOKIE_LOGIN: "yandex_login",
get authdefsUserType() {
return this.authdefs.USER_TYPES.USER_YANDEX;
}
,
_checkCookiesReset: function yauth__checkCookiesReset() {
if (this.user)
{
this._manualResetUsedCookies();
}

}
,
_trySetSessionFromCookies: function yauth__trySetSessionFromCookies(checkCookiesExpiration) {
if (this._checkIfCookiesAllowed())
this._followRequiredCookies();
}
,
_followRequiredCookies: function yauth__followRequiredCookies() {
var yandexURI = utils.newURI("https://" + this.authdefs.DOMAINS.MAIN_DOMAIN + "/",null,null);
var sessionCookie = new this._api.Network.Cookie(this.COOKIE_SESSION_ID, yandexURI, true);
this._addSessionCookie(sessionCookie);
var loginCookie = new this._api.Network.Cookie(this.COOKIE_LOGIN, yandexURI, true);
this._addLoginCookie(loginCookie);
this._setSession(sessionCookie);
}
,
_sendAuthDynamicDataLogin: function yauth__sendAuthDynamicDataLogin(successCallback, errorCallback) {
if (this._barTxtData.ignorePass)
{
if (errorCallback)
errorCallback();
}
 else
{
let url = this.authdefs.LINKS.PASS_ROOT_URL + "xml/login" + "?" + utils.getNCRndStr();
this._loginAuthDynamic = this._getAuthDynamicData(url,successCallback,errorCallback);
}

}
,
_sendAuthDynamicDataLogout: function yauth__sendAuthDynamicDataLogout(callback) {
var errorCallback = (function errorCallback() {
this._manualResetUsedCookies();
if (callback)
callback();
}
).bind(this);
if (this._barTxtData.ignorePass)
{
errorCallback();
}
 else
{
let url = this.authdefs.LINKS.PASS_ROOT_URL + "xml/logout" + "?" + utils.getNCRndStr();
this._logoutAuthDynamic = this._getAuthDynamicData(url,callback,errorCallback);
}

}
,
_resetAuthDynamicRequests: function yauth__resetAuthDynamicRequest() {
if (this._loginAuthDynamic && this._loginAuthDynamic.channel && this._loginAuthDynamic.channel.isPending())
{
this._loginAuthDynamic.channel.cancel(Components.results.NS_BINDING_ABORTED);
}

if (this._logoutAuthDynamic && this._logoutAuthDynamic.channel && this._logoutAuthDynamic.channel.isPending())
{
this._logoutAuthDynamic.channel.cancel(Components.results.NS_BINDING_ABORTED);
}

}
,
_getAuthDynamicData: function yauth__getAuthDynamicData(strURL, successCallback, errorCallback) {
var timeDiff = Math.abs(Date.now() - this._lastLoginCookiesManagement);
if (timeDiff < 1000)
{
this._debug("Warning: too small diff (" + timeDiff + " ms) from last login cookies management.");
return;
}

return utils.sendRequest(strURL,{
bypassCache: true,
callbackFunc: this._getAuthDynamicDataCallback.bind(this,successCallback,errorCallback)});
}
,
_getAuthDynamicDataCallback: function yauth__getAuthDynamicDataCallback(successCallback, errorCallback, req) {
if (! utils.isReqError(req))
{
this._manageCookies(req.target.responseText);
if (successCallback)
successCallback();
}
 else
{
if (errorCallback)
errorCallback();
}

}
,
_lastLoginCookiesManagement: 0,
_manualResetUsedCookies: function yauth__manualResetUsedCookies() {
var presentHosts = utils.getBrowserHostCookies();
const cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
for(let [, domainInfo] in Iterator(this.passportConfig.servedDomains)) {
let hostReg = new RegExp("^" + domainInfo.domain.replace(/(\-|\.)/g,"\\$1").replace(/^(\*\\\.)/,"(.*\\.)?") + "$", "g");
for(let presentHost in presentHosts) {
if (hostReg.test(presentHost))
{
let presentCookies = presentHosts[presentHost];
for each(let staticName in domainInfo.cookieNames) {
let i = presentCookies.length;
while (--i > - 1) {
let presentCookie = presentCookies[i];
if (staticName == presentCookie.name && presentCookie.path === "/")
{
cookieManager.remove(presentCookie.host,presentCookie.name,presentCookie.path,false);
presentCookies.splice(i,1);
}

}

}

}

}

}

}
,
_getUDNValue: function yauth__getUDNValue() {
return utils.utf8Tounicode(atob(this._getYCookieField("udn")));
}
,
_getYCookieField: function yauth__getYCookieField(fieldName) {
var ysCookieValue = this.getYandexCookie("ys");
if (ysCookieValue)
{
let reg = new RegExp("(?:^|#)" + utils.escapeRE(fieldName) + "\\.([^#]+)");
let match = ysCookieValue.match(reg);
if (match)
return match[1];
}

var ypCookieValue = this.getYandexCookie("yp");
if (ypCookieValue)
{
let reg = new RegExp("(?:^|#)(?:\\d+)\\." + utils.escapeRE(fieldName) + "\\.([^#]+)");
let match = ypCookieValue.match(reg);
if (match)
{
return match[1];
}

}

return null;
}
,
_manageCookies: function yauth__manageCookies(strXML) {
this._lastLoginCookiesManagement = Date.now();
var cookiesDOMXml = this._api.XMLUtils.getDOMParser(null,null,false).parseFromString(strXML,"text/xml");
if (! cookiesDOMXml.querySelector("domain"))
return;
const cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
const cookieService = Cc["@mozilla.org/cookieService;1"].getService().QueryInterface(Ci.nsICookieService);
var presentHosts = utils.getBrowserHostCookies();
var timeNow = Date.now();
var timeNowSec = parseInt(timeNow / 1000,10);
var domains = cookiesDOMXml.querySelectorAll("domain");
for (let i = 0, length = domains.length;i < length;i++) {
let domainId = domains[i].getAttribute("id");
if (! domainId)
continue;
let childs = domains[i].childNodes;
for (let j = 0, childsLength = childs.length;j < childsLength;j++) {
if (childs[j].nodeType !== childs[j].ELEMENT_NODE)
continue;
let action = childs[j].localName;
if (! (action == "remove" || action == "set"))
continue;
let cookies = childs[j].querySelectorAll("cookie");
for (let k = 0, cookiesLength = cookies.length;k < cookiesLength;k++) {
let cookieName = cookies[k].getAttribute("id");
if (cookieName > "")
{
let cookiePath = cookies[k].getAttribute("path") || "/";
switch (action) {
case "remove":
cookieManager.remove(domainId,cookieName,cookiePath,false);
break;
case "set":
let maxAge = + cookies[k].getAttribute("max-age");
if (cookies[k].getAttribute("override") != "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 cookieStrArray = ["" + cookieName + "=" + cookies[k].firstChild.nodeValue];
if (domainId.charAt(0) == ".")
cookieStrArray.push("domain=" + domainId);
cookieStrArray.push("path=" + cookiePath);
if (maxAge > 0)
cookieStrArray.push("expires=" + (new Date(timeNow + maxAge * 1000)).toGMTString());
if (cookies[k].getAttribute("http-only") === "1")
cookieStrArray.push("HttpOnly");
if (cookies[k].getAttribute("secure") === "1")
cookieStrArray.push("secure");
cookieService.setCookieStringFromHttp(uri,uri,null,cookieStrArray.join(";"),maxAge > 0 ? (new Date(timeNow)).toGMTString() : "",null);
}

break;
default:
break;
}

}

}

}

}

}
};
function _AuthProcess(user) {
this.user = user;
this._connections = {
login: null,
logout: null};
this._loginState = null;
this.__proto__.__proto__ = utils.NotificationSource.prototype;
utils.NotificationSource.apply(this);
}

_AuthProcess.prototype = {
_getLoginPassUrl: function AuthProcess__getLoginPassUrl() {
return yauth.authdefs.LINKS.AUTH_PASSPORT_URL + "/passport?mode=auth";
}
,
_getLogoutPassUrl: function AuthProcess__getLogoutPassUrl() {
return yauth.authdefs.LINKS.AUTH_PASSPORT_URL + "/passport?mode=logout";
}
,
getPassURL: function AuthProcess_getPassURL(strMode) {
var url = (strMode === "auth" ? this._getLoginPassUrl() : this._getLogoutPassUrl()) + "&target=bar" + "&ver=ff" + encodeURIComponent(yauth.api.Environment.addon.version || "");
if (strMode === "logout")
{
url += "&yu=" + encodeURIComponent(yauth.getYandexCookie("yandexuid",false) || "");
}

return url;
}
,
get loginState() {
return this._loginState;
}
,
set loginState(intValue) {
var newLoginStateValue = parseInt(intValue,10);
if (this._loginState !== newLoginStateValue)
{
if (newLoginStateValue < yauth.authdefs.LOGIN_STATES.NO_AUTH || newLoginStateValue > yauth.authdefs.LOGIN_STATES.AUTH)
{
return this._loginState;
}

this._loginState = newLoginStateValue;
this._notifyListeners("login-state-changed",{
username: this.user.fullName,
state: newLoginStateValue});
}

return this._loginState;
}
,
destroy: function AuthProcess_destroy() {
this._abortConnection("login");
this._abortConnection("logout");
}
,
start: function AuthProcess_start(strPassword, bTwoWeeks, strAuthType, loginCallback) {
this._abortConnection("logout");
this.loginState = yauth.authdefs.LOGIN_STATES.REQUEST;
this._startLoginProcess(strPassword,bTwoWeeks,loginCallback);
}
,
cancel: function AuthProcess_cancel(errorCallback) {
this.loginState = yauth.authdefs.LOGIN_STATES.REQUEST;
this._startLogoutConnection(errorCallback);
}
,
_abortConnection: function AuthProcess__abortConnection(strConnectionType) {
var connection = this._connections[strConnectionType];
try {
if (connection && connection.channel && connection.channel.isPending())
{
connection.channel.cancel(Components.results.NS_BINDING_ABORTED);
}

}
catch (ex) {

}

delete this._connections[strConnectionType];
}
,
_startLogoutConnection: function AuthProcess__startLogoutConnection(errorCallback) {
this._abortConnection("login");
this._connections.logout = utils.sendRequest(this.getPassURL("logout"),{
background: true,
bypassCache: false,
callbackFunc: this._startLogoutConnectionCallback.bind(this,errorCallback)});
}
,
_startLogoutConnectionCallback: function AuthProcess__startLogoutConnectionCallback(errorCallback, req) {
if (utils.isReqError(req))
{
if (errorCallback)
errorCallback();
this.loginState = yauth.authdefs.LOGIN_STATES.NET_ERROR;
}
 else
{
this.loginState = yauth.authdefs.LOGIN_STATES.NO_AUTH;
}

}
,
_startLoginProcess: function AuthProcess__startLoginProcess(strPassword, bTwoWeeks, loginCallback) {
if (! yauth.passportConfig.mainDomain)
{
this.loginState = yauth.authdefs.LOGIN_STATES.NET_ERROR;
}
 else
{
this._startLoginConnection(strPassword,bTwoWeeks,loginCallback);
}

}
,
_startLoginConnection: function AuthProcess__startLoginConnection(strPassword, bTwoWeeks, loginCallback) {
this._abortConnection("logout");
var retpath = yauth.authdefs.LINKS.AUTH_PASSPORT_URL + "/passport?mode=passport&target=bar" + "&ver=ff" + encodeURIComponent(yauth.api.Environment.addon.version || "");
var data = "login=" + encodeURIComponent(this.user.fullName) + "&passwd=" + encodeURIComponent(strPassword) + "&retpath=" + encodeURIComponent(retpath) + "&timestamp=" + Date.now();
if (bTwoWeeks)
data += "&twoweeks=yes";
var callback = function passReqCallback(req) {
var state;
if (! utils.isReqError(req))
{
let successLogin = this.isAuthorized;
if (! successLogin)
{
let warningText = req.target.getResponseHeader("Warning");
if (/showcaptcha/.test(warningText))
{
state = yauth.authdefs.LOGIN_STATES.CAPTCHA_ERROR;
}
 else
{
state = yauth.authdefs.LOGIN_STATES.LOGIN_FAIL;
}

}
 else
{
state = yauth.authdefs.LOGIN_STATES.AUTH;
}

}
 else
{
state = yauth.authdefs.LOGIN_STATES.NET_ERROR;
}

this.loginState = state;
}
;
var reqParams = {
bypassCache: false,
data: data,
referrer: retpath,
background: true,
callbackFunc: callback.bind(this)};
this._connections.login = utils.sendRequest(this.getPassURL("auth"),reqParams);
}
,
get isAuthorized() {
return yauth.findCookieValue(yauth.COOKIE_SESSION_ID,false,"/",false);
}
};
function _MFDAuthProcess(user) {
_AuthProcess.apply(this,arguments);
function isAuthorized() mfdauth.findCookieValue(mfdauth.COOKIE_SESSION_ID,false,"/for/" + this.user.domain,false)
this.__defineGetter__("isAuthorized",isAuthorized);
this._getLoginPassUrl = function _MFDAuthProcess_getLoginPassUrl() {
return mfdauth.authdefs.LINKS.AUTH_PASSPORT_URL + (this.user.domain ? "/for/" + this.user.domain : "") + "/passport?mode=mdauth";
}
;
this._getLogoutPassUrl = function _MFDAuthProcess_getLoginPassUrl() {
return mfdauth.authdefs.LINKS.AUTH_PASSPORT_URL + (this.user.domain ? "/for/" + this.user.domain : "") + "/passport?mode=logout";
}
;
}

_MFDAuthProcess.prototype = _AuthProcess.prototype;
function _User(strUsername, strPwd, isStorePwd) {
this._strPwd = strPwd;
this._isStorePwd = isStorePwd;
var [name, domain] = strUsername.split("@");
if (! domain || /^(yandex|narod|ya)(\.com)?\.[a-z]{2,3}$/i.test(domain))
domain = yauth.authdefs.DOMAINS.MAIN_DOMAIN;
this._fullName = (name + "@" + domain).toLowerCase();
this._displayName = this._fullName.split("@")[0].replace(/\./g,"-");
this._login = this._fullName.split("@")[0].replace(/\./g,"-");
this._strType = yauth.authdefs.USER_TYPES.USER_YANDEX;
this._authorized = false;
this._init();
}

_User.prototype = {
_init: function User__init() {
this.auth = new _AuthProcess(this);
this.__proto__.__proto__ = User.prototype;
var username = this._fullName.split("@")[0].replace(/\./g,"-");
User.apply(this,[username]);
}
,
get authorized() {
return this._authorized;
}
,
set authorized(val) {
this._authorized = ! ! val;
}
,
get id() {
if (this.sessionId)
{
return this.sessionId.split(".")[3];
}

return 0;
}
,
get login() {
return this._login;
}
,
get domain() {
return this._fullName.split("@")[1];
}
,
get domainIsMain() {
return this.domain == yauth.authdefs.DOMAINS.MAIN_DOMAIN;
}
,
get fullName() {
return this._fullName;
}
,
get fullNameForPassManager() {
return this.fullName.split("@" + yauth.authdefs.DOMAINS.MAIN_DOMAIN)[0];
}
,
get displayName() {
return this._displayName;
}
,
set displayName(str) {
this._displayName = str;
}
,
get password() {
return this._strPwd;
}
,
get isStorePwd() {
return this._isStorePwd;
}
,
get type() {
return this._strType;
}
,
set _type(val) {
this._strType = val;
}
,
get authProvider() {
return this._strAuthProvider;
}
,
set _authProvider(val) {
this._strAuthProvider = val;
}
,
get sessionId() {
return this._strSessionId;
}
,
set _sessionId(str) {
this._strSessionId = str;
}
,
update: function User_update(data) {
for(let prop in data) {
this["_" + prop] = data[prop];
}

}
,
toString: function User_toString() {
return this.name;
}
};
function _MFDUser(strUsername, strPwd, isStorePwd) {
this._init = function MFDUser__init() {
this._strType = mfdauth.authdefs.USER_TYPES.USER_MFD;
this._login = this.fullName.split("@")[0];
this.auth = new _MFDAuthProcess(this);
this.__proto__.__proto__ = User.prototype;
User.apply(this,[this._fullName]);
}
;
_User.apply(this,arguments);
}

_MFDUser.prototype = _User.prototype;
function _openAuthDialog(event, dialogParams, isForceLogin, onAuthedCallback, onDlgEventCallback) {
var dlgman = this._getModule("dlgman","/native/fx/modules/dlgman.jsm");
var onDlgCloseCallback;
if (! this.authorized && onAuthedCallback)
{
let me = this;
let observer = {
observe: function _openAuthDialog_observe(subject, topic, data) {
if (topic == me.EVENTS.AUTH_STATE_CHANGED)
{
if (me.authorized)
{
if (onAuthedCallback)
onAuthedCallback();
}

me.removeListener(me.EVENTS.AUTH_STATE_CHANGED,this);
}

}
};
onDlgCloseCallback = function onDlgCloseCallback() {
me.removeListener(me.EVENTS.AUTH_STATE_CHANGED,observer);
}
;
this.addListener(this.EVENTS.AUTH_STATE_CHANGED,observer);
}

dlgman.openAuthDialog(this,event,dialogParams,isForceLogin,onDlgEventCallback,onDlgCloseCallback);
}

;
