def get(self, request, username=None): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) if username is None: user.created_on = datetime.timestamp(user.created_on) * 1000 user.modified_on = datetime.timestamp(user.modified_on) * 1000 teams = Team.objects.filter(members__pk=user.pk) team_payload = list() for team in teams: team_payload.append({ "team_id": team.team_id, "team_name": team.team_name, "member": True, "admin": True if Team.objects.filter( team_admins__pk=user.pk) else False }) context = get_common_view_payload(user, user.get_full_name) context["user"] = user context["team_payload"] = team_payload context["total_team"] = len(team_payload) context["current_user"] = True return render(request, 'frontend/profile.html', context) else: new_user = get_user_object(username=username) new_user.created_on = datetime.timestamp( new_user.created_on) * 1000 new_user.modified_on = datetime.timestamp( new_user.modified_on) * 1000 new_user.last_login = datetime.timestamp( new_user.last_login) * 1000 teams = Team.objects.filter(members__pk=new_user.pk) team_payload = list() for team in teams: team_payload.append({ "team_id": team.team_id, "team_name": team.team_name, "member": True, "admin": True if Team.objects.filter( team_admins__pk=new_user.pk) else False }) context = get_common_view_payload(user, user.get_full_name) context["user"] = new_user context["team_payload"] = team_payload context["total_team"] = len(team_payload) context["current_user"] = False return render(request, 'frontend/profile.html', context)
def get(self, request): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) error_logs = ErrorLog.objects.all() for logs in error_logs: logs.logged_on = datetime.timestamp(logs.logged_on) * 1000 logs.updated_on = datetime.timestamp(logs.updated_on) * 1000 context = get_common_view_payload(user, "Error Log") context["error_logs"] = error_logs context["total_logs"] = ErrorLog.objects.all().count() context["current"] = len(error_logs) context["titles"] = [ "#", "User", "Error Name", "Description", "Origin", "Project", "Logged on", "Status", "Resolved by", "Last Updated", ] return render(request, 'frontend/log.html', context)
def wrapper(self, request, *args, **kwargs): """ # TODO: for failed token, generate a message on screen """ # print("Hits access token") required = ('type', 'exp', 'sub', 'role') epoch = datetime.utcfromtimestamp(0) if 'access_token' not in request.COOKIES: return HttpResponseRedirect(reverse("index")) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # print("|||||||||ACCESS TOKEN CHECK|||||||||") payload = decode_token(request.COOKIES['access_token']) # print(request.COOKIES['access_token']) # print(payload) # print("||||||||||||||||||||||||||||||||||||") # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # Validate user and access token expiry for field in required: if field not in payload: return HttpResponseRedirect(reverse("index")) if payload['type'] != "access": return HttpResponseRedirect(reverse("index")) if get_user_object(username=payload["sub"]) is None: return HttpResponseRedirect(reverse("index")) if payload['exp'] < (datetime.utcnow() - epoch).total_seconds(): # Access token is expired. Checks up refresh token check_refresh_token(request) return function(self, request, *args, **kwargs)
def post(self, request): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) for field in self.required_parameters: if field not in request.POST: return JsonResponse( { "message": "Missing mandatory parameter, {}".format(field), "status": HTTP_400_BAD_REQUEST }, status=HTTP_400_BAD_REQUEST) data = { "org_name": request.POST["org_name"], } data["created_by"] = user.pk data["org_id"] = str(uuid4())[:12] org_serializer = OrgSerializer(data=data) if org_serializer.is_valid(): try: org_obj = org_serializer.save() org_obj.members.add(user) org_obj.org_admins.add(user) org_obj.save() return JsonResponse( { "message": "A new organization, [ {} ] has been created".format( org_obj.org_name), "org_id": org_obj.org_id, "org_name": org_obj.org_name, "created_by": org_obj.created_by.email, "created_on": org_obj.created_on, "status": HTTP_201_CREATED, }, status=HTTP_201_CREATED) except Exception as e: Organization.objects.filter(org_id=org_obj.org_id).delete() return JsonResponse( { "message": "An error occurred! {}".format(e), "status": HTTP_400_BAD_REQUEST }, status=HTTP_400_BAD_REQUEST) else: return JsonResponse( { "message": "An error occurred! {}".format(org_serializer.errors), "status": HTTP_406_NOT_ACCEPTABLE }, status=HTTP_406_NOT_ACCEPTABLE)
def get(self, request, team_id: str): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) team = get_team_object(team_id) if team is None: context = get_common_view_payload(user, "Error!") context["message"] = "This team does not exist!" return render(request, 'frontend/team.html', context) context = get_common_view_payload(user, team.team_name) team.created_on = datetime.timestamp(team.created_on) * 1000 team.modified_on = datetime.timestamp(team.modified_on) * 1000 is_member = True if Team.objects.filter(members__pk=user.pk) else False is_admin = True if Team.objects.filter( team_admins__pk=user.pk) else False projects = Projects.objects.filter(team=team.pk) context["current_team"] = team context["is_member"] = is_member context["is_admin"] = is_admin context["admins"] = team.team_admins.all() context["members"] = team.members.all() context["team_projects"] = projects context["total_projects"] = len(projects) context["total_members"] = len(team.members.all()) context["total_admins"] = len(team.team_admins.all()) return render(request, 'frontend/team.html', context)
def check_refresh_token(request): """ # TODO: generate a message here. After successful refresh token, redirect to the same page. Or sow appropriate error message | request to login again. """ if 'refresh_token' not in request.COOKIES: return HttpResponseRedirect(reverse("index")) # print("Refresh Token hits") # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # print(request.COOKIES['refresh_token']) payload = decode_token(request.COOKIES['refresh_token']) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") required = ('type', 'exp', 'sub', 'role') epoch = datetime.utcfromtimestamp(0) for field in required: if field not in payload: return HttpResponseRedirect(reverse("index")) if payload['type'] != "refresh": return HttpResponseRedirect(reverse("index")) if get_user_object(username=payload["sub"]) is None: return HttpResponseRedirect(reverse("index")) user = get_user_object(username=payload["sub"]) if payload['exp'] < (datetime.utcnow() - epoch).total_seconds(): # Refresh token also expired. Re-login is needed. return HttpResponseRedirect(reverse("index")) else: # Refresh token is still valid. access_token = str(encode_access_token(user.username, "user")) refresh_token = str(encode_refresh_token(user.username, "user")) print("Token refreshed. Redirect to: {}".format(request.path)) response = HttpResponseRedirect(request.path) expiry = datetime.utcnow() + timedelta(hours=5) set_cookie(response, "access_token", access_token, expired_at=expiry) set_cookie(response, "refresh_token", refresh_token) # successful refresh token, redirect to the same page return response
def post(self, request): data = request.data user = get_user_object(username=request.user.username) for field in self.required_field: if field not in data: return JsonResponse({ "status": False, "message": "Required parameter missing. {} is required".format(field), }, status=HTTP_400_BAD_REQUEST) urls = data["urls"] # it's a list if not isinstance(urls, list): return JsonResponse({ "status": False, "message": "urls is supposed to be a list.", }, status=HTTP_400_BAD_REQUEST) final_tally = [] counter = 0 for url in urls: for field in self.child_field: if field not in url: return JsonResponse({ "status": False, "message": "Required parameter missing. {} is required".format(field), }, status=HTTP_400_BAD_REQUEST) url["status"] = 0 url["verbose_status"] = "Initializing" url["created_by"] = user.pk serializer = WebSerializer(data=url) if serializer.is_valid(): serializer.save() final_tally.append({ "url": url["url"], "status": True, "message": "success" }) counter += 1 else: message = serializer.errors final_tally.append({ "url": url["url"], "status": False, "message": message, }) reply = { "status": True, "message": "Success: {} urls. Failed: {}".format(counter, (len(data["urls"]) - counter)), "description": final_tally, } return JsonResponse(reply, status=HTTP_200_OK)
def get(self, request): # print("##########################") # print("DASHBoard") payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) # print("##########################") context = get_common_view_payload(user, "Dashboard") if "ping_message" in request.GET: context["ping_message"] = request.GET["ping_message"] if "status" in request.GET: context["status"] = False else: context["status"] = True web_status = WebStatus.objects.all() server_payload = list() counter = 1 for web in web_status: server_payload.append({ "index": counter, "url": web.url, "last_checked": datetime.timestamp(web.last_checked) * 1000, "status": web.status, "description": web.verbose_status, "request_type": self.HTTP_Methods[web.request_type], }) counter += 1 context["server_status"] = server_payload context["methods"] = [{ "id": 1, "type": "Get", }, { "id": 2, "type": "Head", }, { "id": 3, "type": "Options", }] if "message" in request.GET: context["message"] = request.GET["message"] if "status" in request.GET: context["status"] = request.GET["status"] response = render(request, 'frontend/dashboard.html', context) return response
def get(self, request): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) response = HttpResponseRedirect(reverse('index')) response.delete_cookie('refresh_token') response.delete_cookie('access_token') response.delete_cookie('sessionid') response.delete_cookie('csrftoken') response.delete_cookie('olfsk') response.delete_cookie('hblid') return response
def get(self, request): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) verbose_logs = VerboseLog.objects.all() for logs in verbose_logs: logs.logged_on = datetime.timestamp(logs.logged_on) * 1000 context = get_common_view_payload(user, "Verbose Log") context["verbose_logs"] = verbose_logs context["total_logs"] = VerboseLog.objects.all().count() context["current"] = len(verbose_logs) context["titles"] = [ "#", "User", "Project Name", "Description", "Origin", "Logged on" ] return render(request, 'frontend/log.html', context)
def get(self, request): if request.COOKIES.get("access_token") is not None: payload = decode_token(request.COOKIES.get("access_token")) print("Index e") print(payload) if isinstance(payload, dict) and 'sub' in payload: user = get_user_object(username=payload["sub"]) if user is not None: # HTTP redirect return HttpResponseRedirect(reverse("dashboard")) context = dict() if "login_message" in request.GET: context["login_message"] = request.GET["login_message"] if "register_message" in request.GET: context["register_message"] = request.GET["register_message"] if "status" in request.GET: context["status"] = request.GET["status"] return render(request, 'frontend/index.html', context)
def post(self, request): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) for field in self.required_parameters: if field not in request.POST: message = "Missing mandatory parameter, {}".format(field) return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) data = { "url" : request.POST["url"], "request_type": request.POST["type"], } data["status"] = 0 data["verbose_status"] = "Initializing" data["created_by"] = user.pk web_serializer = WebSerializer(data=data) if web_serializer.is_valid(): try: web_serializer.save() message = "successfully added a new url" return HttpResponseRedirect( reverse("dashboard") + "?ping_message={}".format(message), ) except Exception: message = "An err or occurred! " return HttpResponseRedirect( reverse("dashboard") + "?ping_message={}&status={}".format(message, False), ) else: message = "An error occurred! {}".format(web_serializer.errors) return HttpResponseRedirect( reverse("dashboard") + "?ping_message={}&status={}".format(message, False), )
def get(self, request, project_id: str): payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) project = get_project_object(project_id) if project is None: context = get_common_view_payload(user, "Error!") context["error_message"] = "This project does not exist!" response = render(request, 'frontend/project.html', context) return response project.created_on = datetime.timestamp(project.created_on) * 1000 project.modified_on = datetime.timestamp(project.modified_on) * 1000 project_token = get_project_token_by_project_id(project.pk) if project_token: project_token.generated_on = datetime.timestamp( project_token.generated_on) * 1000 project_token.updated_on = datetime.timestamp( project_token.updated_on) * 1000 context = get_common_view_payload(user, project.project_name) context["project_object"] = project context["project_token"] = project_token context["error_count"] = get_error_count_of_a_project( project.project_id) context["verbose_count"] = get_verbose_count_of_a_project( project.project_id) if "message" in request.GET: context["message"] = request.GET["message"] if "status" in request.GET: context["status"] = request.GET["status"] response = render(request, 'frontend/project.html', context) return response
def post(self, request): """ mandatory field: user_token, project_name, team_id from the user_token, get the user_id and check if user is part of this org. if yes. then Okay else Validation Error :param request: django request obj :return: JSONResponse """ payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) # TODO: check if user is an admin to create a project under this org. for field in self.required_parameters: if field not in request.POST: message = "Missing mandatory parameter, {}".format(field) return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) data = { "project_name": request.POST["project_name"], "team_id": request.POST["team_id"], } team_object = get_team_object(data["team_id"]) if team_object is None: message = "Team does not exist." return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) payload = { "project_id": str(uuid4())[:12], "team": team_object.pk, "project_name": data['project_name'], } project_serializer = ProjectSerializer(data=payload) try: if project_serializer.is_valid(): project = project_serializer.save() if project: message = "Successfully added a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, True), ) else: message = "Failed to create a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) else: message = "Failed to create a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) except Exception: message = "Failed to create a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), )