Sunday, 10 May 2009

User authentication in GAE

Google App Engine provides a set of standard APIs for common tasks, such as user authentication, caching and persistent storage. This post looks at the user authentication API and creates a simple form that is authenticated against a Google login.

We'll use exactly the same structure and build scripts as the previous post, as that just makes life easier.

The servlet below checks whether there is an current user logged in. If not, then redirect to a prompt requiring a user to login, otherwise just display the users nickname.


(ns blogging.login
(:gen-class :extends javax.servlet.http.HttpServlet)
(:import (com.google.appengine.api.users User UserService UserServiceFactory)))

(defn greet
[user response]
(.setContentType response "text/plain")
(let [w (.getWriter response)]
(.println w (str "Hello, " (.getNickname user)))))

(defn -doGet
[_ request response]
(let [userService (UserServiceFactory/getUserService)
user (.getCurrentUser userService)]
(cond
(not (nil? user)) (greet user response)
:else (.sendRedirect response (.createLoginURL userService (.getRequestURI request))))))


If you deploy on the development server, then you get a screen like that shown below:



Neat! Next on the list, persisting data.