douteng5673 2014-05-03 14:37
浏览 12
已采纳

特定页面的Google App Engine身份验证

I am experimenting to develop with google-app-engine on the golang platform and I wish to perform a check (for logged in users) on a specific pages only.

for example:

users visiting the "/" path will be redirected to "/site" if they are logged in or will be shown a page about the product.

while users visiting the "/members","/users","/items" pages will be redirected to a login page if they are not authenticated.

a simple go code suggests:

package hello

import (
    "fmt"
    "net/http"

    "appengine"
    "appengine/user"
)

func init() {
    http.HandleFunc("/", site)
    http.HandleFunc("/", members) // etc for "items" and "products" and whatever restricted pages
}

func user_logged_in() bool {
    // do the check ...
    return true
}

func user_not_logged_in() {
    // fatal error message
}

func site(w http.ResponseWriter, r *http.Request) {
    if !user_logged_in() {
        // show "about" page
    } else {
        // show a "user" page
    }
}

func members(w http.ResponseWriter, r *http.Request) {
    if !user_logged_in() {
        // show "members" page
    } else {
        user_not_logged_in() // fatal error message
    }
}

however this feels a bit hacky, I wish I could test for the page URL in the init function and pre-process the user account once instead of calling a checker function from everywhere in my code ...

what would be a good practice of making the http dispatcher call my "login-required" pages only if a user is logged in?

  • 写回答

1条回答 默认 最新

  • drfu80954 2014-05-03 14:51
    关注

    The init function only initializes your application. You use it for example to register HTTP handlers but it won't run on every request.

    In case you use one of the standard authentication methods you can declare authorization in your app.yaml configuration file. For your use case it would be similar to this:

    handlers:
    
    - url: /members/.*
      script: _go_app
      login: required
    
    - url: /users/.*
      script: _go_app
      login: required
    
    - url: /items/.*
      script: _go_app
      login: required
    
    - url: /.*
      script: _go_app
    

    Have a look at the docs for more details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持