anode

package
v0.9.12 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JWTMapClaimSignedString

func JWTMapClaimSignedString(claims jwt.MapClaims, secretKey []byte) (tokenString string, err error)

func JWTMapClaimValidate

func JWTMapClaimValidate(tokenString string, secretKey []byte, mapMatch map[string]string) (username auser.Username, isExpired bool, err error)

JWTMapClaimValidate validates a JWT token and matches claims against the provided mapMatch. If the mapMatch values match the claims, it returns the username from the claims.

func NewClaims

func NewClaims(username auser.Username, expirationTime time.Time) jwt.MapClaims

NewClaims creates a new JWT claims map with the specified username and expiration time.

func NewClaimsInMinutes

func NewClaimsInMinutes(username auser.Username, expirationTimeMinutes int) jwt.MapClaims

NewClaimsInMinutes creates a new JWT claims map with the specified username and expiration time given in minutes from now.

Types

type AdminLock

type AdminLock struct {
	// IsPasswordLocked indicates whether the password is locked.
	// This can be set to true in two scenarios:
	// 1. The admin manually sets this value to true when managing the user account.
	// 2. The password is empty or the account requires a password reset.
	IsPasswordLocked bool `json:"isPasswordLocked,omitempty"`

	// Date is the actual date when the account was locked.
	Date *time.Time `json:"lockedDate,omitempty"`

	// Message provides the reason for the account lock.
	Message string `json:"message,omitempty"`

	// RequestResetPassword is the date when the admin requested the user to create/reset the password.
	// If this is set, the user is forced to set the password on login, regardless of the IsPasswordLocked value.
	// If IsPasswordLocked is true and RequestResetPassword is valid, the password can only be reset via an email link,
	// whether initiated by the admin or through the forgot-login process.
	RequestResetPassword *time.Time `json:"requestResetPassword,omitempty"`
}

AdminLock represents the lock status of an admin account.

type JWTUserToken

type JWTUserToken struct {
	AccessToken  string `json:"accessToken,omitempty"`  // Access tokens are expected to be JWT.
	RefreshToken string `json:"refreshToken,omitempty"` // Refresh tokens are expected to be JWT.
	// contains filtered or unexported fields
}

JWTUserToken handles JWT-related functionality for user tokens.

func (*JWTUserToken) ClearToken

func (jt *JWTUserToken) ClearToken()

ClearToken clears the access and refresh tokens.

func (*JWTUserToken) GenerateTokensWithUsername

func (jt *JWTUserToken) GenerateTokensWithUsername(username auser.Username, accessExpiresInHours, refreshExpiresInDays int, secretKey []byte) (string, string, error)

GenerateTokensWithUsername generates an access token and a refresh token for the user.

func (*JWTUserToken) GetIsTokenValid

func (jt *JWTUserToken) GetIsTokenValid() bool

GetIsTokenValid returns the token validity status.

func (*JWTUserToken) GetRefreshTokenExpiration

func (jt *JWTUserToken) GetRefreshTokenExpiration() time.Time

GetRefreshTokenExpiration returns the refresh token expiration time.

func (*JWTUserToken) GetTokenExpiration

func (jt *JWTUserToken) GetTokenExpiration() time.Time

GetTokenExpiration returns the token expiration time.

func (*JWTUserToken) RefreshAccessTokenWithSecretKey

func (jt *JWTUserToken) RefreshAccessTokenWithSecretKey(username auser.Username, secretKey []byte) (string, error)

RefreshAccessTokenWithSecretKey generates a new access token using the refresh token.

func (*JWTUserToken) SetTokenExpiration

func (jt *JWTUserToken) SetTokenExpiration(tokenExpires time.Time)

SetTokenExpiration sets the token expiration time.

func (*JWTUserToken) ValidateTokenWithSecretKey

func (jt *JWTUserToken) ValidateTokenWithSecretKey(secretKey []byte) error

ValidateTokenWithSecretKey validates the access and refresh tokens using the provided secret key.

func (*JWTUserToken) VerifyTokenTimeWithSecretKey

func (jt *JWTUserToken) VerifyTokenTimeWithSecretKey(tokenString string, secretKey []byte) (bool, *time.Time, error)

VerifyTokenTimeWithSecretKey verifies the JWT token and returns the expiration time.

func (*JWTUserToken) VerifyTokenWithSecretKey

