コード例 #1
0
ファイル: tests.py プロジェクト: lapsule/python-basicauth
    def test_properly_escapes_colons(self):
        username, password = '******', 'pass:word:'

        encoded_str = encode(username, password)
        self.assertEqual((username, password), decode(encoded_str))

        # This test ensures things work even if the client doesn't properly URL
        # encode the username / password fields.
        encoded_str = 'Basic %s' % b64encode('%s:%s' % (username, password))
        self.assertEqual((username, password), decode(encoded_str))
コード例 #2
0
ファイル: views.py プロジェクト: fjrmoreews/bioshadock_server
def api_library_delete(request):
    repo_id = None
    repo_id = request.matchdict['namespace'] + '/'+ request.matchdict['image']
    endpoints = request.registry.settings['dockerregistry']
    secret = request.registry.settings['secret_passphrase']
    username = None
    password= None
    if request.authorization:
        (type, bearer) = request.authorization
        username, password = decode(bearer)
        if not valid_user(username, password, request) or not user_can_delete(username, repo_id, request):
            return HTTPForbidden()
    existing_repo = request.registry.db_mongo['repository'].find_one({'id': repo_id})
    if existing_repo is None:
        return Response('')
    token = jwt.encode({'repo': repo_id,
                        'user': username,
                        'acl': 'delete',
                        'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=3600)
                        }, secret)
    docker_token = "signature="+token+",repository=\""+repo_id+"\",access=write"
    headers = [("WWW-Authenticate", "Token "+docker_token.encode('utf8')),
               ("X-Docker-Endpoints", endpoints),("X-Docker-Token", docker_token.encode('utf8'))
              ]
    request.registry.db_mongo['repository'].remove({'id': repo_id})
    request.response.headerlist.extend(headers)
    return Response('Accepted', status_code=202, headerlist=request.response.headerlist)
コード例 #3
0
ファイル: views.py プロジェクト: fjrmoreews/bioshadock_server
def api_repositories_push(request):
    '''
    Library repo
    /v1/repositories/{namespace}/{image}
    '''
    images = json.loads(request.body, encoding=request.charset)
    repo_id = None
    repo_id = request.matchdict['namespace'] + '/'+ request.matchdict['image']
    endpoints = request.registry.settings['dockerregistry']
    secret = request.registry.settings['secret_passphrase']
    username = None
    password= None
    if request.authorization:
        (type, bearer) = request.authorization
        username, password = decode(bearer)
        if not valid_user(username, password, request) or not user_can_push(username, repo_id, request):
            return HTTPForbidden()
    existing_repo = request.registry.db_mongo['repository'].find_one({'id': repo_id})

    request.registry.db_mongo['repository'].update({'id': repo_id}, {"$set":{'images': images}})

    (type, bearer) = request.authorization

    token = jwt.encode({'repo': repo_id,
                        'user': username,
                        'acl': 'write',
                        'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=3600)
                        }, secret)
    docker_token = "signature="+token+",repository=\""+repo_id+"\",access=write"
    headers = [("WWW-Authenticate", "Token "+docker_token.encode('utf8')),
               ("X-Docker-Endpoints", endpoints),("X-Docker-Token", docker_token.encode('utf8'))
              ]
    request.response.headerlist.extend(headers)
    return Response('Created', headerlist=request.response.headerlist)
コード例 #4
0
ファイル: __init__.py プロジェクト: kcaylor/old_api
 def pre_GET(resource, request, lookup):
     # If we made it this far, then api_key will resolve.
     # Note: auth has already filtered requests against users
     # and messages
     if request.headers.get('Authorization'):
         api_key, password = decode(request.headers.get('Authorization'))
     user = app.data.models['user'].objects(
         api_key=api_key
     ).first()
     if user:
         # No need to alter anything with admin-only access:
         if len(app.config['DOMAIN'][resource]['allowed_roles']) > 0:
             return
         # If querying pods, filter to owner only:
         elif resource in ['pod']:
             if user.role == 'admin':
                 app.logger.debug("user is admin: do nothing")
                 return
             else:
                 lookup['owner'] = user.id
             # app.auth.set_request_auth_value(user.id)
         # For data and notebooks, filter to public or owned:
         else:
             if user.role == 'admin':
                 return
             else:
                 lookup['$or'] = [{'public': True}, {'owner': user.id}]
