Пример #1
0
def static_file(filename, root=MEDIA_ROOT):
    """
    Выдает статический файл из файловой системы,
    указанной в MEDIA_ROOT.
    """
    if filename is None:
        raise Forbidden("You must specify a file you'd like to access.")

    valid_path = filename.strip('/')

    valid_path = valid_path.replace('//',
                                    '/').replace('/./',
                                                 '/').replace('/../', '/')

    desired_path = os.path.join(root, valid_path)

    if not os.path.exists(desired_path):
        raise NotFound("File does not exist.")

    if not os.access(desired_path, os.R_OK):
        raise Forbidden("You do not have permission to access this file.")

    ct = str(content_type(desired_path))

    if ct.startswith('text') or ct.endswith('xml') or ct.endswith('json'):
        return open(desired_path, 'r').read()

    return open(desired_path, 'rb').read()
Пример #2
0
    def authenticate(self, request):
        """ Authenticate request using HTTP Basic authentication protocl.

        If the user is successfully identified, the corresponding user
        object is stored in `request.user`. If the request has already
        been authenticated (i.e. `request.user` has authenticated user
        object), this function does nothing.

        Raises Forbidden or Unauthorized if the user authentication
        fails. If no exception is thrown, the `request.user` will
        contain authenticated user object.
        """

        # todo: can we trust that request.user variable is even defined?
        if request.user and request.user.is_authenticated():
            return request.user

        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                if auth[0].lower() == "basic":
                    uname, passwd = base64.b64decode(auth[1]).split(':')
                    user = authenticate(username=uname, password=passwd)
                    if user is not None:
                        if user.is_active:
                            request.user = user
                            return user
                    else:
                        raise Forbidden()

        # either no auth header or using some other auth protocol,
        # we'll return a challenge for the user anyway
        raise Unauthorized()
Пример #3
0
def hent_bruker_fra_db():
    brukernavn = request.environ.get('REMOTE_USER') or "LAN"
    bruker = db.brukere.find_one({"brukernavn": brukernavn})
    if not bruker:
        raise Forbidden("Bruker %s har ingen tilknytning til localbank" %
                        brukernavn)
    return bruker
Пример #4
0
def build_file_response(path,
                        cache_timeout=None,
                        cached_modify_time=None,
                        mimetype=None,
                        default_text_mime=DEFAULT_TEXT_MIME,
                        default_binary_mime=DEFAULT_BINARY_MIME,
                        file_wrapper=FileWrapper,
                        response_type=Response):
    resp = response_type('')
    if cache_timeout and cached_modify_time:
        try:
            mtime = get_file_mtime(path)
        except (ValueError, IOError, OSError):  # TODO: winnow this down
            raise Forbidden(is_breaking=False)
        resp.cache_control.public = True
        if mtime <= cached_modify_time:
            resp.status_code = 304
            resp.cache_control.max_age = cache_timeout
            return resp

    if not isfile(path):
        raise NotFound(is_breaking=False)
    try:
        file_obj = open(path, 'rb')
        mtime = get_file_mtime(path)
        fsize = os.path.getsize(path)
    except (ValueError, IOError, OSError):
        raise Forbidden(is_breaking=False)
    if not mimetype:
        mimetype, encoding = mimetypes.guess_type(path)
    if not mimetype:
        peeked = peek_file(file_obj, 1024)
        is_binary = is_binary_string(peeked)
        if peeked and is_binary:
            mimetype = default_binary_mime
        else:
            mimetype = default_text_mime
    resp.response = file_wrapper(file_obj)
    resp.content_type = mimetype
    resp.content_length = fsize
    resp.last_modified = mtime
    resp.cache_control.max_age = cache_timeout
    return resp
Пример #5
0
    def install(self, event, method='oauth.v2.access'):
        # Handle denials
        if event.query.get('error'):
            logger.error(event.query['error'])
            if self.oauth_error_uri:
                return None, self.oauth_error_uri
            raise Forbidden('OAuth error')

        # Check state
        if self.state != event.query['state']:
            logger.error(
                'States do not match: %r != %r',
                self.state,
                event.query['state'],
            )
            if self.oauth_error_uri:
                return None, self.oauth_error_uri
            raise Forbidden('States do not match')

        # Set up OAuth
        payload = urlencode(
            dict(
                code=event.query.get('code'),
                client_id=self.client_id,
                client_secret=self.client_secret,
                redirect_uri=self.oauth_redirect_uri,
            ))

        # Execute OAuth and redirect
        url = f'https://slack.com/api/{ method }'
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        result = self.post(url, payload, headers)
        app_id = result.get('app_id')
        team_id = result.get('team', {}).get('id')
        channel_id = result.get('incoming_webhook', {}).get('channel_id')
        location = self.oauth_success_uri.format(
            APP_ID=app_id or '',
            TEAM_ID=team_id or '',
            CHANNEL_ID=channel_id or '',
        )

        return result, location