func (jt *JWTUserToken) VerifyTokenWithSecretKey(secretKey []byte) (bool, error)

VerifyTokenWithSecretKey verifies the JWT token stored in the AccessToken field.

type RoboCredential

type RoboCredential struct {
	PublicKey        acrypt.CryptKeyBase64 `json:"publicKey,omitempty"`    // Subscriber's public key
	PrivateKey       acrypt.SecretsValue   `json:"privateKey"`             // Secure storage for private key
	AccessToken      string                `json:"accessToken,omitempty"`  // JWT Access Token
	RefreshToken     string                `json:"refreshToken,omitempty"` // JWT Refresh Token
	TokenExpiresAt   time.Time             `json:"-"`                      // Expiration time for the access token
	RefreshExpiresAt time.Time             `json:"-"`                      // Expiration time for the refresh token
	IsTokenValid     bool                  `json:"-"`                      // Tracks token validity
	// contains filtered or unexported fields
}

RoboCredential securely manages credentials for hybrid Pub-Priv Key and JWT authentication.

func (*RoboCredential) GenerateKeyPair

func (rc *RoboCredential) GenerateKeyPair(masterPassword string, durationMinutes int) error

func (*RoboCredential) GetDecodedPrivateKey

func (rc *RoboCredential) GetDecodedPrivateKey(masterPassword string) ([]byte, error)

GetDecodedPrivateKey retrieves the decoded private key from secure storage.

func (*RoboCredential) InvalidateTokens

func (rc *RoboCredential) InvalidateTokens()

InvalidateTokens explicitly invalidates all JWT tokens.

func (*RoboCredential) RefreshAccessToken

func (rc *RoboCredential) RefreshAccessToken(refreshFunc func(string) (string, time.Time, error)) error

RefreshAccessToken uses the refresh token to obtain a new access token.

func (*RoboCredential) RotateKeys

func (rc *RoboCredential) RotateKeys(masterPassword string) error

func (*RoboCredential) Validate

func (rc *RoboCredential) Validate() error

Validate ensures that all required fields are present and valid. Required fields are those needed for two peers to make a connection. The PrivateKey check only ensures a value is present and doesn't try to decode the key.

func (*RoboCredential) ValidateToken

func (rc *RoboCredential) ValidateToken() bool

ValidateToken checks whether the access token is still valid.

type UserAccount

type UserAccount struct {
	// IsDeactivated indicates whether the user account is deactivated.
	IsDeactivated bool `json:"isDeactivated"`

	// MFA contains Multi-Factor Authentication settings.
	MFA struct {
		// TOTP holds the current TOTP (Time-based One-Time Password) configuration.
		TOTP UserAccountIsOnMFA `json:"totp,omitempty"`
		// TOTPNew holds the new TOTP configuration when regenerating a TOTP key.
		// This keeps the original TOTP in place to prevent a security leak.
		TOTPNew *UserAccountIsOnMFA `json:"totpNew,omitempty"`
	} `json:"mfa,omitempty"`

	// Email is required.
	// Depending on the site operation, email could parallel the username.
	// For Username, see UserVault.Credentials.Username.
	Email aemail.EmailAddress `json:"email,omitempty"`

	// Phone is optional but could be required based on the system implementing this struct.
	// Depending on the site operation, email could parallel the username.
	Phone acontact.Phone `json:"phone,omitempty"`

	// Logins holds the history of login sessions.
	Logins asessions.LoginSessionDeviceDates `json:"logins,omitempty"`

	// LDS holds the legal document signatures.
	LDS alegal.LegalDocSignatures `json:"lds"`

	// Roles holds the roles assigned to the user.
	Roles asessions.Roles `json:"roles"`

	// AdminLock holds the admin lock status of the account.
	AdminLock AdminLock `json:"adminLock,omitempty"`
}

UserAccount represents a user's account with various attributes and settings.

func (*UserAccount) AddDeviceLogin

func (ua *UserAccount) AddDeviceLogin(device string, realIP string, maxHistory int) *asessions.LoginSessionDeviceDate

AddDeviceLogin adds a new device login to the user's login history. It trims the device name, sets the IP address, and records the current time. If the login history exceeds maxHistory, the oldest entry is removed.

func (*UserAccount) AddLDSByKey

func (ua *UserAccount) AddLDSByKey(key alegal.LegalDocSignatureKey, appendIfFound bool, effectiveDate *time.Time) (hasChanges bool)

