Beispiel #1
0
def identify_authenticated_user(request):
    bearer_token = request.headers.get('Authorization')
    if not bearer_token:
        raise AppException('Missing authentication token', 401)
    split = bearer_token.split(' ')
    if len(split) != 2:
        raise AppException('Missing authentication token', 401)
    return auth_service.get_user_by_token(split[1])
Beispiel #2
0
        def wrapper(*args, **kwargs):
            user = identify_authenticated_user(request)

            if Roles.validate(role, user['role']):
                return func(*args, **kwargs)

            raise AppException('Role not enough', 403)
Beispiel #3
0
def bulk_delete(collection):
    if not request.json:
        abort(405)
    if not ArgumentParser.validate(request.json):
        raise AppException('Invalid input format', 400)
    query_manager.delete(collection, request.json)
    return jsonify({})
def replicate_auth():
    if request.remote_addr not in DatabaseContext.MASTER:
        raise AppException(
            f'Auth request coming from unknown host {request.remote_addr}',
            403)

    result = auth_service.login_for_api('replicator')
    return jsonify(result)
Beispiel #5
0
    def get_lines(self, col_meta_data, id):
        pname = DatabaseContext.DATA_FOLDER + col_meta_data.collection + '/' + col_meta_data.get_index_fname(
            'id')

        values = FilesReader.get_instance().get_file_content(pname)
        if id in values:
            return values[id]

        raise AppException('Unable to find document with id {}'.format(id),
                           400)
Beispiel #6
0
def search(collection):
    if not request.json:
        abort(405)
    if not ArgumentParser.validate(request.json):
        raise AppException('Invalid input format', 400)
    result = query_manager.search(collection, request.json)
    if len(result) == 0:
        abort(404)
    if SearchContext(request.json).map is None:
        return jsonify(result)
    return jsonify(ResultsMapper.map(result))
Beispiel #7
0
        def wrapper(*args, **kwargs):
            user = identify_authenticated_user(request)

            if Permissions.validate(Roles.EDITOR, user['role']):
                return func(*args, **kwargs)

            collection = kwargs['collection']
            if collection in user['permissions'] and Permissions.validate(
                    permission, user['permissions'][collection]):
                return func(*args, **kwargs)

            raise AppException('Permissions not enough', 403)
Beispiel #8
0
    def login(self, login, password):
        results = self.query_manager.search('users', {
            '$filter': {
                'login': login
            },
            '$size': 1
        })

        if len(results) != 1:
            raise AppException('Authentication failed', 401)
        user = results[0]

        if not self.bcrypt.check_password_hash(user['password'], password):
            raise AppException('Authentication failed', 401)

        token = self.generate_auth_token(user['id'])
        user['tokens'].append(token)

        self.query_manager.upsert('users', [user])

        return {'login': user['login'], 'token': token}
Beispiel #9
0
    def get_user_by_token(self, token):
        payload = jwt.decode(token,
                             DatabaseContext.PASSWORDS_SECRET_KEY,
                             algorithms=['HS256'])
        results = self.query_manager.search(
            'users', {'$filter': {
                'id': payload['sub'],
                'tokens': token
            }})

        if len(results) != 1:
            raise AppException('Authentication failed', 401)
        return results[0]
Beispiel #10
0
def user_details(user: str):
    req = Context()
    auth = req.auth
    is_me = user == "me"
    if is_me:
        if not auth.user:
            raise AppException("Not authenticated", 401)
        user = auth.user
    user_data = get_user_by_username(user)
    show_secure = user_data.user == auth.user or auth.is_admin
    model = (
        UserOutSecure.from_db(user_data) if show_secure else UserOut.from_db(user_data)
    )
    return {"user_data": model.dict()}
Beispiel #11
0
def edit(user: str):
    req = Context()
    user = user.lower()
    if user != req.auth.user and not req.auth.is_admin:
        raise AppException("Not authorized to edit", 401)
    if not req.auth.is_admin:
        body = UserEditable(**req.json)
    else:
        body = UserIn(**req.json)
    user_data = get_user_by_username(user)
    user_data.user = body.user or user_data.user
    user_data.name = body.name or user_data.name
    json = user_data.as_json
    commit()
    return json
Beispiel #12
0
    def login_for_api(self, login):
        results = self.query_manager.search('users',
                                            {'$filter': {
                                                'login': login
                                            }})

        if len(results) != 1:
            raise AppException('Authentication failed', 401)

        token = self.generate_auth_token(user['id'])
        user['tokens'].append(token)

        self.query_manager.upsert('users', [user])

        return {'login': user['login'], 'token': token}
Beispiel #13
0
    def __init__(self, collection):
        if os.path.exists(DatabaseContext.DATA_FOLDER + collection) is False:
            raise AppException(
                'Collection {} doesn\'t exist'.format(collection), 404)

        self.collection = collection
        fname = DatabaseContext.DATA_FOLDER + self.collection + '/' + self.META_DATA_FILE_NAME
        if os.path.exists(fname) is False:
            with open(fname, 'a') as file:
                file.write('1\n')
                file.write('{}\n')

        with open(fname, 'r') as file:
            file.seek(0)
            self.counter = int(file.readline())
            self.indexes = eval(file.readline())
Beispiel #14
0
    def logout(self, token):
        payload = jwt.decode(token,
                             DatabaseContext.PASSWORDS_SECRET_KEY,
                             algorithms=['HS256'])
        results = self.query_manager.search(
            'users', {'$filter': {
                'id': payload['sub'],
                'tokens': token
            }})

        if len(results) != 1:
            raise AppException('Authentication failed', 401)
        user = results[0]

        user['tokens'].remove(token)
        self.query_manager.upsert('users', [user])

        return user
Beispiel #15
0
def refresh_token():
    context = Context()
    headers = context.headers
    access_token = get_bearer_token(headers)
    decoded_access = decode_token(access_token)
    if decoded_access is None:
        refresh_token = headers.get("x-refresh-token")
        decoded_refresh = decode_token(refresh_token)
        access, refresh = regenerate_access_token(decoded_refresh)
        if access is None:
            raise AppException("re-auth")

        return json_response(
            {},
            headers={
                "x-access-token": create_token(access),
                "x-refresh-token": create_token(refresh),
            },
        )
    return {}
Beispiel #16
0
def bulk_patch(collection):
    """ For bulk patch, the documents must contain their IDs. """
    if not request.json:
        abort(405)

    ids = []
    for d in request.json:
        if 'id' in d:
            ids.append(d['id'])
        else:
            raise AppException('Input documents must contain their ID', 400)

    previous_docs = query_manager.search(collection, {'$filter': {'id': ids}})

    previous_docs = sorted(previous_docs, key=itemgetter('id'))
    docs = sorted(list(previous_docs), key=itemgetter('id'))

    patch = sorted(request.json, key=itemgetter('id'))
    for i, p in enumerate(patch):
        for k in p.keys():
            docs[i][k] = p[k]

    query_manager.patch(collection, previous_docs, docs)
    return jsonify({})