Create a verifier for an user authorized client
481789
def authorized(self, request_token):
        """"""
        verifier = generate_token(length=self.verifier_length[1])
        self.save_verifier(request_token, verifier)
        response = [
            (u'oauth_token', request_token),
            (u'oauth_verifier', verifier)
        ]
        callback = self.get_callback(request_token)
        return redirect(add_params_to_uri(callback, response))
1054329
def cli(obj, username, scopes, duration, text, customer, delete):
    """"""
    client = obj['client']
    if delete:
        client.delete_key(delete)
    else:
        try:
            expires = datetime.utcnow() + timedelta(seconds=duration) if duration else None
            key = client.create_key(username, scopes, expires, text, customer)
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
            sys.exit(1)
        click.echo(key.key)
680758
function authorizedHandler(value) {
    if (! value) return value;

    delete value.public_id;
    delete value.version;
    delete value.signature;
    delete value.resource_type;

    return value;
}
1287035
def _verify_client_authentication(self, request_body, http_headers=None):
        # type (str, Optional[Mapping[str, str]] -> Mapping[str, str]
        
        if http_headers is None:
            http_headers = {}
        token_request = dict(parse_qsl(request_body))
        token_request['client_id']  = verify_client_authentication(self.clients, token_request, http_headers.get('Authorization'))
        return token_request
287072
def verify(user, password):
    """"""
    def verify_user(user_name, user_password):
        if user_name == user and user_password == password:
            return user_name
        return False
    return verify_user
1357789
def AuthorizingClient(
    domain,
    auth,
    request_encoder,
    response_decoder,
    user_agent=None
):
    
    
    http_transport = transport.HttpTransport(
        api_url(domain),
        build_headers(auth, user_agent)
    )
    
    return client.Client(
        request_encoder,
        http_transport,
        response_decoder
    )
544057
def request_access(self, verifier):
        
        client = OAuth1(
            client_key=self._server_cache[self.client.server].key,
            client_secret=self._server_cache[self.client.server].secret,
            resource_owner_key=self.store["oauth-request-token"],
            resource_owner_secret=self.store["oauth-request-secret"],
            verifier=verifier,
        )

        request = {"auth": client}
        response = self._requester(
            requests.post,
            "oauth/access_token",
            **request
        )

        data = parse.parse_qs(response.text)

        self.store["oauth-access-token"] = data[self.PARAM_TOKEN][0]
        self.store["oauth-access-secret"] = data[self.PARAM_TOKEN_SECRET][0]
        self._server_tokens = {}
54161
def validate(self):
        """"""

        if not self.server.enabled:

            if self.security.signature_certificate_file is self.security.defaults['signature_certificate_file']:
                print("ISSUE: If you are not configuring a server, you need to set 'signature_certificate_file'")

            if self.security.signature_private_key_file is self.security.defaults['signature_private_key_file']:
                print("ISSUE: If you are not configuring a server, you need to set 'signature_private_key_file'")

        else:

            if self.client.enabled:
                print("ISSUE: Client and server enabled at the same time?")

            if self.server.protocol is self.server.defaults['protocol']:
                if self.server.server_certificate_file is self.server.defaults['server_certificate_file'] or \
                                self.server.server_private_key_file is self.server.defaults['server_private_key_file']:
                   print("ISSUE: 'server_certificate_file' and/or 'server_private_key_file' are not configured and will be auto-generated.")


            if self.server.certification_authority_certificate_file is self.server.defaults['certification_authority_certificate_file'] or \
                            self.server.certification_authority_private_key_file is self.server.defaults['certification_authority_private_key_file']:
                print("ISSUE: 'certification_authority_certificate_file' and/or 'certification_authority_private_key_file' are not configured and will be auto-generated - this is NOT recommended.")

            if self.server.authentication_script is self.server.defaults['authentication_script']:
                print("ISSUE: No 'authentication_script' has been provided and all authentication requests will be rejected!")

        if self.client.enabled:

            if self.client.server_endpoint is self.client.defaults['server_endpoint']:
                print("ISSUE: You are running in client mode, but you are using a default server address.")

            if not self.client.disable_peer_verification is self.client.defaults['disable_peer_verification'] or \
                    not self.client.disable_host_verification is self.client.defaults['disable_host_verification']:
                print("ISSUE: Disabling peer/host verification is NOT recommended - AT ALL.")

            if self.client.username is self.client.defaults['username'] or \
                            self.client.password is self.client.defaults['password']:
                print("ISSUE: No username and/or password has been configured for a client.")

        if self.fscp.contact is self.fscp.defaults['contact']:

            if not self.server.enabled and not self.client.enabled:
                print("ISSUE: You have not defined any contact points while you are neither running as server nor client.")

        ## hostname_resolution_protocol=ipv4/ipv6
        ## ipv4_address_prefix_length=9.0.0.1/24
        ## ipv6_address_prefix_length=2aa1::1/8

        if self.security.authority_certificate_file is self.security.defaults['authority_certificate_file']:
            print("ISSUE: You need to set 'authority_certificate_file'")

        if self.tap_adapter.ipv4_address_prefix_length is self.tap_adapter.defaults['ipv4_address_prefix_length']:
            print("ISSUE: You are using the default network address - make sure you set a different ip for every machine 'ipv4_address_prefix_length'")
