Python flask.request.authorization() Examples

The following are 30 code examples of flask.request.authorization(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source File: __init__.py    From confidant with Apache License 2.0 10 votes vote down vote up
def _get_kms_auth_data():
    data = {}
    auth = request.authorization
    headers = request.headers
    if auth and auth.get('username'):
        if not auth.get('password'):
            raise AuthenticationError('No password provided via basic auth.')
        data['username'] = auth['username']
        data['token'] = auth['password']
    elif 'X-Auth-Token' in headers and 'X-Auth-From' in headers:
        if not headers.get('X-Auth-Token'):
            raise AuthenticationError(
                'No X-Auth-Token provided via auth headers.'
            )
        data['username'] = headers['X-Auth-From']
        data['token'] = headers['X-Auth-Token']
    return data 
Example #2
Source File: auth.py    From hydrus with MIT License 8 votes vote down vote up
def check_authentication_response() -> Union[Response, None]:
    """
    Return the response as per the authentication requirements.
    """
    if get_authentication():
        if get_token():
            token = check_token(request, get_session())
            if not token:
                if request.authorization is None:
                    return failed_authentication(False)
                else:
                    return verify_user()
        elif request.authorization is None:
            return failed_authentication(False)
        else:
            return verify_user()
    else:
        return None 
Example #3
Source File: permissions.py    From bepasty-server with BSD 2-Clause "Simplified" License 8 votes vote down vote up
def get_permissions():
    """
    get the permissions for the current user (if logged in)
    or the default permissions (if not logged in).
    """
    auth = request.authorization
    if auth:
        # http basic auth header present
        permissions = lookup_permissions(auth.password)
    elif 'token' in request.values:
        # token present in query args or post form (can be used by cli clients)
        permissions = lookup_permissions(request.values['token'])
    else:
        # look into session, login might have put something there
        permissions = session.get(PERMISSIONS)
    if permissions is None:
        permissions = current_app.config['DEFAULT_PERMISSIONS']
    permissions = set(permissions.split(','))
    return permissions 
Example #4
Source File: auth_ldap3.py    From bbotte.github.io with Apache License 2.0 7 votes vote down vote up
def ldap_protected(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    # this can be configured and taken from elsewhere
    # path, method, groups_allowed (users in Allowed Users group will be allowed to access / with a GET method)
    authorization_config = {
      "/": {
         "GET": ["Allowed Users"]
      }
    }

    auth_endpoint_rule = authorization_config.get(request.url_rule.rule)
    if auth_endpoint_rule is not None:
      groups_allowed = auth_endpoint_rule.get(request.method) or True
    else:
      groups_allowed = True
    
    auth = request.authorization
    if not ('username' in session):
      if not auth or not ldap_authenticate(request,auth.username, auth.password, groups_allowed):
        return auth_401()
    else:
      auth_logger.debug("%s calling %s endpoint"%(session['username'],f.__name__))
    return f(*args, **kwargs)
  return decorated 
Example #5
Source File: utils.py    From BhagavadGita with GNU General Public License v3.0 7 votes vote down vote up
def extract_params():
    """Extract request params."""

    uri = _get_uri_from_request(request)
    http_method = request.method
    headers = dict(request.headers)
    if 'wsgi.input' in headers:
        del headers['wsgi.input']
    if 'wsgi.errors' in headers:
        del headers['wsgi.errors']
    # Werkzeug, and subsequently Flask provide a safe Authorization header
    # parsing, so we just replace the Authorization header with the extraced
    # info if it was successfully parsed.
    if request.authorization:
        headers['Authorization'] = request.authorization

    body = request.form.to_dict()
    return uri, http_method, body, headers 
Example #6
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 7 votes vote down vote up
def exit_maintenance():
    config = get_config()
    auth = request.authorization
    if auth \
            and auth.username in config.MAINTENANCE_CREDENTIALS \
            and config.MAINTENANCE_CREDENTIALS[auth.username] == auth.password:
        try:
            os.remove(config.MAINTENANCE_FILE)  # remove maintenance file
        except OSError:
            return 'Not in maintenance mode. Ignore command.'
        open(os.path.join(os.getcwd(), 'reload'), "w+").close()  # uwsgi reload
        return 'success'
    else:
        return Response(
            'Could not verify your access level for that URL.\n'
            'You have to login with proper credentials', 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'}) 
Example #7
Source File: decorators.py    From CHN-Server with GNU Lesser General Public License v2.1 7 votes vote down vote up
def sensor_auth(view):
    """
    Authenticates the view, allowing access if user
    is authenticated or if requesting from a sensor.
    """
    @wraps(view)
    def wrapped_view(*args, **kwargs):
        if current_user and current_user.is_authenticated:
            return view(*args, **kwargs)
        elif request.authorization:
            auth = request.authorization
            if auth and auth.get('username') == auth.get('password') and\
               Sensor.query.filter_by(uuid=auth.get('username')).count() == 1:
                return view(*args, **kwargs)
        return error_response(errors.API_NOT_AUTHORIZED, 401)
    return wrapped_view 
Example #8
Source File: web.py    From psdash with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def check_access():
    if not current_node:
        return 'Unknown psdash node specified', 404

    allowed_remote_addrs = current_app.config.get('PSDASH_ALLOWED_REMOTE_ADDRESSES')
    if allowed_remote_addrs:
        if request.remote_addr not in allowed_remote_addrs:
            current_app.logger.info(
                'Returning 401 for client %s as address is not in allowed addresses.',
                request.remote_addr
            )
            current_app.logger.debug('Allowed addresses: %s', allowed_remote_addrs)
            return 'Access denied', 401

    username = current_app.config.get('PSDASH_AUTH_USERNAME')
    password = current_app.config.get('PSDASH_AUTH_PASSWORD')
    if username and password:
        auth = request.authorization
        if not auth or auth.username != username or auth.password != password:
            return Response(
                'Access deined',
                401,
                {'WWW-Authenticate': 'Basic realm="psDash login required"'}
            ) 
Example #9
Source File: auth.py    From kytos with MIT License 6 votes vote down vote up
def _authenticate_user(self):
        """Authenticate a user using Storehouse."""
        username = request.authorization["username"]
        password = request.authorization["password"].encode()
        try:
            user = self._find_user(username)[0].get("data")
            if user.get("password") != hashlib.sha512(password).hexdigest():
                raise KeyError
            time_exp = datetime.datetime.utcnow() + datetime.timedelta(
                minutes=TOKEN_EXPIRATION_MINUTES
            )
            token = self._generate_token(username, time_exp)
            return {"token": token.decode()}, HTTPStatus.OK.value
        except (AttributeError, KeyError) as exc:
            result = f"Incorrect username or password: {exc}"
            return result, HTTPStatus.UNAUTHORIZED.value 
Example #10
Source File: scylla.py    From scylla with Apache License 2.0 6 votes vote down vote up
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

#@app.route('/regex', methods = ["POST"])
#def submit_name_regex():
#
    #request.getdata()
#    request_json = json.loads(request.data.decode('utf-8'))
#    regex = request_json["regex"]
#    print(request_json)
#    subprocess.Popen("/usr/bin/nohup find /home/ubuntu/all_unzipped -type f -exec /bin/grep " + regex + " {} + > /var/www/html/results/" + b58encode(regex).decode('utf-8'), shell=True)
#    return "h'ok"

#@app.route("/status") 
Example #11
Source File: app.py    From ambassador-auth-httpbasic with Apache License 2.0 6 votes vote down vote up
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        # Favicon is the little icon associated with a domain in a web browser. Browsers issue a request for the
        # resource /favicon.ico alongside any other HTTP request which pollutes the logs with lots of 404 Not Found logs
        # because usually the favicon cannot be resolved. This tells the browser to go away; there is no favicon here.
        if request.path == "/favicon.ico":
            return Response(status=403)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return unauthorized()

        return f(*args, **kwargs)

    return decorated 
Example #12
Source File: server.py    From tavern with MIT License 6 votes vote down vote up
def expect_basic_auth():
    auth = request.authorization

    if auth is None:
        return jsonify({"status": "No authorisation"}), 403

    if auth.type == "basic":
        if auth.username == "fakeuser" and auth.password == "fakepass":
            return (
                jsonify(
                    {
                        "auth_type": auth.type,
                        "auth_user": auth.username,
                        "auth_pass": auth.password,
                    }
                ),
                200,
            )
        else:
            return jsonify({"error": "Wrong username/password"}), 401
    else:
        return jsonify({"error": "unrecognised auth type"}), 403 
Example #13
Source File: auth.py    From bowtie with MIT License 6 votes vote down vote up
def before_request(self) -> Optional[Response]:
        """Determine if a user is allowed to view this route."""
        auth = request.authorization
        if (
            not auth
            or auth.username is None
            or auth.password is None
            or not self._check_auth(auth.username, auth.password)
        ):
            return Response(
                'Could not verify your access level for that URL.\n'
                'You have to login with proper credentials',
                401,
                {'WWW-Authenticate': 'Basic realm="Login Required"'},
            )
        session['logged_in'] = auth.username
        return None  # pylint wants this return statement 
Example #14
Source File: auth.py    From eve-auth-jwt with MIT License 6 votes vote down vote up
def authorized(self, allowed_roles, resource, method):
        authorized = False

        if request.authorization:
            auth = request.authorization
            authorized = self.check_auth(auth.username, auth.password,
                                         allowed_roles, resource, method)
        else:
            try:
                access_token = request.args['access_token']
            except KeyError:
                access_token = request.headers.get('Authorization', '').partition(' ')[2]
            authorized = self.check_token(access_token, allowed_roles, resource, method)

        return authorized 
Example #15
Source File: server.py    From captcha22 with MIT License 6 votes vote down vote up
def get(self):
        if (not self.auth_source.verify_connect()):
            return make_response(jsonify({'message': 'Unauthorized access'}), 403)

        # First check how many tokens the user has
        username = request.authorization["username"]
        for user in self.data_source.users:
            if username == user.username:
                count = len(user.tokens)
                if count >= self.data_source.max_tokens:
                    return make_response(jsonify({'token': '', 'message': 'maximum amount of tokens generated'}), 200)
                lst = [random.choice(string.ascii_letters + string.digits)
                       for n in range(128)]
                str_ = "".join(lst)
                user.tokens[uuid.uuid1()] = [str_, time.time()]
                return make_response(jsonify({'message': 'success', 'token': str_}), 200)
        # We should now find and modify the file

        return make_response(jsonify({'token': '', 'message': 'token gen failed'}), 200) 
Example #16
Source File: auth.py    From rbb_core with MIT License 5 votes vote down vote up
def requires_auth(only_username_password=False, keyword_arg='user'):
    def requires_auth_inner(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            auth = request.authorization

            # Username & password based authentication
            if auth:
                user = check_auth(auth.username, auth.password)
                if not user:
                    return authenticate(False)
                kwargs[keyword_arg] = user
                return f(*args, **kwargs)

            # Maybe token authentication
            elif not only_username_password:
                session = get_current_session()
                if session:
                    # TODO: Check expiry of auth token
                    kwargs[keyword_arg] = session.user
                    return f(*args, **kwargs)

            return authenticate()

        return decorated
    return requires_auth_inner 
Example #17
Source File: flask_globals.py    From Python-Microservices-Development with MIT License 5 votes vote down vote up
def authenticate():
	if request.authorization:
		g.user = request.authorization['username']
	else:
		g.user = 'Anonymous' 
Example #18
Source File: flask_auth.py    From Python-Microservices-Development with MIT License 5 votes vote down vote up
def auth():
	print("The raw Authorization header")
	print(request.environ["HTTP_AUTHORIZATION"])
	print("Flask's Authorization header")
	print(request.authorization)
	return "" 
Example #19
Source File: apiServer.py    From AutoTriageBot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def authed(func: Callable[[], str]) -> Callable[[], Union[Response, str]]:
    """ Given a function returns one that requires basic auth """
    @wraps(func)
    def decorator():
        auth = request.authorization
        if auth and validAuth(auth.username, auth.password):
            return func()
        return authFailure()
    return decorator 
Example #20
Source File: app.py    From proselint with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rate():
    """Set rate limits for authenticated and nonauthenticated users."""
    auth = request.authorization

    if not auth or not check_auth(auth.username, auth.password):
        return "60/minute"
    else:
        return "600/minute" 
Example #21
Source File: streamer.py    From Flask-OpenCV-Streamer with GNU General Public License v3.0 5 votes vote down vote up
def requires_auth(self, func):
        """A custom decorator for Flask streams"""

        @wraps(func)
        def decorated(*args, **kwargs):
            if self.req_auth:
                auth = request.authorization
                if not auth or not self.check_auth(auth.username, auth.password):
                    return self.authenticate()
                return func(*args, **kwargs)
            else:
                return func(*args, **kwargs)

        return decorated 
Example #22
Source File: auth.py    From PowerHub with MIT License 5 votes vote down vote up
def requires_auth(f):
    @wraps(f)
    def decorated(*largs, **kwargs):
        auth = request.authorization
        if args.AUTH and (not auth or not check_auth(auth.username,
                                                     auth.password)):
            return authenticate()
        return f(*largs, **kwargs)
    return decorated 
Example #23
Source File: admin.py    From flask-boilerplate with MIT License 5 votes vote down vote up
def is_accessible(self):
        auth = request.authorization or request.environ.get('REMOTE_USER')  # workaround for Apache
        if not auth or (auth.username, auth.password) != app.config['ADMIN_CREDENTIALS']:
            raise HTTPException('', Response('You have to an administrator.', 401,
                {'WWW-Authenticate': 'Basic realm="Login Required"'}
            ))
        return True

# Users 
Example #24
Source File: app.py    From pycon with Apache License 2.0 5 votes vote down vote up
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated 
Example #25
Source File: serverutil.py    From Lightning with MIT License 5 votes vote down vote up
def requires_auth(view):
    """Require basic authentication on requests to this view.

    Also only accept requests from localhost.
    """
    @wraps(view)
    def decorated(*args, **kwargs):
        """Decorated version of view that checks authentication."""
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        if request.remote_addr != "127.0.0.1":
            return Response("Access outside 127.0.0.1 forbidden", 403)
        return view(*args, **kwargs)
    return decorated 
Example #26
Source File: basic_auth.py    From flasgger with MIT License 5 votes vote down vote up
def requires_basic_auth(f):
    """Decorator to require HTTP Basic Auth for your endpoint."""

    def check_auth(username, password):
        return username == "guest" and password == "secret"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @wraps(f)
    def decorated(*args, **kwargs):
        # NOTE: This example will require Basic Auth only when you run the
        # app directly. For unit tests, we can't block it from getting the
        # Swagger specs so we just allow it to go thru without auth.
        # The following two lines of code wouldn't be needed in a normal
        # production environment.
        if __name__ != "__main__":
            return f(*args, **kwargs)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated 
Example #27
Source File: decorators_in_init_app.py    From flasgger with MIT License 5 votes vote down vote up
def requires_basic_auth(f):
    """Decorator to require HTTP Basic Auth for your endpoint."""

    def check_auth(username, password):
        return username == "guest" and password == "secret"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @wraps(f)
    def decorated(*args, **kwargs):
        # NOTE: This example will require Basic Auth only when you run the
        # app directly. For unit tests, we can't block it from getting the
        # Swagger specs so we just allow it to go thru without auth.
        # The following two lines of code wouldn't be needed in a normal
        # production environment.
        if __name__ != "__main__":
            return f(*args, **kwargs)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated 
Example #28
Source File: request_filter.py    From openbrokerapi with MIT License 5 votes vote down vote up
def get_auth_filter(broker_credentials):
    def requires_auth():
        """Check authentication over all provided usernames else sends a 401 response that enables basic auth"""
        from flask import request
        auth = request.authorization
        if auth:
            for credentials in broker_credentials:
                if auth.username == credentials.username and auth.password == credentials.password:
                    return
        return to_json_response(ErrorResponse(
            description='Could not verify your access level for that URL.\nYou have to login with proper credentials'
        )), HTTPStatus.UNAUTHORIZED, {'WWW-Authenticate': 'Basic realm="Login Required"'}

    return requires_auth 
Example #29
Source File: home.py    From bluemix-python-eve-sample with Apache License 2.0 5 votes vote down vote up
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated 
Example #30
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def enter_maintenance():
    config = get_config()
    auth = request.authorization
    if auth \
            and auth.username in config.MAINTENANCE_CREDENTIALS \
            and config.MAINTENANCE_CREDENTIALS[auth.username] == auth.password:
        open(config.MAINTENANCE_FILE, "w+").close()  # maintenance file
        open(os.path.join(os.getcwd(), 'reload'), "w+").close()  # uwsgi reload
        return 'success'
    else:
        return Response(
            'Could not verify your access level for that URL.\n'
            'You have to login with proper credentials', 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'})