Go with Echo

Cover Page

Back-end Page

handlers.go

Change to your chatterd folder and edit handlers.go:

server$ cd ~/reactive/chatterd
server$ vi handlers.go

Add the following libraries to the import block at the top of handlers.go:

import (
    "crypto/sha256"
    "strconv"
    //...
    "google.golang.org/api/idtoken"
)

Next add the following two new structs:

type (
	AuthChatt struct {
		ChatterID string `json:"chatterID"`
		Message   string `json:"message"`
	}
	Chatter struct {
		ClientID string `json:"clientID"`
		IdToken  string `json:"idToken"`
	}
)

Then add the adduser() function:

func adduser(c echo.Context) error {
	var chatter Chatter

	if err := c.Bind(&chatter); err != nil {
		return logClientErr(c, http.StatusUnprocessableEntity, err)
	}

	reqCtx := c.Request().Context()
	idinfo, err := idtoken.Validate(reqCtx, chatter.IdToken, chatter.ClientID)
	if err != nil {
		return logClientErr(c, http.StatusUnauthorized, err)
	}

	username := "Profile NA"
	name := idinfo.Claims["name"]
	if name != nil {
		username = name.(string)
	}

	// compute chatterID

}

The function adduser() first receives a POST request containing a clientID and idToken from the front end. It uses Google’s idtoken package to verify the user’s idToken, passing along the clientID as required by Google. The verification process checks that idToken hasn’t expired and is valid. If the token is invalid or has expired, a 401, “Unauthorized” HTTP error is returned to the front end. If idToken is verified, the user’s name registered with the idToken is returned to the front end.

Next, the function computes a chatterID for the new user. The chatterID is computed as a SHA256 one-way hash of the idToken, a server’s secret, and the current time stamp. The function also assigns a lifetime to the chatterID. The lifetime is set to be no more than the remaining lifetime of the idToken, so always less than the total expected lifetime of the idToken. During the lifetime of a chatterID, the user does not need to check the freshness of their idToken with Google. Replace // compute chatterID with:

	// Compute chatterID
	const backendSecret = "ifyougiveamouse"
	now := time.Now().Unix()
	nonce := strconv.FormatInt(now, 10)
	chatterID := fmt.Sprintf("%x", sha256.Sum256([]byte(chatter.IdToken+backendSecret+nonce)))

	exp := idinfo.Expires
	lifetime := min((exp-now)+1, 300) // secs, up to 1800, idToken lifetime

	// add to database

During testing, setting lifetime to 1 minute allows faster triggering of the various use cases. Longer lifetime leads to less frequent prompting for user to sign in again, but also leaves open a larger window of vulnerability.

The chatterID, the user’s registered name obtained from the idToken, and the chatterID’s lifetime are then entered into the chatters table. At the same time, we take this oppotunity to do some house keeping to remove all expired chatterIDs from the database. Replace // add to database with:

	_, err = chatterDB.Exec(background, `DELETE FROM chatters WHERE $1 > expiration`, now)
	if err != nil {
		return logServerErr(c, err)
	}

	_, err = chatterDB.Exec(background,
		`INSERT INTO chatters (chatterid, username, expiration) VALUES ($1, $2, $3)`,
		chatterID, username, now+lifetime)
	if err != nil {
		return logServerErr(c, err)
	}

	logOk(c)
	return c.JSON(http.StatusOK, map[string]any{"username": username, "chatterID": chatterID, "lifetime": lifetime})

The registered username, the newly created chatterID and its lifetime are returned to the user as a JSON object.

postauth()

We now add postauth(), which is a modified postchatt(), to your handlers.go. To post a chatt, the front end sends a POST request containing the user’s chatterID and message. The function postauth() retrieves the record matching chatterID from the chatters table. If chatterID is not found in the chatters table, or if the chatterID has expired, it returns a 401, “Unauthorized” HTTP error. Otherwise, the registered username corresponding to chatterID is retrieved from the table. Note: chatterIDs are unique in the chatters table.

func postauth(c echo.Context) error {
	var chatt AuthChatt
	var err error

	if err = c.Bind(&chatt); err != nil {
		return logClientErr(c, http.StatusUnprocessableEntity, err)
	}

	var username string
	var exp int64
	now := time.Now().Unix()
	reqCtx := c.Request().Context()
	err = chatterDB.QueryRow(reqCtx, `SELECT username, expiration FROM chatters WHERE chatterID = $1`, chatt.ChatterID).Scan(&username, &exp)
	if err == pgx.ErrNoRows || now > exp {
		return logClientErr(c, http.StatusUnauthorized, err)
	} else if err != nil {
		return logServerErr(c, err)
	}

	// insert chatt
	
}

Insert the chatt into the chatts table under the retrieved username. Replace // insert chatt with:

	_, err = chatterDB.Exec(background, `INSERT INTO chatts (name, message, id) VALUES ($1, $2, gen_random_uuid())`, username, chatt.Message)
	if err != nil {
		return logClientErr(c, http.StatusBadRequest, err)
	}

	logOk(c)
	return c.JSON(http.StatusOK, struct{}{})

We will be using the original getchatts() from the chatter lab without modification.

We’re done with handlers.go. Save and exit the file.

main.go

Edit the file main.go:

server$ vi main.go

Find the global variable router and add the following new routes for the new API endpoints /adduser and /postauth:

var routes = []Route {
    // . . .
    {"POST", "/adduser/", adduser},
    {"POST", "/postauth/", postauth},
}

We’re done with main.go. Save and exit the file.

Build and test run

Since we added new packages, you need to run:

server$ go get

before you can rebuild your server:

server$ go build

:point_right:Go is a compiled language, like C/C++ and unlike Python, which is an interpreted language. This means you must run go build each and every time you made changes to your code, for the changes to show up in your executable.

To run your server:

server$ sudo ./chatterd
# Hit ^C to end the test

The cover back-end spec provides instructions for Testing Signin.

References


Prepared by Benjamin Brengman, Ollie Elmgren, Wendan Jiang, Alexander Wu, and Sugih Jamin Last updated March 13th, 2026