Example #1
0
// CRESTCallbackListener returns a web handler function that listens for a CREST
// SSO callback and accepts the results of authentication.
func CRESTCallbackListener(localdb db.LocalDB, auth evesso.Authenticator, sess server.Sessionizer) web.HandlerFunc {
	return func(c web.C, w http.ResponseWriter, r *http.Request) {
		// Verify state value.
		s := sess.GetSession(&c, w, r)
		passedState := r.FormValue("state")
		if passedState != s.State {
			// CSRF attempt or session expired; reject.
			http.Error(w, "Returned state not valid for this user.", http.StatusBadRequest)
			log.Printf("Got state %#v, expected state %#v", passedState, s.State)
			w.Write([]byte(`{"status": "Error"}`))
			return
		}
		// Extract code from query parameters.
		code := r.FormValue("code")
		// Exchange it for a token.
		tok, err := auth.Exchange(code)
		if err != nil {
			http.Error(w, `{"status": "Error"}`, http.StatusInternalServerError)
			log.Printf("Error exchanging token: %v", err)
			return
		}
		// Get character information.
		charInfo, err := auth.CharacterInfo(tok)
		if err != nil {
			http.Error(w, `{"status": "Error"}`, http.StatusInternalServerError)
			log.Printf("Error getting character information: %v; token was %+v", err, tok)
			return
		}

		// Update session in database.
		err = localdb.AuthenticateSession(s.Cookie, tok, charInfo)
		if err != nil {
			http.Error(w, `{"status": "Error"}`, http.StatusInternalServerError)
			log.Printf("Unable to update session post-auth: %v; info was %+v", err, charInfo)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`
			<html>
				<head>
					<title>Authenticated</title>
				</head>
				<body>
					<p>OK.</p>
					<script type="text/javascript">
						window.onload = function() {
							window.opener.hasAuthenticated();
							window.close();
						}
					</script>
				</body>
			</html>
			`))
	}
}