596166
async def do_authentication(sender):
    
    # Step 1 sending: PQ Request, endianness doesn't matter since it's random
    nonce = int.from_bytes(os.urandom(16), 'big', signed=True)
    res_pq = await sender.send(ReqPqMultiRequest(nonce))
    assert isinstance(res_pq, ResPQ), 'Step 1 answer was %s' % res_pq

    if res_pq.nonce != nonce:
        raise SecurityError('Step 1 invalid nonce from server')

    pq = get_int(res_pq.pq)

    # Step 2 sending: DH Exchange
    p, q = Factorization.factorize(pq)
    p, q = rsa.get_byte_array(p), rsa.get_byte_array(q)
    new_nonce = int.from_bytes(os.urandom(32), 'little', signed=True)

    pq_inner_data = bytes(PQInnerData(
        pq=rsa.get_byte_array(pq), p=p, q=q,
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        new_nonce=new_nonce
    ))

    # sha_digest + data + random_bytes
    cipher_text, target_fingerprint = None, None
    for fingerprint in res_pq.server_public_key_fingerprints:
        cipher_text = rsa.encrypt(fingerprint, pq_inner_data)
        if cipher_text is not None:
            target_fingerprint = fingerprint
            break

    if cipher_text is None:
        raise SecurityError(
            'Step 2 could not find a valid key for fingerprints: {}'
            .format(', '.join(
                [str(f) for f in res_pq.server_public_key_fingerprints])
            )
        )

    server_dh_params = await sender.send(ReqDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        p=p, q=q,
        public_key_fingerprint=target_fingerprint,
        encrypted_data=cipher_text
    ))

    assert isinstance(
        server_dh_params, (ServerDHParamsOk, ServerDHParamsFail)),\
        'Step 2.1 answer was %s' % server_dh_params

    if server_dh_params.nonce != res_pq.nonce:
        raise SecurityError('Step 2 invalid nonce from server')

    if server_dh_params.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 2 invalid server nonce from server')

    if isinstance(server_dh_params, ServerDHParamsFail):
        nnh = int.from_bytes(
            sha1(new_nonce.to_bytes(32, 'little', signed=True)).digest()[4:20],
            'little', signed=True
        )
        if server_dh_params.new_nonce_hash != nnh:
            raise SecurityError('Step 2 invalid DH fail nonce from server')

    assert isinstance(server_dh_params, ServerDHParamsOk),\
        'Step 2.2 answer was %s' % server_dh_params

    # Step 3 sending: Complete DH Exchange
    key, iv = helpers.generate_key_data_from_nonce(
        res_pq.server_nonce, new_nonce
    )
    if len(server_dh_params.encrypted_answer) % 16 != 0:
        # See PR#453
        raise SecurityError('Step 3 AES block size mismatch')

    plain_text_answer = AES.decrypt_ige(
        server_dh_params.encrypted_answer, key, iv
    )

    with BinaryReader(plain_text_answer) as reader:
        reader.read(20)  # hash sum
        server_dh_inner = reader.tgread_object()
        assert isinstance(server_dh_inner, ServerDHInnerData),\
            'Step 3 answer was %s' % server_dh_inner

    if server_dh_inner.nonce != res_pq.nonce:
        raise SecurityError('Step 3 Invalid nonce in encrypted answer')

    if server_dh_inner.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 3 Invalid server nonce in encrypted answer')

    dh_prime = get_int(server_dh_inner.dh_prime, signed=False)
    g_a = get_int(server_dh_inner.g_a, signed=False)
    time_offset = server_dh_inner.server_time - int(time.time())

    b = get_int(os.urandom(256), signed=False)
    gb = pow(server_dh_inner.g, b, dh_prime)
    gab = pow(g_a, b, dh_prime)

    # Prepare client DH Inner Data
    client_dh_inner = bytes(ClientDHInnerData(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        retry_id=0,  # TODO Actual retry ID
        g_b=rsa.get_byte_array(gb)
    ))

    client_dh_inner_hashed = sha1(client_dh_inner).digest() + client_dh_inner

    # Encryption
    client_dh_encrypted = AES.encrypt_ige(client_dh_inner_hashed, key, iv)

    # Prepare Set client DH params
    dh_gen = await sender.send(SetClientDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        encrypted_data=client_dh_encrypted,
    ))

    nonce_types = (DhGenOk, DhGenRetry, DhGenFail)
    assert isinstance(dh_gen, nonce_types), 'Step 3.1 answer was %s' % dh_gen
    name = dh_gen.__class__.__name__
    if dh_gen.nonce != res_pq.nonce:
        raise SecurityError('Step 3 invalid {} nonce from server'.format(name))

    if dh_gen.server_nonce != res_pq.server_nonce:
        raise SecurityError(
            'Step 3 invalid {} server nonce from server'.format(name))

    auth_key = AuthKey(rsa.get_byte_array(gab))
    nonce_number = 1 + nonce_types.index(type(dh_gen))
    new_nonce_hash = auth_key.calc_new_nonce_hash(new_nonce, nonce_number)

    dh_hash = getattr(dh_gen, 'new_nonce_hash{}'.format(nonce_number))
    if dh_hash != new_nonce_hash:
        raise SecurityError('Step 3 invalid new nonce hash')

    if not isinstance(dh_gen, DhGenOk):
        raise AssertionError('Step 3.2 answer was %s' % dh_gen)

    return auth_key, time_offset
