def post(self, request): if self.request.user.is_anonymous(): return response.Ok({"Wrong!"}) serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): serializer.save() return response.Ok(serializer.data)
def list_users(self, request, *args, **kwargs): self.check_permissions(request, "list_users", None) url = request.DATA.get('url', None) token = self._get_token(request) project_id = request.DATA.get('project', None) if not project_id: raise exc.WrongArguments(_("The project param is needed")) if not url: raise exc.WrongArguments(_("The url param is needed")) importer = JiraNormalImporter(request.user, url, token) users = importer.list_users() for user in users: user['user'] = None if not user['email']: continue try: Tina_user = User.objects.get(email=user['email']) except User.DoesNotExist: continue user['user'] = { 'id': Tina_user.id, 'full_name': Tina_user.get_full_name(), 'gravatar_id': get_user_gravatar_id(Tina_user), 'photo': get_user_photo_url(Tina_user), } return response.Ok(users)
def bulk_create(self, request, **kwargs): validator = validators.TasksBulkValidator(data=request.DATA) if not validator.is_valid(): return response.BadRequest(validator.errors) data = validator.data project = Project.objects.get(id=data["project_id"]) self.check_permissions(request, 'bulk_create', project) if project.blocked_code is not None: raise exc.Blocked(_("Blocked element")) tasks = services.create_tasks_in_bulk( data["bulk_tasks"], milestone_id=data["milestone_id"], user_story_id=data["us_id"], status_id=data.get("status_id") or project.default_task_status_id, project=project, owner=request.user, callback=self.post_save, precall=self.pre_save) tasks = self.get_queryset().filter(id__in=[i.id for i in tasks]) for task in tasks: self.persist_history_snapshot(obj=task) tasks_serialized = self.get_serializer_class()(tasks, many=True) return response.Ok(tasks_serialized.data)
def me(self, request, pk=None): """ Get me. """ self.check_permissions(request, "me", None) user_data = self.admin_serializer_class(request.user).data return response.Ok(user_data)
def voted(self, request, *args, **kwargs): for_user = get_object_or_404(models.User, **kwargs) from_user = request.user self.check_permissions(request, 'liked', for_user) filters = { "type": request.GET.get("type", None), "q": request.GET.get("q", None), } self.object_list = services.get_voted_list(for_user, from_user, **filters) page = self.paginate_queryset(self.object_list) elements = page.object_list if page is not None else self.object_list extra_args = { "user_watching": services.get_watched_content_for_user(request.user), "user_votes": services.get_voted_content_for_user(request.user), } response_data = [ serializers.VotedObjectSerializer(into_namedtuple(elem), **extra_args).data for elem in elements ] return response.Ok(response_data)
def auth_url(self, request, *args, **kwargs): self.check_permissions(request, "auth_url", None) jira_url = request.QUERY_PARAMS.get('url', None) if not jira_url: raise exc.WrongArguments(_("The url param is needed")) try: (oauth_token, oauth_secret, url) = JiraNormalImporter.get_auth_url( jira_url, settings.IMPORTERS.get('jira', {}).get('consumer_key', None), settings.IMPORTERS.get('jira', {}).get('cert', None), True ) except exceptions.InvalidServiceConfiguration: raise exc.BadRequest(_("Invalid Jira server configuration.")) (auth_data, created) = AuthData.objects.get_or_create( user=request.user, key="jira-oauth", defaults={ "value": uuid.uuid4().hex, "extra": {}, } ) auth_data.extra = { "oauth_token": oauth_token, "oauth_secret": oauth_secret, "url": jira_url, } auth_data.save() return response.Ok({"url": url})
def authorize(self, request, *args, **kwargs): self.check_permissions(request, "authorize", None) try: oauth_data = request.user.auth_data.get(key="jira-oauth") oauth_verifier = request.DATA.get("oauth_verifier", None) oauth_token = oauth_data.extra['oauth_token'] oauth_secret = oauth_data.extra['oauth_secret'] server_url = oauth_data.extra['url'] oauth_data.delete() jira_token = JiraNormalImporter.get_access_token( server_url, settings.IMPORTERS.get('jira', {}).get('consumer_key', None), settings.IMPORTERS.get('jira', {}).get('cert', None), oauth_token, oauth_secret, oauth_verifier, False ) except Exception as e: raise exc.WrongArguments(_("Invalid or expired auth token")) return response.Ok({ "token": jira_token['access_token'] + "." + jira_token['access_token_secret'], "url": server_url })
def post(self, request): self.check_permissions(request) models.WebNotification.objects.filter(user=self.request.user)\ .update(read=timezone.now()) return response.Ok()
def unwatch(self, request, pk=None): project = self.get_object() self.check_permissions(request, "unwatch", project) self.pre_conditions_on_save(project) user = self.request.user project.remove_watcher(user) return response.Ok()
def list_users(self, request, *args, **kwargs): self.check_permissions(request, "list_users", None) token = request.DATA.get('token', None) project_id = request.DATA.get('project', None) if not project_id: raise exc.WrongArguments(_("The project param is needed")) importer = AsanaImporter(request.user, token) try: users = importer.list_users(project_id) except exceptions.InvalidRequest: raise exc.BadRequest(_('Invalid Asana API request')) except exceptions.FailedRequest: raise exc.BadRequest(_('Failed to make the request to Asana API')) for user in users: if user['detected_user']: user['user'] = { 'id': user['detected_user'].id, 'full_name': user['detected_user'].get_full_name(), 'gravatar_id': get_user_gravatar_id(user['detected_user']), 'photo': get_user_photo_url(user['detected_user']), } del(user['detected_user']) return response.Ok(users)
def import_project(self, request, *args, **kwargs): self.check_permissions(request, "import_project", None) token = request.DATA.get('token', None) project_id = request.DATA.get('project', None) if not project_id: raise exc.WrongArguments(_("The project param is needed")) options = { "name": request.DATA.get('name', None), "description": request.DATA.get('description', None), "template": request.DATA.get('template', "scrum"), "users_bindings": resolve_users_bindings(request.DATA.get("users_bindings", {})), "keep_external_reference": request.DATA.get("keep_external_reference", False), "is_private": request.DATA.get("is_private", False), } if settings.CELERY_ENABLED: task = tasks.import_project.delay(request.user.id, token, project_id, options) return response.Accepted({"task_id": task.id}) importer = AsanaImporter(request.user, token) project = importer.import_project(project_id, options) project_data = { "slug": project.slug, "my_permissions": ["view_us"], "is_backlog_activated": project.is_backlog_activated, "is_kanban_activated": project.is_kanban_activated, } return response.Ok(project_data)
def unlike(self, request, pk=None): obj = self.get_object() self.check_permissions(request, "unlike", obj) self.pre_conditions_on_save(obj) services.remove_like(obj, user=request.user) return response.Ok()
def retrieve(self, request, pk, *args, **kwargs): throttle = throttling.ImportDumpModeRateThrottle() if not throttle.allow_request(request, self): self.throttled(request, throttle.wait()) project = get_object_or_404(self.get_queryset(), pk=pk) self.check_permissions(request, 'export_project', project) dump_format = request.QUERY_PARAMS.get("dump_format", "plain") if settings.CELERY_ENABLED: task = tasks.dump_project.delay(request.user, project, dump_format) tasks.delete_project_dump.apply_async( (project.pk, project.slug, task.id, dump_format), countdown=settings.EXPORTS_TTL) return response.Accepted({"export_id": task.id}) if dump_format == "gzip": path = "exports/{}/{}-{}.json.gz".format(project.pk, project.slug, uuid.uuid4().hex) with default_storage.open(path, mode="wb") as outfile: services.render_project(project, gzip.GzipFile(fileobj=outfile)) else: path = "exports/{}/{}-{}.json".format(project.pk, project.slug, uuid.uuid4().hex) with default_storage.open(path, mode="wb") as outfile: services.render_project(project, outfile) response_data = {"url": default_storage.url(path)} return response.Ok(response_data)
def auth_url(self, request, *args, **kwargs): self.check_permissions(request, "auth_url", None) callback_uri = request.QUERY_PARAMS.get('uri') url = GithubImporter.get_auth_url( settings.IMPORTERS.get('github', {}).get('client_id', None), callback_uri) return response.Ok({"url": url})
def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) if not getattr(self, 'object', None): self.object = self.get_object_or_none() self.check_permissions(request, 'update', self.object) if self.object is None: raise Http404 if hasattr(self, 'pre_validate'): self.pre_validate() validator = self.get_validator(self.object, data=request.DATA, files=request.FILES, partial=partial) if not validator.is_valid(): return response.BadRequest(validator.errors) # Hooks try: self.pre_save(validator.object) self.pre_conditions_on_save(validator.object) except ValidationError as err: # full_clean on model instance may be called in pre_save, # so we have to handle eventual errors. return response.BadRequest(err.message_dict) self.object = validator.save(force_update=True) self.post_save(self.object, created=False) instance = self.get_queryset().get(id=self.object.id) serializer = self.get_serializer(instance) return response.Ok(serializer.data)
def list(self, request, *args, **kwargs): locales = [{ "code": c, "name": n, "bidi": c in settings.LANGUAGES_BIDI } for c, n in settings.LANGUAGES] return response.Ok(locales)
def _bulk_update_order(self, order_field, request, **kwargs): validator = validators.UpdateTasksOrderBulkValidator(data=request.DATA) if not validator.is_valid(): return response.BadRequest(validator.errors) data = validator.data project = get_object_or_404(Project, pk=data["project_id"]) self.check_permissions(request, "bulk_update_order", project) if project.blocked_code is not None: raise exc.Blocked(_("Blocked element")) user_story = None user_story_id = data.get("user_story_id", None) if user_story_id is not None: user_story = get_object_or_404(UserStory, pk=user_story_id) status = None status_id = data.get("status_id", None) if status_id is not None: status = get_object_or_404(TaskStatus, pk=status_id) milestone = None milestone_id = data.get("milestone_id", None) if milestone_id is not None: milestone = get_object_or_404(Milestone, pk=milestone_id) ret = services.update_tasks_order_in_bulk(data["bulk_tasks"], order_field, project, user_story=user_story, status=status, milestone=milestone) return response.Ok(ret)
def create_default(self, request, **kwargs): context = {"request": request} validator = validators.DueDatesCreationValidator(data=request.DATA, context=context) if not validator.is_valid(): return response.BadRequest(validator.errors) project_id = request.DATA.get('project_id') project = models.Project.objects.get(id=project_id) if project.issue_duedates.all(): raise exc.BadRequest(_("Project already have issue due dates")) project_template = models.ProjectTemplate.objects.get( id=project.creation_template.id) for issue_duedate in project_template.issue_duedates: models.IssueDueDate.objects.create( name=issue_duedate["name"], by_default=issue_duedate["by_default"], color=issue_duedate["color"], days_to_due=issue_duedate["days_to_due"], order=issue_duedate["order"], project=project) project.save() serializer = self.get_serializer(project.issue_duedates.all(), many=True) return response.Ok(serializer.data)
def transfer_validate_token(self, request, pk=None): project = self.get_object() self.check_permissions(request, "transfer_validate_token", project) token = request.DATA.get('token', None) services.transfer.validate_project_transfer_token( token, project, request.user) return response.Ok()
def bulk_create(self, request, **kwargs): validator = validators.CreateRelatedUserStoriesBulkValidator( data=request.DATA) if not validator.is_valid(): return response.BadRequest(validator.errors) data = validator.data epic = get_object_or_404(models.Epic, id=kwargs["epic"]) project = Project.objects.get(pk=data.get('project_id')) self.check_permissions(request, 'bulk_create', project) if project.blocked_code is not None: raise exc.Blocked(_("Blocked element")) related_userstories = services.create_related_userstories_in_bulk( data["bulk_userstories"], epic, project=project, owner=request.user) for related_userstory in related_userstories: self.persist_history_snapshot(obj=related_userstory) self.persist_history_snapshot(obj=related_userstory.user_story) related_uss_serialized = self.get_serializer_class()( epic.relateduserstory_set.all(), many=True) return response.Ok(related_uss_serialized.data)
def watch(self, request, pk=None): project = self.get_object() self.check_permissions(request, "watch", project) self.pre_conditions_on_save(project) notify_level = request.DATA.get("notify_level", NotifyLevel.involved) project.add_watcher(self.request.user, notify_level=notify_level) return response.Ok()
def filters_data(self, request, *args, **kwargs): project_id = request.QUERY_PARAMS.get("project", None) project = get_object_or_404(Project, id=project_id) filter_backends = self.get_filter_backends() statuses_filter_backends = (f for f in filter_backends if f != filters.StatusesFilter) assigned_to_filter_backends = (f for f in filter_backends if f != filters.AssignedToFilter) owners_filter_backends = (f for f in filter_backends if f != filters.OwnersFilter) roles_filter_backends = (f for f in filter_backends if f != filters.RoleFilter) tags_filter_backends = (f for f in filter_backends if f != filters.TagsFilter) queryset = self.get_queryset() querysets = { "statuses": self.filter_queryset(queryset, filter_backends=statuses_filter_backends), "assigned_to": self.filter_queryset(queryset, filter_backends=assigned_to_filter_backends), "owners": self.filter_queryset(queryset, filter_backends=owners_filter_backends), "tags": self.filter_queryset(queryset, filter_backends=tags_filter_backends), "roles": self.filter_queryset(queryset, filter_backends=roles_filter_backends), } return response.Ok(services.get_tasks_filters_data(project, querysets))
def export(self, request, pk=None): """ Export user data and photo """ file_url = services.export_profile(request.user) response_data = {"url": file_url} return response.Ok(response_data)
def response_for_queryset(self, queryset): # Switch between paginated or standard style responses page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_pagination_serializer(page) else: serializer = self.get_serializer(queryset, many=True) return response.Ok(serializer.data)
def remove_avatar(self, request): """ Remove the avatar of current logged user. """ self.check_permissions(request, "remove_avatar", None) request.user.photo = None request.user.save(update_fields=["photo"]) user_data = self.admin_serializer_class(request.user).data return response.Ok(user_data)
def patch(self, request, *args, **kwargs): self.check_permissions(request) resource_id = kwargs.get("resource_id", None) resource = get_object_or_404(self.resource_model, pk=resource_id) resource.read = timezone.now() resource.save() return response.Ok({})
def regenerate_userstories_csv_uuid(self, request, pk=None): project = self.get_object() self.check_permissions(request, "regenerate_userstories_csv_uuid", project) self.pre_conditions_on_save(project) data = { "uuid": self._regenerate_csv_uuid(project, "userstories_csv_uuid") } return response.Ok(data)
def list(self, request, *args, **kwargs): qs = self.get_queryset() project_id = request.QUERY_PARAMS.get("project", None) if project_id: qs = qs.filter(project_id=project_id) serializer = self.get_serializer(qs, many=True) return response.Ok(serializer.data)
def test(self, request, pk=None): webhook = self.get_object() self.check_permissions(request, 'test', webhook) self.pre_conditions_blocked(webhook) webhooklog = tasks.test_webhook(webhook.id, webhook.url, webhook.key, request.user, timezone.now()) log = serializers.WebhookLogSerializer(webhooklog) return response.Ok(log.data)
def auth_url(self, request, *args, **kwargs): self.check_permissions(request, "auth_url", None) url = AsanaImporter.get_auth_url( settings.IMPORTERS.get('asana', {}).get('app_id', None), settings.IMPORTERS.get('asana', {}).get('app_secret', None), settings.IMPORTERS.get('asana', {}).get('callback_url', None) ) return response.Ok({"url": url})