ensure appc user is logged in
506525
function ensureLogin(callback) {
		exec('"' + getTitaniumPath() + '" status -o json', function(err, stdout, stderr) {
			if (err) { return callback(err); }
			if (!JSON.parse(stdout).loggedIn) {
				grunt.fail.fatal([
					'You must be logged in to use grunt-titanium. Use `titanium login`.'
				]);
			}
			return callback();
		});
	}
3338
function(user) {
        var promise;
        if (AV.User._currentUser !== user) {
          promise = AV.User.logOut();
        } else {
          promise = Promise.resolve();
        }
        return promise.then(function() {
          user._isCurrentUser = true;
          AV.User._currentUser = user;

          var json = user._toFullJSON();
          json._id = user.id;
          json._sessionToken = user._sessionToken;
          return AV.localStorage
            .setItemAsync(
              AV._getAVPath(AV.User._CURRENT_USER_KEY),
              JSON.stringify(json)
            )
            .then(function() {
              AV.User._currentUserMatchesDisk = true;
              return AV._refreshSubscriptionId();
            });
        });
      }
1264938
function(cb, force) {
        if (!VK._apiId) {
          return;
        }

        if (cb) {
          if (!force && VK.Auth._loadState == 'loaded') {
            cb({status: VK._userStatus, session: VK._session});
            return;
          } else {
            VK.Observer.subscribe('auth.loginStatus', cb);
          }
        }

        if (!force && VK.Auth._loadState == 'loading') {
          return;
        }

        VK.Auth._loadState = 'loading';

        var url = 'https://login.vk.com/?act=openapi&oauth=1&aid=' + parseInt(VK._apiId, 10) + '&location=' + encodeURIComponent(window.location.hostname);
        if (VK.Api.supportCORS()) {
          var loginCallback = function(response) {
            if (!this.JSON) {
              this.JSON = {};
            }

            if (typeof JSON.parse !== 'function') {
              //IE6 and IE7
              response = eval(response);
            } else {
              response = JSON.parse(response);
            }

            VK.Auth._loadState = 'loaded';
            if (response && response.auth) {
              var session = {
                mid: response.user.id,
                sid: response.access_token,
                sig: response.sig,
                secret: response.secret,
                expire: response.expire
              };

              if (force) {
                session.user = response.user;
              }

              var status = 'connected';
            } else {
              var session = null;
              var status = response.user ? 'not_authorized' : 'unknown';
              VK.Cookie.clear();
            }

            VK.Auth.setSession(session, status, false, response);
            VK.Observer.publish('auth.loginStatus', {session: session, status: status});
            VK.Observer.unsubscribe('auth.loginStatus');
          };

          VK.Api.makeRequest(url + '&new=1', loginCallback);
        } else {
          var rnd = parseInt(Math.random() * 10000000, 10);
          while (VK.Auth.lsCb[rnd]) {
            rnd = parseInt(Math.random() * 10000000, 10);
          }

          VK.Auth.lsCb[rnd] = function(response) {
            delete VK.Auth.lsCb[rnd];
            VK.Auth._loadState = 'loaded';
            if (response && response.auth) {
              var session = {
                mid: response.user.id,
                sid: response.access_token,
                sig: response.sig,
                secret: response.secret,
                expire: response.expire
              };
              if (force) session.user = response.user;
              var status = 'connected';
            } else {
              var session = null;
              var status = response.user ? 'not_authorized' : 'unknown';
              VK.Cookie.clear();
            }
            VK.Auth.setSession(session, status, false, response);
            VK.Observer.publish('auth.loginStatus', {session: session, status: status});
            VK.Observer.unsubscribe('auth.loginStatus');
          };

            // AttachScript here
          VK.Api.attachScript(url+'&rnd='+rnd);
        }
      }
245414
def authenticate(self, user, password):
        """"""
        assert user['password_hash'] == '_'.join((password, 'hash'))
        self.logger.debug('User %s has been successfully authenticated',
                          user['uid'])
514677
def verify_appium_is_running(self):
        """"""
        process = Popen(['ps -e | grep "Appium"'], shell=True, stdout=PIPE)
        (grep_output, _grep_error) = process.communicate()
        lines = grep_output.split('\n')
        for line in lines:
            if 'Appium.app' in line:
                self.stdout.write('Appium is already running')
                return True
        self.stdout.write('Please launch and configure Appium first')
        return False
712512
protected void checkAuthenticatedAccount(UserIdentityContext userIdentityContext) {
        if (userIdentityContext.getEffectiveAccount() == null) {
            throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic realm=\"Restcomm realm\"").build());
        }
    }
1021589
def requires_app_credentials(func):
    
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        client_id, client_secret = self._session.retrieve_client_credentials()
        if client_id and client_secret:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires username/password authentication"}'
            )
            raise GitHubError(r)

    return auth_wrapper
101406
def login_listener(app, user):
    
    @after_this_request
    def add_user_session(response):
        """Regenerate current session and add to the SessionActivity table.

        .. note:: `flask.session.regenerate()` actually calls Flask-KVSession's
            `flask_kvsession.KVSession.regenerate`.
        """
        # Regenerate the session to avoid session fixation vulnerabilities.
        session.regenerate()
        # Save the session first so that the sid_s gets generated.
        app.session_interface.save_session(app, session, response)
        add_session(session)
        current_accounts.datastore.commit()
        return response
638208
public static function setUserInfoWithJWT($user, $forever = false, $appId = null)
    {
        $userInfo = null;
        if ($user instanceof User) {
            $userInfo = $user->toArray();
            $userInfo['is_sys_admin'] = $user->is_sys_admin;
        }

        if (!empty($userInfo)) {
            $id = array_get($userInfo, 'id');
            $email = array_get($userInfo, 'email');
            $token = JWTUtilities::makeJWTByUser($id, $email, $forever);
            static::setSessionToken($token);

            if (!empty($appId) && !$user->is_sys_admin) {
                static::setSessionData($appId, $id);

                return true;
            } else {
                return static::setUserInfo($userInfo);
            }
        }

        return false;
    }
94549
private void scheduleAuthentication(final int appId, final String bridgeId,
      final CallStatsHttp2Client httpClient) {
    scheduler.schedule(new Runnable() {
      public void run() {
        sendAsyncAuthenticationRequest(appId, bridgeId, httpClient);
      }
    }, authenticationRetryTimeout, TimeUnit.MILLISECONDS);
  }
1317192
def create_admin(app, appbuilder, username, firstname, lastname, email, password):
    
    auth_type = {
        c.AUTH_DB: "Database Authentications",
        c.AUTH_OID: "OpenID Authentication",
        c.AUTH_LDAP: "LDAP Authentication",
        c.AUTH_REMOTE_USER: "WebServer REMOTE_USER Authentication",
        c.AUTH_OAUTH: "OAuth Authentication",
    }
    _appbuilder = import_application(app, appbuilder)
    click.echo(
        click.style(
            "Recognized {0}.".format(
                auth_type.get(_appbuilder.sm.auth_type, "No Auth method")
            ),
            fg="green",
        )
    )
    role_admin = _appbuilder.sm.find_role(_appbuilder.sm.auth_role_admin)
    user = _appbuilder.sm.add_user(
        username, firstname, lastname, email, role_admin, password
    )
    if user:
        click.echo(click.style("Admin User {0} created.".format(username), fg="green"))
    else:
        click.echo(click.style("No user created an error occured", fg="red"))
338383
def _check_logged_user(self):
        """"""
        if not self._env or not self._password or not self._login:
            raise error.InternalError("Login required")
1310008
def handle_authenticated_user(self, response):
        
        current_user = get_user(self.request)

        ulogin, registered = ULoginUser.objects.get_or_create(
            uid=response['uid'],
            network=response['network'],
            defaults={'identity': response['identity'],
                      'user': current_user})

        if not registered:
            ulogin_user = ulogin.user
            logger.debug('uLogin user already exists')

            if current_user != ulogin_user:
                logger.debug(
                    "Mismatch: %s is not a %s. Take over it!" % (current_user,
                                                                 ulogin_user)
                )
                ulogin.user = current_user
                ulogin.save()

        return get_user(self.request), ulogin, registered
659626
def _set_session():
    
    global __SESSION
    global __USER_ID
    
    if __SESSION is None:
        try:
            __SESSION = AuthorizedSession(google.auth.default(['https://www.googleapis.com/auth/userinfo.profile',
                                                               'https://www.googleapis.com/auth/userinfo.email'])[0])
            health()
            __USER_ID = id_token.verify_oauth2_token(__SESSION.credentials.id_token,
                                                     Request(session=__SESSION))['email']
        except (DefaultCredentialsError, RefreshError) as gae:
            if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
                raise
            logging.warning("Unable to determine/refresh application credentials")
            try:
                subprocess.check_call(['gcloud', 'auth', 'application-default',
                                       'login', '--no-launch-browser'])
                __SESSION = AuthorizedSession(google.auth.default(['https://www.googleapis.com/auth/userinfo.profile',
                                                                   'https://www.googleapis.com/auth/userinfo.email'])[0])
            except subprocess.CalledProcessError as cpe:
                if cpe.returncode < 0:
                    logging.exception("%s was terminated by signal %d",
                                      cpe.cmd, -cpe.returncode)
                else:
                    logging.exception("%s returned %d", cpe.cmd,
                                      cpe.returncode)
                raise gae
1175909
public static function initialize($app_id, $app_key, $master_key)
    {
        AVUser::registerSubclass();
        AVRole::registerSubclass();
        AVInstallation::registerSubclass();
        self::$applicationId = $app_id;
        self::$appKey = $app_key;
        self::$masterKey = $master_key;;
        if (!static::$storage)
        {
            if (session_status() === PHP_SESSION_ACTIVE)
            {
                self::setStorage(new AVSessionStorage());
            } else
            {
                self::setStorage(new AVMemoryStorage());
            }
        }
    }