AddLDSByKey adds a legal document signature by key. If appendIfFound is false and the key is found, no changes are made. If the key is not found or appendIfFound is true, a new signature is added.

type UserAccountIsOnMFA

type UserAccountIsOnMFA struct {
	// IsOn indicates whether MFA is enabled for the user account.
	IsOn bool `json:"isOn,omitempty"`

	// Created is the timestamp when MFA was enabled.
	Created *time.Time `json:"created,omitempty"`

	// Verified is the timestamp when MFA was verified.
	Verified *time.Time `json:"verified,omitempty"`
}

UserAccountIsOnMFA represents the Multi-Factor Authentication (MFA) status of a user account.

func (*UserAccountIsOnMFA) IsVerified

func (uat *UserAccountIsOnMFA) IsVerified() bool

IsVerified checks if the MFA has been verified. Returns true if the Verified timestamp is set and not zero.

type UserBase

type UserBase struct {
	// UID is the primary user ID for the node.
	UID auser.UID `json:"uid,omitempty"`

	// LanguageType defines the language that should be displayed for this user.
	// LanguageType logic is as follows:
	// 1. If the user is unknown, check if the existing session has a LanguageType:
	//    a. If yes, then use it.
	//    b. If no, then use the LanguageType from the client-browser.
	// 2. If the user is known, then get the preferred language from the saved user:
	//    a. If the preferred language is empty, then use the existing session language.
	//    b. If both preferred language and existing session language are unknown, then use the LanguageType from the client-browser.
	// Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
	LanguageType autils.LanguageType `json:"langType"`

	// LastAccess is optional and can be used in different ways.
	// For example, LastAccess may represent:
	// 1. The last "profile/domain switch" of the user (reasonable).
	// 2. It could be updated each time an action was performed on the account (heavier CPU).
	// 3. It is the same as the loginDate (not recommended as it could be confused with #1).
	LastAccess *time.Time `json:"lastAccess,omitempty"`
}

UserBase is the base struct upon which a UserConfig can be created. Different sites/nodes/services will have different user requirements. The building blocks are spread around the User* structs (e.g., UserAccount/Vault/Profile/Credential). For an example of building a user config, see "userbase_test.go".

func (*UserBase) GetLanguageType

func (ub *UserBase) GetLanguageType() autils.LanguageType

GetLanguageType returns the language type of the user.

func (*UserBase) GetLastAccess

func (ub *UserBase) GetLastAccess() *time.Time

GetLastAccess returns the last access time of the user.

func (*UserBase) GetUID

func (ub *UserBase) GetUID() auser.UID

GetUID returns the user's UID.

type UserCredential

type UserCredential struct {
	JWTUserToken
	Username auser.Username `json:"username,omitempty"`
	Password string         `json:"password,omitempty"` // Password is a hashed password using Argon2id.

	// AuthName is optionally used as the name of the
	// connection adapter, link or id used for authentication.
	// Implementation depends on the calling program.
	AuthName string `json:"authName"`

	WhitelistIPs []string `json:"whitelistIPs,omitempty"`
	// contains filtered or unexported fields
}

UserCredential represents a basic node user credential with tokens.

func (*UserCredential) CheckAuthorizationHeaderWithSecretKey

func (uc *UserCredential) CheckAuthorizationHeaderWithSecretKey(authHeader string, secretKey []byte) (bool, error)

CheckAuthorizationHeaderWithSecretKey processes the Authorization header for Basic or Bearer token authentication.

func (*UserCredential) CheckClientIP

func (uc *UserCredential) CheckClientIP(clientIP string) bool

CheckClientIP checks if the client's IP is in the whitelist.

func (*UserCredential) CheckPassword

func (uc *UserCredential) CheckPassword(secret string) (bool, error)

CheckPassword compares a plaintext secret with the hashed secret stored in the Password field.

func (*UserCredential) EncryptPassword

func (uc *UserCredential) EncryptPassword(secret string) error

EncryptPassword hashes the secret using Argon2id and stores it in the Password field.

func (*UserCredential) GenerateTokensWithSecretKey

func (uc *UserCredential) GenerateTokensWithSecretKey(accessExpiresInHours, refreshExpiresInDays int, secretKey []byte) (string, string, error)

GenerateTokensWithSecretKey generates an access token and a refresh token using the Credential's Username and passed-in secretKey.

func (*UserCredential) GetAccessToken

