def datapoints(request): response = HttpResponse() response.status = 400 if request.method == GET: entries = DataPoint.objects.all() dicts = [] for entry in entries: dicts.append(entry.to_dict()) response.body = json.dumps(dicts) response.status = 200 elif request.method == POST: data = json.loads(getBody(request)) try: entry = DataPoint(**data) entry.full_clean() entry.save() response.body = entry.to_json() response.status = 201 except ValidationError: response.status = 400 except IntegrityError: response.status = 400 return response
def deferred(request): from google.appengine.ext.deferred.deferred import ( run, SingularTaskFailure, PermanentTaskFailure ) response = HttpResponse() if 'HTTP_X_APPENGINE_TASKEXECUTIONCOUNT' in request.META: logging.debug("[DEFERRED] Retry %s of deferred task", request.META['HTTP_X_APPENGINE_TASKEXECUTIONCOUNT']) if 'HTTP_X_APPENGINE_TASKNAME' not in request.META: logging.critical('Detected an attempted XSRF attack. The header "X-AppEngine-Taskname" was not set.') response.status = 403 return response in_prod = on_production() if in_prod and os.environ.get("REMOTE_ADDR") != "0.1.0.2": logging.critical('Detected an attempted XSRF attack. This request did not originate from Task Queue.') response.status = 403 return response try: run(request.body) except SingularTaskFailure: logging.debug("Failure executing task, task retry forced") response.status = 408 except PermanentTaskFailure: logging.exception("Permanent failure attempting to execute task") return response
def assignObservable(request, datapoint_id, observable_id): response = HttpResponse() response.status = 400 try: if request.method == PUT: datapoint = DataPoint.objects.get(pk=datapoint_id) datapoint.observable_id = observable_id datapoint.save() response.body = DataPoint.objects.get(pk=datapoint_id).to_json() response.status = 200 except ObjectDoesNotExist: response.status = 404 return response
def article_conversion_status(request, article_id): """ Return a 202 if article is converting, else redirect to article. """ try: article = get_object_or_404(Article, id=article_id) except: return HttpResponseTemporaryServerError( u'Could not find article #{0}'.format(article_id)) if article.content_type not in CONTENT_TYPES_FINAL: # The user is already waiting. # Process the item now for immediate markdown content. article.process() return HttpResponse( redirect_to_read(request.user, article) ) # read = get_object_or_404(Read, user=request.user, item=article) # return HttpResponse(u'http://' + settings.SITE_DOMAIN + # reverse('read_one', args=(read.item.id, ))) res = HttpResponse(u'IN PROGRESS') res.status = 202 return res
def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = User.get_by_auth_id('twitter:%s' % username) if user == None: raise Http404("User not found") if user.key != request.user.key: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 form = EditUserForm(request.POST or None, user=request.user) if form.is_valid(): for key in form.cleaned_data: if key == 'email': continue setattr(user, key, form.cleaned_data.get(key)) slugify(user.location) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username':request.user.username} ) ) return render_to_response(template_name, {'form':form}, context_instance=RequestContext(request))
def delete_email(request, username, email): # the ID we are to delete user = User.objects.get(username=username) auth = UserSocialAuth.objects.get(provider="email", uid=email) e_user = auth.user if user is None or e_user is None: raise Http404("User not found") if user != request.user or user != e_user: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 if request.method == "POST": # delete the email from the user auth.delete() return HttpResponseRedirect( reverse('member-profile', kwargs={'username': request.user.username}) ) return render_to_response( 'people/delete_email.html', {'email': email}, context_instance=RequestContext(request) )
def unauth_access(reason="None"): response = HttpResponse("Unauthorized access: " + reason, status=401) response['Access-Control-Allow-Origin'] = '*' response[ 'WWW-Authenticate'] = 'Basic realm="Access to Aina website", charset="UTF-8"' response.status = 401 return response
def newTestObject(request): name = request.POST['name'] description = request.POST['description'] testObject = createTestObject(title = name, description = description) resp = HttpResponse() resp.status = 200 return resp
def edit_address(request, username, template_name='people/edit_address.html'): from forms import EditAddressForm user = request.user if user.key != request.user.key: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 form = EditAddressForm(request.POST or None, user=user) if form.is_valid(): for key, value in form.cleaned_data.iteritems(): setattr(user, key, value) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username': user.username}) ) ctx = { 'form': form, 'profile': user, 'active': 'edit', } return render(request, template_name, ctx, context_instance=RequestContext(request))
def delete_email(request, username, email): # the ID we are to delete auth_id = 'email:%s' % email user = User.get_by_auth_id('own:%s' % username) e_user = User.get_by_auth_id(auth_id) if user is None or e_user is None: raise Http404("User not found") if user != request.user or user != e_user: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 if request.method == "POST": # delete the email from the user user.auth_ids.remove(auth_id) user.unique_model.delete_multi(['User.auth_id:%s' % auth_id]) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username':request.user.username}) ) return render_to_response('people/delete_email.html', {'email': email}, context_instance=RequestContext(request))
def edit_address(request, username, template_name='people/edit_address.html'): from forms import EditAddressForm user = User.get_by_auth_id('own:%s' % username) if user == None: raise Http404("User not found") if user.key != request.user.key: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 form = EditAddressForm(request.POST or None, user=user) if form.is_valid(): for key, value in form.cleaned_data.iteritems(): setattr(user,key,value) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username':request.user.username} ) ) return render_to_response(template_name, {'form':form}, context_instance=RequestContext(request))
def tasks(request): # tasks supports GET and POST if request.method == "GET": # GET should return all of the tasks # first, create a list of tasks raw_tasks = [] for task in Task.objects.all(): raw_tasks.append(task_to_raw(task)) # now, create and return json (remember, front-end wants it in "contents") return_data = {"content": raw_tasks} return HttpResponse(json.dumps(return_data), mimetype="application/json") elif request.method == "POST": # Create a Task task = Task() # Load data raw = json.loads(request.raw_post_data) raw_to_task(raw, task) # attempt to save task.save() # return just the plain hash # returning Location header causes problems response = HttpResponse(json.dumps({"content": task_to_raw(task)})) response.status = 201 return response
def edit_profile(request, username, template_name="people/edit.html"): from forms import EditUserForm user = request.user if user.username != request.user.username: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 form = EditUserForm(request.POST or None, user=request.user) if form.is_valid(): for key, value in form.cleaned_data.iteritems(): if key in ["gittip"]: continue if key in ["email"]: # send verification email domain = get_current_site(request).domain if value is not None: send_verify_email(value, user.pk, domain) # Don't actually add email to user model. continue if key == "team": # slugify the team to allow easy lookups setattr(user, "team_slug", slugify(value)) setattr(user, key, value) user.save() return HttpResponseRedirect(reverse("member-profile", kwargs={"username": user.username})) ctx = {"form": form, "profile": user, "active": "edit"} return render(request, template_name, ctx, context_instance=RequestContext(request))
def delete_email(request, username, email): # the ID we are to delete auth_id = 'email:%s' % email user = User.get_by_auth_id('twitter:%s' % username) e_user = User.get_by_auth_id(auth_id) if user is None or e_user is None: raise Http404("User not found") if user != request.user or user != e_user: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 if request.method == "POST": # delete the email from the user user.auth_ids.remove(auth_id) user.unique_model.delete_multi(['User.auth_id:%s' % auth_id]) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username':request.user.username}) ) return render_to_response('people/delete_email.html', {'email': email}, context_instance=RequestContext(request))
def article_conversion_status(request, article_id): """ Return a 202 if article is converting, else redirect to article. """ try: article = get_object_or_404(Article, id=article_id) except: return HttpResponseTemporaryServerError( u'Could not find article #{0}'.format(article_id)) if article.content_type not in CONTENT_TYPES_FINAL: # The user is already waiting. # Process the item now for immediate markdown content. article.process() return HttpResponse(redirect_to_read(request.user, article)) # read = get_object_or_404(Read, user=request.user, item=article) # return HttpResponse(u'http://' + settings.SITE_DOMAIN + # reverse('read_one', args=(read.item.id, ))) res = HttpResponse(u'IN PROGRESS') res.status = 202 return res
def edit_address(request, username, template_name='people/edit_address.html'): from forms import EditAddressForm user = request.user if user.key != request.user.key: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 form = EditAddressForm(request.POST or None, user=user) if form.is_valid(): for key, value in form.cleaned_data.iteritems(): setattr(user, key, value) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username': user.username})) ctx = { 'form': form, 'profile': user, 'active': 'edit', } return render(request, template_name, ctx, context_instance=RequestContext(request))
def invalid_credentials(reason): """Return a 400 Bad Request if request contains invalid username and/or password.""" response = HttpResponse(reason, status=400) response['Access-Control-Allow-Origin'] = '*' response.status = 400 return response
def process_response(self, request, response): if "GSS-String" in request.META: response["WWW-Authenticate"] = request.META["GSS-String"] elif "Return-401" in request.META: response = HttpResponse("401 Unauthorized", content_type="text/plain", status=401) response["WWW-Authenticate"] = "Negotiate" response.status = 401 return response
def register(request): """This function will try and register a new account to the database. It will first check for correct request method. It will then check for invalid credentials, and if no error has occured, an attempt will be made to create the user and add it to an existing group using a transaction commit. In case of error, an appropriate response will be returned to the client. """ if request.method == 'OPTIONS': response = HttpResponse() response['Access-Control-Allow-Origin'] = '*' response[ 'Access-Control-Allow-Headers'] = 'accept, content-type, charset' response['Access-Control-Allow-Methods'] = 'POST' return response if request.method == 'POST': data = json.loads(request.body) uname = data['username'] pword = data['password'] group = data['groupname'] name = data['name'].split(' ') if len(name) > 1: first_name = name[0] last_name = name[1] else: first_name = name[0] last_name = '' response = check_for_invalid_credentials(uname, pword, group) if response is not None: return response """ Create user using a transaction commit and add it to a group. If error occurs inside the transaction, all changes to the database will be rolled back. """ try: with transaction.atomic(): user = User.objects.create_user(username=uname, password=pword, first_name=first_name, last_name=last_name) db_group = Group.objects.get(name=group) db_group.user_set.add(user) except DatabaseError: response = HttpResponse( "Server encountered database error while trying to create user.", status=500) response['Access-Control-Allow-Origin'] = '*' return response response = HttpResponse("User created!", status=200) response['Access-Control-Allow-Origin'] = '*' return response else: response = HttpResponse("Method not allowed.", status=405) response.status = 405 return response
def process_response(self, request, response): if 'GSS-String' in request.META: response['WWW-Authenticate'] = request.META['GSS-String'] elif 'Return-401' in request.META: response = HttpResponse("401 Unauthorized", content_type="text/plain", status=401) response['WWW-Authenticate'] = 'Negotiate' response.status = 401 return response
def create_response(vdict=None, valid_form=True): if not vdict: vdict = dict() response = HttpResponse( json.dumps(vdict), content_type='application/json' ) response.status = 200 if valid_form else 500 return response
def posts_handler_generic(request): if (request.method == 'POST'): # TODO: ADD validation user = check_authenticate(request) if (user == None): return HttpResponse(status=403) try: author = Author.objects.get(user_id=user.id) except: return HttpResponse(status=403) post = request.data.copy() post['author_id'] = author.id created = create_post(post) created.comments = [] serializer = PostSerializer(created) json_data = JSONRenderer().render(serializer.data) response = HttpResponse(json_data, content_type='application/json') response.status = 201 response['Location'] = request.path + str(created.id) return response elif (request.method == 'GET'): size = int(request.GET.get('size', 25)) paginator = PostPagination() paginator.page_size = size posts = Post.objects.filter(visibility='PUBLIC').order_by('-published') result_posts = paginator.paginate_queryset(posts, request) for post in result_posts: comments = Comment.objects.filter( post_id=post['id']).order_by('-published')[:5] author = Author.objects.get(id=post['author_id']) post['comments'] = comments post['author'] = author post['count'] = comments.count() post['size'] = size post['next'] = post.origin + '/posts/' + str(post.id) + '/comments' serializer = PostSerializer(result_posts, many=True) return paginator.get_paginated_response(serializer.data, size) elif (request.method == 'PUT'): # TODO: VALIDATION... again body = json.loads(request.body) new_post = create_post(body) data = model_to_dict(new_post) return create_json_response_with_location(data, new_post.id, request.path)
def rssh_file_md5(request, rfile): try: f = open(rfile, 'rb') local_md5 = hashlib.md5() local_md5.update(f.read()) local_md5 = local_md5.hexdigest() r = HttpResponse(local_md5) except Exception, e: r = HttpResponse(str(e)) r.status = 500
def datapoint(request, id): response = HttpResponse() response.status = 400 try: if request.method == GET: response.body = DataPoint.objects.get(pk=id).to_json() response.status = 200 elif request.method == PUT: data = json.loads(getBody(request)) DataPoint.objects.filter(pk=id).update(**data) response.body = DataPoint.objects.get(pk=id).to_json() response.status = 200 elif request.method == DELETE: DataPoint.objects.get(pk=id).delete() response.status = 200 except ObjectDoesNotExist: response.status = 404 return response
def importXslx(request): f = request.FILES['file'] generateLevelsFromExcelFile( f, leftTopLevelTypeCell = request.POST['ltlt'], rightBottomLevelTypeCell = request.POST['ltrb'], leftTopLevelCell = request.POST['llt'], rightBottomLevelCell = request.POST['lrb']) resp = HttpResponse() resp.status = 200 return resp
def HttpMetaRedirect(location='/'): response = HttpResponse() response.status = 200 response.content = """ <html><head> <meta http-equiv="refresh" content="0; url=%s"> </head> <body>Thank you for logging in. Please click <a href="%s">here</a> if you are not redirected.</body> </html> """ % (location, location) return response
def rssh_put_file(request, rfile, content): try: # translate content from hex str to real str content = decodeStrInHex(content) # write content to file f = open(rfile, 'ab+') f.write(content) f.close() r = HttpResponse() except Exception, e: r = HttpResponse(str(e)) r.status = 500
def log(request): test=request.POST.get('log','') response=HttpResponse() ts=time.time() ts=int(ts) with open('/users/stud/inf/erwinr/atm/magic/historia/'+str(ts)+'.txt','wb+') as f: f.write(test) logger.debug(request.POST) response.status=200 return response
def stream(request): song = Song.from_export(json.loads(request.GET['song']), client.connection) if song.id in _cache['streams']: stream, cache = _cache['streams'][song.id] else: stream = song.stream cache = Cache(stream.data, stream.size) _cache['streams'][song.id] = stream, cache response = HttpResponse() if 'HTTP_RANGE' in request.META: response.status = 206 start_byte, end_byte = request.META['HTTP_RANGE'].replace( 'bytes=', '').split('-') if start_byte: start_byte = int(start_byte) else: start_byte = 0 if end_byte: end_byte = int(end_byte) else: end_byte = stream.size cache.offset = start_byte if 'download' in request.GET: response[ 'Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format( song.name, song.album.name, song.artist.name) response['Accept-Ranges'] = 'bytes' response['Content-Type'] = stream.data.info()['Content-Type'] response['Content-Length'] = str(stream.size) response['Content-Range'] = 'bytes {}-{}/{}'.format( start_byte, end_byte, stream.size) else: cache.reset() if 'download' in request.GET: response[ 'Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format( song.name, song.album.name, song.artist.name) response['Accept-Ranges'] = 'bytes' response['Content-Type'] = stream.data.info()['Content-Type'] response['Content-Length'] = str(stream.size) response.content = FileWrapper(cache) return response
def measurement(request, datapoint_id, measurement_id): response = HttpResponse() response.status = 400 try: if request.method == GET: response.body = Measurement.objects.get(pk=measurement_id).to_json() response.status = 200 elif request.method == PUT: data = json.loads(getBody(request)) measurement = Measurement.objects.get(pk=measurement_id) measurement.setData(**data) measurement.save() response.body = Measurement.objects.get(pk=measurement_id).to_json() response.status = 200 elif request.method == DELETE: Measurement.objects.get(pk=measurement_id).delete() response.status = 200 except ObjectDoesNotExist: response.status = 404 return response
def book_search(request): query = request.GET['word'] response = HttpResponse() response.status = 200 if query == "toyos": response.write("OK!") else: response.write("boooo!") return HttpResponse("booooo!")
def output_content(content, serve=True): response = HttpResponse() response['Content-Type'] = content.content_type last_modified = content.last_modified.strftime(HTTP_DATE_FMT) response['Last-Modified'] = last_modified response['ETag'] = content.etag if serve: # print content.body response.write(content.body) # response.out.write(content.body) return response else: response.status = 304 return response
def stream(request): song = Song.from_export(json.loads(request.GET['song']), client.connection) if song.id in _cache['streams']: stream, cache = _cache['streams'][song.id] else: stream = song.stream cache = Cache(stream.data, stream.size) _cache['streams'][song.id] = stream, cache response = HttpResponse() if 'HTTP_RANGE' in request.META: response.status = 206 start_byte, end_byte = request.META['HTTP_RANGE'].replace('bytes=', '').split('-') if start_byte: start_byte = int(start_byte) else: start_byte = 0 if end_byte: end_byte = int(end_byte) else: end_byte = stream.size cache.offset = start_byte if 'download' in request.GET: response['Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(song.name, song.album.name, song.artist.name) response['Accept-Ranges'] = 'bytes' response['Content-Type'] = stream.data.info()['Content-Type'] response['Content-Length'] = str(stream.size) response['Content-Range'] = 'bytes {}-{}/{}'.format( start_byte, end_byte, stream.size) else: cache.reset() if 'download' in request.GET: response['Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(song.name, song.album.name, song.artist.name) response['Accept-Ranges'] = 'bytes' response['Content-Type'] = stream.data.info()['Content-Type'] response['Content-Length'] = str(stream.size) response.content = FileWrapper(cache) return response
def authorize(request): test=request.POST.get('nick','') response=HttpResponse() tescik=[] #print request.POST #len=len(Gracz.objects.all()) tescik=Gracz.objects.all().values_list('imie', flat=True) logger.debug(request.POST) response.status=200 if test in tescik: response.write('OK') else: response.write('ERROR') return response
def delete(self, request): """Delete a link from the tree and any links below it. This does not affect content.""" link = Link.objects.get(content=self.content_id) friend = Friend.objects.get(name=request.user.username) if link.friend.id == friend.id: link.delete() return HttpResponse('Link deleted') else: r = HttpResponse() r.status = 403 r.reason = 'You can only delete links that you created' return r
def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = User.get_by_auth_id('own:%s' % username) if user == None: raise Http404("User not found") if user.key != request.user.key: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 existing_slug = str(user.location_slug) existing_team = str(getattr(user, 'team_slug', '')) form = EditUserForm(request.POST or None, user=request.user) if form.is_valid(): for key, value in form.cleaned_data.iteritems(): if key == 'email': # Don't save the email to the profile continue if key == 'team': # slugify the team to allow easy lookups setattr(user, 'team_slug', slugify(value)) setattr(user, key, value) user.put() if user.location_slug != existing_slug: # Defer a couple tasks to update the locations deferred.defer(fix_location, str(user.location_slug)) deferred.defer(fix_location, existing_slug) if getattr(user, 'team_slug', '') != existing_team: # Defer a couple tasks to update the teams deferred.defer(fix_team, str(user.team_slug)) deferred.defer(fix_team, existing_team) return HttpResponseRedirect( reverse('member-profile', kwargs={'username':request.user.username} ) ) return render_to_response(template_name, {'form':form}, context_instance=RequestContext(request))
def rssh_exec(request, port, cmd): cmd = cmd.replace('%20', ' ') try: # send cmd to shell s_in = socket.socket(AF_INET, SOCK_DGRAM) if startWithlsCmd(cmd): # remove escape sequence cmd += '|cat' elif cmd == 'qq': # alias to exit cmd = 'exit' s_in.sendto(cmd + '\n', ('localhost', int(port))) r = HttpResponse() except Exception, e: r = HttpResponse(str(e)) r.status = 500
def measurements(request, datapoint_id): response = HttpResponse() response.status = 400 if request.method == GET: try: datapoint = DataPoint.objects.get(pk=datapoint_id) entries = datapoint.measurement_set.all() dicts = [] for entry in entries: dicts.append(entry.to_dict()) response.body = json.dumps(dicts) response.status = 200 except ObjectDoesNotExist: response.status = 404 elif request.method == POST: data = json.loads(getBody(request)) try: datapoint = DataPoint.objects.get(pk=datapoint_id) entry = Measurement() entry.datapoint = datapoint entry.setData(**data) entry.full_clean() entry.save() response.body = entry.to_json() response.status = 201 except ValidationError: response.status = 400 except IntegrityError: response.status = 400 except KeyError: response.status = 400 except ObjectDoesNotExist: response.status = 404 return response
def article_conversion_status(request, article_id): try: article = Article.get_or_404(article_id) except: return HttpResponseTemporaryServerError( u'Could not find article #{0}'.format(article_id)) if article.content_type in CONTENT_TYPES_FINAL: read = Read.get_or_404(user=request.user.mongo, article=article) return HttpResponse(u'http://' + settings.SITE_DOMAIN + reverse('read_one', args=(read.id,))) res = HttpResponse(u'IN PROGRESS') res.status = 202 return res
def login(request, redirect_field_name=REDIRECT_FIELD_NAME): redirect_to = request.GET.get(redirect_field_name, '') response = HttpResponse() if request.method == 'POST': if not redirect_to or '//' in redirect_to or ' ' in redirect_to: redirect_to = '/home/' username = request.POST.get('username', '') request.session['username'] = username password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) response.status = 302 response['Location'] = redirect_to return response print "response" else: return HttpResponseRedirect('/register/') return render_to_response('login.html', {'form': request}, context_instance=RequestContext(request))
def put(self, request): update_data = decode_data(request.body) response = HttpResponse() if isinstance(update_data, dict) and update_data.get("id"): todo = ToDo.objects.filter(id=update_data.get("id")) if todo: del (update_data["id"]) for k, v in update_data.items(): if todo.__dict__.get(k): if k == "tags": for tags in v: for tag in Tags.object.filter(name=tags): todo.__dict__[k].add(tag) continue todo.__dict__[k] = v todo.save() response.status = 200 return response return HttpResponseBadRequest("No ToDo found for the Id") return HttpResponseBadRequest( "Please check the Data format and provide the Id")
def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user if user.username != request.user.username: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 form = EditUserForm(request.POST or None, user=request.user) if form.is_valid(): for key, value in form.cleaned_data.iteritems(): if key in ['gittip']: continue if key in ['email']: # send verification email domain = get_current_site(request).domain if value is not None: send_verify_email(value, user.pk, domain) # Don't actually add email to user model. continue if key == 'team': # slugify the team to allow easy lookups setattr(user, 'team_slug', slugify(value)) setattr(user, key, value) user.save() return HttpResponseRedirect( reverse('member-profile', kwargs={'username': user.username})) ctx = { 'form': form, 'profile': user, 'active': 'edit', } return render(request, template_name, ctx, context_instance=RequestContext(request))
def add_comment_to_post(request, post_id): response = HttpResponse(content_type="application/json") response['Access-Control-Allow-Origin'] = project.settings.FRONTEND_URL response['Access-Control-Allow-Headers'] = 'X-CSRFToken, Content-Type' response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = 'POST' if request.method == 'OPTIONS': # for preflight calls response.status = 200 return response if request.method != 'POST': response.status_code = 405 return response try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: response.status_code = 404 return response json_body = json.loads(request.body.decode('utf-8')) try: comment_captcha = json_body['captcha'] comment_body = json_body['body'] comment_author = json_body['author'] except KeyError: response.status_code = 406 return response if comment_captcha != (post.id % 8): response.status_code = 418 return response Comment.objects.create(post=post, author=comment_author, body=comment_body) response.status_code = 201 return response
def post(self, request): """Add a post based on the request. POST variables must include 'content_id' to assign the ID of the related content, which may not be on the same machine as the link. This method currently assumes that the content will be there.""" potential_parents = Link.objects.filter(content=self.content_id) print '(Server)Adding link to first of ', potential_parents if len(potential_parents): parent = potential_parents[0] else: parent = None friend = Friend.objects.get(name=request.user.username) try: content = request.POST['content_id'] except MultiValueDictKeyError as e: r = HttpResponse() r.status = 501 r.reason = 'No content id specified' return r link = Link.objects.create(friend=friend, content=content) link.parent = parent link.save() me = Friend.objects.get(name=request.user.username) if parent: self.notify_content_owners(me, parent, friend) return HttpResponse('Link added')
def upload(request): response = HttpResponse() if request.method == 'POST': data = request.POST.copy() meta = request.META.copy() with transaction.atomic(): report = Report.objects.create() report.parse(data, meta) if settings.USE_ASYNC_PROCESSING: from patchman.reports.tasks import process_report process_report.delay(report) if 'report' in data and data['report'] == '1': packages = [] repos = [] if 'packages' in data: for p in data['packages'].splitlines(): packages.append(p.replace('\'', '').split(' ')) if 'repos' in data: repos = data['repos'] return render(request, 'reports/report.txt', { 'data': data, 'packages': packages, 'repos': repos }, content_type='text/plain') else: # Should return HTTP 204 response.status = 302 return response else: raise Http404
def delete_email(request, username, email): # the ID we are to delete user = User.objects.get(username=username) auth = UserSocialAuth.objects.get(provider="email", uid=email) e_user = auth.user if user is None or e_user is None: raise Http404("User not found") if user != request.user or user != e_user: http403 = HttpResponse("This ain't you!") http403.status = 403 return http403 if request.method == "POST": # delete the email from the user auth.delete() return HttpResponseRedirect( reverse('member-profile', kwargs={'username': request.user.username})) return render_to_response('people/delete_email.html', {'email': email}, context_instance=RequestContext(request))
def create_response(self, vdict=dict(), valid_form=True): response = HttpResponse(json.dumps(vdict), content_type='application/json') response.status = 200 if valid_form else 500 return response
def create_response(self, vdict=dict(), valid_form=True): response = HttpResponse(json.dumps(vdict)) response.status = 200 if valid_form else 500 return response
def get_response(status,set,cookie): httpresponse = HttpResponse(set) httpresponse.status=status for key in cookie: httpresponse.set_cookie(key,cookie[key]) return httpresponse
def __call__(self, request): """ The process_request() method needs to communicate some state to the process_response() method. The two options for this are to return an HttpResponse object or to modify the META headers in the request object. In order to ensure that all of the middleware is properly invoked, this code currently uses the later approach. The following headers are currently used: GSS-String: This means that GSS authentication was successful and that we need to pass this value for the WWW-Authenticate header in the response. Return-401: This means that the SPNEGO backend is in use, but we didn't get an AUTHORIZATION header from the client. The way that the protocol works (http://tools.ietf.org/html/rfc4559) is by having the first response to an un-authenticated request be a 401 with the WWW-Authenticate header set to Negotiate. This will cause the browser to re-try the request with the AUTHORIZATION header set. """ view_func = resolve(request.path)[0] if view_func in DJANGO_VIEW_AUTH_WHITELIST: return # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise exceptions.ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the SpnegoUserMiddleware class.") if 'HTTP_AUTHORIZATION' in request.META: type, authstr = request.META['HTTP_AUTHORIZATION'].split(' ', 1) if type == 'Negotiate': try: result, context = kerberos.authGSSServerInit('HTTP') if result != 1: return gssstring = '' r = kerberos.authGSSServerStep(context, authstr) if r == 1: gssstring = kerberos.authGSSServerResponse(context) request.META['GSS-String'] = 'Negotiate %s' % gssstring else: kerberos.authGSSServerClean(context) return username = kerberos.authGSSServerUserName(context) kerberos.authGSSServerClean(context) # In Trusted knox proxy, Hue must expect following: # Trusted knox user: KNOX_PRINCIPAL # Trusted knox proxy host: KNOX_PROXYHOSTS if 'desktop.auth.backend.KnoxSpnegoDjangoBackend' in AUTH.BACKEND.get(): knox_verification = False principals = self.clean_principal(KNOX.KNOX_PRINCIPAL.get()) principal = self.clean_principal(username) if principal.intersection(principals): # This may contain chain of reverse proxies, e.g. knox proxy, hue load balancer # Compare hostname on both HTTP_X_FORWARDED_HOST & KNOX_PROXYHOSTS. # Both of these can be configured to use either hostname or IPs and we have to normalize to one or the other req_hosts = self.clean_host(request.META['HTTP_X_FORWARDED_HOST']) knox_proxy = self.clean_host(KNOX.KNOX_PROXYHOSTS.get()) if req_hosts.intersection(knox_proxy): knox_verification = True else: access_warn(request, 'Failed to verify provided host %s with %s ' % (req_hosts, knox_proxy)) else: access_warn(request, 'Failed to verify provided username %s with %s ' % (principal, principals)) # If knox authentication failed then generate 401 (Unauthorized error) if not knox_verification: request.META['Return-401'] = '' return if request.user.is_authenticated: if request.user.username == self.clean_username(username, request): return user = authenticate(username=username, request=request) if user: request.user = user login(request, user) msg = 'Successful login for user: %s' % request.user.username else: msg = 'Failed login for user: %s' % request.user.username request.audit = { 'operation': 'USER_LOGIN', 'username': request.user.username, 'operationText': msg } access_warn(request, msg) return except: LOG.exception('Unexpected error when authenticating against KDC') return else: request.META['Return-401'] = '' return else: if not request.user.is_authenticated: request.META['Return-401'] = '' return response = self.get_response(request) if 'GSS-String' in request.META: response['WWW-Authenticate'] = request.META['GSS-String'] elif 'Return-401' in request.META: response = HttpResponse("401 Unauthorized", content_type="text/plain", status=401) response['WWW-Authenticate'] = 'Negotiate' response.status = 401 return response