def dispatch(self, request, *args, **kwargs): key = request.GET.get('management', '') if management_key(int(kwargs['pk'])) != key: return HttpResponseNotAllowed('invalid management key') return super(InitiativeEditView, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs): return HttpResponseNotAllowed(permitted_methods=["post"])
def remove_facebook_association(request): """ Saves the given facebook auth tokens for the current user """ if not request.method == 'POST': return HttpResponseNotAllowed(['POST']) if not request.user.is_authenticated(): return HttpResponseForbidden('Must be logged in!') userprofile = request.user.cosinnus_profile fb_user_id = userprofile.get_facebook_user_id() if fb_user_id: access_token = userprofile.settings['fb_accessToken'] if not access_token: logger.error( 'Could not delete facebook associatione even though it was requested because of missing fb_accessToken!', extra={ 'user-email': userprofile.user.email, 'user_fbID': fb_user_id }) messages.error( request, _('An error occured when trying to disconnect your facebook account! Please contact an administrator!' )) return redirect(reverse('cosinnus:profile-edit')) post_url = 'https://graph.facebook.com/v2.11/%(user_id)s/permissions' % ( { 'user_id': fb_user_id }) data = { 'access_token': access_token, } post_url = post_url + '?' + urllib.parse.urlencode(data) post_url = iriToUri(post_url) req = requests.delete(post_url, data=data, verify=False) if not req.status_code == 200: #logger.error('Facebook deleting association failed, request did not return status=200.', extra={'status':req.status_code, 'content': req._content}) #messages.error(request, _('An error occured when trying to disconnect your facebook account! Please contact an administrator!')) # if this fails, we probably don't have an access token to the app anymore anyways, so just delete the association on our end! userprofile.delete_facebook_association() messages.success( request, _('Your Facebook account was successfully disconnected from this account.' )) return redirect(reverse('cosinnus:profile-edit')) response = req.json() if response.get('success', False) == True: userprofile.delete_facebook_association() messages.success( request, _('Your Facebook account was successfully disconnected from this account.' )) else: logger.error( 'Facebook deleting association failed, response did not return success=True.', extra={'response': response}) messages.warning( request, _('An error occured when trying to disconnect your facebook account! Please contact an administrator!' )) return redirect(reverse('cosinnus:profile-edit'))
def add_measure(request, ticketid): # query for ticket with given id try: ticket = Ticket.objects.get(ticketid=str(ticketid)) # catch possible exceptions except Exception as e: if isinstance(e, Ticket.DoesNotExist): return render( request, 'ticket_error.djhtml', {'errormsg':'No measure found!'} ) elif isinstance(e, Ticket.MultipleObjectsReturned): return render( request, 'ticket_error.djhtml', {'errormsg':'Multiple measures found under unique ID!'} ) else: return render( request, 'ticket_error.djhtml', {'errormsg':'Unknown error in views.add_measure'} ) # if correct ticket was found else: # build list of all groups the user is part of groups = [] for group in request.user.groups.all(): groups.append(group) # if user has permissions to change tickets and no other user is responsible for the ticket if (ticket.sector in groups and request.user.has_perm('tickets.change_ticket') and ticket.responsible_person in [None, request.user]): # GET request display ticket_close template for user input if request.method == 'GET': return render( request, 'measure_add.djhtml', {'measureform': MeasureForm(initial={'ticketid':ticket.ticketid})} ) elif request.method == 'POST': if 'add' in request.POST: # add ticketid through mutable copy of request.POST here since only for displaying purpose in the form POST = request.POST.copy() POST['ticketid'] = ticket.ticketid measureform = MeasureForm(POST) if measureform.is_valid(): measure_cd = measureform.cleaned_data Measures.objects.create( ticket=ticket, creationdatetime=timezone.now(), shortdsc=measure_cd['shortdsc'], dsc=measure_cd['dsc'], result=measure_cd['result'], isSolution=measure_cd['isSolution'] ) return HttpResponseRedirect('/tickets/' + str(ticket.ticketid) + '/?status=added') else: return render( request, 'measure_add.djhtml', {'measureform': measureform, 'infomsg':'Eingaben fehlerhaft'} ) elif 'cancel' in request.POST: return HttpResponseRedirect('/tickets/' + str(ticket.ticketid) + '/') else: return HttpResponseNotAllowed() # if user mustn't edit measures or another user is specified as responsible_person else: # display error template with error description if not request.user.has_perm('tickets.change_ticket'): errormsg = 'Sie haben nicht die Berechtigung Tickets zu bearbeiten (Maßnahmen hinzuzufügen)!' elif ticket.responsible_person != None and \ ticket.responsible_person != request.user: errormsg = 'Für dieses Ticket ist ein anderer Benutzer verantwortlich!' else: errormsg = 'Unbekannter Fehler bei Ticketbearbeitung (in views.add_measure)' return render( request, 'ticket_error.djhtml', {'errormsg': errormsg} )
def close_ticket(request, ticketid): # renewal of session expiration # request.session.set_expiry(COOKIE_EXP_AGE) # query for ticket with given id try: ticket = Ticket.objects.get(ticketid=str(ticketid)) # catch possible exceptions except Exception as e: if isinstance(e, Ticket.DoesNotExist): return render( request, 'ticket_error.djhtml', {'errormsg':'No Ticket found!'} ) elif isinstance(e, Ticket.MultipleObjectsReturned): return render( request, 'ticket_error.djhtml', {'errormsg':'Multiple tickets found for unique ID!'} ) else: return render( request, 'ticket_error.djhtml', {'errormsg':'Unknown error in views.close_ticket!'} ) # if correct ticket was found else: # build list of all groups the user is part of groups = [] for group in request.user.groups.all(): groups.append(group) # if user has permissions to change tickets and no other user is responsible for the ticket if (ticket.sector in groups and request.user.has_perm('tickets.change_ticket') and ticket.responsible_person in [None, request.user]): # convert ticket to dictionary with it's data ticket_dict = model_to_dict(ticket) # set sector to String represantation in ticket_dict ticket_dict['sector'] = ticket.sector # if ticket is closed redirect to detail view; prevents navigation to edit template via entering url if ticket_dict['status'] == 'closed': return HttpResponseRedirect('/tickets/' + str(ticket_dict['ticketid'] + '/')) # build list of headers for display of measures linked to this ticket headers = [] for key in FieldConstants.COMPACT_MEASURE_FIELD_LABELS: headers.append(FieldConstants.COMPACT_MEASURE_FIELD_LABELS[key]) # GET request display ticket_close template for user input if request.method == 'GET': # convert ticket to dictionary, for display set status to closed ('Abgeschlossen') ticket_dict['status'] = 'Abgeschlossen' ticket_dict['sector'] = ticket.sector # build list of compact forms displayed as rows for measures linked to this ticket measures = [] ticket_measures = Measures.objects.filter(ticket=ticket) for measure in ticket_measures: measures.append(CompactMeasureForm(initial=model_to_dict(measure))) detailform = DetailForm(initial=ticket_dict) closeform = ClosingDataForm(initial=ticket_dict) image = ticket_dict['image'] return render( request, 'ticket_close.djhtml', {'detailform':detailform, 'editform':closeform, 'hasImage':image, 'editable':True, 'is_Form':True, 'headers':headers, 'measures': measures} ) # POST request check form data for validity and update database if form is correct elif request.method == 'POST': # if button for overview is clicked -> redirect if 'cancel' in request.POST: return HttpResponseRedirect('/tickets/overview/') # if button for editing is clicked -> redirect to editing form elif 'edit' in request.POST: return HttpResponseRedirect('/tickets/' + ticketid + '/edit/') # when button 'New Measure...' was clicked -> redirect elif 'addmeasure' in request.POST: return HttpResponseRedirect('/tickets/' + ticketid + '/add_measure/') # if button for closing the ticket is clicked -> check input, update db elif 'close' in request.POST: # init form object with POST data closeform = ClosingDataForm(request.POST) # if the data is valid, update ticket in database with entered data if closeform.is_valid(): Ticket.objects.filter(ticketid=str(ticketid)).update( comment=closeform.cleaned_data['comment'], keywords=closeform.cleaned_data['keywords'], closingdatetime=timezone.now(), workinghours=closeform.cleaned_data['workinghours'], priority='low', status='closed', responsible_person=request.user ) ticket = Ticket.objects.get(ticketid=str(ticketid)) ticket_dict = model_to_dict(ticket) ticket_dict['responsible_person'] = request.user.username sendTicketCloseMail(ticket_dict) return HttpResponseRedirect('/tickets/overview/?status=closed') # if data is invalid, display the current template with an additional error messages else: ticket_dict = model_to_dict(ticket) ticket_dict['sector'] = ticket.sector detailform = DetailForm(initial=ticket_dict) image = ticket_dict['image'] # build list of compact forms displayed as rows for measures linked to this ticket measures = [] ticket_measures = Measures.objects.filter(ticket=ticket) for measure in ticket_measures: measures.append(CompactMeasureForm(initial=model_to_dict(measure))) return render( request, 'ticket_close.djhtml', {'detailform':detailform, 'editform':closeform, 'hasImage':image, 'editable':True, 'is_Form':True, 'measures':measures, 'headers':headers} ) # deny any request method except GET and POST else: # send response for 405: Method not allowed return HttpResponseNotAllowed() # if user mustn't edit tickets or another user is specified as responsible_person else: # display error template with error description if not request.user.has_perm('tickets.change_ticket'): errormsg = 'Sie haben nicht die Berechtigung Tickets zu bearbeiten!' elif ticket.responsible_person != None and \ ticket.responsible_person != request.user: errormsg = 'Für dieses Ticket ist ein anderer Benutzer verantwortlich!' else: errormsg = 'Unbekannter Fehler bei Ticketbearbeitung (in tickets.views.edit_ticket_detail())' return render( request, 'ticket_error.djhtml', {'errormsg': errormsg} )
def random_order_router(request, *args, **kwargs): if request.method == 'POST': return random_order_post(request) return HttpResponseNotAllowed()
def show_ticket_detail(request, ticketid): # renewal of session expiration # request.session.set_expiry(COOKIE_EXP_AGE) if request.method == 'GET': # query for ticket with given id try: ticket = Ticket.objects.get(ticketid=str(ticketid)) # catch possible exceptions except Exception as e: if isinstance(e, Ticket.DoesNotExist): return render( request, 'ticket_error.djhtml', {'errormsg':'No Ticket found for this ID'} ) elif isinstance(e, Ticket.MultipleObjectsReturned): return render( request, 'ticket_error.djhtml', {'errormsg':'More than one ticket found for this ID'} ) else: return render( request, 'ticket_error.djhtml', {'errormsg':'An unknown error occured'} ) else: # convert ticket to dictionary with it's data ticket_dict = model_to_dict(ticket) # set sector to String represantation in ticket_dict ticket_dict['sector'] = ticket.sector # build list of all groups the user is part of groups = [] for group in request.user.groups.all(): groups.append(group) # if user is ticket creator or has permissions to change tickets if (ticket.sector in groups and (request.user.username == ticket_dict['creator'] or request.user.has_perm('tickets.change_ticket')) ): # store if the ticket is already closed if ticket_dict['status'] == 'closed': closed = True else: closed = False detailform = DetailForm(initial=ticket_dict) if closed: editform = ClosedDataForm(initial=ticket_dict) else: editform = EditableDataForm(initial=ticket_dict) image = ticket_dict['image'] # build list of headers for compact display of measures linked to this ticket headers = [] for key in FieldConstants.COMPACT_MEASURE_FIELD_LABELS: headers.append(FieldConstants.COMPACT_MEASURE_FIELD_LABELS[key]) # build list of compact forms displayed as rows for measures linked to this ticket measures = [] ticket_measures = Measures.objects.filter(ticket=ticket) for measure in ticket_measures: measures.append(CompactMeasureForm(initial=model_to_dict(measure))) #initialize infomsg and set it according to GET['status'] infomsg = '' if request.GET.get('status') : if request.GET['status'] == 'added': infomsg = 'Maßnahme hinzugefügt!' return render( request, 'ticket_detail.djhtml', {'infomsg':infomsg, 'detailform':detailform, 'editform':editform, 'hasImage':image, 'editable':False, 'is_Form':False, 'headers':headers, 'measures':measures, 'closed':closed} ) # if user doesn't have permission to view/change ticket data, display error page with according message else: return render( request, 'ticket_error.djhtml', {'errormsg':'Sie haben keinen Zugriff auf das Ticket!'} ) # deny any request method except GET else: # send response for 405: Method not allowed return HttpResponseNotAllowed()
def wrap(request, *args, **kwargs): if not request.is_ajax(): return HttpResponseNotAllowed("") return func(request, *args, **kwargs)
def get(self, request, *args, **kwargs): """Returns 404 error as this method is not implemented.""" return HttpResponseNotAllowed(['POST'])
def post(self, request, *args, **kwargs): return HttpResponseNotAllowed('')
def logout_account(request): if request.method == 'GET': logout(request) return redirect('login') else: return HttpResponseNotAllowed('not allowed')
def do_like(request, **kwargs): """ Expected POST arguments: - ct: django content-type string (expects e.g. 'cosinnus_note.Note') - id: Id of the object. (optional if slug is given) - slug: Slug of the object (optional if id is given) - like: (optional) 0/1, whether to like or unlike - follow: (optional) 0/1, whether to follow or unfollow User needs to be logged in. Target object needs to be visible (permissions) to the logged in user. If `follow`=1 param is given without `like`, a liked=False,followed=True object will be created. If the LikeObject results in being liked=False,followed=False, it will be deleted immediately. """ if not request.is_ajax() and not request.method=='POST': return HttpResponseNotAllowed('POST', content='This endpoint is for POST only.') if not request.user.is_authenticated(): return HttpResponseForbidden('Not authenticated.') ct = request.POST.get('ct', None) # expects 'cosinnus_note.Note' obj_id = request.POST.get('id', None) slug = request.POST.get('slug', None) like = request.POST.get('like', None) follow = request.POST.get('follow', None) if ct is None or (id is None and slug is None) or (like is None and follow is None): return HttpResponseBadRequest('Incomplete data submitted.') app_label, model = ct.split('.') model_cls = get_model(app_label, model) content_type = ContentType.objects.get_for_model(model_cls) obj = None if obj_id is None and slug: obj = get_object_or_None(model_cls, slug=slug) else: obj = get_object_or_None(model_cls, id=obj_id) if obj is None: return HttpResponseNotFound('Target object not found on server.') liked_obj = get_object_or_None(LikeObject, content_type=content_type, object_id=obj.id, user=request.user) # unlike and unfollow if (like == '0' or like is None) and (follow == '0' or follow is None): if liked_obj is None: # nothing to do here pass else: liked_obj.delete() liked_obj = None else: if liked_obj is None: # initialize an object but don't save it yet liked_obj = LikeObject(content_type=content_type, object_id=obj.id, user=request.user, liked=False) if not like is None: liked_obj.liked = like == '1' if not follow is None: liked_obj.followed = follow == '1' liked_obj.save() # update the liked object's index if hasattr(obj, 'update_index'): obj.update_index() return JsonResponse({'liked': liked_obj and liked_obj.liked or False, 'followed': liked_obj and liked_obj.followed or False})
def dispatch(self, request, *args, **kwargs): """ Call handler's method according to request HTTP verb. """ ################################## # Request Details # ################################## requested_at = datetime.datetime.now() method = request.method endpoint = request.path source_ip = request.META['REMOTE_ADDR'] user_agent = request.META['HTTP_USER_AGENT'] ################################## # HTTP Method # ################################## # Check if verb is allowed. try: self.allowed_methods.index(method.upper()) except ValueError: return HttpResponseNotAllowed(self.allowed_methods) # Variable containing allowed verbs does not exist, no verbs allowed then. except AttributeError: return HttpResponseNotAllowed([]) # If verb is available, respective method must exist. meth = getattr(self, method.lower(), None) if not meth: return HttpResponse( status=HTTPStatus.SERVER_ERROR_501_NOT_IMPLEMENTED) ################################## # Authentication # ################################## # # 1) Check for authentication requirements. # # Flags if the handler requires authentication (defaults to Yes, changed otherwise). authentication_required = True #### # a) Handler-wide authentication (i.e. ALL methods require auth) ------> try: # If authentication is required, then the handler has the following attribute # consisting of an array of the available authentication types. authentication_classes = self.authentication # <------ No handler-wide authentication required. except AttributeError: #### # b) Check for method-specific authentication requirements. ------> try: # If authentication is required, the respective method decorator adds the array of # available authentication types to the following method var. authentication_classes = meth.authentication # <------ No method-specific authentication required. except AttributeError: #### # c) If this place is reached, then NO auth is required. Period. ------> authentication_classes = None # <------ # # 2) Authentication is required! Check for any valid auth credentials, according to available auth types. # if authentication_classes: authentication = None # Check for valid credentials for each of the available authentication types. for ac in authentication_classes: try: authentication = ac().authenticate(request) # Break the loop as soon as the first authentication class successfully validates respective credentials. if authentication: break except NotImplementedError: pass # If this place is reached without any of the authentication classes having returned success, # then authentication has failed and since we are here because this resource requires authentication, # the request is forbidden. if not authentication: return HttpResponse( status=HTTPStatus.CLIENT_ERROR_401_UNAUTHORIZED) # # 3) No authentication is required. # else: authentication_required = False # Even though authentication is not required, check if request was made by an # authenticated user, for logging purposes. authentication = AnyAuthentication().authenticate(request) # Put the result of the authentication in the request object, as it may be used in executing the API call # (e.g. figuring out how to serialize objects, given the user permissions) request.auth = authentication ################################## # CSRF Validation # ################################## # Check for possible configuration. try: csrf_enabled = settings.YAPI['CSRFValidation'] # By default, CSRF validation is enabled. except (AttributeError, KeyError): csrf_enabled = True # When request is anonymous or authenticated via Django session, explicitly perform CSRF validation. if csrf_enabled == True and authentication_required == True and ( not request.auth or request.auth['class'] == 'SessionAuthentication'): reason = CsrfViewMiddleware().process_view(request, None, (), {}) # CSRF Failed. if reason: return HttpResponse( content=json.dumps({ 'message': 'CSRF verification failed. Request aborted.' }), status=HTTPStatus.CLIENT_ERROR_403_FORBIDDEN, mimetype='application/json') ################################## # Authorization # ################################## # # 1) Check for permission requirements. # #### # a) Handler-wide permissions (i.e. ALL methods same permissions) ------> try: # If specific permissions are required, then the handler has the following attribute # consisting of an array of the required permissions. permission_classes = self.permissions # <------ No handler-wide permissions required. except AttributeError: #### # b) Check for method-specific permission requirements. ------> try: # If permission is required, the respective method decorator adds the array of # required permission types to the following method var. permission_classes = meth.permission # <------ No method-specific permissions required. except AttributeError: #### # c) If this place is reached, then are NOT permission requirements. Period. ------> permission_classes = None # <------ # # 2) Validate permissions. # if permission_classes: # If there are permission restrictions, then the request must be authenticated. if not authentication: return HttpResponseForbidden() # For the request to be authorized, ***ALL** the permission classes must return True. else: for p in permission_classes: try: if not p().has_permission(request, authentication['user']): return HttpResponseForbidden() # The permission class doesn't have the necessary method implemented, we consider the permission check as failed, # thus, the user isn't authorized to access the resource. except NotImplementedError: return HttpResponseForbidden() # There aren't any permission restrictions. else: pass ################################## # Request Body # ################################## # Some requests require for a body. try: ['POST', 'PUT'].index(method.upper()) # If this place is reached, then the HTTP request should have a body. try: # Don't process body if request haz files, because it messes up stream and stuff and basically # everything blows up. # TODO: Got to figure this out better. if request.FILES: request.data = request.FILES # Business as usual... else: # For now, the only parser suported is JSON. data = json.loads(request.body) # If this place is reached, then body was successfully parsed. Add it to the request object. request.data = data # Error parsing request body to JSON. except ValueError: return HttpResponse( content=json.dumps({'message': 'Missing arguments'}), status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST, mimetype='application/json') except ValueError: pass except: logger.error('Unable to process request body!', exc_info=1) return Response( request=request, data={'message': 'Resource #1'}, serializer=None, status=HTTPStatus.SERVER_ERROR_500_INTERNAL_SERVER_ERROR) ################################## # Execute Call # ################################## # Invoke method, logging execution time start and end. exec_start = datetime.datetime.now() try: result = meth(request, *args, **kwargs) except: logger.error('Error executing API call', exc_info=1) result = HttpResponse( status=HTTPStatus.SERVER_ERROR_500_INTERNAL_SERVER_ERROR) exec_end = datetime.datetime.now() ################################## # Log # ################################## try: request_data = None response_data = None # If bad request, log request data (POST and PUT) and response body. if result.status_code >= 400 and result.status_code <= 599: if method == 'POST' or method == 'PUT': request_data = request.data response_data = result.content # Log. ApiCall.new(date=requested_at, method=method, endpoint=endpoint, source_ip=source_ip, execution_start=exec_start, execution_end=exec_end, status=result.status_code, user_agent=user_agent, authentication=authentication, request_get_params=dict(request.GET.iterlists()), request_data=request_data, response_data=response_data) # If error occurs, JUST log. If this place is reached, then the request was successfully # executed and result should be returned. except: logger.error('Unable to log API call!', exc_info=1) ################################## # Return # ################################## return result
def inner(request, *args, **kwargs): if request.method != "POST": return HttpResponseNotAllowed( "Only POST requests are allowed on this url.") return func(request, *args, **kwargs)
def dispatch(self, *args, **kwargs): if not self.request.is_ajax(): return HttpResponseNotAllowed("") return super(JSONResponseMixin, self).dispatch(*args, **kwargs)
def do_likefollow(request, **kwargs): """ Expected POST arguments: - ct: django content-type string (expects e.g. 'cosinnus_note.Note') - id: Id of the object. (optional if slug is given) - slug: Slug of the object (optional if id is given) - like: (optional) 0/1, whether to like or unlike - follow: (optional) 0/1, whether to follow or unfollow User needs to be logged in. Target object needs to be visible (permissions) to the logged in user. If `follow`=1 param is given without `like`, a liked=False,followed=True object will be created. If the LikeObject results in being liked=False,followed=False, it will be deleted immediately. Special for likefollow combined: If the LikeObject results in being liked=False, no matter the follow state, it will be deleted immediately """ if not request.is_ajax() and not request.method == 'POST': return HttpResponseNotAllowed( 'POST', content='This endpoint is for POST only.') if not request.user.is_authenticated(): return HttpResponseForbidden('Not authenticated.') PARAM_VALUE_MAP = { '1': True, '0': False, 1: True, 0: False, } ct = request.POST.get('ct', None) # expects 'cosinnus_note.Note' obj_id = request.POST.get('id', None) slug = request.POST.get('slug', None) like = PARAM_VALUE_MAP.get(request.POST.get('like', None), UNSPECIFIED) follow = PARAM_VALUE_MAP.get(request.POST.get('follow', None), UNSPECIFIED) if ct is None or (id is None and slug is None) or (like is UNSPECIFIED and follow is UNSPECIFIED): return HttpResponseBadRequest('Incomplete data submitted.') app_label, model = ct.split('.') model_cls = get_model(app_label, model) obj = None if obj_id is None and slug: obj = get_object_or_None(model_cls, slug=slug, portal=CosinnusPortal.get_current()) else: obj = get_object_or_None(model_cls, id=obj_id) if obj is None: return HttpResponseNotFound('Target object not found on server.') if not check_object_likefollow_access(obj, request.user): return HttpResponseForbidden( 'Your access to this object is forbidden.') was_liked, was_followed = apply_likefollow_object(obj, request.user, like=like, follow=follow) return JsonResponse({'liked': was_liked, 'followed': was_followed})
def method_not_allowed(): response_obj = {} response_obj['status'] = '403' response_obj['reason'] = 'Method not allowed' return HttpResponseNotAllowed(content_type="application/json", content=json.dumps(response_obj))
def file_upload_inline(request, group): """ Inline file upload to be called from jQuery FileUpload. @param request.on_success: Determines what kind of data will be sent back, and in cosinnus.JS, determines what will be done with the data. Options: - 'add_to_select2' (default): Will render a select2 pill and in JS, append it to the attach-file select2 field. - 'refresh_page' will add a message to the request and in JS refresh the browser page - 'render_object' will render the single file template(s) and in JS append them to the file list """ if not request.is_ajax() or not request.method=='POST': return HttpResponseNotAllowed(['POST']) on_success = request.POST.get('on_success', 'add_to_select2') direct_upload = request.POST.get('direct_upload', False) make_private = request.POST.get('private_upload', False) # resolve group either from the slug, or like the permission group mixin does ist # (group type needs to also be used for that= group = get_group_for_request(group, request) if not group: logger.error('No group found when trying to upload a file!', extra={'group_slug': group, 'request': request, 'path': request.path}) return JSONResponse({'status': 'error', 'message': _('Internal Error: Group not Found')}) # do permission checking using has_write_access(request.user, group) if not check_group_create_objects_access(group, request.user): logger.error('Permission error while uploading an attached file directly!', extra={'user': request.user, 'request': request, 'path': request.path, 'group_slug': group}) return JSONResponse({'status': 'error', 'message': _('Permission for upload denied')}) # add any other required kwargs (group) and stuff correctly so the form can be saved post = request.POST post._mutable = True post.update({ 'group_id': group.id }) base_upload_folder = None upload_to_attachment_folder = False if 'target_folder' in post: base_upload_folder = get_object_or_404(FileEntry, id=int(post.get('target_folder'))) if not base_upload_folder: # check if the group has a folder with slug 'uploads' and if not, create one base_upload_folder = get_or_create_attachment_folder(group) upload_to_attachment_folder = True file_info_array = json.loads(post.get('file_info', '[]')) result_list = [] for file_index, dict_file in enumerate(request.FILES.getlist('file')): upload_folder = None # unless we are uploading as attachment, see if we have any further folder info for this file if not upload_to_attachment_folder and len(file_info_array) > file_index: # get relative path for the ith file, it should be the same as in the FILES list relative_path = file_info_array[file_index]['relative_path'] name = file_info_array[file_index]['name'] if relative_path: # sanity check, file name in file info must match FILES file name if not name == dict_file._name: logger.warn('File upload sanity check failed: File order of file with relative path info and FILES list did not match! (Upload may have sorted the user\'s file in the wrong folder)', extra={ 'file_info': file_info_array, 'FILES_list': request.FILES.getlist('file')}) upload_folder = _create_folders_for_path_string(base_upload_folder, relative_path) # switch mode to refresh page if we had at least one folder upload on_success = 'refresh_page' if not upload_folder: upload_folder = base_upload_folder single_file_dict = MultiValueDict({'file': [dict_file]}) post.update({ 'title': clean_single_line_text(dict_file._name), }) form = FileForm(post, single_file_dict, group=group, initial={}) if form.is_valid(): # form.instance is the FileEntry, not the media tag form.instance.group = group form.instance.creator = request.user form.instance.path = upload_folder.path form.instance._filesize = form.instance.file.file.size if not direct_upload: form.instance.no_notification = True # disable notifications on non-direct (attached, etc) uploads saved_file = form.save() # flag for uploading the file visible only to oneself, as used in message attachments if make_private: saved_file.media_tag.visibility = BaseTagObject.VISIBILITY_USER saved_file.media_tag.save() # render either for the file list or for the attached objects if on_success == 'render_object': context = { 'file': saved_file, 'do_highlight': True } result_list.append(render_to_string('cosinnus_file/single_file_detailed.html', context, request)) else: # pipe the file into the select2 JSON representation to be displayed as select2 pill pill_id, pill_html = build_attachment_field_result('cosinnus_file.FileEntry', saved_file) result_list.append({'text': pill_html, 'id': pill_id}) else: logger.warn('Form error while uploading an attached file directly!', extra={'form.errors': form.errors, 'user': request.user, 'request': request, 'path': request.path, 'group_slug': group}) message = _('The uploaded file was invalid.') if form.forms['obj'].errors.get('file', None): message = form.forms['obj'].errors.get('file', None) return JSONResponse({'status': 'error', 'message': message}) if result_list: if on_success == 'refresh_page': messages.success(request, ungettext('%(count)d File was added successfully.', '%(count)d Files were added successfully.', len(result_list)) % {'count': len(result_list)}) return JSONResponse({'status': 'ok', 'on_success': on_success, 'data': result_list}) else: return JSONResponse({'status': 'error', 'message': _('The file you uploaded was too large or the file type was not permitted to be uploaded!')})
def __wrapper(request, *args, **kwargs): if not isinstance(request, HttpRequest): return HttpResponseBadRequest() if request.method.upper() != method.upper(): return HttpResponseNotAllowed([method]) return func(request, *args, **kwargs)
def get(self, request, *args, **kwargs): return HttpResponseNotAllowed(['POST',])
def edit_ticket_detail(request, ticketid): # renewal of session expiration # request.session.set_expiry(COOKIE_EXP_AGE) # query for ticket with given id, catch possible exceptions try: ticket = Ticket.objects.get(ticketid=str(ticketid)) # catch possible exceptions except Exception as e: if isinstance(e, Ticket.DoesNotExist): return render( request, 'ticket_error.djhtml', {'errormsg':'No Ticket found for this ID'} ) elif isinstance(e, Ticket.MultipleObjectsReturned): return render( request, 'ticket_error.djhtml', {'errormsg':'More than one ticket found for this ID'} ) else: return render( request, 'ticket_error.djhtml', {'errormsg':'An unknown error occured'} ) else: # build list of all groups the user is part of groups = [] for group in request.user.groups.all(): groups.append(group) # if user has permissions to change tickets and no other user is responsible for the ticket if (ticket.sector in groups and request.user.has_perm('tickets.change_ticket') and ticket.responsible_person in [None, request.user]): # convert ticket to dictionary with it's data ticket_dict = model_to_dict(ticket) # set sector to String represantation in ticket_dict ticket_dict['sector'] = ticket.sector # if ticket is closed redirect to detail view; prevents navigation to edit template via entering url if ticket_dict['status'] == 'closed': return HttpResponseRedirect('/tickets/' + str(ticket_dict['ticketid'] + '/')) # build list of headers for compact display of measures linked to this ticket headers = [] for key in FieldConstants.COMPACT_MEASURE_FIELD_LABELS: headers.append(FieldConstants.COMPACT_MEASURE_FIELD_LABELS[key]) # GET request, display of input fields (with current data) if request.method == 'GET': detailform = DetailForm(initial=ticket_dict) editform = EditableDataForm(initial=ticket_dict) # build list of compact forms displayed as rows for measures linked to this ticket measures = [] ticket_measures = Measures.objects.filter(ticket=ticket) for measure in ticket_measures: measures.append(CompactMeasureForm(initial=model_to_dict(measure))) image = ticket_dict['image'] return render( request, 'ticket_edit.djhtml', {'detailform':detailform, 'editform':editform, 'hasImage':image, 'editable':True, 'is_Form':True, 'headers':headers, 'measures':measures} ) # POST request, form was submitted, data will be validated and database updated (if input correct) elif request.method == 'POST': infomsg = '' # when editing is canceled (button 'Übersicht' clicked) -> redirect if 'cancel' in request.POST: return HttpResponseRedirect('/tickets/overview/') # when button 'To Details' is clicked -> redirect elif 'back' in request.POST: return HttpResponseRedirect('/tickets/' + ticketid + '/') # when button 'New Measure...' was clicked -> redirect elif 'addmeasure' in request.POST: return HttpResponseRedirect('/tickets/' + ticketid + '/add_measure/') # redirect to closing for when button 'Abschließen' is clicked elif 'close' in request.POST: return HttpResponseRedirect('/tickets/' + ticketid + '/close/') # change responsible person to currently logged in user elif 'takeover' in request.POST: if ticket.responsible_person == None: Ticket.objects.filter(ticketid=str(ticketid)).update(responsible_person=request.user) infomsg = 'Ticket übernommen' elif ticket.responsible_person != request.user: infomsg = 'Ticketübernahme nicht möglich' # 'refresh' ticket-object after updating in db ticket = Ticket.objects.get(ticketid=str(ticketid)) # convert ticket to dictionary with it's data ticket_dict = model_to_dict(ticket) ticket_dict['sector'] = ticket.sector detailform = DetailForm(initial=ticket_dict) editform = EditableDataForm(initial=ticket_dict) image = ticket_dict['image'] # build list of compact forms displayed as rows for measures linked to this ticket measures = [] ticket_measures = Measures.objects.filter(ticket=ticket) for measure in ticket_measures: measures.append(CompactMeasureForm(initial=model_to_dict(measure))) return render( request, 'ticket_edit.djhtml', {'infomsg':infomsg, 'editform':editform, 'detailform':detailform, 'hasImage':image, 'editable':True, 'is_Form':True, 'headers': headers, 'measures': measures} ) # check input data and update database when button 'Speichern'/'Save' is clicked elif 'confirm' in request.POST: # init form with POST data editform = EditableDataForm(request.POST) ticket_dict = model_to_dict(ticket) ticket_dict['sector'] = ticket.sector detailform = DetailForm(initial=ticket_dict) ticket_measures = Measures.objects.filter(ticket=ticket) measures = [] for measure in ticket_measures: measures.append(CompactMeasureForm(initial=model_to_dict(measure))) # check user input for validity if editform.is_valid(): # get cleaned data and update ticket in database cd = editform.cleaned_data Ticket.objects.filter(ticketid=str(ticketid)).update( status=cd['status'], comment=cd['comment'], keywords=cd['keywords'], priority=cd['priority'] ) infomsg = 'Änderungen gespeichert!' else: infomsg = 'Fehlerhafte Eingabe(n)' image = ticket_dict['image'] # build list of compact forms displayed as rows for measures linked to this ticket measures = [] ticket_measures = Measures.objects.filter(ticket=ticket) for measure in ticket_measures: measures.append(CompactMeasureForm(initial=model_to_dict(measure))) return render( request, 'ticket_edit.djhtml', {'infomsg':infomsg, 'detailform':detailform, 'editform':editform, 'hasImage':image, 'editable':True, 'is_Form':True, 'headers':headers, 'measures':measures} ) #deny any request method except GET and POST else: # send response for 405: Method not allowed return HttpResponseNotAllowed() # if user mustn't edit tickets or another user is specified as responsible_person else: # display error template with error description if not request.user.has_perm('tickets.change_ticket'): errormsg = 'Sie haben nicht die Berechtigung Tickets zu bearbeiten!' elif ticket.responsible_person != None and \ ticket.responsible_person != request.user: errormsg = 'Für dieses Ticket ist ein anderer Benutzer verantwortlich!' else: errormsg = 'Unbekannter Fehler bei Ticketbearbeitung (in tickets.views.edit_ticket_detail())' return render( request, 'ticket_error.djhtml', {'errormsg': errormsg} )
def update(self, request, *args, **kwargs): return HttpResponseNotAllowed()
def edit_measure(request, measureid): # query for measure with given id try: measure = Measures.objects.get(measureid=str(measureid)) # catch possible exceptions except Exception as e: if isinstance(e, Measures.DoesNotExist): return render( request, 'ticket_error.djhtml', {'errormsg':'No measure found!'} ) elif isinstance(e, Measures.MultipleObjectsReturned): return render( request, 'ticket_error.djhtml', {'errormsg':'Multiple measures found under unique ID!'} ) else: return render( request, 'ticket_error.djhtml', {'errormsg':'Unknown error in views.edit_measure!'} ) # if correct measure was found else: # get the ticket to which this measure belongs ticket = Ticket.objects.get(ticketid=measure.ticket.ticketid) # build list of all groups the user is part of groups = [] for group in request.user.groups.all(): groups.append(group) # if user has permissions to change tickets and no other user is responsible for the ticket if (ticket.sector in groups and ticket.responsible_person in [None, request.user]): # set fields as editable if user has the corresponding permissions if request.user.has_perm('tickets.change_measures'): editable = True else: editable = False # display the measure in a MeasureForm with the according template if request.method == 'GET': measure_dict = model_to_dict(measure) measure_dict['ticketid'] = ticket.ticketid measureform = MeasureForm(initial=measure_dict) return render( request, 'measure_edit.djhtml', {'measureform':measureform, 'editable':editable} ) # if the form was submitted via http-POST-Request elif request.method == 'POST': # if cancelled, redirect to ticket details, if 'cancel' in request.POST: return HttpResponseRedirect('/tickets/' + str(ticket.ticketid) + '/') # if confirmed, check the data for validity and save the changes or display the form with error messages for the input elif 'confirm' in request.POST: # add ticketid via a mutable copy of the post data (read only in form) POST = request.POST.copy() POST['ticketid'] = measure.ticket.ticketid measureform = MeasureForm(POST) # check input validity if measureform.is_valid(): # get cleaned data and update changes to the corresponding fields measureform_cd = measureform.cleaned_data Measures.objects.filter(measureid=str(measure.measureid)).update( shortdsc=measureform_cd['shortdsc'], dsc=measureform_cd['dsc'], result=measureform_cd['result'], isSolution=measureform_cd['isSolution'] ) # 'refresh' measure object, create a new MeasureForm with the new data measure = Measures.objects.get(measureid=str(measure.measureid)) measure_dict = model_to_dict(measure) measure_dict['ticketid'] = measure.ticket.ticketid measureform = MeasureForm(initial=measure_dict) # set infomsg to 'saved changes!' infomsg = 'Änderungen gespeichert!' else: # set infomsg to 'faulty input!' infomsg = 'Fehlerhafte Eingaben!' # render and return the according template with measureform (with new data OR error messages for faulty input) return render( request, 'measure_edit.djhtml', {'measureform':measureform, 'infomsg':infomsg, 'editable':editable} ) #deny any request method except GET and POST else: return HttpResponseNotAllowed() # if user mustn't edit measures or another user is specified as responsible_person else: # display error template with an error description if not request.user.has_perm('tickets.change_measures'): errormsg = 'Sie haben nicht die Berechtigung Maßnahmen zu bearbeiten!' elif ticket.responsible_person != None and \ ticket.responsible_person != request.user: errormsg = 'Für das Ticket ist ein anderer Benutzer verantwortlich!' else: errormsg = 'Unbekannter Fehler bei der Bearbeitung (in tickets.views.edit_measure())' return render( request, 'ticket_error.djhtml', {'errormsg': errormsg} )
def userState(request): if request.method != "POST": return HttpResponseNotAllowed("POST") if not request.user.is_authenticated: return HttpResponseBadRequest( json.dumps( {"error": { "code": "NOT_AUTHENTICATED", "msg": "ログインが必要です。" }})) state = request.POST.get("changeState") if state == None: return HttpResponseBadRequest( json.dumps({ "error": { "code": "INVALID_FORM", "msg": "changeStateに値がありません" } })) if state == "follow": if request.POST.get("target") != None: try: existFollow = FollowModel.objects.get( fromUser=request.user, target=get_object_or_404( UserModel, username__iexact=request.POST["target"])) # pylint: disable=no-member existFollow.delete() isNewFollow = False except ObjectDoesNotExist: if BlockModel.objects.filter(target=request.user, fromUser=get_object_or_404( UserModel, username__iexact=request. POST["target"])).count() > 0: # pylint: disable=no-member return HttpResponseForbidden( json.dumps({ "error": { "code": "YOU_ARE_BLOCKED", "msg": "このユーザーにブロックされています。" } })) newFollow = FollowModel( fromUser=request.user, target=get_object_or_404( UserModel, username__iexact=request.POST["target"])) isNewFollow = True elif request.POST.get("targetFedi") != None: try: existFollow = FollowModel.objects.get( fromUser=request.user, targetFedi=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])) # pylint: disable=no-member existFollow.delete() isNewFollow = False except ObjectDoesNotExist: if BlockModel.objects.filter( target=request.user, fromFediUser=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])).count() > 0: # pylint: disable=no-member return HttpResponseForbidden( json.dumps({ "error": { "code": "YOU_ARE_BLOCKED", "msg": "このユーザーにブロックされています。" } })) newFollow = FollowModel(fromUser=request.user, targetFedi=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])) isNewFollow = True else: return HttpResponseBadRequest( json.dumps( {"error": { "code": "INVALID_FORM", "msg": "ターゲットが不明です" }})) if isNewFollow: newFollow.save() return HttpResponse(status=204) elif state == "mute": if request.POST.get("target") != None: try: existMute = MuteModel.objects.get( fromUser=request.user, target=UserModel.objects.get( username__iexact=request.POST["target"])) # pylint: disable=no-member existMute.delete() isNewMute = False except ObjectDoesNotExist: newMute = MuteModel( fromUser=request.user, target=get_object_or_404( UserModel, username__iexact=request.POST["target"])) isNewMute = True elif request.POST.get("targetFedi") != None: try: existMute = MuteModel.objects.get( fromUser=request.user, targetFedi=FediverseUser.objects.get( uuid=request.POST["targetFedi"])) # pylint: disable=no-member existMute.delete() isNewMute = False except ObjectDoesNotExist: newMute = MuteModel(fromUser=request.user, targetFedi=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])) isNewMute = True else: return HttpResponseBadRequest( json.dumps( {"error": { "code": "INVALID_FORM", "msg": "ターゲットが不明です" }})) if isNewMute: newMute.save() return HttpResponse(status=204) elif state == "block": if request.POST.get("target") != None: try: existBlock = BlockModel.objects.get( fromUser=request.user, target=get_object_or_404( UserModel, username__iexact=request.POST["target"])) # pylint: disable=no-member existBlock.delete() isNewBlock = False except ObjectDoesNotExist: if FollowModel.objects.filter(target=request.user, fromUser=get_object_or_404( UserModel, username__iexact=request. POST["target"])).count() > 0: # pylint: disable=no-member FollowModel.objects.get( target=request.user, fromUser=get_object_or_404( UserModel, username__iexact=request.POST["target"])).delete() # pylint: disable=no-member if FollowModel.objects.filter( fromUser=request.user, target=get_object_or_404(UserModel, username__iexact=request. POST["target"])).count() > 0: # pylint: disable=no-member FollowModel.objects.get( fromUser=request.user, target=get_object_or_404( UserModel, username__iexact=request.POST["target"])).delete() # pylint: disable=no-member newBlock = BlockModel( fromUser=request.user, target=get_object_or_404( UserModel, username__iexact=request.POST["target"])) isNewBlock = True elif request.POST.get("targetFedi") != None: try: existBlock = BlockModel.objects.get( fromUser=request.user, targetFedi=FediverseUser.objects.get( uuid=request.POST["targetFedi"])) # pylint: disable=no-member existBlock.delete() isNewBlock = False except ObjectDoesNotExist: if FollowModel.objects.filter( target=request.user, fromFediUser=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])).count() > 0: # pylint: disable=no-member FollowModel.objects.get( target=request.user, fromFediUser=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])).delete() # pylint: disable=no-member if FollowModel.objects.filter( fromUser=request.user, targetFedi=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])).count() > 0: # pylint: disable=no-member FollowModel.objects.get( fromUser=request.user, targetFedi=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])).delete() # pylint: disable=no-member newBlock = BlockModel(fromUser=request.user, targetFedi=get_object_or_404( FediverseUser, uuid=request.POST["targetFedi"])) isNewBlock = True else: return HttpResponseBadRequest( json.dumps( {"error": { "code": "INVALID_FORM", "msg": "ターゲットが不明です" }})) if isNewBlock: newBlock.save() return HttpResponse(status=204) return HttpResponse(json.dumps( {"error": { "code": "NOT_IMPLEMENTED", "msg": "実装中" }}), content_type="application/json", status=501)
def search_tickets(request): # renewal of session expiration # request.session.set_expiry(COOKIE_EXP_AGE) if request.method == 'GET': # initialize searchform with GET data searchform = SearchForm(request.GET) # if entered data is valid, build a query and query the db for tickets if searchform.is_valid(): searchterms = searchform.cleaned_data query_dict = {} # check all fields/keys for data entered, adjust keys depending on # the field's properties (full text, choice, char...?) # save the adjusted key-value pairs in query_dict for key in searchterms: if searchterms[key] != '' and searchterms[key] is not None: ######################### # TODO: full text will only work with MySQL (or postgreSQL); # full text indices must be configured directly in db manager ######################### # append '__search' -> full text search for these fields if key == 'description' or key == 'comment': query_key = key + '__search' # append '__contains' -> in SQL 'LIKE '%...%'' for non-choice-fields elif key != 'sector' and key != 'category' and key != 'status': query_key = key + '__contains' # else: key is unchanged -> in SQL '='...'' else: query_key=key #for the sector field get the corresponding group-id to the chosen group-name from Djangos Group DB if key=='sector': searchterms[key] = Group.objects.get(name=searchterms[key]).id query_dict[query_key] = searchterms[key] # build query from entered data via _functools.reduce and '&' as Q object # one liner form of version with one Q object query = reduce(lambda q, key: q & Q(**{key: query_dict[key]}), query_dict, Q()) tickets = Ticket.objects.filter(query) # init label_dict from FieldConstants.TICKET_FIELD_LABELS labels_dict = FieldConstants.TICKET_FIELD_LABELS # generate list from query results results = [] for ticket in tickets: ticket_dict = model_to_dict(ticket) # replace the value for 'sector' with the corresponding groups name (instead of primary key in/from group table) ticket_dict['sector'] = ticket.sector.name for key, value in ticket_dict.items(): if value is None: ticket_dict[key] = '' #check if an image for the ticket exists and display 'Ja/Nein' ('Yes/No') accordingly if ticket_dict['image'] != '': ticket_dict['image'] = 'Ja' else: ticket_dict['image'] = 'Nein' results.append(ticket_dict) # return ticket search template with searchform and result list return render( request, 'ticket_search.djhtml', {'searchform':searchform, 'results':results, 'labels_dict':labels_dict} ) else: return render( request, 'ticket_error.djhtml', {'errormsg':'Searchform input invalid!'} ) # deny any request method except GET else: # send response for 405: Method not allowed return HttpResponseNotAllowed()
def get(self, request, *args, **kwargs): return HttpResponseNotAllowed("GET")
def save_auth_tokens(request): """ Saves the given facebook auth tokens for the current user """ if not request.is_ajax() or not request.method == 'POST': return HttpResponseNotAllowed(['POST']) if not request.user.is_authenticated(): return HttpResponseForbidden('Must be logged in!') if not 'authResponse' in request.POST: return HttpResponseBadRequest('authResponse data missing!') if not settings.COSINNUS_FACEBOOK_INTEGRATION_APP_ID: raise ImproperlyConfigured( 'Missing setting COSINNUS_FACEBOOK_INTEGRATION_APP_ID for facebook integration!' ) if not settings.COSINNUS_FACEBOOK_INTEGRATION_APP_SECRET: raise ImproperlyConfigured( 'Missing setting COSINNUS_FACEBOOK_INTEGRATION_APP_SECRET for facebook integration!' ) authResponse = json.loads(request.POST.get('authResponse')) user_id = authResponse['userID'] try: # The client only gets a short ~2hr access token. We will now exchange that for a long-lived ~60day token. location_url = "https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%(app-id)s&client_secret=%(app-secret)s&fb_exchange_token=%(short-lived-token)s" \ % { 'app-id': settings.COSINNUS_FACEBOOK_INTEGRATION_APP_ID, 'app-secret': settings.COSINNUS_FACEBOOK_INTEGRATION_APP_SECRET, 'short-lived-token':authResponse['accessToken'], } response = urllib.request.urlopen(location_url) except Exception as e: logger.error( 'Error when trying to retrieve long-lived-access-token from Facebook:', extra={ 'exception': force_text(e), 'url': location_url }) return HttpResponseServerError( 'Facebook request could not be completed (1).') if not response.code == 200: logger.error( 'Error when trying to retrieve long-lived-access-token from Facebook (non-200 response):', extra={'response': force_text(response.__dict__)}) return HttpResponseServerError( 'Facebook request could not be completed (2).') # this node finally returns JSON content_auth = json.loads(response.read()) # content should contain 'access_token' (string) and 'expires' (string, in seconds) seconds_expired = 60 * 60 * 24 * 60 # this used to be the old style API # seconds = int(content_auth['expires']) if not 'access_token' in content_auth: #or not 'expires' in content_auth or not _is_number(content_auth['expires']): logger.error( 'Error when trying to retrieve long-lived-access-token from Facebook (missing data):', extra={'content_auth': content_auth}) return HttpResponseServerError( 'Facebook request could not be completed (3).') access_token = content_auth['access_token'] # get username! fb_username = None try: location_url = "https://graph.facebook.com/%(user_id)s?access_token=%(access_token)s" \ % { 'user_id': user_id, 'access_token': access_token, } response_info = urllib.request.urlopen(location_url) except Exception as e: logger.warn('Error when trying to retrieve user info from Facebook:', extra={ 'exception': force_text(e), 'url': location_url }) fb_username = '******' if not fb_username and not response_info.code == 200: logger.warn( 'Error when trying to retrieveuser info from Facebook (non-200 response):', extra={'response_info': force_text(response_info.__dict__)}) fb_username = '******' if not fb_username: content_info = json.loads(response_info.read( )) # this graph returns a JSON string, not a query response if 'name' in content_info: fb_username = content_info.get('name') else: fb_username = None # save long lived token to userprofile profile = request.user.cosinnus_profile profile.settings['fb_userID'] = user_id profile.settings['fb_accessToken'] = access_token profile.settings['fb_username'] = fb_username # we save the time-point in UTC seconds after which this token must be renewed then = datetime.now() + timedelta(seconds=seconds_expired) profile.settings['fb_expiresAfterUTCSeconds'] = datetime_in_seconds(then) profile.save() return JsonResponse({ 'status': 'ok', 'username': fb_username, 'user_id': user_id, 'avatar': profile.get_facebook_avatar_url() })
def stripe_webhook(request): """Handle webhooks from stripe""" if request.method != "POST": return HttpResponseNotAllowed(['POST']) payload = request.body sig_header = request.META.get('HTTP_STRIPE_SIGNATURE') try: if settings.STRIPE_WEBHOOK_SECRET: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET, ) else: event = json.loads(request.body) event_id = event['id'] event_type = event['type'] if event_type.startswith(('charge', 'invoice')): event_object_id = event['data']['object'].get('id', '') else: event_object_id = '' except (TypeError, ValueError, SyntaxError) as exception: logging.error( 'Stripe Webhook: Error parsing JSON: %s', exception, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() except KeyError as exception: logging.error( 'Stripe Webhook: Unexpected structure: %s in %s', exception, event, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() except stripe.error.SignatureVerificationError as exception: logging.error( 'Stripe Webhook: Signature Verification Error: %s', sig_header, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() # If we've made it this far, then the webhook message was successfully sent! # Now it's up to us to act on it. success_msg = ( 'Received Stripe webhook\n' '\tfrom:\t%(address)s\n' '\tid:\t%(id)s\n' '\ttype:\t%(type)s\n' '\tdata:\t%(data)s\n' ) % { 'address': request.META['REMOTE_ADDR'], 'id': event_id, 'type': event_type, 'data': event } logger.info(success_msg) if event_type == 'charge.succeeded': send_charge_receipt.delay(event_object_id) elif event_type == 'invoice.payment_succeeded': send_invoice_receipt.delay(event_object_id) elif event_type == 'invoice.payment_failed': failed_payment.delay(event_object_id) return HttpResponse()
def get(self, request, *args, **kwargs): return HttpResponseNotAllowed(["post", "delete"])
def ask(request): if request.method == "POST": arguments = request.POST elif request.method == "GET": arguments = request.GET else: return HttpResponseNotAllowed(("GET", "POST")) query = arguments["query"] query_up = query.upper() try: model_query = Query.objects.get(query=query_up) g_result = json.loads(model_query.googleresult.result) a_result = json.loads(model_query.alchemyresult.result) tout = json.loads(model_query.finalresult.tout) partition = json.loads(model_query.finalresult.partition) cover = json.loads(model_query.finalresult.cover) except ObjectDoesNotExist: model_query = Query(query=query_up) model_query.save() g_result = get_result_google(query_up) model_g_result = GoogleResult(query=model_query, result=json.dumps(g_result)) model_g_result.save() a_result = get_result_alchemy(g_result) model_a_result = AlchemyResult(query=model_query, result=json.dumps(a_result)) model_a_result.save() partition = {} for key, value in a_result["quentin"].items(): if value["info"]["tab"] or value["info"]["partition"]: partition[key] = g_result[key] # for key, result in a_result["quentin"].items(): # pprint.pprint(result) # triplet = main(a_result) categories = ["cover", "partition", "tablature", "chords"] dico = graphRDF(a_result["mathieu"]) dico_milly = routineMatrice(dico, categories) pprint.pprint(dico_milly) cover_url_list = dico_milly[categories[0]] partition_url_list = dico_milly[categories[1]] tab_url_list = dico_milly[categories[2]] chords_url_list = dico_milly[categories[3]] cover = [] for url in cover_url_list: cover.append(g_result[url]) for url in partition_url_list: partition[url] = g_result[url] for url in tab_url_list: partition[url] = g_result[url] for url in chords_url_list: partition[url] = g_result[url] tout = order_result(g_result) f_result = FinalResult(query=model_query, tout=json.dumps(tout), cover=json.dumps(cover), partition=json.dumps(partition)) f_result.save() # print(triplet) # dicoMilly = graphRDF(triplet) # queryList = [query,query+" cover",query+" partition",query+" album"] # resultfinal = routineMatrice(dicoMilly, queryList, 0.5) # web = resultfinal[query] # cover = resultfinal[query+" cover"] # album = resultfinal[query + " album"] # partition = resultfinal[query + " partition"] except MultipleObjectsReturned: # remove ceux qui sont vide print("ici") pass return render_to_response("result.html", locals())