1144086
def authenticate(cls, client_id, secret):
        
        result = yield views.oauth_client.get(key=[secret, client_id])
        if not result['rows']:
            raise Return()

        service = yield Service.get(client_id)
        raise Return(service)
763332
def verifier(self, url):
        
        webbrowser.open(url)
        print('A browser should have opened up with a link to allow us to access')
        print('your account, follow the instructions on the link and paste the verifier')
        print('Code into here to give us access, if the browser didn\'t open, the link is:')
        print(url)
        print()
        return input('Verifier: ').lstrip(" ").rstrip(" ")
506848
def _authenticate_client(self, client):
        """"""
        if self.login and not self.restart_required:
            try:
                db = client[self.auth_source]
                if self.x509_extra_user:
                    db.authenticate(
                        DEFAULT_SUBJECT,
                        mechanism='MONGODB-X509'
                    )
                else:
                    db.authenticate(
                        self.login, self.password)
            except Exception:
                logger.exception(
                    "Could not authenticate to %r as %s/%s"
                    % (client, self.login, self.password))
                raise
1033048
def authenticate_storage(client_secrets, read_only=False):
    """"""
    if read_only:
        scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
    else:
        scopes = ['https://www.googleapis.com/auth/devstorage.read_write']

    credentials = service_account.Credentials.from_service_account_info(
            client_secrets)
    
    scoped_credentials = credentials.with_scopes(scopes)
    
    return scoped_credentials
920174
function checkAuthenticated(req, res, next) {
	if (!req.user) {
		api.writeError(401, res, "Not authenticated");
	} else {
		req.user.workspaceDir = workspaceDir + (req.user.workspace ? "/" + req.user.workspace : "");
		req.user.checkRights = checkRights;
		next();
	}
}
959508
def create_user_dci(access_token):
    """"""
    user_data = {'username': 'dci',
                 'email': 'dci@distributed-ci.io',
                 'enabled': True,
                 'emailVerified': True,
                 'credentials': [{'type': 'password',
                                  'value': 'dci'}]}
    r = requests.post('http://keycloak:8080/auth/admin/realms/dci-test/users',
                      data=json.dumps(user_data),
                      headers=get_auth_headers(access_token))
    if r.status_code in (201, 409):
        print('Keycloak user dci created successfully.')
    else:
        raise Exception('Error while creating user dci:\nstatus code %s\n'
                        'error: %s' % (r.status_code, r.content))
1218542
def authenticated(viewfunc):
    """"""
    @wraps(viewfunc)
    def wrapper(*args, **kwargs):
        ctx = stack.top
        if ctx and hasattr(ctx, 'htauth'):
            auth_header = request.headers.get('Authorization', None)
            if not auth_header:
                return _unauthorized_response()

            if not auth_header.startswith('Basic '):
                raise RuntimeError('Flask-HTAuth supports only Basic auth.')

            auth_header = auth_header.replace('Basic ', '')
            auth_header = base64.b64decode(auth_header)
            username, password = auth_header.split(':', 1)

            if not username in ctx.htauth['users']:
                return _unauthorized_response()

            if not check_password(password, ctx.htauth['users'][username]):
                return _unauthorized_response()

            g.htauth_user = username

        return viewfunc(*args, **kwargs)

    return wrapper
1341162
def authenticate_credentials(self, userid, password, request=None):
        """"""

        user = auth.authenticate(username=userid, password=password)

        if user is None or (user and not user.is_active):
            raise exceptions.AuthenticationFailed("Invalid username/password.")

        return (user, None)