Switches an authenticated user from one project to another.
347726
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME):
    """"""
    LOG.debug('Switching to tenant %s for user "%s".',
              tenant_id, request.user.username)

    endpoint, __ = utils.fix_auth_url_version_prefix(request.user.endpoint)
    session = utils.get_session()
    # Keystone can be configured to prevent exchanging a scoped token for
    # another token. Always use the unscoped token for requesting a
    # scoped token.
    unscoped_token = request.user.unscoped_token
    auth = utils.get_token_auth_plugin(auth_url=endpoint,
                                       token=unscoped_token,
                                       project_id=tenant_id)

    try:
        auth_ref = auth.get_access(session)
        msg = 'Project switch successful for user "%(username)s".' % \
            {'username': request.user.username}
        LOG.info(msg)
    except keystone_exceptions.ClientException:
        msg = (
            _('Project switch failed for user "%(username)s".') %
            {'username': request.user.username})
        messages.error(request, msg)
        auth_ref = None
        LOG.exception('An error occurred while switching sessions.')

    # Ensure the user-originating redirection url is safe.
    # Taken from django.contrib.auth.views.login()
    redirect_to = request.GET.get(redirect_field_name, '')
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if auth_ref:
        user = auth_user.create_user_from_token(
            request,
            auth_user.Token(auth_ref, unscoped_token=unscoped_token),
            endpoint)
        auth_user.set_session_from_user(request, user)
        message = (
            _('Switch to project "%(project_name)s" successful.') %
            {'project_name': request.user.project_name})
        messages.success(request, message)
    response = shortcuts.redirect(redirect_to)
    utils.set_response_cookie(response, 'recent_project',
                              request.user.project_id)
    return response
1039253
@Remoted
    public IPromise<Object[]> login(String user, String pw, String jwt) {
        Promise res = new Promise();
        ConnectionRegistry remoteConnection = connection.get();
        getCredentials(user,pw,jwt).then( (authres, err) -> {
            if ( err != null ) {
                res.reject(err);
            } else {
                String sessionId = remoteConnection != null ? remoteConnection.getSocketRef().getConnectionIdentifier() : null;
                getSession(user,sessionId, authres ).then( (sess,serr) -> {
                    if ( sess != null ) {
                        if ( sessionId != null && sessionStorage != null ) {
                            sessionStorage.putUserAtSessionId(sessionId,user);
                        }
                        res.resolve(new Object[]{sess,authres});
                    } else
                        res.complete(sess,serr);
                });
            }
        });
        return res;
    }
216302
def delete_user(self, user):
        
        self.project_service.set_auth(self._token_project)
        self.project_service.delete_user(user)
397343
def change_password(ctx):
    """"""

    username, passhash = _get_credentials(ctx.obj['username'],
                                          ctx.obj['password'],
                                          ctx.obj['db'])

    change_user = ctx.obj['db'].objectmodels['user'].find_one({
        'name': username
    })
    if change_user is None:
        log('No such user', lvl=warn)
        return

    change_user.passhash = passhash
    change_user.save()

    log("Done")
106746
def switch_region(request, region_name,
                  redirect_field_name=auth.REDIRECT_FIELD_NAME):
    
    if region_name in request.user.available_services_regions:
        request.session['services_region'] = region_name
        LOG.debug('Switching services region to %s for user "%s".',
                  region_name, request.user.username)

    redirect_to = request.GET.get(redirect_field_name, '')
    if not is_safe_url(url=redirect_to, host=request.get_host()):
        redirect_to = settings.LOGIN_REDIRECT_URL

    response = shortcuts.redirect(redirect_to)
    utils.set_response_cookie(response, 'services_region',
                              request.session['services_region'])
    return response