Пример #6
0
    def verify_slack_signature(self, event):
        if not self.verify:  # pragma: no cover
            logger.warning('VERIFICATION DISABLED')
            return True

        # 403 FORBIDDEN if message is older than 5min
        now = datetime.utcnow().timestamp()
        ts = event.headers.get('x-slack-request-timestamp')
        delta = int(now) - int(ts or '0')
        if delta > 5 * 60:
            raise Forbidden('Request too old')

        # 403 FORBIDDEN if signatures do not match
        data = f'{ self.signing_version }:{ ts }:{ event.body }'.encode()
        secret = self.signing_secret.encode()
        hex = hmac.new(secret, data, hashlib.sha256).hexdigest()
        ret = f'{ self.signing_version }={ hex }'
        exp = event.headers.get('x-slack-signature')
        if ret != exp:
            raise Forbidden('Signatures do not match')

        return True
Пример #7
0
def get_kontekst(bank=None):
    bruker = hent_bruker_fra_db()
    bank = bank or bruker["defaultBank"]
    if bank not in bruker["banker"]:
        raise Forbidden("Du har ikke tilgang til bank '%s'" % bank)
    kontoer = db.kontoer.find({"bank": bank})

    return json.dumps({
        "valgtBank": bank,
        "bruker": {
            "brukernavn": bruker["brukernavn"],
            "banker": bruker["banker"],
            "admin": bruker.get("admin", False)
        },
        "kontoer": map(dto.konto, kontoer),
        "valuttaer": valuttaer
    })
Пример #8
0
 def get_file_response(self, path, request):
     try:
         if not isinstance(path, basestring):
             path = '/'.join(path)
         full_path = find_file(self.search_paths, path)
         if full_path is None:
             raise NotFound(is_breaking=False)
     except (ValueError, IOError, OSError):
         raise Forbidden(is_breaking=False)
     bfr = build_file_response
     resp = bfr(full_path,
                cache_timeout=self.cache_timeout,
                cached_modify_time=request.if_modified_since,
                mimetype=None,
                default_text_mime=self.default_text_mime,
                default_binary_mime=self.default_binary_mime,
                file_wrapper=request.environ.get('wsgi.file_wrapper',
                                                 FileWrapper))
     return resp
Пример #9
0
    def get_file_response(self, path, request):
        try:
            if not isinstance(path, basestring):
                path = '/'.join(path)
            full_path = find_file(self.search_paths, path)
            if full_path is None:
                raise NotFound()
            file_obj = open(full_path, 'rb')
            mtime = get_file_mtime(full_path)
            fsize = os.path.getsize(full_path)
        except (ValueError, IOError, OSError):
            raise Forbidden()
        mimetype, encoding = mimetypes.guess_type(full_path)
        if not mimetype:
            peeked = peek_file(file_obj, 1024)
            is_binary = is_binary_string(peeked)
            if peeked and is_binary:
                mimetype = self.default_binary_mime
            else:
                mimetype = self.default_text_mime  # TODO: binary

        resp = Response('')
        cached_mtime = request.if_modified_since
        if self.cache_timeout:
            resp.cache_control.public = True
            if mtime == cached_mtime:
                file_obj.close()
                resp.status_code = 304
                resp.cache_control.max_age = self.cache_timeout
                return resp
        file_wrapper = request.environ.get('wsgi.file_wrapper', FileWrapper)
        resp.response = file_wrapper(file_obj)
        resp.content_type = mimetype
        resp.content_length = fsize
        resp.last_modified = mtime
        return resp
Пример #10
0
 def forbidden(self, message=None):
     return Forbidden(self.request, self.response, message)
Пример #11
0
def krev_admin():
    if not hent_bruker_fra_db().get("admin", False):
        raise Forbidden("Krever admintilgang")
Пример #12
0
def krev_tilgang_til_bank(bank):
    bruker = hent_bruker_fra_db()
    if not bank in bruker["banker"] and not bruker.get("admin", False):
        raise Forbidden("Du har ikke tilgang til bank '%s'" % bank)