Exemplo n.º 1
0
    def has_permission(self, view):
        token = view.request.headers.get('Authorization')
        session_create = not getattr(view, 'session')
        permission = getattr(view, 'required_project_permission', None)

        if not token:
            return False

        try:
            session = Session() if session_create else getattr(view, 'session')

            if token[:len(self.token_prefix)] == self.token_prefix:
                token = token[len(self.token_prefix):]

                result = project_auth(session, token, permission)

                if result.get('warning'):
                    view.headers['X-Application-Warning'] = result['warning']

                return result['result']
            elif token[:len(self.project_token_prefix
                            )] == self.project_token_prefix:
                token = token[len(self.project_token_prefix):]

                result = project_auth(session, token, permission)

                if result.get('warning'):
                    view.headers['X-Application-Warning'] = result['warning']

                return result['result']
            else:
                return False
        finally:
            if session_create:
                session.close()
Exemplo n.º 2
0
    def get(self, *args, **kwargs):
        try:
            session = Session()
            token, created = register_token(session)

            if not token:
                return

            if is_token_activated(session):
                response = Response(
                    {'message': 'Project token is already activated'})
                self.write_response(response)
                return

            if settings.WEB_BASE_URL.startswith(
                    'https'
            ) and not self.request.full_url().startswith('https'):
                web_base_url = 'http{}'.format(settings.WEB_BASE_URL[5:])
            else:
                web_base_url = settings.WEB_BASE_URL

            url = '{}/projects/register/{}'.format(web_base_url, token.token)
            query_string = 'referrer={}'.format(
                quote(self.request.full_url().encode('utf8')))

            self.redirect('%s?%s' % (url, query_string))
        finally:
            session.close()
Exemplo n.º 3
0
def token_command():
    try:
        session = Session()
        token = get_token(session)

        if token:
            logging.info('Jet Admin Token:')
            logging.info(token)
        else:
            logging.info('Jet Admin Token is not set')
    finally:
        session.close()
Exemplo n.º 4
0
def set_token_command(args):
    try:
        session = Session()
        token = uuid.UUID(args[1]) if len(args) >= 2 else None

        if not token:
            logging.info('No token was specified')
            return

        set_token(session, token)
    finally:
        session.close()
Exemplo n.º 5
0
def register_token_command():
    try:
        session = Session()
        token, created = register_token(session)

        if not created and token:
            logging.info('Token already exists: {}'.format(token.token))
        elif not created and not token:
            logging.info('Token creation failed')
        elif created and token:
            logging.info('Token created: {}'.format(token.token))
    finally:
        session.close()
Exemplo n.º 6
0
def run_command():
    logging.info(datetime.now().strftime('%B %d, %Y - %H:%M:%S %Z'))
    logging.info('Jet Bridge version {}'.format(VERSION))

    if missing_options == settings.required_options_without_default:
        create_config()
        return
    elif len(missing_options) and len(missing_options) < len(
            settings.required_options_without_default):
        logging.info('Required options are not specified: {}'.format(
            ', '.join(missing_options)))
        return

    from jet_bridge.app import make_app

    app = make_app()
    app.listen(settings.PORT, settings.ADDRESS)
    address = 'localhost' if settings.ADDRESS == '0.0.0.0' else settings.ADDRESS
    url = 'http://{}:{}/'.format(address, settings.PORT)

    logging.info('Starting server at {}'.format(url))

    if settings.DEBUG:
        logging.warning('Server is running in DEBUG mode')

    logging.info('Quit the server with CONTROL-C')

    try:
        session = Session()
        token, created = register_token(session)

        if not token:
            return

        if not is_token_activated(session):
            token = get_token(session)
            register_url = '{}api/register/?token={}'.format(url, token)
            logging.warning('[!] Your server token is not activated')
            logging.warning('[!] Token: {}'.format(token))

            if settings.AUTO_OPEN_REGISTER and webbrowser.open(register_url):
                logging.warning(
                    '[!] Activation page was opened in your browser - {}'.
                    format(register_url))
    except RequestException:
        logging.error('[!] Can\'t connect to Jet Admin API')
        logging.error('[!] Token verification failed')
    finally:
        session.close()

    tornado.ioloop.IOLoop.current().start()
