Authentication
Goffee comes with a built-in users authentication feature, you can turn it on by uncommenting the auth related routes in routes.go
, the authentication feature consists of the following features:
- registration
- signin
- reset password
- signout
- auth check hook to protect from none authenticated users
hook/auth-check.go
Enabling the authentication
You can simply enable the authentication by uncommenting the following routes in the file routes.go
:
- router.Post("/signup", controllers.Signup)
- router.Post("/signin", controllers.Signin)
- router.Post("/signout", controllers.Signout)
- router.Post("/reset-password", controllers.ResetPasswordRequest)
- router.Post("/reset-password/code/:code", controllers.SetNewPassword)
- router.Get("/dashboard", controllers.WelcomeToDashboard, hooks.AuthCheck) // temp protected route
Authentication if templates are enabled
If templates are enabled in the .env file, the token will not be returned. Instead, it will be created in an encrypted cookie and the token will be maintained on it. In future requests with templates, the token will be retrieved from the cookie and if it passes validation, the session will be maintained.
Updating the registration fields
The registration route supports three fields:
- name
- password
To modify or add new fields you will have to modify the signup
handler function in controllers/authentication.go
First, you need to add the filed to the User
model in the file models/user.go
, here is how the file looks like
package models
import "gorm.io/gorm"
type User struct {
gorm.Model
Name string
Email string
Password string
}
// Override the table name
func (User) TableName() string {
return "users"
}
Next, grab the filed from the request data like below
name := c.GetRequestParam("name")
email := c.GetRequestParam("email")
password := c.GetRequestParam("password")
Next, add the filed to the validation struct like below
// validation data
data := map[string]interface{}{
"name": name,
"email": email,
"password": password,
}
Next, add the validation rules for the filed like below
// validation rules
rules := map[string]interface{}{
"name": "required|alphaNumeric",
"email": "required|email",
"password": "required|length:6,10",
}
Next, add the filed to the User
struct instance to be stored in the database like below
user = models.User{
Name: c.CastToString(name),
Email: c.CastToString(email),
Password: passwordHashed,
}
res = c.GetGorm().Create(&user)