/*
Overriding default to support Dailex user token validation within cookie auto login flow
491319
private function registerRememberMeServices(Container $app)
    {
        $app['security.remember_me.service._proto'] = $app->protect(function ($providerKey, $options) use ($app) {
            return function () use ($providerKey, $options, $app) {
                $options = array_replace([
                    'name' => 'REMEMBERME',
                    'lifetime' => 31536000,
                    'path' => '/',
                    'domain' => null,
                    'secure' => false,
                    'httponly' => true,
                    'always_remember_me' => false,
                    'remember_me_parameter' => '_remember_me',
                ], $options);

                return new UserTokenBasedRememberMeServices(
                    [$app['security.user_provider.'.$providerKey]],
                    $options['key'],
                    $providerKey,
                    $options,
                    $app['logger']
                );
            };
        });
    }
185298
function (methodInvocation, options) {
  for (var i = 0; i < loginHandlers.length; ++i) {
    var handler = loginHandlers[i];

    var result = tryLoginMethod(
      handler.name,
      function () {
        return handler.handler.call(methodInvocation, options);
      }
    );

    if (result)
      return result;
    else if (result !== undefined)
      throw new Meteor.Error(400, "A login handler should return a result or undefined");
  }

  return {
    type: null,
    error: new Meteor.Error(400, "Unrecognized options for login request")
  };
}
506860
function(user) {
      if (Parse.User._currentUser !== user) {
        Parse.User.logOut();
      }
      user._isCurrentUser = true;
      Parse.User._currentUser = user;
      Parse.User._currentUserMatchesDisk = true;

      var json = user.toJSON();
      json._id = user.id;
      json._sessionToken = user._sessionToken;
      Parse.localStorage.setItem(
          Parse._getParsePath(Parse.User._CURRENT_USER_KEY),
          JSON.stringify(json));
    }
931609
private function cookieLogin()
    {
        $read = new Read();
        $prazoTokenExpira = date('Y-m-d H:i:s', strtotime("-2 months", strtotime(date("Y-m-d H:i:s"))));
        $read->exeRead("usuarios", "WHERE token = :to", "to={$_COOKIE['token']}");

        if ($read->getResult() && $read->getResult()[0]['status'] === 1 && $read->getResult()[0]['token_expira'] > $prazoTokenExpira) {
            $login = new Login();
            $login->setLogin(["user" => $read->getResult()[0]['nome'], "password" => $read->getResult()[0]['password']]);
        } else {
            new Logout();
        }
    }
751231
function init(ctx) {
        var server = ctx.server;

        if (!privateKey) {
            throw new Error('Please set config.security.token.privateKey');
        }

        server.ext('onPreAuth', validateToken);

        return new Q(ctx);
    }
686600
function init(ctx) {
        var server = ctx.server;
        var deferred = Q.defer();

        server.register({register: require('bell')}, function (err) {

            if (err) {
                deferred.reject(err);
                return;
            }

            _.each(config.security.social, function (providerConfig, providerName) {
                var opts = _.extend({}, config.security.cookie, {
                    'cookie': 'bell-' + providerName,
                    'clientId': providerConfig.appId,
                    'clientSecret': providerConfig.appSecret,
                    'isSecure': config.useSSL,
                    'forceHttps': config.useSSL,
                    'provider': getProvider(providerName, providerConfig)
                });

                server.auth.strategy(providerName, 'bell', opts);
            });

            deferred.resolve();
        });

        return deferred.promise.then(function () {
            return Q.when(ctx);
        });
    }
258671
function ensureValidJWTCookie(request) {
    const originalRequest = request;
    const isAuthUrl = authenticatedAPIClient.isAuthUrl(originalRequest.url);
    const accessToken = authenticatedAPIClient.getDecodedAccessToken();
    const tokenExpired = authenticatedAPIClient.isAccessTokenExpired(accessToken);
    if (isAuthUrl || !tokenExpired) {
      return request;
    }

    if (!queueRequests) {
      queueRequests = true;
      authenticatedAPIClient.refreshAccessToken()
        .then(() => {
          queueRequests = false;
          PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: true });
        })
        .catch((error) => {
          // If no callback is supplied frontend-auth will (ultimately) redirect the user to login.
          // The user is redirected to logout to ensure authentication clean-up, which in turn
          // redirects to login.
          if (authenticatedAPIClient.handleRefreshAccessTokenFailure) {
            authenticatedAPIClient.handleRefreshAccessTokenFailure(error);
          } else {
            authenticatedAPIClient.logout();
          }
          PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: false });
        });
    }

    return new Promise((resolve, reject) => {
      logInfo(`Queuing API request ${originalRequest.url} while access token is refreshed`);
      PubSub.subscribeOnce(ACCESS_TOKEN_REFRESH, (msg, { success }) => {
        if (success) {
          logInfo(`Resolving queued API request ${originalRequest.url}`);
          resolve(originalRequest);
        } else {
          reject(originalRequest);
        }
      });
    });
  }
1090035
function(user, passwd){
                //setter only

                validators.string(user);
                validators.string(passwd);
                data.auth = {
                    user : user,
                    passwd : passwd
                };

                return this;
            }
671507
function() {

            // We perform the bindings so that every function works
            // properly when it is passed as a callback.
            this.get                = utils.bind(this, this.get);
            this.del                = utils.bind(this, this.del);
            this.post               = utils.bind(this, this.post);
            this.request            = utils.bind(this, this.request);
            this._buildResponse     = utils.bind(this, this._buildResponse);

            // Set our default version to "none"
            this._setSplunkVersion("none");

            // Cookie store for cookie based authentication.
            this._cookieStore = {};
        }
147666
function init(ctx) {
  let token = ctx.cookies.get('pToken') || ctx.request.header.token
  if (token) {
    ctx.response.append('token', token)
    ctx.request.header.token = token
  }
  let userId = ctx.cookies.get('userId') || ctx.request.header.userid
  if (userId) {
    ctx.response.append('userid', userId)
    ctx.request.header.userid = userId
  }
  let accountId = ctx.cookies.get('accountId') || ctx.request.header.accountid
  if (accountId) {
    ctx.response.append('accountid', accountId)
    ctx.request.header.accountid = accountId
  }
  let companyId = ctx.cookies.get('companyId') || ctx.request.header.companyid
  if (companyId) {
    ctx.response.append('companyid', companyId)
    ctx.request.header.companyid = companyId
  }
  ctx.user = {
    companyid: companyId,
    accountid: accountId,
    userid: userId,
    language: ctx.cookies.get('language') || 'zh'
  }
}
1252579
private void configureStateAuth() {
        setIsControlEnable(authButton, false);
        if(isAuthenticated()) {
            authStatusLabel.setText(I18nLabelsLoader.ADDON_LOGIN_STATUS_OK);
            setDefaultButton(nextButtonName, true);
            if(userPasswordText.getText() != null && userPasswordText.getText().length() == 0) {
                userPasswordText.setText("********");
            }            
            setDefaultButton(authButton, false);
            setDefaultButton(cancelButtonName, false);
            setDefaultButton(nextButtonName, true);
        } else if (gotCommunicationError) {
            // leave previous state
            setIsControlEnable(authButton, true);
            setDefaultButton(cancelButtonName, true);
        }
    }
201596
@Override
    public void validateDefault(InputProblemReporter rep, boolean normalize)
        throws XMLStreamException
    {
        String def = validateDefaultNmToken(rep, normalize);
        if (normalize) {
            mDefValue.setValue(def);
        }
    }
367524
public void isValidLogin( AsyncCallback<Boolean> responder )
  {
    String userToken = UserTokenStorageFactory.instance().getStorage().get();
    if( userToken != null && !userToken.equals( "" ) )
    {
      Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "isValidUserToken", new Object[] { userToken }, responder );
    }
    else
    {
      responder.handleResponse( CurrentUser() != null );
    }
  }
1158747
function doLogin (opts, csrf, email, password) {
  return fetch(`${opts.host}/_/auth/login`, json({
    ...opts,
    method: 'post',
    body: { csrf, email, password }
  })).then((response) => props({
    session: getSessionCookie(response.headers.get('set-cookie')),
    body: getJSON(response)
  }))
}
1294839
function(request, username, password, callback) {
    const user = users[username];
    if (!user) {
        return callback(null, false);
    }
    const isValid = password === user.password;
    callback(null, isValid, { id: user.id, name: user.name });
}
245470
function(username, pw) {
    return _.ajax({
      verb: 'POST',
      url: '/login',
      data: {
        username: username,
        password: pw
      }
    }).then(function(id) {
      document.cookie = 'user=' + id;
      return id;
    });
  }
152659
function get_jwt_token(ctx)
{
	// Parses "Authorization: Bearer ${token}"
	if (ctx.header.authorization)
	{
		const match = ctx.header.authorization.match(/^Bearer (.+)$/i)

		if (match)
		{
			return match[1]
		}
	}

	// (doesn't read cookies anymore to protect users from CSRF attacks)
	// // Tries the "authentication" cookie
	// if (ctx.cookies.get('authentication'))
	// {
	// 	return ctx.cookies.get('authentication')
	// }
}