コード例 #5
0
ファイル: views.py プロジェクト: fjrmoreews/bioshadock_server
def api_library_images(request):
    '''
    Library repo
    /v1/repositories/{image}/images
    '''
    #images = json.loads(request.body, encoding=request.charset)
    repo_id = 'library/' + request.matchdict['image']
    existing_repo = request.registry.db_mongo['repository'].find_one({'id': repo_id})
    if existing_repo is None:
        return HTTPNotFound()
    endpoints = request.registry.settings['dockerregistry']
    secret = request.registry.settings['secret_passphrase']
    username = None
    password= None
    if request.authorization:
        (type, bearer) = request.authorization
        username, password = decode(bearer)
        if not valid_user(username, password, request):
            return HTTPForbidden()
    (type, bearer) = request.authorization
    token = jwt.encode({'repo': repo_id,
                        'user': username,
                        'acl': 'read',
                        'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=3600)
                        }, secret)
    docker_token = "signature="+token+",repository=\""+repo_id+"\",access=read"
    headers = [("WWW-Authenticate", "Token "+docker_token.encode('utf8')),
               ("X-Docker-Endpoints", endpoints),("X-Docker-Token", docker_token.encode('utf8'))
              ]
    request.registry.db_mongo['repository'].update({'id': repo_id},{"$inc": { "pulls": 1}})
    request.response.headerlist.extend(headers)
    return Response(json.dumps(existing_repo['images']), headerlist=request.response.headerlist)
コード例 #6
0
ファイル: RouteUtils.py プロジェクト: Sh4yy/CherryAuth
def extract_basic(authorization):
    """
    extract basic authorization from header
    :param authorization: Authorization header value
    :return: uid, password on success
    :raises TokenDoesNotExist:
    """
    if not authorization:
        raise TokenDoesNotExist()

    return basicauth.decode(authorization)
コード例 #7
0
ファイル: decorators.py プロジェクト: rdegges/flask-samurai
    def decorated_function(*args, **kwargs):
        try:
            username, password = decode(request.headers['AUTHORIZATION'])
        except (DecodeError, KeyError):
            abort(401)

        if (username != current_app.config.get('SAMURAI_USERNAME') or
                password != current_app.config.get('SAMURAI_PASSWORD')):
            abort(401)

        return f(*args, **kwargs)
コード例 #8
0
def basic_auth(auth_request):
    username, password = decode(auth_request.token)
    if username == password:
        context = {"is_admin": True}
        return AuthResponse(
            routes=[AuthRoute("/*", ["GET", "POST"])],
            principal_id=username,
            context=context,
        )
    else:
        return AuthResponse(routes=[], principal_id=None)
コード例 #9
0
ファイル: server.py プロジェクト: cooperlees/firestarter
async def _get_user_and_ip(
    request: web.Request, ip_header: str = "X-Forwarded-For"
) -> Tuple[str, str]:
    user = "******"
    ip = str(request.remote)
    if "Authorization" in request.headers:
        user, _ = basicauth.decode(request.headers["Authorization"])
        if ip_header in request.headers and request.headers[ip_header]:
            ip = request.headers[ip_header]

    return (user, ip)
コード例 #10
0
def webhook():
    """This method handles the http requests for the Dialogflow webhook

    This is meant to be used in conjunction with the weather Dialogflow agent
    """
    # request.headers is actually an EnvironHeaders object that can be accessed like a dictionary
    # Extract the request headers
    #return environmentVariable['COMPUTERNAME']
    res="Undefined"
    
    headers = dict(request.headers)
    
    
    # To decode an encoded basic auth string:'''
    
    try:
        encoded_str = headers['Authorization']
        username, password = decode(encoded_str)
        hash = pbkdf2_sha256.hash(password)
        
        
        if username != env['config.username'] and pbkdf2_sha256.verify(password, hash):
            res = "You are not allowed to call this API"
            return make_response(jsonify({'fulfillmentText': res}))
    except AttributeError:
        res = 'illegal operation'
        return make_response(jsonify({'fulfillmentText': res}))
  
    
    req = request.get_json(silent=True, force=True)
    
    try:
        action = req.get('queryResult').get('action')
        print('Current action: '+action)
    except AttributeError:
        res =  'json error'
        return make_response(jsonify({'fulfillmentText': res}))

    if action == 'register-truck':
        res = registerTruck(req)
    if action == 'add_user':
        res = add_user(req)
    if action == 'search_truck':
        res = search(req)
    if action == 'auth':
        res = auth(req)
    if action == 'email':
        res = covadMail(req)
    else:
        log.error('Unexpected action.')

    return make_response(jsonify({'fulfillmentText': res}))
コード例 #11
0
ファイル: views.py プロジェクト: Bek-End/TirmizakoBack
 def get(request):
     username, password = decode(request.headers['Authorization'])
     account = authenticate(username=username, password=password)
     prod_list = []
     if (account is not None):
         items = UserCart.objects.all().filter(user=account)
         for element in items.iterator():
             prod_list.append(element.fruit)
         products = FruitSerializer(prod_list, many=True)
         return Response({"products": products.data},
                         status=status.HTTP_200_OK)
     else:
         return Response(status=status.HTTP_401_UNAUTHORIZED)
コード例 #12
0
ファイル: localuser.py プロジェクト: redhat-cip/managesf
def bind_user(authorization):
    try:
        username, password = decode(authorization)
        username = unicode(username, encoding='utf8')
    except DecodeError:
        raise BindForbidden("Wrong authorization header")
    ret = model.get_user(username)
    if not ret:
        raise UserNotFound("%s not found" % username)
    if pbkdf2_sha256.verify(password, ret['hashed_password']):
        del ret['hashed_password']
        return ret
    else:
        raise BindForbidden("Authentication failed")
