Beispiel #1
0
def sessions():
    with DBConnection() as conn:
        col = conn.db.get_collection(db_config.SESSION_COL)

        if request.method == 'GET':
            return tojson(list(col.find({})))

        # Post data
        data = dict(request.get_json())
        col.insert_one(data)
        return tojson(data)
Beispiel #2
0
def login():
    """Log in a registered user by adding the user id to the session."""
    name = request.args.get('name')
    passwd = request.args.get('passwd')
    user = users.find_one({'name': name, 'passwd': passwd})
    if user:
        session.clear()
        session['user_id'] = user['_id'].binary.hex()
        return tojson(True, 'ok')
    else:
        return tojson(False, 'password or account is wrong!')
 def on_put(self, req, res):
     raw_json = req.stream.read()
     result = json.loads(raw_json, encoding='utf-8')
     o = ReservationRepo.items[str(result['reservation_id'])]
     o.client_name = result['client_name']
     o.location = result['location']
     res.body = utils.tojson(o)
Beispiel #4
0
def delfile():
    file_hash = request.args.get('file_hash')
    users.update_one({'_id': ObjectId(session['user_id'])},
                     {'$pullAll': {
                         'files': [file_hash]
                     }})
    return tojson(1, 'delete success')
Beispiel #5
0
def mate():
    filename = request.args.get('filename')
    file_hash = request.args.get('file_hash')
    if not files.find_one({'_id': file_hash}):
        files.insert_one({
            '_id': file_hash,
            'filename': filename,
            'chunks': []
        })  # {chunk_hash: '', nodes: []}
        users.update_one({'_id': ObjectId(session['user_id'])},
                         {'$push': {
                             'files': file_hash
                         }})
        return tojson(0, '')
    else:
        return tojson(1, 'Already have this file')
Beispiel #6
0
def file_mate():
    file_hash = request.args.get('file_hash')
    r = files.aggregate([{
        "$match": {
            "_id": file_hash
        }
    }, {
        "$unwind": "$chunks"
    }, {
        "$unwind": "$chunks.nodes"
    }, {
        "$lookup": {
            "from": "nodes",
            "localField": "chunks.nodes",
            "foreignField": "uuid",
            "as": "nodes"
        }
    }, {
        "$project": {
            "_id": 0,
            "chunk_hash": "$chunks.chunk_hash",
            "nodes": "$nodes.ip"
        }
    }])
    return tojson(True, '', list(r))
Beispiel #7
0
def sessions_sessionid(session_id):
    with DBConnection() as conn:
        col = conn.db.get_collection(db_config.SESSION_COL)

        if request.method == 'GET':
            return tojson(col.find_one({'_id': session_id}))

        elif request.method == 'DELETE':
            return tojson(col.delete_one({'_id': session_id}))

        # Update data
        col.update_one(
            {'_id': session_id},
            {'$set': dict(request.get_json())}
        )
        return tojson(col.find_one({'_id': session_id}))
Beispiel #8
0
def root():
    res = {}
    with DBConnection() as conn:
        db = conn.db
        res['db_host'] = db.client.HOST
        res['db_port'] = db.client.PORT
        res['collections'] = db.list_collection_names()
    return tojson(res)
Beispiel #9
0
 def todb(self):
     """
     save list to database
     """
     print '.. save labeled data to database'
     for id, data in enumerate(self.iter_labeled_data()):
         print id
         self.db['%s-%d' % (env.KEY_LABELED_DATA, id)] = tojson(data)
     print '.. end database'
Beispiel #10
0
def list_user_file():
    _id = ObjectId(session['user_id'])
    r = users.find_one({
                           '_id': _id})
    r = files.find({
                       '_id': {
                           '$in': r['files']}}, {
                       'filename': 1})
    return tojson(True, '', list(r))
Beispiel #11
0
 def todb(self):
     """
     save list to database
     """
     print '.. save labeled data to database'
     for id, data in enumerate(self.iter_labeled_data()):
         print id
         self.db['%s-%d' % (env.KEY_LABELED_DATA, id)] = tojson(data)
     print '.. end database'
Beispiel #12
0
def users():
    with DBConnection() as conn:
        col = conn.db.get_collection(db_config.USER_COL)

        if request.method == 'GET':
            return tojson(list(col.find({})))

        # Post data
        data = dict(request.get_json())
        hash_user(data)
        response = conn.validate_unique(db_config.USER_COL, data)
        if not response['valid']:
            response = tojson(response)
            response.status_code = 401
            return response

        col.insert_one(data)
        return tojson(data)
Beispiel #13
0
def login_response(email, user_id, user_success, auth_success):
    response = tojson({
        'email': email,
        'user_id': user_id,
        'user_success': user_success,
        'auth_success': auth_success,
    })
    response.status_code = 200 if user_success and auth_success else 401
    return response