1261901
def authenticate(self, auth_url=None, **kwargs):
        """"""
        LOG.debug('Beginning user authentication')

        if not auth_url:
            auth_url = settings.OPENSTACK_KEYSTONE_URL

        auth_url, url_fixed = utils.fix_auth_url_version_prefix(auth_url)
        if url_fixed:
            LOG.warning("The OPENSTACK_KEYSTONE_URL setting points to a v2.0 "
                        "Keystone endpoint, but v3 is specified as the API "
                        "version to use by Horizon. Using v3 endpoint for "
                        "authentication.")

        plugin, unscoped_auth = self._get_auth_backend(auth_url, **kwargs)

        # the recent project id a user might have set in a cookie
        recent_project = None
        request = kwargs.get('request')
        if request:
            # Grab recent_project found in the cookie, try to scope
            # to the last project used.
            recent_project = request.COOKIES.get('recent_project')
        unscoped_auth_ref = plugin.get_access_info(unscoped_auth)

        # Check expiry for our unscoped auth ref.
        self.check_auth_expiry(unscoped_auth_ref)

        domain_name = kwargs.get('user_domain_name', None)
        domain_auth, domain_auth_ref = plugin.get_domain_scoped_auth(
            unscoped_auth, unscoped_auth_ref, domain_name)
        scoped_auth, scoped_auth_ref = plugin.get_project_scoped_auth(
            unscoped_auth, unscoped_auth_ref, recent_project=recent_project)

        # Abort if there are no projects for this user and a valid domain
        # token has not been obtained
        #
        # The valid use cases for a user login are:
        #    Keystone v2: user must have a role on a project and be able
        #                 to obtain a project scoped token
        #    Keystone v3: 1) user can obtain a domain scoped token (user
        #                    has a role on the domain they authenticated to),
        #                    only, no roles on a project
        #                 2) user can obtain a domain scoped token and has
        #                    a role on a project in the domain they
        #                    authenticated to (and can obtain a project scoped
        #                    token)
        #                 3) user cannot obtain a domain scoped token, but can
        #                    obtain a project scoped token
        if not scoped_auth_ref and domain_auth_ref:
            # if the user can't obtain a project scoped token, set the scoped
            # token to be the domain token, if valid
            scoped_auth = domain_auth
            scoped_auth_ref = domain_auth_ref
        elif not scoped_auth_ref and not domain_auth_ref:
            msg = _('You are not authorized for any projects.')
            if utils.get_keystone_version() >= 3:
                msg = _('You are not authorized for any projects or domains.')
            raise exceptions.KeystoneAuthException(msg)

        # Check expiry for our new scoped token.
        self.check_auth_expiry(scoped_auth_ref)

        # We want to try to use the same region we just logged into
        # which may or may not be the default depending upon the order
        # keystone uses
        region_name = None
        id_endpoints = scoped_auth_ref.service_catalog.\
            get_endpoints(service_type='identity')
        for id_endpoint in [cat for cat in id_endpoints['identity']]:
            if auth_url in id_endpoint.values():
                region_name = id_endpoint['region']
                break

        interface = getattr(settings, 'OPENSTACK_ENDPOINT_TYPE', 'public')

        endpoint, url_fixed = utils.fix_auth_url_version_prefix(
            scoped_auth_ref.service_catalog.url_for(
                service_type='identity',
                interface=interface,
                region_name=region_name))
        if url_fixed:
            LOG.warning("The Keystone URL in service catalog points to a v2.0 "
                        "Keystone endpoint, but v3 is specified as the API "
                        "version to use by Horizon. Using v3 endpoint for "
                        "authentication.")

        # If we made it here we succeeded. Create our User!
        unscoped_token = unscoped_auth_ref.auth_token

        user = auth_user.create_user_from_token(
            request,
            auth_user.Token(scoped_auth_ref, unscoped_token=unscoped_token),
            endpoint,
            services_region=region_name)

        if request is not None:
            # if no k2k providers exist then the function returns quickly
            utils.store_initial_k2k_session(auth_url, request, scoped_auth_ref,
                                            unscoped_auth_ref)
            request.session['unscoped_token'] = unscoped_token
            if domain_auth_ref:
                # check django session engine, if using cookies, this will not
                # work, as it will overflow the cookie so don't add domain
                # scoped token to the session and put error in the log
                if utils.using_cookie_backed_sessions():
                    LOG.error('Using signed cookies as SESSION_ENGINE with '
                              'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT is '
                              'enabled. This disables the ability to '
                              'perform identity operations due to cookie size '
                              'constraints.')
                else:
                    request.session['domain_token'] = domain_auth_ref

            request.user = user
            timeout = getattr(settings, "SESSION_TIMEOUT", 3600)
            token_life = user.token.expires - datetime.datetime.now(pytz.utc)
            session_time = min(timeout, int(token_life.total_seconds()))
            request.session.set_expiry(session_time)

            keystone_client_class = utils.get_keystone_client().Client
            session = utils.get_session()
            scoped_client = keystone_client_class(session=session,
                                                  auth=scoped_auth)

            # Support client caching to save on auth calls.
            setattr(request, KEYSTONE_CLIENT_ATTR, scoped_client)

        LOG.debug('Authentication completed.')
        return user