コード例 #13
0
 def wrapper(*args, **kwargs):
     auth_code = request.headers['authorization']
     email, password = decode(auth_code)
     user_dict = app.db.users.find_one({'email': email})
     if user_dict is not None:
         encoded_pw = password.encode('utf-8')
         if bcrypt.hashpw(
                 encoded_pw,
                 user_dict['password']) == user_dict['password']:
             return func(*args, **kwargs)
         else:
             return ({'error': 'email or password incorect'}, 401, None)
     else:
         return ({'error': 'user does not exist'}, 400, None)
コード例 #14
0
ファイル: routes.py プロジェクト: pbullor/CryptoSmart-Wallet
def Login():
    headers = request.headers
    AuthHeader = headers['Authorization']
    email, password = decode(AuthHeader)

    # Validate User
    user = CryptoUser.query.filter_by(email=email.lower(),
                                      password=password.lower()).first()
    if user is None:
        return jsonify({"msg": "Correo o Contraseña incorrecta"}), 401

    # Create Token
    delta = relativedelta(minutes=30)
    access_token = create_access_token(identity=user.id, expires_delta=delta)
    return jsonify({"token": access_token, "user_id": user.id}), 200
コード例 #15
0
def auth(event, context):
    user, pwd = decode(event['headers']['Authorization'])
    if user != config['username'] or pwd != config['password']:
        raise Exception('Unauthorized')
    principalId = user
    tmp = event['methodArn'].split(':')
    apiGatewayArnTmp = tmp[5].split('/')
    awsAccountId = tmp[4]
    policy = AuthPolicy(principalId, awsAccountId)
    policy.restApiId = apiGatewayArnTmp[0]
    policy.region = tmp[3]
    policy.stage = apiGatewayArnTmp[1]
    policy.allowAllMethods()
    authResponse = policy.build()
    return authResponse
コード例 #16
0
def check_auth_token(headers):
    token = headers.get('Shorturl-Access-Token')
    if token is not None:
        try:
            user, passwd = decode(token)
            user_in_db = au_model.User.query.filter_by(username=user).first()
            if user_in_db is not None:
                if user_in_db.check_password(passwd):
                    if user_in_db.verified:
                        return True, user
                    return False, user
            return False, ''
        except DecodeError as e:
            logging.error(e)
            return False, ''
    else:
        return False, 'public'
コード例 #17
0
ファイル: user_basics.py プロジェクト: AnandMoorthy/ReadMe
def signin(request):
    """ Login Module """
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    platform = body['platform']
    print platform
    if 'HTTP_AUTHORIZATION' not in request.META:
        return JsonResponse({"details":"Authorization code missing"}, status=401)
    email, password = decode(request.META['HTTP_AUTHORIZATION'])
    print email, password
    token = generate_hash()
    user_details = UserDetails.objects.filter(email=email)
    if len(user_details) == 0:
        return JsonResponse({'message':'Invalid Email'}, status=401)
    if user_details[0].password == password:
        if platform == "android":
            UserDetails.objects.filter(
                email=email
            ).update(android_token=token)
        if platform == "ios":
            UserDetails.objects.filter(
                email=email
            ).update(ios_token=token)
        if platform == "desktop":
            UserDetails.objects.filter(
                email=email
            ).update(desktop_token=token)
        # UserDetails.objects.filter(email=email).update(token=token)
        get_user_details = UserDetails.objects.filter(email=email)
        if platform == "android":
            token_platform = get_user_details[0].android_token
        if platform == "ios":
            token_platform = get_user_details[0].ios_token
        if platform == "desktop":
            token_platform = get_user_details[0].desktop_token
        data_to_return = {
            'id':get_user_details[0].id,
            'name':get_user_details[0].name,
            'username':get_user_details[0].username,
            'email':get_user_details[0].email,
            'access_token':token_platform,
            }
        return JsonResponse({'message':'Login Success', 'user':data_to_return}, status=200)
    else:
        return JsonResponse({'message':'Incorrect Password'}, status=401)
コード例 #18
0
    def authenticate_client_id(
        self,
        client_id: str,
        request: oauthlib.common.Request,
        *args: Any,
        **kwargs: Any,
    ) -> bool:
        """
        Ensure client_id belong to a non-confidential client.

        A non-confidential client is one that is not required to authenticate
        through other means, such as using HTTP Basic.

        Note, while not strictly necessary it can often be very convenient
        to set request.client to the client object associated with the
        given client_id.

        Method is used by:
            - Authorization Code Grant
        """
        del args, kwargs

        LOG.debug("authenticate_client_id %s", client_id)

        from c2cgeoportal_commons.models import DBSession, static  # pylint: disable=import-outside-toplevel

        params = dict(request.decoded_body)

        if "client_secret" in params:
            client_secret = params["client_secret"]
        elif "Authorization" in request.headers:
            username, password = basicauth.decode(
                request.headers["Authorization"])
            assert client_id == username
            client_secret = password
        else:
            # Unable to get the client secret
            return False

        request.client = (DBSession.query(static.OAuth2Client).filter(
            static.OAuth2Client.client_id == client_id).filter(
                static.OAuth2Client.secret == client_secret).one_or_none())

        LOG.debug("authenticate_client_id => %s", request.client is not None)
        return request.client is not None
