user340495
user340495

Reputation: 321

google app engine authentication for specific pages

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?

Upvotes: 0

Views: 112

Answers (1)

Sebastian
Sebastian

Reputation: 17443

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.

Upvotes: 2

Related Questions