如何限制用户将任务添加到任务队列



我试图让只有用户"foo"才能使用以下谷歌应用程序引擎代码将任务添加到任务队列中,但任务似乎失败了。(添加任务成功。)

在我设置"login:required"之前,代码是有效的。

app.yaml

- url: /main.*
  script: main.app
  login: required

主.py

class ProcessHandler(webapp2.RequestHandler):
  def get(self):
    if users.get_current_user().nickname == 'foo': 
      # Do something here.
    else: 
      self.response.write('access is not allowed. ')
class TaskHandler(webapp2.RequestHandler):
  def get(self):
    q = taskqueue.Queue('myQueue')
    task_url = 'http://myapp.appspot.com/process'
    task = taskqueue.Task(url=url, method='GET')
    q.add(task)
app = webapp2.WSGIApplication([
  ('/addTask', TaskHandler),
  ('/process', ProcessHandler)
  ], debug=True)

我应该如何更改代码,以便只允许用户"foo"成功添加任务?

url通常是相对于应用程序根目录的路径。不包括'http://myapp.appspot.com"。

为了防止用户向队列中添加用户"foo"以外的任务,您需要在TaskHandler代码中检查该用户。

from google.appengine.api import taskqueue
if users.get_current_user().nickname == 'foo': 
        # Add task here
        taskqueue.add(queue_name=‘myQueue’, url='/path/to/my/worker/', params={'key': key})

为了防止任何人通过点击该url来处理任务处理程序,请添加标头以验证只有应用程序引擎在发出请求。

if self.request.headers.get('X-AppEngine-TaskName') is not None:
    # Process task

这些标题由谷歌应用引擎内部设置。如果您的请求处理程序找到这些头中的任何一个,它可以相信该请求是一个任务队列请求。如果您的应用程序的外部用户请求中存在上述任何标头,则会将其剥离。例外情况是来自已登录的应用程序管理员的请求,他们可以出于测试目的设置标头。https://cloud.google.com/appengine/docs/python/taskqueue/overview-push

最新更新