554025
@Override
    public Subject authenticate(String assertedUser) throws AuthenticationException {
        AuthenticateUserHelper authHelper = new AuthenticateUserHelper();
        return authHelper.authenticateUser(authenticationService, assertedUser, jaasEntryName);
    }
603551
def restart_user(self, subid):
    ''''''
    p = self.revoke_token(subid)
    p = self.refresh_token(subid)
    return p
355467
function onCopyActiveUser() {
  tempAuth.updateCurrentUser(activeUser()).then(function() {
    alertSuccess('Copied active user to temp Auth');
  }, function(error) {
    alertError('Error: ' + error.code);
  });
}
953509
public function replaceMemberAuthor(User $from, User $to)
    {
        $fromIsMember = false;
        $froms = $this->memberRepo->findByUser($from);
        if (count($froms) > 0) {
            $fromIsMember = true;
        }

        $toIsMember = false;
        $tos = $this->memberRepo->findByUser($to);
        if (count($tos) > 0) {
            $toIsMember = true;
        }

        if ($toIsMember && $fromIsMember) {
            //user kept already have its member entry, delete the old one
            foreach ($froms as $member) {
                $this->objectManager->remove($member);
            }
            $this->objectManager->flush();
        } elseif (!$toIsMember && $fromIsMember) {
            //update entry for kept user
            foreach ($froms as $member) {
                $member->setUser($to);
            }
            $this->objectManager->flush();
        }
    }
886121
def change_profile(self, profile_name):
        """"""
        self._server_side_completer = self._create_server_side_completer(
            session=botocore.session.Session(profile=profile_name))
148180
def change_owner(self, new_owner):
        
        old_owner = self.owner.organization_user
        self.owner.organization_user = new_owner
        self.owner.save()

        # Owner changed signal
        owner_changed.send(sender=self, old=old_owner, new=new_owner)
903216
def reassign(self, from_email, user_ids):
        """"""
        endpoint = '/'.join((self.endpoint, self.id,))

        if from_email is None or not isinstance(from_email, six.string_types):
            raise MissingFromEmail(from_email)

        if user_ids is None or not isinstance(user_ids, list):
            raise InvalidArguments(user_ids)
        if not all([isinstance(i, six.string_types) for i in user_ids]):
            raise InvalidArguments(user_ids)

        assignees = [
            {
                'assignee': {
                    'id': user_id,
                    'type': 'user_reference',
                }
            }
            for user_id in user_ids
        ]

        add_headers = {'from': from_email, }
        data = {
            'incident': {
                'type': 'incident',
                'assignments': assignees,
            }
        }

        result = self.request('PUT',
                              endpoint=endpoint,
                              add_headers=add_headers,
                              data=data,)
        return result
807619
public function postImport($result, CommandData $commandData) {
    if ($commandData->input()->getOption('userid')) {
      $accountSwitcher = \Drupal::service('account_switcher');
      $this->logger()->notice(dt(
                                  'Switching back from user @uid.',
                                  ['@uid' => \Drupal::currentUser()->id()]
                                ));
      $accountSwitcher->switchBack();
    }
  }
1373673
public static BackendUser from(ValidCredentials credentials){
        BackendUser beu = new BackendUser();
        beu.initFrom(credentials);
        return beu;
    }
154929
function exchangePassword(client, username, password, scope, body, authInfo, done) {
    if (!client || !client.id) {
        return done(new common.errors.UnauthorizedError({
            message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided')
        }), false);
    }

    // Validate the user
    return models.User.check({email: username, password: password})
        .then(function then(user) {
            return authUtils.createTokens({
                clientId: client.id,
                userId: user.id
            });
        })
        .then(function then(response) {
            web.shared.middlewares.api.spamPrevention.userLogin()
                .reset(authInfo.ip, username + 'login');

            return done(null, response.access_token, response.refresh_token, {expires_in: response.expires_in});
        })
        .catch(function (err) {
            done(err, false);
        });
}
634302
def reset(project, user):
        """"""
        d = Project.path(project, user) + "output"
        if os.path.isdir(d):
            shutil.rmtree(d)
            os.makedirs(d)
        else:
            raise flask.abort(404)
        if os.path.exists(Project.path(project, user) + ".done"):
            os.unlink(Project.path(project, user) + ".done")
        if os.path.exists(Project.path(project, user) + ".status"):
            os.unlink(Project.path(project, user) + ".status")