Exemple #1
0
    def data_association(self, association_id=None):
        self.container.validate_auth()

        attributes = request.json or {}

        if request.method == 'POST':
            assoc_name = attributes.get('Name', None)
            source_context_id = attributes.get('SourceID', None)
            dest_context_id = attributes.get('DestID', None)

            success, association = self.container.exec_cmd('add-association', params=(assoc_name, source_context_id, dest_context_id))

            response = {}
            if not success:
                response_code = 501
            else:
                response_code = 200
                response = association

            return json_response(response), response_code

        elif request.method == 'PUT':
            assoc_name = attributes.get('Name', None)
            source_context_id = attributes.get('SourceID', None)
            dest_context_id = attributes.get('DestID', None)

            association = self.container.exec_cmd('update-association', params=(assoc_name, source_context_id, dest_context_id))
            return json_response(association)

        elif request.method == 'DELETE':
            self.container.exec_cmd('delete-association', params=(association_id,))
            return json_response(True)
Exemple #2
0
    def data_point(self, point_id=None):
        self.container.validate_auth()
        attributes = request.json or {}

        if not point_id:
            point_id = attributes.get('ID', None)

        try:
            point_id = int(point_id)
        except:
            raise Exception('Invalid PointID')

        if request.method == 'GET':
            response = self.container.exec_cmd('get-point', params=(point_id,))
            return json_response(response)

        elif request.method == 'POST':
            time_offset = 0
            try:
                time_offset = int(attributes.get('1__TimeOffset', 0))
            except:
                pass

            success, point = self.container.exec_cmd('add-point', params=(attributes, point_id))

            response = {}
            if not success:
                response_code = 501
            else:
                response_code = 200
                response = point

            return json_response(response), response_code

        elif request.method == 'PUT':
            create = True
            point = self.container.exec_cmd('update-point', params=(point_id, attributes, create))

            response = {}
            if not point:
                response_code = 501
            else:
                response_code = 200
                response = point

            return json_response(response)

        elif request.method == 'DELETE':
            self.container.exec_cmd('delete-point', params=(point_id,))
            return json_response(True)
Exemple #3
0
    def ping(self):
        if self.api_disabled:
            raise Exception('Interface is not available')

        return json_response({
            'Success': True
        })
Exemple #4
0
def api_exception_handler(error):
    from flask import g

    http_code = 200

    if type(error) is BenomeAuthException:
        error_type = 'Authentication Error'
        http_code = 403
    elif type(error) is BenomeControllerException:
        error_type = 'Controller Error'
    else:
        error_type = 'Internal Error'

    import traceback
    traceback.print_exc()

    error_result = {
        'Error': True,
        'Type': error_type,
        'Message': str(error)
    }

    if hasattr(g, 'jsonp') and g.jsonp:
        return '%s(%s)' % (g.jsonp, simplejson.dumps(error_result))
    else:
        return json_response(error_result), http_code
Exemple #5
0
def user_login():
    username = request.form.get('Username')
    password = request.form.get('Password')

    if not username:
        raise BenomeControllerException('Username required')

    user_details = user_manager.get_user(username=username, exception=False)
    if not user_details:
        raise BenomeControllerException('Login failed')

    user_id = None
    context_id = None

    if current_user and not current_user.is_anonymous and current_user.get_name() == username:
        user_id = current_user.get_id()
        context_id = current_user.get_root_context_id()
        user = current_user
    else:
        user = init_user(username=username, password=password)
        if user:
            login_user(user, remember=True)
            user_id = user.get_id()
            context_id = user.get_root_context_id()
        else:
            raise BenomeControllerException('Login failed')

    return json_response(auth_result(user))
Exemple #6
0
    def auth(self):
        if current_user and current_user.is_authenticated() and self.enc_vol and self.enc_vol.is_open(quick=True):
            raise BenomeAuthError('Already authenticated')

        password = request.args.get('Password', None)

        if not password:
            raise BenomeAuthError('Passphrase required')

        if self.enc_vol:
            if self.enc_vol.is_initialized():
                self.enc_vol.open(password)
            elif not self.enc_vol.is_open():
                init_success = self.enc_vol.init(password)

        if not self.enc_vol or self.enc_vol.is_open():
            if self.exec_cmd('init'):
                print 'Database loaded'

            if self.exec_cmd('inituser'):
                print 'User initialized'

            user = init_user('ContainerUser')
            login_user(user, remember=True)
            return json_response('Success'), 200
        else:
            raise BenomeDataError('Unavailable')

        raise BenomeAuthError('Unauthorized')
Exemple #7
0
    def data_context(self, context_id):
        self.container.validate_auth()

        try:
            context_id = int(context_id)
        except:
            raise Exception('Invalid ContextID')

        attributes = request.json or {}

        context = None
        if request.method == 'GET':
            response = self.container.exec_cmd('get-context', params=(context_id,))
            return json_response(response)

        elif request.method == 'POST':
            parent_id = attributes.get('ParentID')
            label = attributes.get('1__Label')
            try:
                del attributes['1__Label']
            except:
                pass
                
            timestamp = None
            success, context = self.container.exec_cmd('add-context', params=(parent_id, label, context_id, timestamp, attributes))

            response = {}
            if not success:
                response_code = 501
            else:
                response_code = 200
                response = context
            return json_response(response), response_code

        elif request.method == 'PUT':
            success, context = self.container.exec_cmd('update-context', params=(context_id, attributes))
            return json_response(context)

        elif request.method == 'DELETE':
            self.container.exec_cmd('delete-context', params=(context_id,))
            return json_response(True)

        return json_response(True), 200