コード例 #19
0
 def process_request(self, req, resp):
     if req.path in {'/api/ping', '/api/status'}:
         return True
     
     log.debug("authenticator.process_request")
     try:
         username, password = basicauth.decode(req.auth)
         u = self.mapper.user.User.get_by_username(username, application_flag=True)
         if u:
             log.debug("checking %s: %s", username, password)
             log.debug("against  %s: %s", password, u.password)
             user_applications = {a.uid for a in u.applications}
             if all((self.application_id in user_applications, compare_passwords(password, u.password))):
                 return True
     except Exception as e:
         log.debug("Caught an exception during authentication: {}".format(e))
     
     raise falcon.HTTPUnauthorized('401 Unauthorized', "Authentication required", ['Basic realm="eContext Authentication"'])
コード例 #20
0
def basicAuth(username, password, hash):
    #GET USER, PASSWORD
    print(
        "################ Uebergabe von Benutzername und Passwort ###############"
    )
    #username, password = "******", "MTB_Admin"
    encode_str = encode(username, password)
    print(encode_str)
    print(
        "################ Uebergabe von Benutzername und Passwort ###############"
    )
    print(
        "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    )
    print("################ Uebergabe von Hash ###############")
    #GET HASH
    username, password = decode(encode_str)
    print(username, password)
    print("################ Uebergabe von Hash ###############")
コード例 #21
0
 def wrapper(*args, **kwargs):
     auth = request.authorization
     # Gets the headers in the Authorization JSON
     auth_code = request.headers['authorization']
     # import pdb; pdb.set_trace()
     email, password = decode(auth_code)
     if email is not None and password is not None:
         user_collection = app.db.users
         found_user = user_collection.find_one({"email" : email})
         if found_user is not None:
             encoded_password = password.encode("utf-8")
             if bcrypt.checkpw(encoded_password, found_user["password"]):
                 return func(*args, **kwargs)
             else:
                 return ({'error' : 'email or password is not correct'}, 401, None)
         else:
             return ({'error' : 'email or password is not correct'}, 401, None)
     else:
      return ({'error' : 'could not find user in the database'})
コード例 #22
0
    def delete(self):

        # pdb.set_trace()
        auth_code = request.headers['authorization']
        #email_json = auth.username('email')
        email_json, password = decode(auth_code)

        if self.is_user_exist(email_json) is True:
            user_dict = app.db.users.find_one({'email': email_json})
            app.db.users.remove(user_dict)
            return ({
                'delete': 'the user ' + email_json + ' as been deleted'
            }, 200, None)
        else:

            return ({
                'error':
                'User with email ' + email_json + " does not exist"
            }, 404, None)
コード例 #23
0
ファイル: views.py プロジェクト: fjrmoreews/bioshadock_server
def api_library_images_push(request):
    images = json.loads(request.body, encoding=request.charset)
    repo_id = None
    repo_id = 'library/'+ request.matchdict['image']
    endpoints = request.registry.settings['dockerregistry']
    secret = request.registry.settings['secret_passphrase']
    username = None
    password= None
    if request.authorization:
        (type, bearer) = request.authorization
        username, password = decode(bearer)
        if not valid_user(username, password, request):
            return HTTPForbidden()
    if images:
        existing_repo = request.registry.db_mongo['repository'].find_one({'id': repo_id})
        if existing_repo is None:
            return HTTPNotFound()
        return {"access": True}
    else:
        return Response('',status_code=204)
コード例 #24
0
ファイル: views.py プロジェクト: Bek-End/TirmizakoBack
 def post(request):
     username, password = decode(request.headers['Authorization'])
     account = authenticate(username=username, password=password)
     day, month, year = (request.data["today"]).split(".")
     print(day, month, year)
     if (account is not None):
         fruits = Fruit.objects.all()
         for fruit in fruits.iterator():
             exDay, exMonth, exYear = fruit.expire_date.split(".")
             today = datetime(day=int(day),
                              month=int(month),
                              year=int(year))
             exPireDate = datetime(day=int(exDay),
                                   month=int(exMonth),
                                   year=int(exYear))
             if (today >= exPireDate):
                 fruit.isExpired = True
                 fruit.save()
                 print("cool")
         return Response(status=status.HTTP_200_OK)
     else:
         return Response(status=status.HTTP_401_UNAUTHORIZED)
コード例 #25
0
 def __init__(self, auth=None, basicauth=None, basicauthfile=None):
     # type: (Optional[Tuple[str, str]]) -> None
     s = requests.Session()
     if basicauthfile is not None:
         if basicauth is not None:
             raise DownloadError('Both basicauth and basicauthfile supplied!')
         elif auth is not None:
             raise DownloadError('Both auth and basicauthfile supplied!')
         else:
             basicauth = load_file_to_str(basicauthfile)
     if basicauth is not None:
         if auth is None:
             auth = decode(basicauth)
         else:
             raise DownloadError('Both auth and basicauth supplied!')
     s.auth = auth
     retries = Retry(total=5, backoff_factor=0.4, status_forcelist=[429, 500, 502, 503, 504], raise_on_redirect=True,
                     raise_on_status=True)
     s.mount('http://', HTTPAdapter(max_retries=retries, pool_connections=100, pool_maxsize=100))
     s.mount('https://', HTTPAdapter(max_retries=retries, pool_connections=100, pool_maxsize=100))
     self.session = s
     self.response = None
コード例 #26
0
def basic_auth(auth_header, api_key_service, user_service):
    # we expect a basic Authorization header: "Basic base64('api_key,secret_key')"
    # E.g. auth_header = encode('rdegges', 'omghax!!!') ## => auth_header = 'Basic cmRlZ2dlczpvbWdoYXglMjElMjElMjE='
    # E.g. api_key, secret_key = decode(auth_header) ## ==> 'rdegges', 'omghax!!!'
    api_key_value, secret_key_value = decode(auth_header)

    api_key_record = api_key_service.get_api_key(api_key_value, False)
    if not api_key_record:
        raise DartAuthenticationException(
            'DART is unable to authenticate your request, api_key missing or not found. api_key=%s' % api_key_value)

    user_record = user_service.get_user_by_email(api_key_record.user_id, False)
    if not user_record:
        raise DartAuthenticationException(
            'DART is unable to authenticate your request, user not found. user_id=%s' % api_key_record.user_id)

    # Authenticated means: 1. We found the user in the user table, 2. The secret key is matching the one in the api_key table.
    user_record.is_authenticated = api_key_record.api_secret and (api_key_record.api_secret == secret_key_value)

    if not user_record.is_authenticated:
        raise DartAuthenticationException('DART is unable to authenticate your request')

    return user_record
コード例 #27
0
def get_tile(path):
    s3key = 'tiles/' + path
    try:
        # we cheat with a usual basic-auth header to get the AWS public and secret key
        # the true authorization will be done via boto3 on AWS api
        # reminder:
        # Authorization: Basic $(echo -n aws_key:aws_secret.session_token | base64 --wrap=0)
        authHeader = request.headers['Authorization']
    except AttributeError as e:
        raise NgmHttpError('Authorization required',
                           status.HTTP_401_UNAUTHORIZED)
    except KeyError as e:
        raise NgmHttpError('Authorization required',
                           status.HTTP_401_UNAUTHORIZED)
    try:
        access_key, tmp = decode(authHeader)
        aws_secret_key, session_token = tmp.split('.')
    except Exception as e:
        raise NgmHttpError("unknown error: {}".format(e),
                           status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return get_file_from_bucket('ngm-dev-authenticated-resources', s3key,
                                access_key, aws_secret_key, session_token)
コード例 #28
0
ファイル: default.py プロジェクト: Mexarm/hzdauth
def verifyuser():
    from basicauth import decode
    response.view = 'generic.json'
    #return response.toolbar()
    auth_header = request.env.HTTP_AUTHORIZATION
    if not auth_header: raise HTTP(400)  #bad request
    body = request.post_vars
    if not request.env.CONTENT_TYPE == "application/json":
        raise HTTP(400)  # bad request
    username = body['username'] if 'username' in body else False
    if not username: raise HTTP(400)  #bad request
    user, apikey = decode(auth_header)
    #return dict(user = user, apikey=apikey)
    if user <> 'api': raise HTTP(401)  # not authorized
    tenant = db(db.tenant.apikey == apikey).select(limitby=(0, 1)).first()
    if not tenant: raise HTTP(401)  # not authorized
    #this is a valid request
    dbuser = db(db.auth_user.email == username).select(limitby=(0, 1)).first()
    if not dbuser: raise HTTP(404)  #user does no exist
    #send email to user
    if not auth.email_reset_password(dbuser):
        raise HTTP(500)  ## email not sent
    return dict(message="email enviado")
コード例 #29
0
    def wrapper(*args, **kwargs):
        auth = request.authorization
        print('***********')
        print(request.authorization)
        print('***********')
        auth_code = request.headers['authorization']
        email, password = decode(auth_code)

        if email is not None and password is not None:
            user = user_collection.find_one({'email': email})
            if user is not None:
                encoded_password = password.encode('utf-8')
                if bcrypt.checkpw(encoded_password, user['password']):
                    return func(*args, **kwargs)
                else:
                    return ({
                        'error': 'email or password is not correct'
                    }, 401, None)
            else:
                return ({
                    'error': 'could not find user in the database'
                }, 400, None)
        else:
            return ({'error': 'enter both email and password'}, 400, None)
コード例 #30
0
 def test_decodes_fully_encoded_strings(self):
     username, password = '******', 'password'
     encoded_str = encode(username, password)
     self.assertEqual((username, password), decode(encoded_str))
コード例 #31
0
def decode_basic_auth_info(request):
    """Returns a tuple of the username, password from basic auth header.
  """
    auth_string = request.headers['Authorization']
    auth_username, auth_password = basicauth.decode(auth_string)
    return (auth_username, auth_password)
コード例 #32
0
 def test_decodes_hashes_only(self):
     username, password = '******', 'omgawesome!'
     encoded_str = encode(username, password)
     encoded_hash = encoded_str.split(' ')[1]
     self.assertEqual((username, password), decode(encoded_hash))
コード例 #33
0
def get_session(
    user_agent: Optional[str] = None,
    user_agent_config_yaml: Optional[str] = None,
    user_agent_lookup: Optional[str] = None,
    use_env: bool = True,
    fail_on_missing_file: bool = True,
    **kwargs: Any,
) -> requests.Session:
    """Set up and return Session object that is set up with retrying. Requires either global user agent to be set or
    appropriate user agent parameter(s) to be completed. If the EXTRA_PARAMS or BASIC_AUTH environment variable is
    supplied, the extra_params* parameters will be ignored.

    Args:
        user_agent (Optional[str]): User agent string. HDXPythonUtilities/X.X.X- is prefixed.
        user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml.
        user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied.
        use_env (bool): Whether to read environment variables. Defaults to True.
        fail_on_missing_file (bool): Raise an exception if any specified configuration files are missing. Defaults to True.
        **kwargs: See below
        auth (Tuple[str, str]): Authorisation information in tuple form (user, pass) OR
        basic_auth (str): Authorisation information in basic auth string form (Basic xxxxxxxxxxxxxxxx) OR
        basic_auth_file (str): Path to file containing authorisation information in basic auth string form (Basic xxxxxxxxxxxxxxxx)
        extra_params_dict (Dict): Extra parameters to put on end of url as a dictionary OR
        extra_params_json (str): Path to JSON file containing extra parameters to put on end of url OR
        extra_params_yaml (str): Path to YAML file containing extra parameters to put on end of url
        extra_params_lookup (str): Lookup key for parameters. If not given assumes parameters are at root of the dict.
        headers (Dict): Additional headers to add to request.
        status_forcelist (iterable): HTTP statuses for which to force retry. Defaults to [429, 500, 502, 503, 504].
        allowed_methods (iterable): HTTP methods for which to force retry. Defaults t0 frozenset(['GET']).
    """
    s = requests.Session()

    ua = kwargs.get("full_agent")
    if not ua:
        ua = UserAgent.get(user_agent, user_agent_config_yaml,
                           user_agent_lookup, **kwargs)
    s.headers["User-Agent"] = ua

    auths_found = list()
    headers = kwargs.get("headers")
    if headers is not None:
        s.headers.update(headers)
        if "Authorization" in headers:
            auths_found.append("headers")

    extra_params_found = False
    extra_params_dict = None
    basic_auth = None
    if use_env:
        basic_auth_env = os.getenv("BASIC_AUTH")
        if basic_auth_env:
            basic_auth = basic_auth_env
            auths_found.append("basic_auth environment variable")
        extra_params = os.getenv("EXTRA_PARAMS")
        if extra_params:
            if "=" in extra_params:
                extra_params_dict = dict()
                logger.info(
                    "Loading extra parameters from environment variable")
                for extra_param in extra_params.split(","):
                    key, value = extra_param.split("=")
                    extra_params_dict[key] = value
            extra_params_found = True
    if not extra_params_found:
        # only do this if extra params env vars not supplied
        extra_params_dict = kwargs.get("extra_params_dict")
        if extra_params_dict:
            extra_params_found = True
            logger.info("Loading extra parameters from dictionary")

        extra_params_json = kwargs.get("extra_params_json", "")
        if extra_params_json:
            if extra_params_found:
                raise SessionError(
                    "More than one set of extra parameters given!")
            extra_params_found = True
            logger.info(f"Loading extra parameters from: {extra_params_json}")
            try:
                extra_params_dict = load_json(extra_params_json)
            except OSError:
                if fail_on_missing_file:
                    raise
        extra_params_yaml = kwargs.get("extra_params_yaml", "")
        if extra_params_yaml:
            if extra_params_found:
                raise SessionError(
                    "More than one set of extra parameters given!")
            logger.info(f"Loading extra parameters from: {extra_params_yaml}")
            try:
                extra_params_dict = load_yaml(extra_params_yaml)
            except OSError:
                if fail_on_missing_file:
                    raise
        extra_params_lookup = kwargs.get("extra_params_lookup")
        if extra_params_lookup and extra_params_dict:
            extra_params_dict = extra_params_dict.get(extra_params_lookup)
            if extra_params_dict is None:
                raise SessionError(
                    f"{extra_params_lookup} does not exist in extra_params!")
    if extra_params_dict:
        basic_auth_param = extra_params_dict.get("basic_auth")
        if basic_auth_param:
            basic_auth = basic_auth_param
            auths_found.append("basic_auth parameter")
            del extra_params_dict["basic_auth"]

    s.params = extra_params_dict

    basic_auth_arg = kwargs.get("basic_auth")
    if basic_auth_arg:
        basic_auth = basic_auth_arg
        auths_found.append("basic_auth argument")

    auth = kwargs.get("auth")
    if auth:
        auths_found.append("auth argument")
    basic_auth_file = kwargs.get("basic_auth_file")
    if basic_auth_file:
        logger.info(f"Loading basic auth from: {basic_auth_file}")
        try:
            basic_auth = load_file_to_str(basic_auth_file, strip=True)
            auths_found.append(f"file {basic_auth_file}")
        except OSError:
            if fail_on_missing_file:
                raise
    if len(auths_found) > 1:
        auths_found_str = ", ".join(auths_found)
        raise SessionError(
            f"More than one authorisation given! ({auths_found_str})")
    if "headers" not in auths_found:
        if basic_auth:
            auth = decode(basic_auth)
        s.auth = auth

    status_forcelist = kwargs.get("status_forcelist",
                                  [429, 500, 502, 503, 504])
    allowed_methods = kwargs.get(
        "allowed_methods",
        frozenset(["HEAD", "TRACE", "GET", "PUT", "OPTIONS", "DELETE"]),
    )

    retries = Retry(
        total=5,
        backoff_factor=0.4,
        status_forcelist=status_forcelist,
        allowed_methods=allowed_methods,
        raise_on_redirect=True,
        raise_on_status=True,
    )
    s.mount("file://", FileAdapter())
    s.mount(
        "http://",
        HTTPAdapter(max_retries=retries,
                    pool_connections=100,
                    pool_maxsize=100),
    )
    s.mount(
        "https://",
        HTTPAdapter(max_retries=retries,
                    pool_connections=100,
                    pool_maxsize=100),
    )
    return s
コード例 #34
0
ファイル: tests.py プロジェクト: rhelmer/python-basicauth
 def test_decodes_fully_encoded_strings(self):
     username, password = '******', 'password'
     encoded_str = encode(username, password)
     self.assertEqual((username, password), decode(encoded_str))
コード例 #35
0
ファイル: auth.py プロジェクト: michalpomykacz/trickster
 def _get_username_password(self, token: str) -> Tuple[str, str]:
     """Parse base64 string to username and password."""
     try:
         return basicauth.decode(token)
     except basicauth.DecodeError:
         raise AuthenticationError(f'Invalid authentication header {token}.')
コード例 #36
0
ファイル: http.py プロジェクト: ericso/prismo-backend
def decode_basic_auth_info(request):
  """Returns a tuple of the username, password from basic auth header.
  """
  auth_string = request.headers['Authorization']
  auth_username, auth_password = basicauth.decode(auth_string)
  return (auth_username, auth_password)
コード例 #37
0
ファイル: tests.py プロジェクト: rhelmer/python-basicauth
 def test_decodes_empty_username(self):
     self.assertEqual('', decode(encode('', 'password'))[0])
コード例 #38
0
 def test_decodes_empty_username(self):
     self.assertEqual('', decode(encode('', 'password'))[0])
コード例 #39
0
def test_doesnt_decode_invalid_auth_types():
    encoded_str = b'error woot'
    with raises(DecodeError):
        decode(encoded_str)
コード例 #40
0
ファイル: tests.py プロジェクト: rhelmer/python-basicauth
 def test_decodes_empty_password(self):
     self.assertEqual('', decode(encode('username', ''))[1])
コード例 #41
0
ファイル: tests.py プロジェクト: rhelmer/python-basicauth
 def test_properly_escapes_colons(self):
     username, password = '******', 'pass:word:'
     encoded_str = encode(username, password)
     self.assertEqual((username, password), decode(encoded_str))
コード例 #42
0
ファイル: views.py プロジェクト: fjrmoreews/bioshadock_server
def api2_token(request):
    account = None
    try:
        account = request.params['account']
    except Exception:
        pass
    service = request.params['service']
    scope = None
    try:
        scope = request.params['scope']
    except Exception:
        pass
    if request.authorization or request.authorization is None:
        # Login request
        if request.authorization is None:
            account = 'anonymous'
        if account != 'anonymous' and not is_logged(request):
            (type, bearer) = request.authorization
            username, password = decode(bearer)
            if username == 'anonymous':
                username = account
            elif not valid_user(username, password, request):
                logging.error("User authentication failure")
                return HTTPForbidden()
        else:
            username = account
        secret = None

        private_key = None
        passphrase = None
        if request.registry.settings['private_key_passphrase']:
            passphrase = request.registry.settings['private_key_passphrase']
        with open(request.registry.settings['private_key'], 'r') as content_file:
            private_key = load_pem_private_key(content_file.read().encode('utf-8'),
                                              password=passphrase, backend=default_backend())


        pub_key = None
        pem = None
        exponent = None
        modulus = None
        with open(request.registry.settings['public_key'], 'r') as content_file:
            pub_key = content_file.read().encode('utf-8')

            pub_key = load_pem_x509_certificate(pub_key, backend=default_backend())
            pub_key = pub_key.public_key()
            pem = pub_key.public_bytes(
                      encoding=serialization.Encoding.PEM,
                      format=serialization.PublicFormat.SubjectPublicKeyInfo)
            pub_numbers = pub_key.public_numbers()
            exponent = pub_numbers._e
            modulus= pub_numbers._n
            modulus = ('%%0%dx' % (256 << 1) % modulus).decode('hex')[-256:]
            exponent = ('%%0%dx' % (3 << 1) % exponent).decode('hex')[-3:]


        der = None
        with open(request.registry.settings['cacert_der'], 'rb') as content_file:
            der = content_file.read()


        access = []
        if scope is not None:
            scope = scope.split(':')
            type = scope[0]
            repository = scope[1]
            actions = scope[2].split(',')
            allowed_actions = []
            for action in actions:
                if action == 'push' and user_can_push(username, repository, request):
                    allowed_actions.append(action)
                if action == 'pull' and user_can_pull(username, repository, request):
                    allowed_actions.append(action)
                    request.registry.db_mongo['repository'].update({'id': repository},{"$inc": { "pulls": 1}})
                if action == 'manifest' and user_can_pull(username, repository, request):
                    allowed_actions.append('pull')
            access = [
                 {
                   "type": type,
                   "name": repository,
                   "actions": allowed_actions
                 }
            ]
        claims = {'iss': request.registry.settings['issuer'],
                        'sub': username,
                        'aud': service,
                        'access': access,
                        #'nbf': datetime.datetime.utcnow(),
                        'iat': datetime.datetime.utcnow(),
                        'exp': datetime.datetime.utcnow()+datetime.timedelta(seconds=3600*24),
                        }
        token = jwt.encode(claims,
                        private_key,  algorithm='RS256',
                        headers={'jwk': {'kty': 'RSA', 'alg': 'RS256',
                                          'n': base64.urlsafe_b64encode(modulus),
                                          'e': base64.urlsafe_b64encode(exponent),
                                          'x5c': [base64.b64encode(der)]
                        }}
                        )
        return {'token': token}
    return HTTPForbidden()
コード例 #43
0
 def test_decodes_empty_password(self):
     self.assertEqual('', decode(encode('username', ''))[1])
コード例 #44
0
def create_token(data,status):
    username, password = decode(data)
    password = md5.new(password + secret).hexdigest()
    ses = md5.new(username+password).hexdigest()
    
    try:
        res = jwt.decode(session.get(ses),secret,algorithms=['HS256'])
        data = {"token":session.get(ses)}
        return response(data=data,code=200,message="Token Not Expired")

    except jwt.ExpiredSignatureError:
        del session[ses]
        
        if(status=='user'):
            
            sql = "SELECT id,username FROM users WHERE username='******' AND password='******'" % (username,password)
            cur = db.query(sql)
            res = cur.fetchone()
            cur.close()
            result = {
                "id":res[0],
                "username":res[1],
                "status":"user",
                "exp": token_expired
                }
        elif(status=='admin'):
            sql = "SELECT id,username FROM admins WHERE username='******' AND password='******'" % (username,password)
            cur = db.query(sql)
            res = cur.fetchone()
            cur.close()
            result = {
                "id":res[0],
                "username":res[1],
                "status":"admin",
                "exp": token_expired
                }

        print 'processing create token'
        token = jwt.encode(result, secret, algorithm='HS256')
        session[ses] = token
        print "token refreshed"
        
        data = {"token":token}
      
        print "cursor closed token login refresh"
        
        time.sleep(0.1)
        return response(data=data,code=200,message="Token Refreshed")

        
    except:
        
        try:
            
            if(status=='user'):
            
                sql = "SELECT id,username FROM users WHERE username='******' AND password='******'" % (username,password)
                cur = db.query(sql)
                res = cur.fetchone()
                cur.close()
                result = {
                    "id":res[0],
                    "username":res[1],
                    "status":"user",
                    "exp": token_expired
                    }
            elif(status=='admin'):
                sql = "SELECT id,username FROM admins WHERE username='******' AND password='******'" % (username,password)
                cur = db.query(sql)
                res = cur.fetchone()
                cur.close()
                result = {
                    "id":res[0],
                    "username":res[1],
                    "status":"admin",
                    "exp": token_expired
                    }

            print 'processing create token'
            token = jwt.encode(result, secret, algorithm='HS256')
            session[ses] = token
            print "token created"
            #db.commit()
            data = {"token":token}
           # cur.close()
            print "cursor closed token login login"
            
            time.sleep(0.1)
            return response(data=data,code=200,message="Login Success")
            #cur.close()
            #db.close()

        except:
            #cur.close()
            #print "cursor closed token login failed"
            return response(code=403,message="Login Failed")
コード例 #45
0
ファイル: tests.py プロジェクト: rhelmer/python-basicauth
 def test_decodes_hashes_only(self):
     username, password = '******', 'omgawesome!'
     encoded_str = encode(username, password)
     encoded_hash = encoded_str.split(' ')[1]
     self.assertEqual((username, password), decode(encoded_hash))