Using the Middleware
Middleware can be used in Gin in a number of ways. You can apply them to a single route, a group of routes or to all routes depending on your requirements. In our case, we want to
- Use the
setUserStatus
middleware on all routes, - Use the
ensureLoggedIn
middleware on routes that require authentication, and - Use the
ensureNotLoggedIn
middleware on routes that require users to be unauthenticated.
Since we want to use the setUserStatus
middleware on all routes, we can use the Use
method of the router:
router.Use(setUserStatus())
In all the routes where we want to use a particular middleware, we can place it before the route handler in the route definition. For example, since we want to ensure that only authenticated users can see the Create Article
page, we can modify that route definition from
articleRoutes.GET("/create", showArticleCreationPage)
to
articleRoutes.GET("/create", ensureLoggedIn(), showArticleCreationPage)
The updated routes.go
file should have the following content:
// routes.go
package main
func initializeRoutes() {
router.Use(setUserStatus())
router.GET("/", showIndexPage)
userRoutes := router.Group("/u")
{
userRoutes.GET("/login", ensureNotLoggedIn(), showLoginPage)
userRoutes.POST("/login", ensureNotLoggedIn(), performLogin)
userRoutes.GET("/logout", ensureLoggedIn(), logout)
userRoutes.GET("/register", ensureNotLoggedIn(), showRegistrationPage)
userRoutes.POST("/register", ensureNotLoggedIn(), register)
}
articleRoutes := router.Group("/article")
{
articleRoutes.GET("/view/:article_id", getArticle)
articleRoutes.GET("/create", ensureLoggedIn(), showArticleCreationPage)
articleRoutes.POST("/create", ensureLoggedIn(), createArticle)
}
}
After updating the routes, you should notice that the unauthenticated users won't see the Create Article
and Logout
pages, and authenticated users won't see the Register
and Login
pages.
Now that we have implemented an authorization scheme, the only thing left to do is to ensure that the user interface reflects this scheme.