def get_context_data(self, **kwargs): context = super(RequestDetailView, self).get_context_data(**kwargs) context['can_edit'] = self.request.user.has_perm( Request.get_permission_name('edit'), self.object) context['show_edit_button'] = (self.object.status == 'I' or self.object.status == 'U') and context['can_edit'] mb = MailBox.objects.get_or_create(usr=self.object.author)[0] context['replies'] = mb.get_threads(self.object.id) context['can_view'] = self.request.user.has_perm( Request.get_permission_name('view'), self.object) context['DEBUG'] = settings.DEBUG context['groups'] = get_groups_and_usergroups(self.request.user) context['user_tags'] = [] if context['can_edit']: context['user_tags'] = UserProfile.objects.get( user=self.request.user).tags.all() context['is_author'] = (self.request.user == self.object.author) context['provisioned_email'] = mb.get_provisioned_email() editperm = Request.get_permission_name('edit') context['contacts_sin_email'] = len( self.object.get_contacts_with_email) context['can_view'] = self.request.user.has_perm( Request.get_permission_name('view'), self.object) return context
def send_request(request, pk=None): obj = get_object_or_404(Request, id=pk) can_edit = request.user.has_perm(Request.get_permission_name('edit'), obj) if not can_edit: #don't let other fools spam return render_to_response('403.html', {}, context_instance=RequestContext(request)) user = request.user up = UserProfile.objects.get(user=request.user) nthisweek = len(Request.get_user_in_threshold(user)) if not up.is_verified: return render_to_response('users/confirm_email.html', { 'nthisweek': nthisweek, 'limit': up.requests_per_week }, context_instance=RequestContext(request)) if nthisweek >= up.requests_per_week: return render_to_response('requests/send_limit.html', { 'nthisweek': nthisweek, 'limit': up.requests_per_week }, context_instance=RequestContext(request)) if not obj.sent: #if len(obj.get_contacts_with_email): #set the final version of the printed request obj.create_pdf_body() obj.send() rdv = RequestDetailView.as_view() return rdv(request=request, pk=pk)
def post(self, request, *args, **kwargs): user = self.request.user form = UpdateForm(self.request.POST) if not form.is_valid(): return render_to_response('403.html', {}, context_instance=RequestContext(request)) requests_to_modify = form.cleaned_data['requests_to_modify'] for obj in requests_to_modify: can_edit = user.has_perm(Request.get_permission_name('edit'), obj) if not can_edit: # Chicanery? return render_to_response( '403.html', {}, context_instance=RequestContext(request)) if form.cleaned_data['newduedate']: obj.due_date = form.cleaned_data['newduedate'] if form.cleaned_data['newsubject']: obj.title = form.cleaned_data['newsubject'] if form.cleaned_data['newupdateddate']: obj.date_updated = form.cleaned_data['newupdateddate'] if form.cleaned_data['newfulfilleddate']: obj.date_fulfilled = form.cleaned_data['newfulfilleddate'] if form.cleaned_data['newstatus']: #allow requests to be set even if they aren't sent because not all requests can be emailed obj.set_status(form.cleaned_data['newstatus']) if obj.status != 'F' and obj.status != 'P': obj.date_fulfilled = None elif obj.status == 'F' or obj.status == 'P' and form.cleaned_data[ 'newfulfilleddate']: obj.date_fulfilled = form.cleaned_data['newfulfilleddate'] elif obj.status == 'F' or obj.status == 'P' and not form.cleaned_data[ 'newfulfilleddate']: obj.date_fulfilled = datetime.now(tz=pytz.utc) else: obj.date_fulfilled = None if form.cleaned_data['addgroups']: editperm = Request.get_permissions_path('edit') viewperm = Request.get_permissions_path('view') for group in form.cleaned_data['addgroups']: assign_perm(editperm, group, obj) assign_perm(viewperm, group, obj) if form.cleaned_data['removegroups']: for group in form.cleaned_data['removegroups']: # Can't remove the author of the request if group.name != obj.author.username: remove_perm('edit_this_request', group, obj) action = form.cleaned_data['action'] if action == "Make Public": obj.private = False if action == "Make Private": obj.private = True obj.save() return self.get(request, *args, **kwargs)
def obj_create(self, bundle, **kwargs): try: attachments = [] data = bundle.data contacts = associate_contacts(bundle, data) if 'attachments' in bundle.data: for atch in data['attachments']: attachment = Attachment.objects.get(id=atch['id']) attachments.append(attachment) del data['attachments'] fields_to_use = {'author': bundle.request.user} for field in ['title', 'free_edit_body', 'private', 'text']: if field in data: try: #setattr(bundle.obj, field, data[field]) fields_to_use[field] = data[field] except Exception as e: logger.info('error setting field %s e=%s' % (field, e)) else: logger.info('field %s not allowed' % field) therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = contacts therequest.attachments = attachments therequest.save() bundle.obj = therequest logger.info("request %s created" % therequest.id) except Exception as e: logger.exception(e) return bundle
def post(self, request, *args, **kwargs): user = self.request.user form = UpdateForm(self.request.POST) if not form.is_valid(): return render_to_response('403.html', {}, context_instance=RequestContext(request)) requests_to_modify = form.cleaned_data['requests_to_modify'] for obj in requests_to_modify: can_edit = user.has_perm(Request.get_permission_name('edit'), obj) if not can_edit: # Chicanery? return render_to_response('403.html', {}, context_instance=RequestContext(request)) if form.cleaned_data['newduedate']: obj.due_date = form.cleaned_data['newduedate'] if form.cleaned_data['newsubject']: obj.title = form.cleaned_data['newsubject'] if form.cleaned_data['newupdateddate']: obj.date_updated = form.cleaned_data['newupdateddate'] if form.cleaned_data['newfulfilleddate']: obj.date_fulfilled = form.cleaned_data['newfulfilleddate'] if form.cleaned_data['newstatus']: #allow requests to be set even if they aren't sent because not all requests can be emailed obj.set_status(form.cleaned_data['newstatus']) if obj.status != 'F' and obj.status != 'P': obj.date_fulfilled = None elif obj.status == 'F' or obj.status == 'P' and form.cleaned_data['newfulfilleddate']: obj.date_fulfilled = form.cleaned_data['newfulfilleddate'] elif obj.status == 'F' or obj.status == 'P' and not form.cleaned_data['newfulfilleddate']: obj.date_fulfilled = datetime.now(tz=pytz.utc) else: obj.date_fulfilled = None if form.cleaned_data['addgroups']: editperm = Request.get_permissions_path('edit') viewperm = Request.get_permissions_path('view') for group in form.cleaned_data['addgroups']: assign_perm(editperm, group, obj) assign_perm(viewperm, group, obj) if form.cleaned_data['removegroups']: for group in form.cleaned_data['removegroups']: # Can't remove the author of the request if group.name != obj.author.username: remove_perm('edit_this_request', group, obj) action = form.cleaned_data['action'] if action == "Make Public": obj.private = False if action == "Make Private": obj.private = True obj.save() return self.get(request, *args, **kwargs)
def obj_create(self, bundle, **kwargs): try: attachments = [] data = bundle.data contacts = associate_contacts(bundle, data) if 'attachments' in bundle.data: for atch in data['attachments']: attachment = Attachment.objects.get(id=atch['id']) attachments.append(attachment) del data['attachments'] fields_to_use = { 'author': bundle.request.user } for field in ['title', 'free_edit_body', 'private', 'text']: if field in data: try: #setattr(bundle.obj, field, data[field]) fields_to_use[field] = data[field] except Exception as e: logger.info('error setting field %s e=%s' % (field, e)) else: logger.info('field %s not allowed' % field) therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = contacts therequest.attachments = attachments therequest.save() bundle.obj = therequest logger.info("request %s created" % therequest.id) except Exception as e: logger.exception(e) return bundle
def apply_filters(self, request, applicable_filters): filters = applicable_filters if 'groups__name' in filters: groups_name = filters.pop('groups__name') else: groups_name = None if 'groups__id' in filters: groups_id = filters.pop('groups__id') else: groups_id = None filtered = super(RequestResource, self).apply_filters(request, applicable_filters) group = None if groups_id: try: group = Group.objects.get(id=groups_id) except: pass if groups_name: try: group = Group.objects.get(name=groups_name) except: pass if group and request.user.has_perm( UserProfile.get_permission_name('view'), group): return get_objects_for_group( group, Request.get_permissions_path('view')).filter(~Q(status='X')) return filtered
def obj_create(self, bundle, **kwargs): #validator not being called data = bundle.data user = bundle.request.user thegroup = Group.objects.create(name=data['name']) thegroup.save() #creator of the group can edit by default assign_perm(UserProfile.get_permission_name('edit'), user, thegroup) assign_perm(UserProfile.get_permission_name('view'), user, thegroup) bundle.obj = thegroup # User always has edit permissions for group he made user.groups.add(thegroup) user.save() # Users are in the group if 'users' in data: thegroup.user_set = [] users = [User.objects.get(pk=userid) for userid in data['users']] thegroup.user_set = users if 'request_id' in data and data['request_id']: req = Request.objects.get(id=data['request_id']) assign_perm(Request.get_permission_name('view'), thegroup, req) thegroup.save() return bundle
def obj_create(self, bundle, **kwargs): try: data = bundle.data user = bundle.request.user up = UserProfile.objects.get(user=user) if 'data' in data.keys(): #tags need to be added to an object, this can be expanded to other objects like contacts if 'request_id' in data.keys(): req = Request.objects.get(id=data['request_id']) up.tags.add(data['name']) obj = up.tags.get(name=data['name']) req.tags.add(data['name']) bundle.data['data']['result'] = 'created' bundle.obj = obj if 'request_ids' in data.keys(): requests = Request.objects.filter(id__in=data['request_ids']) for req in requests: can_edit = user.has_perm(Request.get_permission_name('view'), req) if not can_edit: logger.info("%s tried to add/edit/rename tags from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse(HttpForbidden("It appears you do not have permissions to add or remove tags here.")) bundle.data['data']['result'] = 'created' up.tags.add(data['name']) obj = up.tags.get(name=data['name']) bundle.obj = obj for req in requests: req.tags.add(data['name']) except Exception as e: logger.exception(e) return bundle
def apply_filters(self, request, applicable_filters): filters = applicable_filters if 'groups__name' in filters: groups_name = filters.pop('groups__name') else: groups_name = None if 'groups__id' in filters: groups_id = filters.pop('groups__id') else: groups_id = None filtered = super(RequestResource, self).apply_filters(request, applicable_filters) group = None if groups_id: try: group = Group.objects.get(id = groups_id) except: pass if groups_name: try: group = Group.objects.get(name = groups_name) except: pass if group and request.user.has_perm(UserProfile.get_permission_name('view'), group): return get_objects_for_group(group, Request.get_permissions_path('view')).filter(~Q(status='X')) return filtered
def handle(self, *args, **options): length = settings.SUNSET_CONFIG['time'] units = settings.SUNSET_CONFIG['units'] days_old = length if units == 'months': days_old = days_old * 30 if units == 'years': days_old = days_old * 365 days_to_wait = settings.SUNSET_CONFIG['days_to_wait_before_action'] therequests = Request.get_all_sunsetting(days_old - days_to_wait) for request in therequests: print "SUNSET NOTIFICATION requst %s" % request.id user = request.author address = user.email try: address = settings.TASK_EMAIL_RECIPIENT except: pass notifcation = Notification( type=Notification.get_type_id('Sunset clause notification'), sent=datetime.now(), request=request) notifcation.save() data = { "from": "*****@*****.**", "to": address, 'subject': 'An important message regarding your request to ' + request.agency.name, 'html': """ According to our records, you sent a request to %s about %s %s ago. <br /> It's FOIA Machine's policy to make private requests public after %s %s if you take no further action.<br/> If you do nothing your request will be made public in %s days. <br/> If you'd like to keep your request private, follow this link: <a href="https://www.foiamachine.org/requests/privacy/%s">https://www.foiamachine.org/requests/privacy/%s</a> """ % (request.agency.name, length, units, length, units, days_to_wait, request.id, request.id) } if settings.MG_ROUTE: post_url = 'https://api.mailgun.net/v2/%s.%s/messages' % ( settings.MG_ROUTE, settings.MG_DOMAIN) else: post_url = 'https://api.mailgun.net/v2/%s/messages' % settings.MG_DOMAIN post_url = settings.MG_POST_URL if settings.SEND_NOTIFICATIONS: resp = requests.post(post_url, auth=("api", settings.MAILGUN_KEY), data=data) content = json.loads(resp.content) logging.info('SENT NOTIFICATION STATUS:%s' % content)
def send_limit(request, pk=None, template='requests/send_limit.html'): context = {} user = request.user up = UserProfile.objects.get(user=request.user) nthisweek = len(Request.get_user_in_threshold(user)) context['sent_too_many'] = nthisweek >= up.requests_per_week context['limit'] = up.requests_per_week return render_to_response(template, context, context_instance=RequestContext(request))
def get_queryset(self, **kwargs): try: pk = self.kwargs['pk'] user = self.request.user group = user.groups.get(pk=pk) return get_objects_for_group(group, Request.get_permissions_path('view')).filter(~Q(status='X')) except Exception as e: return Request.objects.none()
def s3_file_view(request, rpk, pk): attachment = get_object_or_404(Attachment, id=pk) user = request.user therequest = get_object_or_404(Request, id=rpk) can_view = user.has_perm(Request.get_permission_name('view'), therequest) if not can_view: return render_to_response('403.html', {}, context_instance=RequestContext(request)) return HttpResponseRedirect(attachment.file.url)
def get_queryset(self, **kwargs): try: pk = self.kwargs['pk'] user = self.request.user group = user.groups.get(pk=pk) return get_objects_for_group( group, Request.get_permissions_path('view')).filter(~Q(status='X')) except Exception as e: return Request.objects.none()
def get_context_data(self, **kwargs): context = super(LinkRequestDetailView, self).get_context_data(**kwargs) context['can_edit'] = False mb = MailBox.objects.get_or_create(usr=self.object.author)[0] context['replies'] = mb.get_threads(self.object.id) context['can_view'] = True context['DEBUG'] = settings.DEBUG context['groups'] = get_groups_and_usergroups(self.request.user) context['user_tags'] = [] editperm = Request.get_permission_name('edit') return context
def get_context_data(self, **kwargs): context = super(RequestDetailView, self).get_context_data(**kwargs) context['can_edit'] = self.request.user.has_perm(Request.get_permission_name('edit'), self.object) context['show_edit_button'] = (self.object.status == 'I' or self.object.status == 'U') and context['can_edit'] mb = MailBox.objects.get_or_create(usr=self.object.author)[0] context['replies'] = mb.get_threads(self.object.id) context['can_view'] = self.request.user.has_perm(Request.get_permission_name('view'), self.object) context['DEBUG'] = settings.DEBUG context['groups'] = get_groups_and_usergroups(self.request.user) context['user_tags'] = [] if context['can_edit']: context['user_tags'] = UserProfile.objects.get(user=self.request.user).tags.all() context['is_author'] = (self.request.user == self.object.author) context['provisioned_email'] = mb.get_provisioned_email() editperm = Request.get_permission_name('edit') context['contacts_sin_email'] = len(self.object.get_contacts_with_email) context['can_view'] = self.request.user.has_perm(Request.get_permission_name('view'), self.object) return context
def send_request(request, pk=None): obj = get_object_or_404(Request, id=pk) can_edit = request.user.has_perm(Request.get_permission_name('edit'), obj) if not can_edit: #don't let other fools spam return render_to_response('403.html', {}, context_instance=RequestContext(request)) user = request.user up = UserProfile.objects.get(user=request.user) nthisweek = len(Request.get_user_in_threshold(user)) if not up.is_verified: return render_to_response('users/confirm_email.html', {'nthisweek' : nthisweek, 'limit' : up.requests_per_week}, context_instance=RequestContext(request)) if nthisweek >= up.requests_per_week: return render_to_response('requests/send_limit.html', {'nthisweek' : nthisweek, 'limit' : up.requests_per_week}, context_instance=RequestContext(request)) if not obj.sent: #if len(obj.get_contacts_with_email): #set the final version of the printed request obj.create_pdf_body() obj.send() rdv = RequestDetailView.as_view() return rdv(request=request, pk=pk)
def handle(self, *args, **options): nargs = len(args) if nargs == 0: ndays = -1 elif nargs > 1: raise CommandError("Usage: notify_overdue_requests [ndays]") elif nargs == 1: try: ndays = int(args[0]) except ValueError: raise CommandError("%s not an integer number of days" % args[0]) therequests = Request.get_all_overdue() for request in therequests: print 'Doing request %s response due %s' % (request.id, request.get_due_date) user = request.author address = user.email try: address = settings.TASK_EMAIL_RECIPIENT except: pass notifcation = Notification(type=Notification.get_type_id("Late request"), request=request) notifcation.save() data = { "from" : "*****@*****.**", "to" : address, 'subject' : 'Response due from ' + request.agency.name, 'html' : """ According to our records, you're overdue to receive a response from %s. <br /> If that's not the case, you can log in and update the status of your request at <a href="https://www.foiamachine.org/requests/%s">https://www.foiamachine.org/requests/%s</a> """ % (request.agency.name, request.pk, request.pk) } if settings.MG_ROUTE: post_url = 'https://api.mailgun.net/v2/%s.%s/messages' % (settings.MG_ROUTE, settings.MG_DOMAIN) else: post_url = 'https://api.mailgun.net/v2/%s/messages' % settings.MG_DOMAIN post_url = settings.MG_POST_URL if settings.SEND_NOTIFICATIONS: resp = requests.post( post_url, auth=("api", settings.MAILGUN_KEY), data=data) content = json.loads(resp.content) logging.info('SENT NOTIFICATION STATUS:%s' % content)
def dehydrate(self, bundle): if 'request_id' not in bundle.data.keys(): bundle.data['request_id'] = bundle.request.GET.get("request_id", None) bundle.data['toggle_to_edit'] = bundle.request.user.has_perm(UserProfile.get_permission_name('edit'), bundle.obj) if bundle.data['request_id']: checker = ObjectPermissionChecker(bundle.obj) bundle.data['toggle_to_edit'] = checker.has_perm(Request.get_permission_name('edit'), Request.objects.get(id=bundle.data['request_id'])) if not bundle.request.user.is_authenticated(): bundle.data['can_edit'] = False bundle.data['can_edit'] = bundle.request.user.has_perm(UserProfile.get_permission_name('edit'), bundle.obj) bundle.data['type'] = 'group' for usr in bundle.data['users']: usr.data['toggle_to_edit'] = usr.obj.has_perm(UserProfile.get_permission_name('edit'), bundle.obj) return bundle
def handle(self, *args, **options): nargs = len(args) if nargs == 0: ndays = -1 elif nargs > 1: raise CommandError("Usage: notify_overdue_requests [ndays]") elif nargs == 1: try: ndays = int(args[0]) except ValueError: raise CommandError("%s not an integer number of days" % args[0]) therequests = Request.get_all_overdue() for request in therequests: print 'Doing request %s response due %s' % (request.id, request.get_due_date) user = request.author address = user.email try: address = settings.TASK_EMAIL_RECIPIENT except: pass notifcation = Notification(type=Notification.get_type_id("Late request"), request=request) notifcation.save() data = { "from" : "*****@*****.**", "to" : address, 'subject' : 'Response due from ' + request.agency.name, 'html' : """ According to our records, you're overdue to receive a response from %s. <br /> If that's not the case, you can log in and update the status of your request at <a href="https://www.foiamachine.org/requests/%s">https://www.foiamachine.org/requests/%s</a> """ % (request.agency.name, request.pk, request.pk) } if settings.MG_ROUTE: post_url = 'https://api.mailgun.net/v2/%s.foiamachine.mailgun.org/messages' % settings.MG_ROUTE else: post_url = 'https://api.mailgun.net/v2/foiamachine.mailgun.org/messages' if settings.SEND_NOTIFICATIONS: resp = requests.post( post_url, auth=("api", settings.MAILGUN_KEY), data=data) content = json.loads(resp.content) logging.info('SENT NOTIFICATION STATUS:%s' % content)
def obj_update(self, bundle, **kwargs): data = bundle.data bundle.obj = Request.objects.get(id=bundle.data['id']) can_edit = bundle.request.user.has_perm( Request.get_permission_name('edit'), bundle.obj) if not can_edit: raise ImmediateHttpResponse( HttpBadRequest( "It appears you don't have permission to change this request." )) if 'status' in bundle.data: status = bundle.data['status'] del bundle.data['status'] if status: bundle.obj.set_status(status) attachments = [] if 'attachments' in bundle.data: for atch in data['attachments']: attachment = Attachment.objects.get(id=atch['id']) attachments.append(attachment) bundle.obj.attachments = attachments del data['attachments'] for field in [ 'title', 'free_edit_body', 'private', 'text', 'phone_contact', 'prefer_electornic', 'max_cost', 'fee_waiver' ]: if field in data: try: setattr(bundle.obj, field, data[field]) except Exception as e: logger.info('error setting field %s e=%s' % (field, e)) else: logger.info('field %s not allowed' % field) contacts = associate_contacts(bundle, data) bundle.obj.contacts = contacts bundle.obj.save() #bundle.data['can_send'] = bundle.obj.can_send if 'generate_pdf' in bundle.data: bundle.obj.create_pdf_body() if 'do_send' in bundle.data and bundle.data['do_send']: #obj sent property will reflect whether it has been sent bundle.obj.send() #bundle.data['sent'] = bundle.obj.sent return bundle
def free_request_edit(request, pk=None, template='requests/free_edit.html'): context = {} user = request.user up = UserProfile.objects.get(user=request.user) if not up.default_request_creator_free: up.default_request_creator_free = True up.save() context['is_verified'] = up.is_verified nthisweek = len(Request.get_user_in_threshold(user)) context['sent_too_many'] = nthisweek >= up.requests_per_week context['limit'] = up.requests_per_week if pk is not None: obj = get_object_or_404(Request, id=pk) #TODO this is basically two lookups, one to render the page and then one to the api context['edit_obj'] = obj return render_to_response(template, context, context_instance=RequestContext(request))
def handle(self, *args, **options): length = settings.SUNSET_CONFIG['time'] units = settings.SUNSET_CONFIG['units'] days_old = length if units == 'months': days_old = days_old * 30 if units == 'years': days_old = days_old * 365 days_to_wait = settings.SUNSET_CONFIG['days_to_wait_before_action'] therequests = Request.get_all_sunsetting(days_old - days_to_wait) for request in therequests: print "SUNSET NOTIFICATION requst %s" % request.id user = request.author address = user.email try: address = settings.TASK_EMAIL_RECIPIENT except: pass notifcation = Notification(type=Notification.get_type_id('Sunset clause notification'), sent=datetime.now(), request=request) notifcation.save() data = { "from" : "*****@*****.**", "to" : address, 'subject' : 'An important message regarding your request to ' + request.agency.name, 'html' : """ According to our records, you sent a request to %s about %s %s ago. <br /> It's FOIA Machine's policy to make private requests public after %s %s if you take no further action.<br/> If you do nothing your request will be made public in %s days. <br/> If you'd like to keep your request private, follow this link: <a href="https://www.foiamachine.org/requests/privacy/%s">https://www.foiamachine.org/requests/privacy/%s</a> """ % (request.agency.name, length, units, length, units, days_to_wait, request.id, request.id) } post_url = settings.MG_POST_URL if settings.SEND_NOTIFICATIONS: resp = requests.post( post_url, auth=("api", settings.MAILGUN_KEY), data=data) content = json.loads(resp.content) logging.info('SENT NOTIFICATION STATUS:%s' % content)
def handle(self, *args, **options): length = settings.SUNSET_CONFIG['time'] units = settings.SUNSET_CONFIG['units'] days_old = length if units == 'months': days_old = days_old * 30 if units == 'years': days_old = days_old * 365 days_to_wait = settings.SUNSET_CONFIG['days_to_wait_before_action'] therequests = Request.get_sunsetted(days_old) for request in therequests: request.private = False #don't put user in a loop if they don't follow teh email link to set this flag #if we don't set it adn the user makes the request private after we make it public #it will become public again when this script runs request.keep_private = True request.save() print request.id
def obj_update(self, bundle, **kwargs): user = bundle.request.user if 'request' not in bundle.data: raise BadRequest("No request to associate with") data = bundle.data request = Request.objects.get(id=data['request']) if not user.has_perm(Request.get_permission_name('edit'), request): return bundle try: data = bundle.data message = bundle.obj = MailMessage.objects.get(id=data['id']) for field in ['body', 'subject', 'deprecated']: if field in data: setattr(message, field, data[field]) message.save() return bundle except Exception as e: logger.exception(e) raise BadRequest(str(e)) return bundle
def dehydrate(self, bundle): if 'request_id' not in bundle.data.keys(): bundle.data['request_id'] = bundle.request.GET.get( "request_id", None) bundle.data['toggle_to_edit'] = bundle.request.user.has_perm( UserProfile.get_permission_name('edit'), bundle.obj) if bundle.data['request_id']: checker = ObjectPermissionChecker(bundle.obj) bundle.data['toggle_to_edit'] = checker.has_perm( Request.get_permission_name('edit'), Request.objects.get(id=bundle.data['request_id'])) if not bundle.request.user.is_authenticated(): bundle.data['can_edit'] = False bundle.data['can_edit'] = bundle.request.user.has_perm( UserProfile.get_permission_name('edit'), bundle.obj) bundle.data['type'] = 'group' for usr in bundle.data['users']: usr.data['toggle_to_edit'] = usr.obj.has_perm( UserProfile.get_permission_name('edit'), bundle.obj) return bundle
def obj_update(self, bundle, **kwargs): data = bundle.data bundle.obj = Request.objects.get(id=bundle.data['id']) can_edit = bundle.request.user.has_perm(Request.get_permission_name('edit'), bundle.obj) if not can_edit: raise ImmediateHttpResponse(HttpBadRequest("It appears you don't have permission to change this request.")) if 'status' in bundle.data: status = bundle.data['status'] del bundle.data['status'] if status: bundle.obj.set_status(status) attachments = [] if 'attachments' in bundle.data: for atch in data['attachments']: attachment = Attachment.objects.get(id=atch['id']) attachments.append(attachment) bundle.obj.attachments = attachments del data['attachments'] for field in ['title', 'free_edit_body', 'private', 'text', 'phone_contact', 'prefer_electornic', 'max_cost', 'fee_waiver']: if field in data: try: setattr(bundle.obj, field, data[field]) except Exception as e: logger.info('error setting field %s e=%s' % (field, e)) else: logger.info('field %s not allowed' % field) contacts = associate_contacts(bundle, data) bundle.obj.contacts = contacts bundle.obj.save() #bundle.data['can_send'] = bundle.obj.can_send if 'generate_pdf' in bundle.data: bundle.obj.create_pdf_body() if 'do_send' in bundle.data and bundle.data['do_send']: #obj sent property will reflect whether it has been sent bundle.obj.send() #bundle.data['sent'] = bundle.obj.sent return bundle
def post(self, request, *args, **kwargs): """ Lets user edit settings on posts """ user = self.request.user form = UpdateForm(self.request.POST) if not form.is_valid(): return render_to_response('403.html', {}, context_instance=RequestContext(request)) requests_to_modify = form.cleaned_data['requests_to_modify'] action = form.cleaned_data['action'] for obj in requests_to_modify: can_edit = user.has_perm(Request.get_permission_name('edit'), obj) if not can_edit: # Chicanery? return render_to_response( '403.html', {}, context_instance=RequestContext(request)) if action == "Make Public": obj.private = False elif action == "Make Private": obj.private = True elif action == "Delete": obj.status = 'X' else: obj.status = form.cleaned_data['newstatus'] if obj.status != 'F' and obj.status != 'P': obj.date_fulfilled = None elif obj.status == 'F' or obj.status == 'P': obj.date_fulfilled = datetime.now() #groups = form.cleaned_data['groups'] obj.save() # Now use the get handler to reapply the filters # and pagination return self.get(request, *args, **kwargs)
def post(self, request, *args, **kwargs): """ Lets user edit settings on posts """ user = self.request.user form = UpdateForm(self.request.POST) if not form.is_valid(): return render_to_response('403.html', {}, context_instance=RequestContext(request)) requests_to_modify = form.cleaned_data['requests_to_modify'] action = form.cleaned_data['action'] for obj in requests_to_modify: can_edit = user.has_perm(Request.get_permission_name('edit'), obj) if not can_edit: # Chicanery? return render_to_response('403.html', {}, context_instance=RequestContext(request)) if action == "Make Public": obj.private = False elif action == "Make Private": obj.private = True elif action == "Delete": obj.status = 'X' else: obj.status = form.cleaned_data['newstatus'] if obj.status != 'F' and obj.status != 'P': obj.date_fulfilled = None elif obj.status == 'F' or obj.status == 'P': obj.date_fulfilled = datetime.now() #groups = form.cleaned_data['groups'] obj.save() # Now use the get handler to reapply the filters # and pagination return self.get(request, *args, **kwargs)
def obj_create(self, bundle, **kwargs): try: data = bundle.data user = bundle.request.user up = UserProfile.objects.get(user=user) if 'data' in data.keys(): #tags need to be added to an object, this can be expanded to other objects like contacts if 'request_id' in data.keys(): req = Request.objects.get(id=data['request_id']) up.tags.add(data['name']) obj = up.tags.get(name=data['name']) req.tags.add(data['name']) bundle.data['data']['result'] = 'created' bundle.obj = obj if 'request_ids' in data.keys(): requests = Request.objects.filter( id__in=data['request_ids']) for req in requests: can_edit = user.has_perm( Request.get_permission_name('view'), req) if not can_edit: logger.info( "%s tried to add/edit/rename tags from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse( HttpForbidden( "It appears you do not have permissions to add or remove tags here." )) bundle.data['data']['result'] = 'created' up.tags.add(data['name']) obj = up.tags.get(name=data['name']) bundle.obj = obj for req in requests: req.tags.add(data['name']) except Exception as e: logger.exception(e) return bundle
def obj_update(self, bundle, **kwargs): ''' NOTES about permissions on tags Tags should be scoped to the UserProfile.tags so multiple users can have tags with the same name If a tag is not in UserProfile.tags then it wasn't created by that user Any user with edit access to the request should be able to add/remove a tag We should check that a request doesn't already have a tag of the same name so a request can't have two different tags of the same name BUT only the person who created a tag should be able to rename it (user1 has a tag phase1, user2 has a tag phase2, user2's phase1 tag shouldn't be changed if user1 updates his or her tag name) ''' data = bundle.data user = bundle.request.user up = UserProfile.objects.get(user=user) bundle.obj = Group.objects.get(id=data['id']) if 'data' in data.keys(): if 'action' in data['data'].keys() and 'request_ids' in data.keys( ): # For bulk tagging requests = Request.objects.filter(id__in=data['request_ids']) for req in requests: can_edit = user.has_perm( Request.get_permission_name('view'), req) if not can_edit: logger.info( "%s tried to add/edit/rename tags from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse( HttpForbidden( "It appears you do not have permissions to add or remove tags here." )) for req in requests: # OK, they have permission, now let's actually do it if data['data']['action'] == 'associate': obj = up.tags.get(id=data['id']) tags = req.tags.filter(name=data['name']) if tags: # Already tagged like that for tag in tags: if tag.id != obj.id: # Already tagged by another user raise ImmediateHttpResponse( HttpForbidden( "A tag by this name is already associated with one of these requests by another user." )) else: # Tag it now req.tags.add(obj) elif data['data']['action'] == 'disassociate': req.tags.remove(data['name']) bundle.obj = Tag.objects.get(id=data['id']) if 'request_id' in data.keys(): req = Request.objects.get(id=data['request_id']) can_edit = user.has_perm(Request.get_permission_name('view'), req) if 'action' in data['data'].keys() and can_edit: if data['data']['action'] == 'associate': if req.tags.filter(name=data['name']).count() > 0: raise ImmediateHttpResponse( HttpForbidden( "A tag by this name is already associated with this request." )) obj = up.tags.get(id=data['id']) req.tags.add(obj) elif data['data']['action'] == 'disassociate': req.tags.remove(data['name']) #refresh the obj for backbone to update bundle.obj = Tag.objects.get(id=data['id']) else: logger.info( "%s tried to add/edit/rename tags from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse( HttpForbidden( "It appears you do not have permissions to add or remove tags here." )) #action independent of request if data['data']['action'] == 'rename': usertags = up.tags.all() if usertags.filter(id=data['id']).count() == 0: #not my tag, presumably raise ImmediateHttpResponse( HttpForbidden( "It appears you do not have permissions to edit this tag." )) elif usertags.filter(name=data['name']).count() < 2: tag = Tag.objects.get(id=data['id']) tag.name = data['name'] tag.save() bundle.obj = tag else: raise ImmediateHttpResponse( HttpForbidden( "An error occurred while trying to modify this tag." )) return bundle
def obj_update(self, bundle, **kwargs): data = bundle.data user = bundle.request.user bundle.obj = Group.objects.get(id=data['id']) if 'data' in data.keys(): #if 'action' in data['data'].keys() and data['data']['action'] == 'chown': #we are associating, disassociating... assuming the USER is taking action here if 'request_id' in data.keys() and data['request_id']: req = Request.objects.get(id=data['request_id']) if 'action' in data['data'].keys() and req.author == bundle.request.user: if data['data']['action'] == 'associate': assign_perm(Request.get_permission_name('view'), bundle.obj, req) bundle.data['data']['result'] = 'associated' elif data['data']['action'] == 'disassociate': remove_perm(Request.get_permission_name('view'), bundle.obj, req) remove_perm(Request.get_permission_name('edit'), bundle.obj, req) bundle.data['data']['result'] = 'disassociated' elif data['data']['action'] == 'change-access': #right now we are toggling between view and edit checker = ObjectPermissionChecker(bundle.obj) if checker.has_perm(Request.get_permission_name('view'), req) and not checker.has_perm(Request.get_permission_name('edit'), req): assign_perm(Request.get_permission_name('edit'), bundle.obj, req) elif user.has_perm(Request.get_permission_name('edit'), req): remove_perm(Request.get_permission_name('edit'), bundle.obj, req) else: raise ImmediateHttpResponse(HttpForbidden("We couldn't determine the appropriate permissions to assign. Sorry.")) else: logger.info("%s tried to remove users from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse(HttpBadRequest("It appears you don't have permission to change that user or group's permission.")) else: can_edit = bundle.request.user.has_perm(UserProfile.get_permission_name('edit'), bundle.obj) if not can_edit: raise ImmediateHttpResponse(HttpForbidden("It doesn't appear you can edit this group.")) if 'action' in data['data'].keys() and data['data']['action'] == 'rename': bundle.obj.name = data['name'] bundle.obj.save() if 'action' in data['data'].keys() and data['data']['action'] == 'chown' and 'user_id' in data['data'].keys() and data['data']['user_id']: #change user permission on a group object other_user = User.objects.get(id=data['data']['user_id']) o_can_edit = other_user.has_perm(UserProfile.get_permission_name('edit'), bundle.obj) if o_can_edit: #toggled to view remove_perm(UserProfile.get_permission_name('edit'), other_user, bundle.obj) else: #toggled to edit assign_perm(UserProfile.get_permission_name('edit'), other_user, bundle.obj) else: ''' NOTE about group permissions The creator of the requst is the only one who can share a request with other users and groups Otherwise the request could be shared with any number of people ''' can_edit = bundle.request.user.has_perm(UserProfile.get_permission_name('edit'), bundle.obj) if not can_edit: raise ImmediateHttpResponse(HttpForbidden("It doesn't appear you can edit this group.")) #we are adding or removing users to the group on the group page users = set([User.objects.get(pk=user['id']) for user in data['users']]) existing_users = set([usr for usr in bundle.obj.user_set.all()]) to_remove = existing_users - users #need to remove and set permissions here for usr in to_remove: remove_perm(UserProfile.get_permission_name('edit'), usr, bundle.obj) remove_perm(UserProfile.get_permission_name('view'), usr, bundle.obj) for usr in users: #users can view but not edit by default assign_perm(UserProfile.get_permission_name('view'), usr, bundle.obj) bundle.obj.user_set = users bundle.obj.save() data.pop('data', None) data.pop('request_id', None) return bundle
def handle(self, *args, **options): letter_responses = {} if len(args) < 1: print "Please provide ID of Google Spreadsheet" return -1 idd = args[0] resp = requests.get("https://docs.google.com/spreadsheets/d/%s/pub?output=csv" % idd) reader = list(csv.reader(resp.content.split('\n'), delimiter=',')) header = reader[0] for row in reader[1:-1]: #get user, contact and agency user = User.objects.get(username=row[header.index('username')]) user_profile = UserProfile.objects.get(user=user) govt = get_or_create_us_govt(row[header.index("state")], 'state') agency, acreated = Agency.objects.get_or_create(name=row[header.index("agency")], government=govt) contact, ccreated = agency.contacts.get_or_create( first_name=row[header.index("contact.first.name")], middle_name=row[header.index("contact.middle.name")], last_name=row[header.index("contact.last.name")]) if row[header.index("contact.email")] != "": contact.add_email(row[header.index("contact.email")]) if row[header.index("contact.phone")] != "": contact.add_phone(row[header.index("contact.phone")]) #set up group and tags group, created = Group.objects.get_or_create(name=row[header.index("group")]) assign_perm(UserProfile.get_permission_name('edit'), user, group) assign_perm(UserProfile.get_permission_name('view'), user, group) user.groups.add(group) user_profile.tags.add(row[header.index("tag")]) #assemble law text law_texts = [] for l in govt.statutes.all(): law_texts.append('%s' % (l.short_title,)) law_text = ' and '.join(law_texts) #get the letter template letter_url = row[header.index("letter.url")] letter_template = '' if letter_url in letter_responses.keys(): letter_template = letter_responses[letter_url] else: letter_resp = requests.get(letter_url) letter_template = letter_resp.content letter_responses[letter_url] = letter_template #render the template context = Context({ 'contact': contact, 'user_profile': user_profile, 'user': user, 'law_text': law_text }) template = Template(letter_template) letter = template.render(context) #create the request fields_to_use = { 'author': user, 'title': row[header.index("request.title")], 'free_edit_body': letter, 'private': True if row[header.index("request.private")] == "TRUE" else False, 'text': letter#silly distinction leftover from old days but fill it in } #delete all requests that look like the one i'm about to make so we don't have duplicates floating around Request.objects.filter(author=user, title=row[header.index("request.title")]).delete() #create the request therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = [contact] therequest.government = govt therequest.agency = agency therequest.tags.add(row[header.index("tag")]) therequest.save() #assing permissions to the request assign_perm(Request.get_permission_name('view'), group, therequest) assign_perm(Request.get_permission_name('edit'), group, therequest) if row[header.index("request.send")] == "TRUE": therequest.send() print "SENT request %s" % row[header.index("request.title")] else: print "STAGED request %s" % row[header.index("request.title")]
def handle(self, *args, **options): users = [ User.objects.get(username='******'), #User.objects.get(username='******'), #User.objects.get(username='******'), #User.objects.get(username='******') ] up = UserProfile.objects.get(user=users[0]) up.tags.add(ncaa_tag_name) up.tags.add(coach_tag_name) for user in users: assign_perm(UserProfile.get_permission_name('edit'), user, ncaa_group) assign_perm(UserProfile.get_permission_name('view'), user, ncaa_group) assign_perm(UserProfile.get_permission_name('edit'), user, coach_group) assign_perm(UserProfile.get_permission_name('view'), user, coach_group) #Request.objects.all().delete() ncaa_text_to_use = """ Pursuant to the %s, I am requesting the following documents:<br/><br/>\ The equity/revenue-and-expenses report completed by the athletic department for the \ National Collegiate Athletic Association for the 2014 fiscal year. This report is a \ multi-page document that had to be submitted to the NCAA by Jan. 15, 2015. \ It contains 38 revenue and expense categories, followed by specific breakdowns of \ each of those categories, by sport and gender. I am requesting the full report, \ including the detail tables and the Statement of Revenues and Expenses that appear at the end of the report. <br/><br/>\ PLEASE NOTE: The NCAA report is different than the equity report that is sent to the\ U.S. Department of Education for Title IX compliance. <br/><br/>\ %s """ coach_text_to_use = """ Pursuant to %s, I am requesting the following documents:<br/><br/>\ The current contracts for %s. If a contract is under negotiation, \ please forward the current contract but let me know that a new contract may be forthcoming. \ If there is no contact for one or both, please forward the letter(s) of intent or other \ document(s) outlining each employee's conditions of employment \ -- including bonus structure -- and/or a current statement of salary. <br/><br/>\ %s """ fname = settings.SITE_ROOT + "/apps/requests/data/NCAA-pio.csv" #with codecs.open(fname, 'w', encoding="utf-8") as f: # resp = requests.get("https://docs.google.com/spreadsheets/d/1kccaiCCYIHOTEvpUWQiKs51v6K2TNRX7-NN6l1WtzyM/pub?output=csv") # f.write(resp.text) reader = list(UnicodeReader(open(fname, 'rb'))) #create contacts header = reader[0] for idx, row in enumerate(reader[1:]): user = users[0] up = UserProfile.objects.get(user=user) state = row[header.index('STATE')] agency_name = row[header.index("UNIVERSITY")] pio = row[header.index("PIO OFFICER")] email = row[header.index("PIO Email")] phone = row[header.index("PIO Phone")] sid_pio = row[header.index("SID ")] sid_email = row[header.index("SID Email")] sid_phone = row[header.index("SID Phone")] is_power = (row[header.index("Power Conference")] == 'TRUE') is_private = (row[header.index("Is Private")] == 'TRUE') if not is_private and state != '' and email != 'N/A' and pio != 'N/A' and agency_name != '': govt = get_or_create_us_govt(state, 'state') fname = pio.split(" ")[0] lname = pio.split(" ")[-1] middle = '' #alter table `contacts_contact` convert to character set utf8 collate utf8_general_ci; #alter table `agency_agency` convert to character set utf8 collate utf8_general_ci; #alter table `requests_request` convert to character set utf8 collate utf8_general_ci; try: agency, acreated = Agency.objects.get_or_create( name=agency_name, government=govt) except Exception as e: print e print "If more than one agency was returned, pick one!" import pdb pdb.set_trace() try: contact, ccreated = agency.contacts.get_or_create( first_name=fname, middle_name=middle, last_name=lname) except Exception as e: print e print "If more than one contact was returned, pick one!" import pdb pdb.set_trace() sid_contact = None if phone != 'N/A': contact.add_phone(phone) contact.add_email(email) #agency.contacts.add(contact) if sid_pio != 'N/A' and sid_email != 'N/A': fname = sid_pio.split(" ")[0] lname = sid_pio.split(" ")[-1] sid_contact, ccreated = Contact.objects.get_or_create( first_name=fname, middle_name='', last_name=lname) sid_contact.add_title("SID") sid_contact.add_email(sid_email) if sid_phone != 'N/A': sid_contact.add_phone(sid_phone) agency.contacts.add(sid_contact) contacts = [contact] if sid_contact is not None: contacts = [contact, sid_contact] agency.save() #logger.info('agency %s %s contact %s %s %s %s' % (agency_name, acreated, fname, middle, lname, ccreated)) law_texts = [] for l in govt.statutes.all(): law_texts.append('%s' % (l.short_title, )) misc_graf = """ Please advise me in advance of the estimated charges associated with fulfilling \ this request.</br></br>In the interest of expediency, and to minimize the research\ and/or duplication burden on your staff, please send records electronically if possible.\ If this is not possible, please notify me by phone at %s before sending to the address listed below. """ % (up.phone) misc_graf += '<br/></br>Sincerly,<br/><br/>%s<br/>%s<br/>%s<br/>%s' % ( user.first_name + ' ' + user.last_name, up.mailing_address, up.mailing_city + ', ' + up.mailing_state + ' ' + up.mailing_zip, up.phone) if not is_power: fields_to_use = { 'author': user, 'title': 'NCAA Report - %s' % agency_name, 'free_edit_body': ncaa_text_to_use % (' and '.join(law_texts), misc_graf), 'private': True, 'text': ncaa_text_to_use } therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = contacts therequest.government = govt therequest.agency = agency therequest.tags.add(ncaa_tag_name) therequest.save() assign_perm(Request.get_permission_name('view'), ncaa_group, therequest) #assign_perm(Request.get_permission_name('edit'), thegroup, therequest) coaches = [ 'Football Coach', 'Offensive Coord.', 'Defensive Coord.', "Men's BB Coach", "Women's BB Coach" ] coaches_str = [] for coach in coaches: val = row[header.index(coach)].strip() if val != 'N/A' and val != '': coaches_str.append("%s (%s)" % (val, coach)) print val fields_to_use = { 'author': user, 'title': 'Coach Contracts - %s' % agency_name, 'free_edit_body': coach_text_to_use % (' and '.join(law_texts), ', '.join(coaches_str), misc_graf), 'private': True, 'text': coach_text_to_use } therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = contacts therequest.government = govt therequest.agency = agency therequest.tags.add(coach_tag_name) therequest.save() assign_perm(Request.get_permission_name('view'), coach_group, therequest)
def test_add_request_to_group(self): ''' Anyone in a group can edit the request ''' self.create_group() self.create_request() self.assertEqual(self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) #show that the API won't return the request for a user not in teh group resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other(self.usertwo.username)) self.assertEqual(resp.content, '') resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) self.add_user_to_group(self.usertwo) groupjson = self.groupJSON.copy() groupjson['data'] = {'action': 'associate'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put(self.groupJSON['resource_uri'], format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual(self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('view'), self.request), True) #user two can now view a request, has to look through group requests function data = {'groups__id': self.groupJSON['id']} resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data=data, authentication=self.get_credentials_other(self.usertwo.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) #user can view a request, not edit resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() requestjson['title'] = 'TEST UPDATING THE TITLE' #no content on puts for request #user two should not be able to change a request (they only have view for this group) self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials_other(self.usertwo.username)) self.assertEqual(self.request.title, 'test bangarang') self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials()) #for some reason self.request is not reflecting the change (stale?) self.assertEqual(Request.objects.get(id=self.request.id).title, 'TEST UPDATING THE TITLE') #ensure that we can list objects in a group self.create_request() resp = self.api_client.get('/api/v1/request/', format='json', data=data, authentication=self.get_credentials_other(self.usertwo.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 1) #make sure we only get requests for the group for this user (he should have 2 or more requests at this point) resp = self.api_client.get('/api/v1/request/', format='json', data=data, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 1) resp = self.api_client.get('/api/v1/request/', format='json', data={}, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 2) #ensure users who aren't part of the group can't access those requests resp = self.api_client.get('/api/v1/request/', format='json', data=data, authentication=self.get_credentials_other(self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 0)
def obj_create(self, bundle, **kwargs): try: data = bundle.data user = bundle.request.user mb = MailBox.objects.get(usr=user) parent = None if 'following' in bundle.data: parent = MailMessage.objects.get(id=bundle.data['following']) del bundle.data['following'] bcc = [] cc = [] to = [] attachments = [] request = None if 'request' in data: request = Request.objects.get(id=data['request']) del data['request'] if request is None: return bundle if not user.has_perm(Request.get_permission_name('edit'), request): return bundle if 'bcc' in data: bcc = data['bcc'] del data['bcc'] if 'cc' in data: cc = data['cc'] del data['cc'] if 'to' in data: to = data['to'] del data['to'] if 'attachments' in data: attachments = [ Attachment.objects.get(id=id) for id in data['attachments'] ] del data['attachments'] theMessage = MailMessage(**data) theMessage.save() for address in to: item, created = EmailAddress.objects.get_or_create( content=address) item.save() theMessage.to.add(item) for address in bcc: item, created = EmailAddress.objects.get_or_create( content=address) item.save() theMessage.bcc.add(item) for address in cc: item, created = EmailAddress.objects.get_or_create( content=address) item.save() theMessage.cc.add(item) if request: theMessage.request = request for attachment in attachments: theMessage.attachments.add(attachment) if parent: parent.replies.add(theMessage) parent.save() theMessage.dated = timezone.now() theMessage.save() mb.messages.add(theMessage) mb.save() bundle.obj = theMessage except Exception as e: logger.exception(e) return bundle
def test_add_user_to_request(self): self.create_group() self.create_request() self.assertEqual(self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual(self.user.has_perm(Request.get_permission_name('view'), self.request), True) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('view'), self.request), False) usergroup = self.get_user_group(self.userthree) groupjson = self.get_group_json(usergroup).copy() groupjson['data'] = {'action': 'associate'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put("/api/v1/group/%s/" % usergroup.id, format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('view'), self.request), True) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual(self.user.has_perm(Request.get_permission_name('view'), self.request), True) #test that users can query for request resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other(self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) requestjson['title'] = 'TEST UPDATING THE TITLE' self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials_other(self.userthree.username)) self.assertEqual(Request.objects.get(id=self.request.id).title, 'test bangarang') #only get the requests I created resp = self.api_client.get('/api/v1/request/', format='json', data={'authored': True}, authentication=self.get_credentials_other(self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 0) resp = self.api_client.get('/api/v1/request/', format='json', data={'authored': ''}, authentication=self.get_credentials_other(self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 1) #ensure people can't view it resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other(self.usertwo.username)) self.assertEqual(resp.content, '') groupjson = self.get_group_json(usergroup).copy() groupjson['data'] = {'action': 'change-access'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put("/api/v1/group/%s/" % usergroup.id, format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('view'), self.request), True) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual(self.user.has_perm(Request.get_permission_name('view'), self.request), True) #test that users can query for request resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other(self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) requestjson['title'] = 'TEST UPDATING THE TITLE' self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials_other(self.userthree.username)) self.assertEqual(Request.objects.get(id=self.request.id).title, 'TEST UPDATING THE TITLE') groupjson = self.get_group_json(usergroup).copy() groupjson['data'] = {'action': 'disassociate'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put("/api/v1/group/%s/" % usergroup.id, format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.userthree.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual(self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual(self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual(self.user.has_perm(Request.get_permission_name('view'), self.request), True)
def obj_create(self, bundle, **kwargs): try: data = bundle.data user = bundle.request.user mb = MailBox.objects.get(usr=user) parent = None if 'following' in bundle.data: parent = MailMessage.objects.get(id=bundle.data['following']) del bundle.data['following'] bcc = [] cc = [] to = [] attachments = [] request = None if 'request' in data: request = Request.objects.get(id=data['request']) del data['request'] if request is None: return bundle if not user.has_perm(Request.get_permission_name('edit'), request): return bundle if 'bcc' in data: bcc = data['bcc'] del data['bcc'] if 'cc' in data: cc = data['cc'] del data['cc'] if 'to' in data: to = data['to'] del data['to'] if 'attachments' in data: attachments = [Attachment.objects.get(id=id) for id in data['attachments']] del data['attachments'] theMessage = MailMessage(**data) theMessage.save() for address in to: item, created = EmailAddress.objects.get_or_create(content=address) item.save() theMessage.to.add(item) for address in bcc: item, created = EmailAddress.objects.get_or_create(content=address) item.save() theMessage.bcc.add(item) for address in cc: item, created = EmailAddress.objects.get_or_create(content=address) item.save() theMessage.cc.add(item) if request: theMessage.request = request for attachment in attachments: theMessage.attachments.add(attachment) if parent: parent.replies.add(theMessage) parent.save() theMessage.dated = timezone.now() theMessage.save() mb.messages.add(theMessage) mb.save() bundle.obj = theMessage except Exception as e: logger.exception(e) return bundle
def get_queryset(self): from guardian.shortcuts import get_objects_for_user queryset = get_objects_for_user(self.request.user, Request.get_permissions_path('view')) #queryset = Request.objects.for_user(self.request.user).filter(private=True).exclude(author=self.request.user).order_by('-date_added') return super(GroupRequestListView, self).filter_queryset(queryset)
def obj_update(self, bundle, **kwargs): ''' NOTES about permissions on tags Tags should be scoped to the UserProfile.tags so multiple users can have tags with the same name If a tag is not in UserProfile.tags then it wasn't created by that user Any user with edit access to the request should be able to add/remove a tag We should check that a request doesn't already have a tag of the same name so a request can't have two different tags of the same name BUT only the person who created a tag should be able to rename it (user1 has a tag phase1, user2 has a tag phase2, user2's phase1 tag shouldn't be changed if user1 updates his or her tag name) ''' data = bundle.data user = bundle.request.user up = UserProfile.objects.get(user=user) bundle.obj = Group.objects.get(id=data['id']) if 'data' in data.keys(): if 'action' in data['data'].keys() and 'request_ids' in data.keys(): # For bulk tagging requests = Request.objects.filter(id__in=data['request_ids']) for req in requests: can_edit = user.has_perm(Request.get_permission_name('view'), req) if not can_edit: logger.info("%s tried to add/edit/rename tags from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse(HttpForbidden("It appears you do not have permissions to add or remove tags here.")) for req in requests: # OK, they have permission, now let's actually do it if data['data']['action'] == 'associate': obj = up.tags.get(id=data['id']) tags = req.tags.filter(name=data['name']) if tags: # Already tagged like that for tag in tags: if tag.id != obj.id: # Already tagged by another user raise ImmediateHttpResponse(HttpForbidden("A tag by this name is already associated with one of these requests by another user.")) else: # Tag it now req.tags.add(obj) elif data['data']['action'] == 'disassociate': req.tags.remove(data['name']) bundle.obj = Tag.objects.get(id=data['id']) if 'request_id' in data.keys(): req = Request.objects.get(id=data['request_id']) can_edit = user.has_perm(Request.get_permission_name('view'), req) if 'action' in data['data'].keys() and can_edit: if data['data']['action'] == 'associate': if req.tags.filter(name=data['name']).count() > 0: raise ImmediateHttpResponse(HttpForbidden("A tag by this name is already associated with this request.")) obj = up.tags.get(id=data['id']) req.tags.add(obj) elif data['data']['action'] == 'disassociate': req.tags.remove(data['name']) #refresh the obj for backbone to update bundle.obj = Tag.objects.get(id=data['id']) else: logger.info("%s tried to add/edit/rename tags from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse(HttpForbidden("It appears you do not have permissions to add or remove tags here.")) #action independent of request if data['data']['action'] == 'rename': usertags = up.tags.all() if usertags.filter(id=data['id']).count() == 0: #not my tag, presumably raise ImmediateHttpResponse(HttpForbidden("It appears you do not have permissions to edit this tag.")) elif usertags.filter(name=data['name']).count() < 2: tag = Tag.objects.get(id=data['id']) tag.name = data['name'] tag.save() bundle.obj = tag else: raise ImmediateHttpResponse(HttpForbidden("An error occurred while trying to modify this tag.")) return bundle
def handle(self, *args, **options): users = [ User.objects.get(username='******'), #User.objects.get(username='******'), #User.objects.get(username='******'), #User.objects.get(username='******') ] up = UserProfile.objects.get(user=users[0]) up.tags.add(ncaa_tag_name) up.tags.add(coach_tag_name) for user in users: assign_perm(UserProfile.get_permission_name('edit'), user, ncaa_group) assign_perm(UserProfile.get_permission_name('view'), user, ncaa_group) assign_perm(UserProfile.get_permission_name('edit'), user, coach_group) assign_perm(UserProfile.get_permission_name('view'), user, coach_group) #Request.objects.all().delete() ncaa_text_to_use = """ Pursuant to the %s, I am requesting the following documents:<br/><br/>\ The equity/revenue-and-expenses report completed by the athletic department for the \ National Collegiate Athletic Association for the 2014 fiscal year. This report is a \ multi-page document that had to be submitted to the NCAA by Jan. 15, 2015. \ It contains 38 revenue and expense categories, followed by specific breakdowns of \ each of those categories, by sport and gender. I am requesting the full report, \ including the detail tables and the Statement of Revenues and Expenses that appear at the end of the report. <br/><br/>\ PLEASE NOTE: The NCAA report is different than the equity report that is sent to the\ U.S. Department of Education for Title IX compliance. <br/><br/>\ %s """ coach_text_to_use = """ Pursuant to %s, I am requesting the following documents:<br/><br/>\ The current contracts for %s. If a contract is under negotiation, \ please forward the current contract but let me know that a new contract may be forthcoming. \ If there is no contact for one or both, please forward the letter(s) of intent or other \ document(s) outlining each employee's conditions of employment \ -- including bonus structure -- and/or a current statement of salary. <br/><br/>\ %s """ fname = settings.SITE_ROOT + "/apps/requests/data/NCAA-pio.csv" #with codecs.open(fname, 'w', encoding="utf-8") as f: # resp = requests.get("https://docs.google.com/spreadsheets/d/1kccaiCCYIHOTEvpUWQiKs51v6K2TNRX7-NN6l1WtzyM/pub?output=csv") # f.write(resp.text) reader = list(UnicodeReader(open(fname, 'rb'))) #create contacts header = reader[0] for idx, row in enumerate(reader[1:]): user = users[0] up = UserProfile.objects.get(user=user) state = row[header.index('STATE')] agency_name = row[header.index("UNIVERSITY")] pio = row[header.index("PIO OFFICER")] email = row[header.index("PIO Email")] phone = row[header.index("PIO Phone")] sid_pio = row[header.index("SID ")] sid_email = row[header.index("SID Email")] sid_phone = row[header.index("SID Phone")] is_power = (row[header.index("Power Conference")] == 'TRUE') is_private = (row[header.index("Is Private")] == 'TRUE') if not is_private and state != '' and email != 'N/A' and pio != 'N/A' and agency_name != '': govt = get_or_create_us_govt(state, 'state') fname = pio.split(" ")[0] lname = pio.split(" ")[-1] middle = '' #alter table `contacts_contact` convert to character set utf8 collate utf8_general_ci; #alter table `agency_agency` convert to character set utf8 collate utf8_general_ci; #alter table `requests_request` convert to character set utf8 collate utf8_general_ci; try: agency, acreated = Agency.objects.get_or_create(name=agency_name, government=govt) except Exception as e: print e print "If more than one agency was returned, pick one!" import pdb;pdb.set_trace() try: contact, ccreated = agency.contacts.get_or_create(first_name=fname, middle_name=middle, last_name=lname) except Exception as e: print e print "If more than one contact was returned, pick one!" import pdb;pdb.set_trace() sid_contact = None if phone != 'N/A': contact.add_phone(phone) contact.add_email(email) #agency.contacts.add(contact) if sid_pio != 'N/A' and sid_email != 'N/A': fname = sid_pio.split(" ")[0] lname = sid_pio.split(" ")[-1] sid_contact, ccreated = Contact.objects.get_or_create(first_name=fname, middle_name='', last_name=lname) sid_contact.add_title("SID") sid_contact.add_email(sid_email) if sid_phone != 'N/A': sid_contact.add_phone(sid_phone) agency.contacts.add(sid_contact) contacts = [contact] if sid_contact is not None: contacts = [contact, sid_contact] agency.save() #logger.info('agency %s %s contact %s %s %s %s' % (agency_name, acreated, fname, middle, lname, ccreated)) law_texts = [] for l in govt.statutes.all(): law_texts.append('%s' % (l.short_title,)) misc_graf = """ Please advise me in advance of the estimated charges associated with fulfilling \ this request.</br></br>In the interest of expediency, and to minimize the research\ and/or duplication burden on your staff, please send records electronically if possible.\ If this is not possible, please notify me by phone at %s before sending to the address listed below. """ % (up.phone) misc_graf += '<br/></br>Sincerly,<br/><br/>%s<br/>%s<br/>%s<br/>%s' % (user.first_name + ' ' + user.last_name, up.mailing_address, up.mailing_city + ', ' + up.mailing_state + ' ' + up.mailing_zip, up.phone) if not is_power: fields_to_use = { 'author': user, 'title': 'NCAA Report - %s' % agency_name, 'free_edit_body': ncaa_text_to_use % (' and '.join(law_texts), misc_graf), 'private': True, 'text': ncaa_text_to_use } therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = contacts therequest.government = govt therequest.agency = agency therequest.tags.add(ncaa_tag_name) therequest.save() assign_perm(Request.get_permission_name('view'), ncaa_group, therequest) #assign_perm(Request.get_permission_name('edit'), thegroup, therequest) coaches = [ 'Football Coach', 'Offensive Coord.', 'Defensive Coord.', "Men's BB Coach", "Women's BB Coach" ] coaches_str = [] for coach in coaches: val = row[header.index(coach)].strip() if val != 'N/A' and val != '': coaches_str.append("%s (%s)" % (val, coach)) print val fields_to_use = { 'author': user, 'title': 'Coach Contracts - %s' % agency_name, 'free_edit_body': coach_text_to_use % (' and '.join(law_texts), ', '.join(coaches_str), misc_graf), 'private': True, 'text': coach_text_to_use } therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = contacts therequest.government = govt therequest.agency = agency therequest.tags.add(coach_tag_name) therequest.save() assign_perm(Request.get_permission_name('view'), coach_group, therequest)
def test_add_user_to_request(self): self.create_group() self.create_request() self.assertEqual( self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual( self.user.has_perm(Request.get_permission_name('view'), self.request), True) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('view'), self.request), False) usergroup = self.get_user_group(self.userthree) groupjson = self.get_group_json(usergroup).copy() groupjson['data'] = {'action': 'associate'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put( "/api/v1/group/%s/" % usergroup.id, format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('view'), self.request), True) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual( self.user.has_perm(Request.get_permission_name('view'), self.request), True) #test that users can query for request resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other( self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) requestjson['title'] = 'TEST UPDATING THE TITLE' self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials_other( self.userthree.username)) self.assertEqual( Request.objects.get(id=self.request.id).title, 'test bangarang') #only get the requests I created resp = self.api_client.get('/api/v1/request/', format='json', data={'authored': True}, authentication=self.get_credentials_other( self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 0) resp = self.api_client.get('/api/v1/request/', format='json', data={'authored': ''}, authentication=self.get_credentials_other( self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 1) #ensure people can't view it resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other( self.usertwo.username)) self.assertEqual(resp.content, '') groupjson = self.get_group_json(usergroup).copy() groupjson['data'] = {'action': 'change-access'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put( "/api/v1/group/%s/" % usergroup.id, format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('view'), self.request), True) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual( self.user.has_perm(Request.get_permission_name('view'), self.request), True) #test that users can query for request resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other( self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) requestjson['title'] = 'TEST UPDATING THE TITLE' self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials_other( self.userthree.username)) self.assertEqual( Request.objects.get(id=self.request.id).title, 'TEST UPDATING THE TITLE') groupjson = self.get_group_json(usergroup).copy() groupjson['data'] = {'action': 'disassociate'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put( "/api/v1/group/%s/" % usergroup.id, format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.userthree.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual( self.user.has_perm(Request.get_permission_name('view'), self.request), True)
def test_add_request_to_group(self): ''' Anyone in a group can edit the request ''' self.create_group() self.create_request() self.assertEqual( self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('view'), self.request), False) #show that the API won't return the request for a user not in teh group resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials_other( self.usertwo.username)) self.assertEqual(resp.content, '') resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) self.add_user_to_group(self.usertwo) groupjson = self.groupJSON.copy() groupjson['data'] = {'action': 'associate'} groupjson['request_id'] = self.request.id update_resp = self.api_client.put( self.groupJSON['resource_uri'], format='json', data=groupjson, authentication=self.get_credentials()) self.assertEqual( self.user.has_perm(Request.get_permission_name('edit'), self.request), True) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('edit'), self.request), False) self.assertEqual( self.usertwo.has_perm(Request.get_permission_name('view'), self.request), True) #user two can now view a request, has to look through group requests function data = {'groups__id': self.groupJSON['id']} resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data=data, authentication=self.get_credentials_other( self.usertwo.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(requestjson['id'], self.request.id) #user can view a request, not edit resp = self.api_client.get('/api/v1/request/%s/' % self.request.id, format='json', data={}, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() requestjson['title'] = 'TEST UPDATING THE TITLE' #no content on puts for request #user two should not be able to change a request (they only have view for this group) self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials_other( self.usertwo.username)) self.assertEqual(self.request.title, 'test bangarang') self.api_client.put('/api/v1/request/%s/' % self.request.id, format='json', data=requestjson, authentication=self.get_credentials()) #for some reason self.request is not reflecting the change (stale?) self.assertEqual( Request.objects.get(id=self.request.id).title, 'TEST UPDATING THE TITLE') #ensure that we can list objects in a group self.create_request() resp = self.api_client.get('/api/v1/request/', format='json', data=data, authentication=self.get_credentials_other( self.usertwo.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 1) #make sure we only get requests for the group for this user (he should have 2 or more requests at this point) resp = self.api_client.get('/api/v1/request/', format='json', data=data, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 1) resp = self.api_client.get('/api/v1/request/', format='json', data={}, authentication=self.get_credentials()) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 2) #ensure users who aren't part of the group can't access those requests resp = self.api_client.get('/api/v1/request/', format='json', data=data, authentication=self.get_credentials_other( self.userthree.username)) requestjson = json.loads(resp.content).copy() self.assertEqual(len(requestjson['objects']), 0)
def handle(self, *args, **options): letter_responses = {} if len(args) < 1: print "Please provide ID of Google Spreadsheet" return -1 idd = args[0] resp = requests.get( "https://docs.google.com/spreadsheets/d/%s/pub?output=csv" % idd) reader = list(csv.reader(resp.content.split('\n'), delimiter=',')) header = reader[0] for row in reader[1:-1]: #get user, contact and agency user = User.objects.get(username=row[header.index('username')]) user_profile = UserProfile.objects.get(user=user) govt = get_or_create_us_govt(row[header.index("state")], 'state') agency, acreated = Agency.objects.get_or_create( name=row[header.index("agency")], government=govt) contact, ccreated = agency.contacts.get_or_create( first_name=row[header.index("contact.first.name")], middle_name=row[header.index("contact.middle.name")], last_name=row[header.index("contact.last.name")]) if row[header.index("contact.email")] != "": contact.add_email(row[header.index("contact.email")]) if row[header.index("contact.phone")] != "": contact.add_phone(row[header.index("contact.phone")]) #set up group and tags group, created = Group.objects.get_or_create( name=row[header.index("group")]) assign_perm(UserProfile.get_permission_name('edit'), user, group) assign_perm(UserProfile.get_permission_name('view'), user, group) user.groups.add(group) user_profile.tags.add(row[header.index("tag")]) #assemble law text law_texts = [] for l in govt.statutes.all(): law_texts.append('%s' % (l.short_title, )) law_text = ' and '.join(law_texts) #get the letter template letter_url = row[header.index("letter.url")] letter_template = '' if letter_url in letter_responses.keys(): letter_template = letter_responses[letter_url] else: letter_resp = requests.get(letter_url) letter_template = letter_resp.content letter_responses[letter_url] = letter_template #render the template context = Context({ 'contact': contact, 'user_profile': user_profile, 'user': user, 'law_text': law_text }) template = Template(letter_template) letter = template.render(context) #create the request fields_to_use = { 'author': user, 'title': row[header.index("request.title")], 'free_edit_body': letter, 'private': True if row[header.index("request.private")] == "TRUE" else False, 'text': letter #silly distinction leftover from old days but fill it in } #delete all requests that look like the one i'm about to make so we don't have duplicates floating around Request.objects.filter( author=user, title=row[header.index("request.title")]).delete() #create the request therequest = Request(**fields_to_use) therequest.date_added = datetime.now() therequest.save() therequest.contacts = [contact] therequest.government = govt therequest.agency = agency therequest.tags.add(row[header.index("tag")]) therequest.save() #assing permissions to the request assign_perm(Request.get_permission_name('view'), group, therequest) assign_perm(Request.get_permission_name('edit'), group, therequest) if row[header.index("request.send")] == "TRUE": therequest.send() print "SENT request %s" % row[header.index("request.title")] else: print "STAGED request %s" % row[header.index("request.title")]
def obj_update(self, bundle, **kwargs): data = bundle.data user = bundle.request.user bundle.obj = Group.objects.get(id=data['id']) if 'data' in data.keys(): #if 'action' in data['data'].keys() and data['data']['action'] == 'chown': #we are associating, disassociating... assuming the USER is taking action here if 'request_id' in data.keys() and data['request_id']: req = Request.objects.get(id=data['request_id']) if 'action' in data['data'].keys( ) and req.author == bundle.request.user: if data['data']['action'] == 'associate': assign_perm(Request.get_permission_name('view'), bundle.obj, req) bundle.data['data']['result'] = 'associated' elif data['data']['action'] == 'disassociate': remove_perm(Request.get_permission_name('view'), bundle.obj, req) remove_perm(Request.get_permission_name('edit'), bundle.obj, req) bundle.data['data']['result'] = 'disassociated' elif data['data']['action'] == 'change-access': #right now we are toggling between view and edit checker = ObjectPermissionChecker(bundle.obj) if checker.has_perm( Request.get_permission_name('view'), req) and not checker.has_perm( Request.get_permission_name('edit'), req): assign_perm(Request.get_permission_name('edit'), bundle.obj, req) elif user.has_perm(Request.get_permission_name('edit'), req): remove_perm(Request.get_permission_name('edit'), bundle.obj, req) else: raise ImmediateHttpResponse( HttpForbidden( "We couldn't determine the appropriate permissions to assign. Sorry." )) else: logger.info( "%s tried to remove users from request %s owned by %s" % (bundle.request.user, req, req.author)) raise ImmediateHttpResponse( HttpBadRequest( "It appears you don't have permission to change that user or group's permission." )) else: can_edit = bundle.request.user.has_perm( UserProfile.get_permission_name('edit'), bundle.obj) if not can_edit: raise ImmediateHttpResponse( HttpForbidden( "It doesn't appear you can edit this group.")) if 'action' in data['data'].keys( ) and data['data']['action'] == 'rename': bundle.obj.name = data['name'] bundle.obj.save() if 'action' in data['data'].keys( ) and data['data']['action'] == 'chown' and 'user_id' in data[ 'data'].keys() and data['data']['user_id']: #change user permission on a group object other_user = User.objects.get(id=data['data']['user_id']) o_can_edit = other_user.has_perm( UserProfile.get_permission_name('edit'), bundle.obj) if o_can_edit: #toggled to view remove_perm(UserProfile.get_permission_name('edit'), other_user, bundle.obj) else: #toggled to edit assign_perm(UserProfile.get_permission_name('edit'), other_user, bundle.obj) else: ''' NOTE about group permissions The creator of the requst is the only one who can share a request with other users and groups Otherwise the request could be shared with any number of people ''' can_edit = bundle.request.user.has_perm( UserProfile.get_permission_name('edit'), bundle.obj) if not can_edit: raise ImmediateHttpResponse( HttpForbidden( "It doesn't appear you can edit this group.")) #we are adding or removing users to the group on the group page users = set( [User.objects.get(pk=user['id']) for user in data['users']]) existing_users = set([usr for usr in bundle.obj.user_set.all()]) to_remove = existing_users - users #need to remove and set permissions here for usr in to_remove: remove_perm(UserProfile.get_permission_name('edit'), usr, bundle.obj) remove_perm(UserProfile.get_permission_name('view'), usr, bundle.obj) for usr in users: #users can view but not edit by default assign_perm(UserProfile.get_permission_name('view'), usr, bundle.obj) bundle.obj.user_set = users bundle.obj.save() data.pop('data', None) data.pop('request_id', None) return bundle