Exemple #1
0
class DetailView(HTTPMethodView):
    decorators = [scoped(['user', 'admin'], require_all=False)]

    async def get(self, request):
        user_id = request.raw_args['id']
        async with db.cursor() as cur:
            await cur.execute(
                "SELECT login_time, logout_time,"
                " timestampdiff(minute, login_time, logout_time),"
                " upload, download, upload + download, inet_ntoa(host), bind_port "
                "from detail where user_id=%s", [user_id])
            res = await cur.fetchall()
        detail_list = []
        for row in res:
            login_time, logout_time, online_time, upload, download, used, host, bind_port = row
            login_time = login_time.strftime("%Y-%m-%d %H:%M:%S")
            logout_time = logout_time.strftime("%Y-%m-%d %H:%M:%S")
            detail_list.append({
                'host': host,
                'login_time': login_time,
                'logout_time': logout_time,
                'online_time': online_time,
                'upload': upload,
                'download': download,
                'used': used,
                'bind_port': bind_port
            })
        return json({'detail': detail_list})

    async def options(self, request):
        return json({})
Exemple #2
0
class RecordView(HTTPMethodView):
    decorators = [protected(), scoped('user'), inject_user()]

    async def post(self, request, user):

        payload = request.json

        project = Project.objects(name=payload['project_name']).first()
        payload = {
            "function_name": payload['name'],
            "start_time": datetime.fromtimestamp(payload['start']),
            "end_time": datetime.fromtimestamp(payload['end']),
            "arguments": json.dumps(payload['arguments']),
            "call_params": json.dumps(payload['call_params']),
            "type": payload['type'],
            "project_id": project.id,
            "user_id": user['id'],
        }
        print(payload)

        record = Record.create(**payload)

        return res.json({
            "status": 201,
            "message": "Record Created",
            "record_id": str(record.id)
        })

    async def get(self, request, user):
        payload = request.raw_args
        print(request.raw_args)
        project = Project.objects(
            name=payload['project_name']).allow_filtering().first()
        records = Record.objects(
            user_id=user['id'], project_id=project.id).allow_filtering().all()

        for record in records:
            if record['arguments']:
                record['arguments'] = json.loads(record['arguments'])

            if record['call_params']:
                record['call_params'] = json.loads(record['call_params'])
        payload = [{
            **r, "start_time": r['start_time'].timestamp(),
            "end_time": r['end_time'].timestamp(),
            "id": str(r['id']),
            "project_id": str(r['project_id']),
            "user_id": str(r['user_id'])
        } for r in records]

        return res.json(payload)
Exemple #3
0
class UsersView(HTTPMethodView):
    decorators = [scoped(['admin'])]

    async def get(self, request):
        async with db.cursor() as cur:
            await cur.execute(
                "SELECT id, username, quota, is_admin FROM user order by id")
            res = await cur.fetchall()
        user_list = []
        for row in res:
            id, username, quota, is_admin = row
            user_list.append({
                'id': id,
                'username': username,
                'quota': quota,
                'is_admin': is_admin
            })
        async with db.cursor() as cur:
            await cur.execute(
                "SELECT sum(upload) as total_upload, "
                "sum(download) as total_download, "
                "sum(timestampdiff(minute, login_time, logout_time)) as online_time "
                "FROM detail group by user_id order by user_id")
            res = await cur.fetchall()
        for idx, user in enumerate(user_list):
            if idx >= len(res):
                total_upload = total_download = online_time = 0
            else:
                total_upload, total_download, online_time = res[idx]
            user.update({
                'total_upload': total_upload,
                'total_download': total_download,
                'used': total_upload + total_download,
                'online_time': online_time
            })
        return json({"users": user_list})

    async def delete(self, request):
        async with db.cursor() as cur:
            await cur.execute("DELETE FROM user")
        return json({"delete all": "OK"})

    async def options(self, request):
        return json({})
Exemple #4
0
class OnlineUsersView(HTTPMethodView):
    decorators = [scoped(['admin'])]

    async def get(self, request):
        res = []
        for user in port_traffic_dict.values():
            res.append({
                'id': user.user_id,
                'username': user.username,
                'host': user.host,
                'bind_port': user.bind_port,
                'upload': user.upload,
                'download': user.download,
                'login_time': user.login_time
            })
        return json({"online_users": res})

    async def options(self, request):
        return json({})
Exemple #5
0
class ProjectView(HTTPMethodView):
    decorators = [protected(), scoped('user'), inject_user()]

    async def post(self, request, user):
        payload = request.json

        payload['access_token'] = "some_token"
        payload['user_id'] = user['id']

        if 'name' not in payload:
            return res.json({"message": "name is required"}, status=400)

        project_exists = Project.objects(
            name=payload['name'],
            user_id=user['id']).allow_filtering().first()
        if project_exists:
            return res.json({
                "message": "Project Already Exists",
            },
                            status=409)

        project = Project.create(**payload)

        return res.json(
            {
                "message": "Project Created",
                "project_id": str(project.id)
            },
            status=200)

    async def get(self, request, user):
        print(user)
        payload = Project.objects(user_id=user['id']).all()
        payload = [{
            **p, "id": str(p['id']),
            "user_id": str(p['user_id'])
        } for p in payload]

        return res.json(payload)
 def scoped(self, scopes, **kwargs):
     kwargs.update({"initialized_on": self.instance})
     return scoped(scopes, **kwargs)