Link an OAuth to existing user
337207
public function oAuthLink()
    {
        $providerName = $_REQUEST["provider"];
        $userProfile = $this->getAuthProvider()->authenticate($providerName);

        $this->_getUser()->first_name = $userProfile->firstName;
        $this->_getUser()->last_name = $userProfile->lastName;
        $this->_getUser()->email = $userProfile->email;

        foreach (['login', 'register'] as $_action) {
            $form = $this->_getUser()->getForm($_action);

            if ($form->execute()) {
                $userLogin = User_Logins::instance()->getNew();
                $userLogin->id_user = $this->_getUser()->id;
                $userLogin->provider_name = $providerName;
                $userLogin->provider_uid = $userProfile->identifier;
                $userLogin->insert();


                $this->{'after' . ucfirst($_action) . 'Redirect'}();
            }
            $this->forms[$_action] = $form;
        }

        $this->setLoginMeta('login');
    }
1195177
def _request(self, base_url, client_id, client_secret,
                 parameters, **kwargs):
        """"""
        logging.debug('Getting an OAuth token for client "%s" with scope "%s"',
                      client_id, parameters.get('scope'))
        headers = {'Content-Type': 'application/x-www-form-urlencoded',
                   'Accept': 'application/json'}

        api = API(base_url,
                  auth_username=client_id,
                  auth_password=client_secret,
                  **kwargs)
        endpoint = api.auth.token

        response = yield endpoint.post(body=urllib.urlencode(parameters),
                                       request_timeout=60,
                                       headers=headers)

        logging.debug('Received token: %s', response.get('access_token'))
        raise Return(response)
541161
def _on_auth(self, user):
        
        app = current_app._get_current_object()
        if not user:
            # Google auth failed.
            login_error.send(app, user=None)
            abort(403)
        session["openid"] = user
        login.send(app, user=user)
        return redirect(request.args.get("next", None) or request.referrer or "/")
220472
public static function authUserTokenMiddleware(string $oauthClientId, string $secret, string $baseUrl, string $username): callable
    {
        return Middleware::mapRequest(
            function (RequestInterface $request) use ($oauthClientId, $secret, $baseUrl, $username) {
                return new Request(
                    $request->getMethod(),
                    $request->getUri(),
                    \array_merge($request->getHeaders(), [
                        'Authorization' => 'Bearer '.self::getAuthToken($oauthClientId, $secret, $baseUrl, $username),
                        'Accept' => 'application/json',
                    ]),
                    $request->getBody()
                );
            }
        );
    }
43689
def auth_uri(self):

        """"""

        return self.oauth.auth_uri(redirect_uri=self.redirect_uri, scope=self.scope)
1325748
def user_related(self, id, **kwargs):
        ""
        api_path = "/api/v2/users/{id}/related.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
1261258
def account_setup(remote, token, resp):
    
    gh = github3.login(token=resp['access_token'])
    with db.session.begin_nested():
        me = gh.me()

        token.remote_account.extra_data = {'login': me.login, 'id': me.id}

        # Create user <-> external id link.
        oauth_link_external_id(
            token.remote_account.user, dict(
                id=str(me.id),
                method='github')
        )
990838
def authorize(client_key, client_secret, credfile=CONFIG_FILE, app='trlo.py',
              expiration='never', scope='read,write'):
    
    # 1. Obtain the request token.
    oauth = OAuth1Session(client_key, client_secret=client_secret)
    request_token = oauth.fetch_request_token(OAUTH_REQUEST_TOKEN_URL)

    # 2. Authorize the user (in the browser).
    authorization_url = oauth.authorization_url(OAUTH_BASE_AUTHORIZE_URL,
        name=app, expiration=expiration, scope=scope)
    print("Please visit the following URL to authorize this app:")
    print(authorization_url)
    print('')
    print("Once you've authorized, copy and paste the token Trello gives you below.")
    # Py3K backwards-compatibility shim
    global input
    try:
        input = raw_input
    except NameError:
        pass
    verifier = input("Trello's token: ").strip()

    # 3. Obtain the access token
    oauth = OAuth1Session(client_key, client_secret=client_secret,
        resource_owner_key=request_token['oauth_token'],
        resource_owner_secret=request_token['oauth_token_secret'],
        verifier=verifier)
    access_token = oauth.fetch_access_token(OAUTH_ACCESS_TOKEN_URL)

    # Save all our creds to ~/.trlo so we can get at 'em later.
    # The names are specially chosen so we can do OAuth1Session(**creds)
    creds = {
        'client_key': client_key,
        'client_secret': client_secret,
        'resource_owner_key': access_token['oauth_token'],
        'resource_owner_secret': access_token['oauth_token_secret'],
    }
    with open(credfile, 'w') as fp:
        json.dump(creds, fp)
96834
def OpenUrlWithBasicAuth(url, user='root', pwd=''):
   
   return requests.get(url, auth=HTTPBasicAuth(user, pwd), verify=False)
1245518
def oauth_login(self, provider, id_column, id, attrs, defaults, redirect_url=None):
        
        user = self.query.filter(**dict([(id_column, id)])).first()
        if not redirect_url:
            redirect_url = request.args.get('next') or url_for(self.options["redirect_after_login"])
        if self.logged_in():
            if user and user != self.current:
                if self.options["oauth_user_already_exists_message"]:
                    flash(self.options["oauth_user_already_exists_message"].format(provider=provider), "error")
                return redirect(redirect_url)
            if provider not in self.current.auth_providers:
                self.current.auth_providers.append(provider)
            current_app.features.models.save(self.current, **attrs)
        elif not user:
            return self.oauth_signup(provider, attrs, defaults, redirect_url=redirect_url)
        else:
            self.login(user, provider=provider, **attrs)
        return redirect(redirect_url)
696254
def handle_existing_user(self, provider, user, access, info):
        ""
        login(self.request, user)
        return redirect(self.get_login_redirect(provider, user, access))
932898
def auth_as(self, user):
        """"""
        old_user = self._user
        self.auth(user)
        try:
            yield
        finally:
            self.auth(old_user)
690336
def AuthorizeUser(self, user, subject):
    """"""

    user_set = self.authorized_users.setdefault(subject, set())
    user_set.add(user)
88247
def add_auth_args(parser, config):

    """"""

    parser.add_argument('-p', '--provider', default=config.DEFAULT_PROVIDER)
    parser.add_argument('-u', '--userid', default=config.DEFAULT_USERID)
    parser.add_argument('-k', '--secret_key', default=config.DEFAULT_SECRET_KEY)
    return parser
953747
def get_url_with_auth(self, url) -> str:
        """"""
        if not self._username:
            return url

        url += '&user={:s}'.format(self._username)

        if not self._password:
            return url

        return url + '&pass={:s}'.format(self._password)
1169018
def authorize_url(params = nil)
      return nil if self.token.nil?

      params = (params || {}).merge(:oauth_token => self.token)
      build_authorize_url(consumer.authorize_url, params)
    end
886870
def authorization_link(self, redirect_uri):
        '''
        '''
        args = '?client_id=%s&redirect_uri=%s' % (
            self.app_key,
            redirect_uri
        )
        uri = "/".join([BASE_URL, API_VERSION, OAUTH, args])
        return uri