Beispiel #14
0
def report():
    volume = request.args.get('volume')
    uuid = request.args.get('uuid')
    nodes.update_one({
                         'uuid': uuid}, {
                         '$set': {
                             'ip': request.remote_addr,
                             'volume': int(volume),
                             }}, upsert=True)
    return tojson(True, 'update node ok')
Beispiel #15
0
def success():
    file_hash = request.args.get('file_hash')
    files.update_one({'_id': file_hash},
                     {'$currentDate': {
                         'success_date': True
                     }})
    users.update_one({'_id': ObjectId(session['user_id'])},
                     {'$push': {
                         'files': file_hash
                     }})
    return tojson(True, '')
Beispiel #16
0
def users_userid(user_id):
    with DBConnection() as conn:
        col = conn.db.get_collection(db_config.USER_COL)

        if request.method == 'GET':
            return tojson(col.find_one({'user_id': user_id}))

        elif request.method == 'DELETE':
            return tojson(col.delete_one({'user_id': user_id}))

        # Update data
        data = dict(request.get_json())
        hash_user(data)
        response = conn.validate_unique(db_config.USER_COL, data)
        if not response['valid']:
            response = tojson(response)
            response.status_code = 401
            return response

        col.update_one({'user_id': user_id}, {'$set': data})
        return tojson(col.find_one({'user_id': user_id}))
Beispiel #17
0
def mate():
    filename = request.args.get('filename')
    file_hash = request.args.get('file_hash')
    if files.find_one({
                              '_id': file_hash}):
        return tojson(1, 'success')

    elif users.find_one({
                           'files': {
                               '$all': [file_hash]}}):
        return tojson(2, 'file exist')

    else:
        files.insert_one({
            '_id': file_hash,
            'filename': filename,
            'chunks': []})  # {chunk_hash: '', nodes: []}
        users.update_one({
            '_id': ObjectId(session['user_id'])}, {
            '$push': {
                'files': file_hash}})
        return tojson(0, '')
Beispiel #18
0
 def filter(self, request):
     out = {"state":"null"}
     #request = HttpRequest()
     path = request.path_info
     path = path[len(self.path):]
     path_a = path.split("/")
     if self.checkreg(path_a[0]):
         c = self.registry.get(path_a[0])
         if request.method == 'GET':
             out = c.GET(request)
         elif request.method == 'POST':
             out = c.POST(request)
         elif request.method == 'PUT':
             out = c.PUT(request)
         elif request.method == 'OPTIONS':
             out = SchemaValidator.get(c.clazz, c.get_FIELDS())
         elif request.method == 'DELETE':
             out = c.DELETE(request)
     return utils.tojson(out)
Beispiel #19
0
def chunk():
    file_hash = request.args.get('file_hash')
    chunk_index = request.args.get('chunk_index')
    chunk_hash = request.args.get('chunk_hash')
    uuid = request.args.get('uuid')
    files.update_one({
                         '_id': file_hash}, {
                         '$set': {
                             'chunks.' + chunk_index: {
                                 'chunk_hash': chunk_hash}}})
    files.update_one({
                         '_id': file_hash}, {
                         '$push': {
                             'chunks.' + chunk_index + '.nodes': uuid}})

    # nodes.update_one({
    #                      'uuid': uuid}, {
    #                      '$push': {
    #                          'chunks': chunk_hash}})
    return tojson(True, '')
Beispiel #20
0
def submit():
    opt = request.get_json()['options']
    res = len([q for q in opt if int(opt[q]) == correct[int(q)]])
    return tojson(res)
Beispiel #21
0
def logout():
    """Clear the current session, including the stored user id."""
    session.clear()
    return tojson(True, 'ok')
Beispiel #22
0
def root():
    res = {}
    return tojson({'foo': 'bar'})
Beispiel #23
0
def _construct_message(type, msg):
    data = {
        'type':type,
        'data':msg
    }
    return utils.tojson(data)
 def on_get(self, req, res, id):
     o = ReservationRepo.items[id]
     res.body = utils.tojson(o)
 def on_delete(self, req, res, id):
     ReservationRepo.delete_reservation(id)
     res.body = utils.tojson({'success': 1})
Beispiel #26
0
def get_nodes():
    r = nodes.find({}, {'ip': 1, 'uuid': 1, '_id': 0}).limit(10)
    return tojson(True, '', list(r))
 def on_get(self, req, res):
     ls = list(ReservationRepo.items.values())
     res.body = utils.tojson(ls)
 def on_post(self, req, res):
     raw_json = req.stream.read()
     result = json.loads(raw_json, encoding='utf-8')
     o = Reservation(result['client_name'], result['location'])
     ReservationRepo.add_reservation(o)
     res.body = utils.tojson(o)
Beispiel #29
0
def courses_courseid(course_id):
    with DBConnection() as conn:
        col = conn.db.get_collection(db_config.COURSE_COL)
        return tojson(col.delete_one({'_id': course_id}))
Beispiel #30
0
def personalization():
    opt = request.get_json()['options']
    return tojson(personalization_service.get_locs(opt))