Allowing Users to Log in and Log out
In this section, we'll add functionality that will allow registered users to log in and logged in users to log out of our application.
The code for this section will be organized as follows:
models.user.gowill be updated to check if the login credentials are valid,handlers.user.gowill be updated with the new request handlers,routes.gowill be updated with the new routes,templates/login.htmlwill display the login form, andtemplates/menu.htmlwill be updated with theLoginandLogoutmenus.
Let's begin by creating a placeholder for the function to validate the login credentials, in models.user.go, as follows:
// models.user.go
func isUserValid(username, password string) bool {
return false
}
We also need to update handlers.user.go with:
- A
showLoginPagehandler to show the login page, - A
performLoginhandler to handle the login request, and - A
logouthandler to handle the logout request.
For now, let's just add these handlers without any functionality so that we can write tests for them. Let's update the handlers.user.go file with the following code:
// handlers.user.go
func showLoginPage(c *gin.Context) {}
func performLogin(c *gin.Context) {}
func logout(c *gin.Context) {}