Golang HTTP User Authentication Yabi Series 15 | Golang Web Development | WebAssembly Auth System

Опубликовано: 08 Октябрь 2024
на канале: Maharlikans Code
106
8

In this Golang Web Development Series #35, 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
#GolangWebDevelopment35
#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

Source Codes:
yabi/settings.go:
package yabi

import (
"strings"
"sync"
)

// YabiCookieName is the default cookie name for the yabi auth system
const YabiCookieName = "yabi"

// ExpireCookieInDays is the default user's cookie expiration in 30 days if not provided
var ExpireCookieInDays int = 30 // number of days

// 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 the trailing "/" slash
DBConStr string // MySQL database connection string
mu sync.Mutex // ensures atomic writes; protect the following fields
}

// YB is the pointer for InitYabi configuration
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/"
}
return &InitYabi{
BaseURL: b.BaseURL,
DBConStr: b.DBConStr,
}
}

func init() {
// Set initial default yabi config
YB = InitYabiConfig(&InitYabi{})
}

// SetYabiConfig sets the custom config values from the user
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-assign whatever the new custom config values
return b
}
yabi/users.go:
package yabi

...
// DeleteUserToken will physically delete the specific user's token during logout process
// This process will delete all of the user's specified token key and its token src
func DeleteUserToken(dbCon *sql.DB, encUserName, tokenSrc string) {
upd, err := dbCon.Prepare("DELETE FROM " + YabiUserToken + " WHERE token_key = ? " +
"AND token_src = ? AND expire_on gte ?")
if err != nil {
itrlog.Error("ERROR FROM DeleteUserToken: ", err)
}
// Pass on all the parameter values here
upd.Exec(encUserName, tokenSrc, time.Now().Unix()) // activate the user's status now
defer upd.Close()
}
...
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(""),
})
...
yabi/helpers.go:
// LogOut will be called when the user has been properly logout from the system.
func LogOut(w http.ResponseWriter, r *http.Request, secretKey string) {
// Read cookie and get the cookie here and decrypt it.
cookie, err := r.Cookie(YabiCookieName)
if err != nil {
itrlog.Error(err)
ReAuth(w, r) // Back to login page
return
}

// Decrypt the cookie encrypted username.
userName, err := tago.Decrypt(cookie.Value, secretKey)
if err != nil {
itrlog.Error(err)
ReAuth(w, r) // Back to login page
return
}

// Delete the specified username once logout
_, err = timaan.UT.Remove(userName)
if err != nil {
itrlog.Error(err)
ReAuth(w, r) // Back to login page
return
}

// Delete from the "yabi_user_token" table as well
dbYabi, err := sql.Open("mysql", YB.DBConStr)
if err != nil {
itrlog.Error(err)
}
defer dbYabi.Close()
DeleteUserToken(dbYabi, cookie.Value, YabiTokenAuth)

// Expire the cookie immediately.
cookie = &http.Cookie{
Name: YabiCookieName,
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(w, cookie)

itrlog.Warn("User has been log-out: ", userName)
ReAuth(w, r) // Back to the login page
}
yabi/model_user.go:
// YabiTokenAuth is the login auth indicator for the yabi auth system
const YabiTokenAuth = "auth"

Get the full source codes:
https://github.com/maharlikanscode/Go...