检查登录用户是否是当前正在查看的实体的作者

时间:2013-11-29 19:29:48

标签: google-app-engine python-2.7 cookies authorization app-engine-ndb

我想检查当前登录的用户是否是当前正在查看的实体的“作者”。

这就是我所拥有的:

class Account(ndb.Model):
    username = ndb.StringProperty(required = True)
    password = ndb.StringProperty(required = True)

登录时,Cookie名称“user_id”设置为等于Account实体ID的值。 user_id cookie如下所示:

"user_id=5629499534213120" 

因此,一旦user_id cookie存在,并且其值等于数据存储区中的Account实体ID,则用户已登录

现在我们有BlogPost:

class BlogPost(ndb.Model):
    author_key = ndb.KeyProperty() #This value is set to the user_id of the currently logged in user
    title = ndb.StringProperty(required = True)

现在,可以在此网址中找到BlogPost实体:

http://www.example.com/blogpost/<blogpost entity's id>
Example: http://www.example.com/blogpost/8234086234786238649236423

我想创建一个is_author()函数:

def is_author():
    # Gets the url argument of the entity currently being viewed.
    # Compares it to the user_id cookie of the currently logged in user.
    # If they match, then the currently user is the author of the blogpost being viewed.

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

def is_author(blogpostid, account):    
    if BlogPost.query(ndb.And(BlogPost.id=blogpostid, BlogPost.author_key == account.key)).get():
        return True
    else:
        return False

然后使用它:

#get the account object based on your cookie
account = Account.get_by_id(self.request.cookies["user_id"])

#get your blog post id
blogpostid = "12341234214"


#check if it's the author
if is_author(blogpostid, account):
    do_whatever()

<强>更新

要从URL获取blogpost id,只需将其作为参数传递。例如:

class BlogPostHandler(webapp2.RequestHandler):
    def get(self, blogpostid):
       #you can use the blogpostid variable here now.

...

app = webapp2.WSGIApplication([('/blogpost/(.*)', BlogPostHandler)
], debug=True)