Exemple #8
0
    def get_id_block(self, block_size=None):
        if block_size:
            block_size = int(block_size)

        block_begin, block_end = self.container.exec_cmd('get-id-block', params=(block_size,))

        return json_response({
            'Begin': block_begin,
            'End': block_end
        }), 200
Exemple #9
0
    def unauth(self):
        if not current_user or not current_user.is_authenticated():
            raise BenomeAuthError('Unauthorized')

        logout_user()

        if self.enc_vol:
            self.enc_vol.close()

        return json_response('Closed'), 200
Exemple #10
0
def user_logout():
    if current_user and not current_user.is_anonymous:
        logout_user()
    else:
        raise BenomeControllerException('Not logged in')

    response = {
        'Success': True
    }

    return json_response(response)
Exemple #11
0
def data_load(context_id=None):
    if not current_user or current_user.is_anonymous:
        return json_response({
            'ContextID': None,
            'Points': [],
            'Contexts': [],
            'Associations': []
        })

    if not context_id or str(context_id) in ('null', 'None'):
        context_id = current_user.get_root_context_id()

    contexts = call_container('get_contexts', data=context_id)
    points = call_container('get_points', data=context_id)
    associations = call_container('get_associations', data=context_id)

    return json_response({
        'ContextID': context_id,
        'LastID': current_user.get_last_id(),
        'Points': points,
        'Contexts': contexts,
        'Associations': associations
    })
Exemple #12
0
def user_change_password():
    if current_user and current_user.is_anonymous:
        raise BenomeControllerException('Must be already authenticated')

    old_password = request.form.get('OldPassword')
    new_password = request.form.get('NewPassword')

    if not old_password or old_password == new_password:
        raise BenomeControllerException('Invalid input')

    success = user_manager.change_password(current_user.get_id(), old_password, new_password)

    response = {
        'Success': success
    }
    return json_response(response)
Exemple #13
0
    def data_points(self, context_id):
        self.container.validate_auth()

        anchor_time = None
        try:
            anchor_time = int(request.args.get('AnchorTime'))
        except:
            pass

        interval = None
        try:
            interval = int(request.args.get('Interval'))
        except:
            pass

        result = self.container.exec_cmd('get-points', params=(context_id, anchor_time, interval))
        return json_response(result), 200
Exemple #14
0
def api_exception_handler(error):
    return_code = 200

    if 'BenomeAuthError' in str(error.__class__):
        error_type = 'Auth Error'
        return_code = 401
    elif 'BenomeDataError' in str(error.__class__):
        error_type = 'Data Error'
        return_code = 403
    elif 'BenomeContainerException' in str(error.__class__):
        error_type = 'Container Error'
    else:
        error_type = 'Internal Error'

    error_result = {
        'Error': True,
        'Type': error_type,
        'Message': str(error)
    }
    return json_response(error_result), return_code
Exemple #15
0
    def get_report(self):
        self.container.validate_auth()

        attributes = request.json

        context_id = int(attributes.get('ContextID'))
        interval = attributes.get('Interval')
        day = attributes.get('Day', None)
        month = attributes.get('Month', None)
        year = attributes.get('Year', None)
        begin_date = attributes.get('BeginDate', None)

        # (Y, M, D)
        if begin_date:
            pass        

        max_depth = attributes.get('MaxDepth', None)
        leaf_notes = attributes.get('LeafNotes', True)
        leaf_note_timing = attributes.get('LeafNoteTiming', False)
        public = attributes.get('Public', False)

        params = (context_id, interval, day, month, year, begin_date, max_depth, leaf_notes, leaf_note_timing, public)
        report = self.container.exec_cmd('get-report', params=params)
        success = not not report

        if not success:
            response_code = 501
        else:
            response_code = 200

        return json_response({
            'Success': success,
            'Data': {
                'Report': report
            }
        }), response_code
Exemple #16
0
 def get_last_id(self):
     result = self.container.exec_cmd('get-last-id', params=())
     return json_response(result), 200
Exemple #17
0
 def get_root_context_id(self):
     result = self.container.exec_cmd('get-root-context-id', params=())
     return json_response(result), 200
Exemple #18
0
    def data_contexts(self, context_id, anchor_time=None, interval=None):
        self.container.validate_auth()

        result = self.container.exec_cmd('get-contexts', params=(context_id, anchor_time, interval))
        return json_response(result), 200
Exemple #19
0
    def data_associations(self, context_id):
        self.container.validate_auth()

        result = self.container.exec_cmd('get-associations', params=(context_id,))
        return json_response(result), 200
Exemple #20
0
def client_test():
    if not current_user or current_user.is_anonymous:
        return 'Unauthorized', 403

    return json_response(auth_result(current_user)), 200
Exemple #21
0
            r = requests.get(base_host + url_path, headers=headers, timeout=timeout)

        if callable(r.json):
            json = r.json()
        else:
            json = r.json

        status_code = r.status_code

    except Exception, e:
        print 'Forward error to %s: %s' % (url_path, e)
        json = None
        status_code = 600

    if return_code:
        return json_response(json), status_code
    else:
        return json_response(json)

def call_container(cmd, data=None, port=None, timeout=5, **kwargs):
    base_host = get_container_host()

    # from flask.ext.login import current_user
    # if current_user.is_anonymous:
    #     raise Exception('Authentication required')

    # if not port:
    #     port = current_user.get_port()
    #     if not port or type(port) is not int:
    #         raise Exception('Container not available')
Exemple #22
0
    def sync(self):
        self.exec_cmd('shutdown', disable=True)

        return json_response({
            'Success': True
        })
Exemple #23
0
 def data_query(self, context_id=None):
     result = self.container.exec_cmd('data-query')
     return json_response({
         'GraphData': result
     }), 200