Exemplo n.º 7
0
def run_command():
    from jet_bridge.app import make_app

    app = make_app()
    app.listen(settings.PORT, settings.ADDRESS)
    address = 'localhost' if settings.ADDRESS == '0.0.0.0' else settings.ADDRESS
    url = 'http://{}:{}/'.format(address, settings.PORT)

    logging.info('Starting server at {}'.format(url))

    if settings.DEBUG:
        logging.warning('Server is running in DEBUG mode')

    logging.info('Quit the server with CONTROL-C')

    try:
        session = Session()
        token, created = register_token(session)

        if not token:
            return

        if not is_token_activated(session):
            token = get_token(session)
            register_url = '{}api/register/?token={}'.format(url, token)
            logging.warning('[!] Your server token is not activated')
            logging.warning('[!] Token: {}'.format(token))

            if settings.AUTO_OPEN_REGISTER and webbrowser.open(register_url):
                logging.warning('[!] Activation page was opened in your browser - {}'.format(register_url))
    except RequestException:
        logging.error('[!] Can\'t connect to Jet Admin API')
        logging.error('[!] Token verification failed')
    finally:
        session.close()

    tornado.ioloop.IOLoop.current().start()
Exemplo n.º 8
0
    def execute(self, data):
        session = Session()

        query = data['query']
        params = data.get('params', [])

        try:
            result = session.execute(
                text(query),
                params
            )

            rows = list(map(lambda x: x.itervalues(), result))

            def map_column(x):
                if x == '?column?':
                    return
                return x

            return {'data': rows, 'columns': map(map_column, result.keys())}
        except (SQLAlchemyError, TypeError) as e:
            raise SqlError(e)
        finally:
            session.close()
Exemplo n.º 9
0
class APIView(tornado.web.RequestHandler):
    permission_classes = []
    session = None

    @property
    def data(self):
        content_type = self.request.headers.get('Content-Type', '')
        if content_type.startswith('application/json'):
            return json_decode(self.request.body)
        else:
            return self.request.body_arguments

    def prepare(self):
        method_override = self.request.headers.get('X-Http-Method-Override')
        if method_override is not None:
            self.request.method = method_override

        if self.request.method != 'OPTIONS':
            self.check_permissions()

        self.session = Session()

    def on_finish(self):
        if self.session:
            self.session.close()
            self.session = None

    def set_default_headers(self):
        ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'
        ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers'
        ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials'
        ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers'
        ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods'

        self.set_header(ACCESS_CONTROL_ALLOW_ORIGIN, '*')
        self.set_header(ACCESS_CONTROL_ALLOW_METHODS,
                        'GET, POST, PUT, PATCH, DELETE, OPTIONS')
        self.set_header(
            ACCESS_CONTROL_ALLOW_HEADERS,
            'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,X-Application-Warning,X-HTTP-Method-Override'
        )
        self.set_header(ACCESS_CONTROL_EXPOSE_HEADERS,
                        'Content-Length,Content-Range,X-Application-Warning')
        self.set_header(ACCESS_CONTROL_ALLOW_CREDENTIALS, 'true')

    def get_permissions(self):
        return [permission() for permission in self.permission_classes]

    def check_permissions(self):
        for permission in self.get_permissions():
            if not permission.has_permission(self):
                raise PermissionDenied(
                    getattr(permission, 'message', 'forbidden'))

    def check_object_permissions(self, obj):
        for permission in self.get_permissions():
            if not permission.has_object_permission(self, obj):
                raise PermissionDenied(
                    getattr(permission, 'message', 'forbidden'))

    def options(self, *args, **kwargs):
        self.set_status(204)
        self.finish()

    def build_absolute_uri(self, url):
        return self.request.protocol + "://" + self.request.host + url

    def write_response(self, response):
        for name, value in response.header_items():
            self.set_header(name, value)
        self.write(response.render())

    def write_error(self, status_code, **kwargs):
        exc_type = exc = traceback = None

        if kwargs.get('exc_info'):
            exc_type, exc, traceback = kwargs['exc_info']

            if isinstance(exc, APIException):
                status_code = exc.status_code

        if status_code == status.HTTP_403_FORBIDDEN:
            self.render('403.html', **{
                'path': self.request.path,
            })
        else:
            if settings.DEBUG:
                ctx = {
                    'path':
                    self.request.path,
                    'full_path':
                    self.request.protocol + "://" + self.request.host +
                    self.request.path,
                    'method':
                    self.request.method,
                    'version':
                    VERSION,
                    'current_datetime':
                    datetime.now().strftime('%c'),
                    'python_version':
                    platform.python_version(),
                    'python_executable':
                    sys.executable,
                    'python_path':
                    sys.path
                }

                if exc:
                    last_traceback = traceback

                    while last_traceback.tb_next:
                        last_traceback = last_traceback.tb_next

                    ctx.update({
                        'exception_type':
                        exc_type.__name__,
                        'exception_value':
                        str(exc),
                        'exception_last_traceback_line':
                        last_traceback.tb_lineno,
                        'exception_last_traceback_name':
                        last_traceback.tb_frame
                    })

                self.render('500.debug.html', **ctx)
            else:
                self.render('500.html')