func (uc *UserCredential) GetAccessToken() string

GetAccessToken returns the access token.

func (*UserCredential) GetHasCredential

func (uc *UserCredential) GetHasCredential() (isJWT, isPassword, ok bool)

GetHasCredential returns if one credential form is valid.

func (*UserCredential) GetHasJWT

func (uc *UserCredential) GetHasJWT() bool

GetHasJWT returns if this credential uses JWT.

func (*UserCredential) GetHasPassword

func (uc *UserCredential) GetHasPassword() bool

GetHasPassword returns if this credential uses passwords.

func (*UserCredential) GetParsedWhitelistIPs

func (uc *UserCredential) GetParsedWhitelistIPs() anetwork.NetIPs

func (*UserCredential) GetRefreshToken

func (uc *UserCredential) GetRefreshToken() string

GetRefreshToken returns the refresh token.

func (*UserCredential) GetUsername

func (uc *UserCredential) GetUsername() auser.Username

GetUsername returns the username.

func (*UserCredential) GetWhitelistIPs

func (uc *UserCredential) GetWhitelistIPs() []string

GetWhitelistIPs returns the access white-listed IPs.

func (*UserCredential) MatchUsernamePassword

func (uc *UserCredential) MatchUsernamePassword(username auser.Username, password string) bool

MatchUsernamePassword checks if the provided username and password match the stored ones. By default case sensitivity for username matches is false.

func (*UserCredential) MatchUsernamePasswordWithCaseSensitive

func (uc *UserCredential) MatchUsernamePasswordWithCaseSensitive(username auser.Username, password string, isUserCaseSensitive bool) bool

MatchUsernamePasswordWithCaseSensitive checks if the provided username and password match the stored ones with an optional case-sensitivity modifier for the username.

func (*UserCredential) ValidateWithSecretKey

func (uc *UserCredential) ValidateWithSecretKey(secretKey []byte) error

ValidateWithSecretKey validates the UserCredential.

func (*UserCredential) WhitelistIPContains

func (uc *UserCredential) WhitelistIPContains(ipTarget string) (hasParsedIPs, containsIP bool)

WhitelistIPContains checks if the ipTarget is in the list of parsed IPs or subnets.

type UserVault

type UserVault struct {
	// Credential holds the user's credentials.
	Credential UserCredential `json:"credential,omitempty"`

	// TOTP holds the current TOTP (Time-based One-Time Password) configuration.
	TOTP acrypt.TOTP `json:"totp,omitempty"`

	// TOTPNew holds the new TOTP configuration, if any.
	TOTPNew *acrypt.TOTP `json:"totpNew,omitempty"`

	// TokenBackups holds the backup tokens for the user.
	TokenBackupsDate *time.Time             `json:"tokenBackupsDate,omitempty"`
	TokenBackups     acrypt.MiniRandomCodes `json:"tokenBackups,omitempty"`

	// Support contains the support pin used to verify a user instead of a social security number.
	Support struct {
		Pin acrypt.IdBrief `json:"pin,omitempty"`
	} `json:"support,omitempty"`
}

UserVault represents a user's vault containing credentials, TOTP, and backup tokens.

func (*UserVault) GenerateTokenBackups

func (uv *UserVault) GenerateTokenBackups() error

GenerateTokenBackups generates backup tokens with default options.

func (*UserVault) GenerateTokenBackupsWithOptions

func (uv *UserVault) GenerateTokenBackupsWithOptions(maxCount int, length int) error

GenerateTokenBackupsWithOptions generates backup tokens with specified options.

func (*UserVault) GetCredential

func (uv *UserVault) GetCredential() *UserCredential

GetCredential returns a pointer to the user's credential.

func (*UserVault) GetSupportPin

func (uv *UserVault) GetSupportPin() acrypt.IdBrief

GetSupportPin returns the support pin.

func (*UserVault) HasTOTP

func (uv *UserVault) HasTOTP() bool

HasTOTP checks if the current TOTP configuration has a secret.

func (*UserVault) HasTOTPNew

func (uv *UserVault) HasTOTPNew() bool

HasTOTPNew checks if the new TOTP configuration exists and has a secret.

func (*UserVault) HasTokenBackups

func (uv *UserVault) HasTokenBackups() bool

HasTokenBackups checks if the vault has tokens that can be used for backup and recover.

Jump to

Keyboard shortcuts

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