604963
def _check_settings(self, app):
        """"""

        # Check for invalid settings
        # --------------------------

        # Check self.UserInvitationClass and USER_ENABLE_INVITE_USER
        if self.USER_ENABLE_INVITE_USER and not self.UserInvitationClass:
            raise ConfigError(
                'UserInvitationClass is missing while USER_ENABLE_INVITE_USER is True.' \
                ' Specify UserInvitationClass with UserManager(app, db, User, UserInvitationClass=...' \
                ' or set USER_ENABLE_INVITE_USER=False.')

        # Check for deprecated settings
        # -----------------------------

        # Check for deprecated USER_ENABLE_CONFIRM_EMAIL
        setting = app.config.get('USER_ENABLE_LOGIN_WITHOUT_CONFIRM_EMAIL', None)
        if setting is not None:
            print(
                'Deprecation warning: USER_ENABLE_LOGIN_WITHOUT_CONFIRM_EMAIL'\
                ' will be deprecated.' \
                ' It has been replaced by USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL.'\
                ' Please change this as soon as possible.')
            self.USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL = setting

        # Check for deprecated USER_ENABLE_RETYPE_PASSWORD
        setting = app.config.get('USER_ENABLE_RETYPE_PASSWORD', None)
        if setting is not None:
            print(
                'Deprecation warning: USER_ENABLE_RETYPE_PASSWORD'\
                ' will be deprecated.' \
                ' It has been replaced with USER_REQUIRE_RETYPE_PASSWORD.'\
                ' Please change this as soon as possible.')
            self.USER_REQUIRE_RETYPE_PASSWORD = setting

        # Check for deprecated USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST
        setting = app.config.get('USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST', None)
        if setting is not None:
            print(
                'Deprecation warning: USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST' \
                ' will be deprecated.' \
                ' It has been replaced with USER_SHOW_USERNAME_DOES_NOT_EXIST'
                ' and USER_SHOW_EMAIL_DOES_NOT_EXIST.'
                ' Please change this as soon as possible.')
            self.USER_SHOW_USERNAME_DOES_NOT_EXIST = setting
            self.USER_SHOW_EMAIL_DOES_NOT_EXIST = setting

        # Check for deprecated USER_PASSWORD_HASH
        setting = app.config.get('USER_PASSWORD_HASH', None)
        if setting is not None:
            print(
                "Deprecation warning: USER_PASSWORD_HASH=<string>"\
                " will be deprecated."\
                " It has been replaced with USER_PASSLIB_CRYPTCONTEXT_SCHEMES=<list>."
                " Please change USER_PASSWORD_HASH='something' to"\
                " USER_PASSLIB_CRYPTCONTEXT_SCHEMES=['something'] as soon as possible.")
            self.USER_PASSLIB_CRYPTCONTEXT_SCHEMES = [setting]

        # Check that USER_EMAIL_SENDER_EMAIL is set when USER_ENABLE_EMAIL is True
        if not self.USER_EMAIL_SENDER_EMAIL and self.USER_ENABLE_EMAIL:
            raise ConfigError(
                'USER_EMAIL_SENDER_EMAIL is missing while USER_ENABLE_EMAIL is True.'\
                ' specify USER_EMAIL_SENDER_EMAIL (and USER_EMAIL_SENDER_NAME) or set USER_ENABLE_EMAIL to False.')

        # Disable settings that rely on a feature setting that's not enabled
        # ------------------------------------------------------------------

        # USER_ENABLE_REGISTER=True must have USER_ENABLE_USERNAME=True or USER_ENABLE_EMAIL=True.
        if not self.USER_ENABLE_USERNAME and not self.USER_ENABLE_EMAIL:
            self.USER_ENABLE_REGISTER = False

        # Settings that depend on USER_ENABLE_EMAIL
        if not self.USER_ENABLE_EMAIL:
            self.USER_ENABLE_CONFIRM_EMAIL = False
            self.USER_ENABLE_MULTIPLE_EMAILS = False
            self.USER_ENABLE_FORGOT_PASSWORD = False
            self.USER_SEND_PASSWORD_CHANGED_EMAIL = False
            self.USER_SEND_REGISTERED_EMAIL = False
            self.USER_SEND_USERNAME_CHANGED_EMAIL = False
            self.USER_REQUIRE_INVITATION = False

        # Settings that depend on USER_ENABLE_USERNAME
        if not self.USER_ENABLE_USERNAME:
            self.USER_ENABLE_CHANGE_USERNAME = False
42288
public function login($appKey, $username, $password)
    {
        self::$appKey = $appKey;

        $request = $this->httpClient
            ->setMethod('post')
            ->setEndPoint(self::ENDPOINT.'login/')
            ->setFormData([ 'username' => $username, 'password' => $password ]);

        $result = $this->execute($request);

        self::$sessionToken = $result->token;
        self::$lastLogin = time();

        return $result->token;
    }