In this Golang Web Development Series #36, we're building a complete Golang HTTP User Authentication System from scratch with the backend MySQL database by using Golang's official MySQL Database Driver. The Golang HTTP Authentication will consist of Golang User Registration, Golang Login Auth, Golang Password Reset, Golang Change Password, Golang Set Cookie, Golang Web Assembly (WASM), Golang Map Token, Golang Persisted Token, etc. with step by step guide here in Golang's Web Development Series.
#MaharlikansCode
#GolangWebDevelopment36
#GolangTutorial
#LearnGolangWebDevelopment
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper
Get Linode Account:
https://www.linode.com/?r=6aae17162e9...
If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode
You can use this tool online which is to convert epoch to human-readable date and vice versa:
https://www.epochconverter.com/
Source Codes:
package yabi
import (
"database/sql"
"fmt"
"strings"
"sync"
"time"
"github.com/itrepablik/itrlog"
"github.com/itrepablik/timaan"
)
// YabiCookieName is the default cookie name for the yabi auth system
const YabiCookieName = "yabi"
// YabiTokenAuth is the login auth indicator for the yabi auth system
const YabiTokenAuth = "auth"
// ExpireCookieInDays is the default user's cookie expiration in 30 days if not provided
var ExpireCookieInDays int = 30 // number of days
// RemoveExpiredTokens is the default scheduled time in seconds to auto remove expired persisted tokens
var RemoveExpiredTokens int = 1800 // number of seconds, default to 1800 seconds which is 30 mins
// InitYabi initializes the common configurations that yabi package use
type InitYabi struct {
BaseURL string // e.g http://127.0.0.1:8081/ or https://maharlikanscode.com/ with trailing "/" slash
DBConStr string // MySQL database connection string
AutoRemoveExpiredToken int // value must be in seconds, it will be permanently delete the rows from the "yabi_user_token" table
mu sync.Mutex // ensures atomic writes; protects the following fields
}
// YB is the pointer for InitYabi configurations
var YB *InitYabi
// InitYabiConfig initialize all the necessary yabi configurations and its default values
func InitYabiConfig(b *InitYabi) *InitYabi {
// Check all the required configurations are in place or not
if len(strings.TrimSpace(b.BaseURL)) == 0 {
b.BaseURL = "http://127.0.0.1:8081/"
}
// Set the default time interval to auto remove the expired persisted tokens
if b.AutoRemoveExpiredToken lte 0 {
b.AutoRemoveExpiredToken = RemoveExpiredTokens
}
// Run task to auto remove expired persisted tokens
go TaskRemovePersistedTokens()
// Run the auto remove expired timaan tokens stored in the memory
go TaskRemoveMapTokens()
return &InitYabi{
BaseURL: b.BaseURL,
DBConStr: b.DBConStr,
AutoRemoveExpiredToken: b.AutoRemoveExpiredToken,
}
}
func init() {
// Set initial default itrlog required settings.
YB = InitYabiConfig(&InitYabi{})
}
// SetYabiConfig sets the custom log requirement to initialize the itr logger.
func SetYabiConfig(b *InitYabi) *InitYabi {
b.mu.Lock()
defer b.mu.Unlock()
// Check all the required configurations are in place or not
if len(strings.TrimSpace(b.BaseURL)) == 0 {
b.BaseURL = "http://127.0.0.1:8081/"
}
// Re-configure the yabi configurations
b = InitYabiConfig(b)
YB = b // Must re-assigned whatever the new custom config values
return b
}
// TaskRemovePersistedTokens task to auto remove the persisted token stored in "yabi_user_token" table
func TaskRemovePersistedTokens() {
for {
if len(strings.TrimSpace(YB.DBConStr)) gt 0 {
// Delete from the "yabi_user_token" table as well
dbCon, err := sql.Open("mysql", YB.DBConStr)
if err != nil {
itrlog.Error(err)
}
defer dbCon.Close()
upd, err := dbCon.Prepare("DELETE FROM " + YabiUserToken + " WHERE expire_on lt ?")
if err != nil {
itrlog.Error("ERROR FROM TaskDeleteUserToken: ", err)
}
// Pass on all the parameter values here
upd.Exec(time.Now().Unix())
defer upd.Close()
}
time.Sleep(time.Duration(YB.AutoRemoveExpiredToken) * time.Second)
}
}
main.go:
...
// Initialize the Yabi auth API here
yabiBaseURL := "http://" + webServerIP + "/" // default to dev localhost
if IsProdServerMode {
yabiBaseURL = config.SiteBaseURLProd
}
yabi.SetYabiConfig(&yabi.InitYabi{
BaseURL: yabiBaseURL,
DBConStr: api.DBConStr(""),
AutoRemoveExpiredToken: 5,
})
...
Get the full source codes:
https://github.com/maharlikanscode/Go...