jwt_auth

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 1, 2022 License: MIT Imports: 36 Imported by: 2

Documentation

Index

Constants

View Source
const (
	LoginRequired = 1
	PublicApiCall = 0
	LoginOptional = 2
)

Variables

View Source
var GinSetupTable = []GinLoginType{

	{Method: "POST", Path: "/api/v1/auth/login", Fx: authHandleLogin, UseLogin: PublicApiCall},
	{Method: "POST", Path: "/api/v1/auth/register", Fx: authHandleRegister, UseLogin: PublicApiCall},
	{Method: "POST", Path: "/api/v1/auth/validate-2fa-token", Fx: authHandleValidate2faToken, UseLogin: PublicApiCall},
	{Method: "POST", Path: "/api/v1/auth/email-confirm", Fx: authHandlerEmailConfirm, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/email-confirm", Fx: authHandlerEmailConfirm, UseLogin: PublicApiCall},
	{Method: "POST", Path: "/api/v1/auth/recover-password-01-setup", Fx: authHandleRecoverPassword01Setup, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/recover-password-01-setup", Fx: authHandleRecoverPassword01Setup, UseLogin: PublicApiCall},
	{Method: "POST", Path: "/api/v1/auth/recover-password-02-fetch-info", Fx: authHandleRecoverPassword02FetchInfo, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/recover-password-02-fetch-info", Fx: authHandleRecoverPassword02FetchInfo, UseLogin: PublicApiCall},
	{Method: "POST", Path: "/api/v1/auth/recover-password-03-set-password", Fx: authHandleRecoverPassword03SetPassword, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/recover-password-03-set-password", Fx: authHandleRecoverPassword03SetPassword, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/no-login-status", Fx: authHandleNoLoginStatus, UseLogin: PublicApiCall},
	{Method: "POST", Path: "/api/v1/auth/no-login-status", Fx: authHandleNoLoginStatus, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/2fa-has-been-setup", Fx: authHandle2faHasBeenSetup, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/email-has-been-validated", Fx: authHandleEmailHasBeenSetup, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/auth/acct-status", Fx: authHandleAcctHasBeenSetup, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/id.json", Fx: loginTrackingJsonHandler, UseLogin: PublicApiCall},
	{Method: "GET", Path: "/api/v1/set-debug-flag", Fx: authHandlerSetDebugFlag, UseLogin: PublicApiCall},

	{Method: "GET", Path: "/api/v1/auth/logout", Fx: authHandleLogout, UseLogin: LoginOptional},
	{Method: "POST", Path: "/api/v1/auth/logout", Fx: authHandleLogout, UseLogin: LoginOptional},

	{Method: "POST", Path: "/api/v1/auth/login-status", Fx: authHandleLoginStatus, UseLogin: LoginRequired},
	{Method: "GET", Path: "/api/v1/auth/login-status", Fx: authHandleLoginStatus, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/refresh-token", Fx: authHandleAcctHasBeenSetup, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/change-password", Fx: authHandleChangePassword, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/delete-acct", Fx: authHandleDeleteAccount, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/regen-otp", Fx: authHandleRegenOTP, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/register-un-pw", Fx: authHandleRegisterUnPw, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/register-token", Fx: authHandleRegisterToken, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/change-email-address", Fx: authHandleChangeEmailAddress, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/change-account-info", Fx: authHandleChangeAccountInfo, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/change-password-admin", Fx: authHandleChangePasswordAdmin, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/add-2fa-secret", Fx: authHandleAdd2faSecret, UseLogin: LoginRequired},
	{Method: "POST", Path: "/api/v1/auth/remove-2fa-secret", Fx: authHandleRemove2faSecret, UseLogin: LoginRequired},
}
View Source
var PrivilegedNames = []string{"__is_logged_in__", "__user_id__", "__auth_token__", "__privs__", "__jwt_token__", "__email_hmac_password__", "__user_password__"}
View Source
var XDbOn = make(map[string]bool)
View Source
var XDbOnLock = sync.RWMutex{}

Functions

func AppendToSecurityTable

func AppendToSecurityTable(x ...GinLoginType)

-------------------------------------------------------------------------------------------------------------------------

func BindFormOrJSON

func BindFormOrJSON(c *gin.Context, bindTo interface{}) (err error)

func BindFormOrJSONOptional

func BindFormOrJSONOptional(c *gin.Context, bindTo interface{}) (err error)

func CallDatabaseJSONFunction

func CallDatabaseJSONFunction(c *gin.Context, fCall string, encPat string, data ...interface{}) (rv string, err error)

func Confirm2faSetupAccount

func Confirm2faSetupAccount(c *gin.Context, UserId int)

-------------------------------------------------------------------------------------------------------------------------

func ConfirmEmailAccount

func ConfirmEmailAccount(c *gin.Context, EmailVerifyToken string) (rv, stmt string, err error)

-------------------------------------------------------------------------------------------------------------------------

ConfirmEmailAccount uses the token to lookup a user and confirms that the email that received the token is real.

func ConnectToDb

func ConnectToDb()

func ConvPrivs

func ConvPrivs(Privileges string) (rv string)

Input : [{"priv_name":"May Change Password"}, {"priv_name":"May Password"}] Outupt : {"May Change Password":true, "May Password":true}

func ConvPrivs2

func ConvPrivs2(Privileges string) (rv string, mr map[string]bool)

Input : ["May Change Password", "May Do Whatever"] Outupt : {"May Change Password":true, "May Do Whatever":true}

func CookieHeaderAuthMiddleware

func CookieHeaderAuthMiddleware(ginSetupTable []GinLoginType) gin.HandlerFunc

func CreateJWTSignedCookie

func CreateJWTSignedCookie(c *gin.Context, DBAuthToken string) (rv string)

func DecryptText

func DecryptText(key, text []byte) ([]byte, error)

func DisConnectToDb

func DisConnectToDb()

DisConnectToDb() closes connection to databse.

func EmptyDflt

func EmptyDflt(s, d string) string

EmptyDflt if s is empty, then return d. Creates a default value for parametrs

func EncryptText

func EncryptText(key, text []byte) ([]byte, error)

func EncryptTextIndexable

func EncryptTextIndexable(key, xiv, text []byte) ([]byte, error)

func EncryptTextToB64

func EncryptTextToB64(key, text []byte) string

func EncryptTextToB64Indexable

func EncryptTextToB64Indexable(key, iv, text []byte) string

func GenUUID

func GenUUID() string

GenUUID generates a UUID and returns it.

func GenerateSecret

func GenerateSecret() string

-------------------------------------------------------------------------------------------------------------------------

func GetAuthToken

func GetAuthToken(c *gin.Context) (UserId int, AuthToken string)

func GetMapKeys

func GetMapKeys[K comparable, V any](m map[K]V) []K

GetMapKeys Get all the keys from any typed map. (generic)

func GetUserId

func GetUserId(c *gin.Context) (UserId int, err error)

------------------------------------------------------------------------------------------------------------------------- GetUserId will return a UserID - if the user is currently logged in then it is from __user_id__ in the context. If the user is not logged in then 0 will be returned.

func GinInitAuthPaths

func GinInitAuthPaths(router *gin.Engine)

-------------------------------------------------------------------------------------------------------------------------

func HasCookie

func HasCookie(cookieName string, c *gin.Context) (has bool, val string)

HasCookie returns true, `has` and a value if the cookie exists. If not then it returns false.

func IsLoggedIn

func IsLoggedIn(c *gin.Context) (ItIs bool)

------------------------------------------------------------------------------------------------------------------------- IsLoggedIn returns true if the user is currently logged in or if the user can be logged in. The login can be determined with a cookie or an berrer auth token. This call has side-effects - it will add authentication information to the context like, __is_logged_in__. See GetAuthToken().

This is the fucntion to call to login a user.

func IsTLS

func IsTLS(c *gin.Context) bool

func IsXDBOn

func IsXDBOn(name string) (b bool)

func MintQRPng

func MintQRPng(c *gin.Context, InputString string) (qrurl string)

-------------------------------------------------------------------------------------------------------------------------

func ParseBool

func ParseBool(s string) (b bool)

ParseBool convers a string to bool based on the table of trueValues.

func ReadJson

func ReadJson(fn string, x interface{}) (err error)

ReadJson read in a JSON file into a go data structure.

func RmExt

func RmExt(filename string) string

RmExt removes the extenstion from a file name if it exits. if filename is "bc.js", then "bc" will be retuend.

func SVar

func SVar(v interface{}) string

SVar return the JSON encoded version of the data.

func SVarI

func SVarI(v interface{}) string

SVarI return the JSON encoded version of the data with tab indentation.

func SaveState

func SaveState(cookieValue string, UserId int, c *gin.Context) (err error)

-------------------------------------------------------------------------------------------------------------------------

func SetCookie

func SetCookie(cookieName, cookieValue string, c *gin.Context)

SetCookie sets the header to create a cookie. If using TLS then this will be a secure HTTP-Only cookie.

func SetDefaultRunner

func SetDefaultRunner()

func SetInsecureCookie

func SetInsecureCookie(cookieName, cookieValue string, c *gin.Context)

func SetJsonHdr

func SetJsonHdr(c *gin.Context)

SetJsonHdr will set a content-type header to "application/json; charset=utf-8"

func SetupConnectToJwtAuth

func SetupConnectToJwtAuth(xctx context.Context, xconn *pgxpool.Pool, gcfg *data.GlobalConfigData, log *os.File)

func SortSlice

func SortSlice[T constraints.Ordered](s []T)

SortSlice will Sort a slice of any type. (generic)

func SortedMapKeys

func SortedMapKeys[K constraints.Ordered, V any](m map[K]V) []K

SortMapKeys will sort the keys on a map and return a slice of sorted keys (generic)

func SqlRunStmt

func SqlRunStmt(c *gin.Context, stmt string, encPat string, data ...interface{}) (rv []map[string]interface{}, err error)

-------------------------------------------------------------------------------------------------------------------------

func StatusSuccess

func StatusSuccess(s string, c *gin.Context) string

StatusSuccess prepends to a JSON return value with a status:success. This will also set the "Content-Type" to "application/json; charset=utf-8".

func TokenAuthMiddleware

func TokenAuthMiddleware() gin.HandlerFunc

Types

type AcctSetupSuccess

type AcctSetupSuccess struct {
	Status           string `json:"status"`
	SetupComplete2fa string `json:"setup_complete_2fa,omitempty"`
	EmailVerified    string `json:"email_verified,omitempty"`
	Msg              string `json:"msg,omitempty"`
}

type ApiAuthChangeEmail

type ApiAuthChangeEmail struct {
	NewEmail string `json:"new_email" form:"new_email"`
	OldEmail string `json:"old_email" form:"old_email"`
	Pw       string `json:"password" form:"password"`
}

type ApiAuthChangePassword

type ApiAuthChangePassword struct {
	Email string `json:"email"  form:"email"   binding:"required,email"`
	NewPw string `json:"new_pw" form:"new_pw"  binding:"required"`
	OldPw string `json:"old_pw" form:"old_pw"  binding:"required"`
}

------------------------------------------------------------------------------------------------------------------------- jwtConfig.authInternalHandlers["POST:/api/v1/auth/change-password"] = authHandleChangePassword // change passwword

type ApiAuthEmailValidate

type ApiAuthEmailValidate struct {
	EmailVerifyToken string `json:"email_verify_token" form:"email_verify_token"   binding:"required"`
}

type ApiAuthLogin

type ApiAuthLogin struct {
	Email    string `json:"email"      form:"email"       binding:"required,email"`
	Pw       string `json:"password"   form:"password"    binding:"required"`
	AmIKnown string `json:"am_i_known" form:"am_i_known"`
}

Input for login

type ApiAuthRecoverPassword03SetPassword

type ApiAuthRecoverPassword03SetPassword struct {
	Email         string `json:"email"          form:"email"           binding:"required,email"`
	NewPw         string `json:"new_pw"         form:"new_pw"          binding:"required"`
	RecoveryToken string `json:"recovery_token" form:"recovery_token"  binding:"required"`
}

type ApiAuthRecoveryPassword02FetchInfo

type ApiAuthRecoveryPassword02FetchInfo struct {
	Email         string `json:"email"          form:"email"            binding:"required,email"`
	RecoveryToken string `json:"recovery_token" form:"recovery_token"   binding:"required"`
}

type ApiAuthRegister

type ApiAuthRegister struct {
	Email     string `json:"email"      form:"email"       binding:"required,email"`
	FirstName string `json:"first_name" form:"first_name"  binding:"required"`
	LastName  string `json:"last_name"  form:"last_name"   binding:"required"`
	Pw        string `json:"password"   form:"password"          binding:"required"`
}

Input for api endpoint

type ApiAuthSetDebugFlag

type ApiAuthSetDebugFlag struct {
	Name    string `json:"name"          form:"name"           binding:"required"`
	Value   string `json:"value"         form:"value"          binding:"required"`
	AuthKey string `json:"auth_key"		 form:"auth_key"`
}

type ApiAuthSipLogin0

type ApiAuthSipLogin0 struct {
	Email      string `json:"email"       form:"email"        binding:"required,email"`
	Commitment string `json:"commitment"  form:"commitment"   binding:"required"` // this is the 'x' value, the random from the client.
}

type ApiAuthSipRegister

type ApiAuthSipRegister struct {
	Email     string `json:"email"      form:"email"       binding:"required,email"`
	FirstName string `json:"first_name" form:"first_name"  binding:"required"`
	LastName  string `json:"last_name"  form:"last_name"   binding:"required"`
	Validator string `json:"validator"  form:"validator"   binding:"required"`
}

type ApiAuthUn

type ApiAuthUn struct {
	Email string `json:"email" form:"email"`
}

type ApiAuthValidate2faToken

type ApiAuthValidate2faToken struct {
	Email    string `json:"email"      form:"email"      binding:"required"`
	TmpToken string `json:"tmp_token"  form:"tmp_token"  binding:"required"`
	X2FaPin  string `json:"x2fa_pin"   form:"x2fa_pin"   binding:"required"`
	AmIKnown string `json:"am_i_known" form:"am_i_known"`
}

authHandleValidate2faToken is called after login to validate a 2fa token and after registration to comnplete the registration.

This calls: "q_auth_v1_validate_2fa_token ( $1, $2, $3, $4 )" in the databse. This sets q_qr_users.setup_complete_2fa = 'y' to mark the account as fully registered. Login requires that this is a 'y' before login occures.

type ApiEmail

type ApiEmail struct {
	Email string `json:"email"  form:"email"  binding:"required,email"`
}

type ApiEmailOptional

type ApiEmailOptional struct {
	Email string `json:"email"  form:"email"`
}

type EmailConfirmSuccess

type EmailConfirmSuccess struct {
	Status   string `json:"status"`
	TmpToken string `json:"tmp_token"`
}

type GinLoginType

type GinLoginType struct {
	Path     string
	Method   string
	Fx       func(c *gin.Context)
	UseLogin int // 0 required - or not found in table, 1 not required, 2 optional
}

type JwtClaims

type JwtClaims struct {
	AuthToken string `json:"auth_token"`
	jwt.StandardClaims
}

type LoginSuccess

type LoginSuccess struct {
	Status     string `json:"status"`
	TmpToken   string `json:"tmp_token,omitempty"` // May be "" - used in 2fa part 1 / 2
	Token      string `json:"token,omitempty"`     // the JWT Token???
	Require2fa string `json:"require_2fa,omitempty"`
	Privileges string `json:"privileges,omitempty"`
	FirstName  string `json:"first_name,omitempty"`
	LastName   string `json:"last_name,omitempty"`
}

Output - returned on success copier.Copy(&employee, &user)

type RecoverPassword02Success

type RecoverPassword02Success struct {
	Status    string `json:"status"`
	Email     string `json:"email,omitempty"`
	FirstName string `json:"first_name,omitempty"`
	LastName  string `json:"last_name,omitempty"`
}

type RecoverPassword03SetPasswordSuccess

type RecoverPassword03SetPasswordSuccess struct {
	Status    string `json:"status"`
	FirstName string `json:"first_name,omitempty"`
	LastName  string `json:"last_name,omitempty"`
}

type RegenOTPSuccess

type RegenOTPSuccess struct {
	Status string   `json:"status"`
	Otp    []string `json:"otp"`
	Msg    string   `json:"msg"`
}

type RegisterSuccess

type RegisterSuccess struct {
	Status      string   `json:"status"`
	URLFor2faQR string   `json:"url_for_2fa_qr"`
	TotpSecret  string   `json:"totp_secret"`
	Otp         []string `json:"otp"`
	TmpToken    string   `json:"tmp_token,omitempty"` // May be "" - used in 2fa part 1 / 2
}

type ReturnStatusSuccess

type ReturnStatusSuccess struct {
	Status string `json:"status"`
	Msg    string `json:"msg"`
}

type ReturnSuccess

type ReturnSuccess struct {
	Status string `json:"status"`
}

type RvEmailConfirm

type RvEmailConfirm struct {
	StdErrorReturn
	TmpToken string `json:"tmp_token,omitempty"` // May be "" - used in 2fa part 1 / 2
}

type RvGetSecretType

type RvGetSecretType struct {
	StdErrorReturn
	Secret2fa string `json:"secret_2fa"`
	UserId    int    `json:"user_id"`
}

type RvLoginType

type RvLoginType struct {
	StdErrorReturn
	UserId      *int   `json:"user_id,omitempty"`
	AuthToken   string `json:"auth_token,omitempty"` // May be "" - meaning no auth.
	TmpToken    string `json:"tmp_token,omitempty"`  // May be "" - used in 2fa part 1 / 2
	Token       string `json:"token,omitempty"`      // the JWT Token???
	Require2fa  string `json:"require_2fa,omitempty"`
	Secret2fa   string `json:"secret_2fa,omitempty"`
	AccountType string `json:"account_type,omitempty"`
	Privileges  string `json:"privileges,omitempty"`
	FirstName   string `json:"first_name,omitempty"`
	LastName    string `json:"last_name,omitempty"`
}

type RvRecoverPassword01Setup

type RvRecoverPassword01Setup struct {
	StdErrorReturn
	RecoveryToken string `json:"recovery_token,omitempty"`
	FirstName     string `json:"first_name,omitempty"`
	LastName      string `json:"last_name,omitempty"`
}

type RvRecoverPassword02FetchInfo

type RvRecoverPassword02FetchInfo struct {
	StdErrorReturn
	Email     string `json:"email,omitempty"`
	FirstName string `json:"first_name,omitempty"`
	LastName  string `json:"last_name,omitempty"`
}

type RvRecoverPassword03SetPassword

type RvRecoverPassword03SetPassword struct {
	StdErrorReturn
	RecoveryToken string `json:"recovery_token,omitempty"`
	FirstName     string `json:"first_name,omitempty"`
	LastName      string `json:"last_name,omitempty"`
}

type RvRegenOTPType

type RvRegenOTPType struct {
	StdErrorReturn
	Otp []string `json:"otp"`
}

type RvRegisterType

type RvRegisterType struct {
	StdErrorReturn
	UserId           *int     `json:"user_id,omitempty"`
	EmailVerifyToken string   `json:"email_verify_token,omitempty"`
	Require2fa       string   `json:"require_2fa,omitempty"`
	Secret2fa        string   `json:"secret_2,omitempty"`
	URLFor2faQR      string   `json:"url_for_2fa_qr"`
	TotpSecret       string   `json:"totp_secret"`
	Otp              []string `json:"otp"`
	TmpToken         string   `json:"tmp_token,omitempty"` // May be "" - used in 2fa part 1 / 2
}

Returned form stored procedure

l_data = '{"status":"error","msg":"Account already exists.  Please login or recover password.","code":"0007","location":"m4___file__ m4___line__"}';
	||', "user_id":' ||coalesce(to_json(l_user_id)::text,'""')

type RvValidate2faTokenType

type RvValidate2faTokenType struct {
	StdErrorReturn
	UserId         *int   `json:"user_id,omitempty"`
	AuthToken      string `json:"auth_token,omitempty"` // May be "" - meaning no auth.
	Token          string `json:"token,omitempty"`
	Expires        string `json:"expires,omitempty"`
	Privileges     string `json:"privileges,omitempty"`
	Secret2fa      string `json:"secret_2fa,omitempty"`
	EmailValidated string `json:"email_validated,omitempty"`
}

type SQLAcctStatusType

type SQLAcctStatusType struct {
	SetupComplete2fa string `json:"setup_complete_2fa" db:"setup_complete_2fa"`
	EmailVerified    string `json:"email_verified"     db:"email_verified"`
}

type SQLIntType

type SQLIntType struct {
	X *int
}

type SQLStringType

type SQLStringType struct {
	X string
}

-------------------------------------------------------------------------------------------------------------------------

type SQLUserIdPrivsType

type SQLUserIdPrivsType struct {
	UserId     int    `json:"user_id,omitempty" db:"user_id"`
	Privileges string `json:"privileges,omitempty"`
}

-------------------------------------------------------------------------------------------------------------------------

type SetDebugFlagSuccess

type SetDebugFlagSuccess struct {
	Status string `json:"status"`
}

type SipLogin0Success

type SipLogin0Success struct {
	Status     string `json:"status"`
	TmpToken   string `json:"tmp_token,omitempty"`
	Challenge  string `json:"challenge,omitempty"`
	Require2fa string `json:"require_2fa,omitempty"`
	Privileges string `json:"privileges,omitempty"`
	FirstName  string `json:"first_name,omitempty"`
	LastName   string `json:"last_name,omitempty"`
}

type SipLogin1Success

type SipLogin1Success struct {
	Status    string `json:"status"`
	TmpToken  string `json:"tmp_token,omitempty"`
	Challenge string `json:"challenge,omitempty"`
}

-------------------------------------------------------------------------------------------------------------------------

type SipLogin22uccess

type SipLogin22uccess struct {
	Status   string `json:"status"`
	TmpToken string `json:"tmp_token,omitempty"`
	Proof    string `json:"proof,omitempty"`
}

-------------------------------------------------------------------------------------------------------------------------

type StdErrorReturn

type StdErrorReturn struct {
	Status   string `json:"status"`
	Msg      string `json:",omitempty"`
	Code     string `json:",omitempty"`
	Location string `json:",omitempty"`
	LogUUID  string `json:",omitempty"`
}

type Validate2faTokenSuccess

type Validate2faTokenSuccess struct {
	Status         string `json:"status"`
	Token          string `json:"token,omitempty"`
	EmailValidated string `json:"email_validated,omitempty"`
	Expires        string `json:"expires,omitempty"`
}

type X2faSetupSuccess

type X2faSetupSuccess struct {
	Status string `json:"status"`
	Msg    string `json:"msg"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL