Implementing the Route Handlers
In the user route handler, the showRegistrationPage
handler should show the registration page to unauthenticated users while the register
handler should handle the registration request.
After implementing these handlers, handlers.user.go
should look as follows:
// handlers.user.go
package main
import (
"math/rand"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func generateSessionToken() string {
// We're using a random 16 character string as the session token
// This is NOT a secure way of generating session tokens
// DO NOT USE THIS IN PRODUCTION
return strconv.FormatInt(rand.Int63(), 16)
}
func showRegistrationPage(c *gin.Context) {
// Call the render function with the name of the template to render
render(c, gin.H{
"title": "Register"}, "register.html")
}
func register(c *gin.Context) {
// Obtain the POSTed username and password values
username := c.PostForm("username")
password := c.PostForm("password")
if _, err := registerNewUser(username, password); err == nil {
// If the user is created, set the token in a cookie and log the user in
token := generateSessionToken()
c.SetCookie("token", token, 3600, "", "", false, true)
c.Set("is_logged_in", true)
render(c, gin.H{
"title": "Successful registration & Login"}, "login-successful.html")
} else {
// If the username/password combination is invalid,
// show the error message on the login page
c.HTML(http.StatusBadRequest, "register.html", gin.H{
"ErrorTitle": "Registration Failed",
"ErrorMessage": err.Error()})
}
}
If we run the tests again, we'll see the following output:
=== RUN TestArticleXML
[GIN] 2016/08/04 - 09:13:30 | 200 | 27.544µs | | GET /article/view/1
--- PASS: TestArticleXML (0.00s)
=== RUN TestShowRegistrationPageUnauthenticated
[GIN] 2016/08/04 - 09:13:30 | 200 | 96.805µs | | GET /u/register
--- PASS: TestShowRegistrationPageUnauthenticated (0.00s)
=== RUN TestRegisterUnauthenticated
[GIN] 2016/08/04 - 09:13:30 | 200 | 107.286µs | | POST /u/register
--- PASS: TestRegisterUnauthenticated (0.00s)
=== RUN TestRegisterUnauthenticatedUnavailableUsername
[GIN] 2016/08/04 - 09:13:30 | 400 | 116.63µs | | POST /u/register
--- PASS: TestRegisterUnauthenticatedUnavailableUsername (0.00s)
=== RUN TestGetAllArticles
--- PASS: TestGetAllArticles (0.00s)
=== RUN TestGetArticleByID
--- PASS: TestGetArticleByID (0.00s)
=== RUN TestValidUserRegistration
--- PASS: TestValidUserRegistration (0.00s)
=== RUN TestInvalidUserRegistration
--- PASS: TestInvalidUserRegistration (0.00s)
=== RUN TestUsernameAvailability
--- PASS: TestUsernameAvailability (0.00s)
PASS
ok github.com/demo-apps/go-gin-app 0.007s
With the registration functionality complete, it's time to allow users to log in and log out.