tokendb

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 10 Imported by: 0

README

tokendb

A secure, SQLite-backed Go package for managing user tokens with customizable purposes (e.g., login sessions, password resets, API keys). Uses Argon2id for token hashing and enforces strict validation to prevent common vulnerabilities (e.g., SQL injection).

Features

  • Predefined Token Purposes – Standardized use cases (login sessions, password resets, etc.).
  • Secure Hashing – Tokens are hashed with Argon2id (configurable memory/thread costs).
  • Automatic Cleanup – Remove expired/revoked tokens via CleanupInvalidTokens.
  • Device Awareness – Track device fingerprints and user agents.
  • Concurrency-Safe – Thread-safe SQLite operations.
  • Validation – UUID checks, purpose whitelisting, and lifetime enforcement.

Security Notes:

  • Tokens are never stored in plaintext (only hashed versions persist).
  • SQL queries use prepared statements to prevent injection.
  • Supports single-use or multi-device tokens.

Installation

go get bitbucket.org/sifhg/tokendb

Usage

Initialize the Database
import (
	"database/sql"
	"bitbucket.org/sifhg/tokendb"
)

tokenDB, err := tokendb.InitDB("/path/to/tokens.db")
if err != nil {
	// Handle error (e.g., database already exists)
}
defer tokenDB.Close()
AddToken Function
token, err := tokendb.AddToken(
	tokenDB,
	"user-uuid-here",          // Valid UUIDv4
	tokendb.PurposeLoginSession, // Predefined purpose
	24 * time.Hour,            // Lifetime
	"device-fingerprint-123",  // Optional: track device
	"Mozilla/5.0",             // Optional: user agent
	false,                     // Allow only on this device?
)
if err != nil {
	// Handle error (e.g., invalid purpose)
}
fmt.Println("New token:", token.Token) // Share this with the user
IsValid Function
isValid, err := tokendb.IsValid(tokenDB, tokendb.TokenInfo{
	TokenID: token.TokenID,
	Token:   "token-string-from-user",
})
if err != nil {
	// Handle error (e.g., token not found)
}
if !isValid {
	// Token expired/revoked
}
RevokeToken Function
// Revoke a single token
err := tokendb.RevokeToken(tokenDB, token.TokenID)

// Revoke ALL tokens for a user (e.g., on logout)
err := tokendb.RevokeAllTokensForUser(tokenDB, "user-uuid-here")
GetAllTokensForUser Function
tokens, err := tokendb.GetAllTokensForUser(tokenDB, "user-uuid-here")
for _, t := range tokens {
	fmt.Printf(
		"ID: %s, Purpose: %s, Valid: %t\n",
		t.TokenID, t.Purpose, t.IsValid,
	)
}
deletedCount, err := tokendb.CleanupInvalidTokens(tokenDB)
fmt.Printf("Deleted %d invalid tokens\n", deletedCount)

Token Purposes

Use these predefined constants for purpose:

| Constant               | Description                    |
| ---------------------- | ------------------------------ |
| `PurposeLoginSession`  | User authentication session.   |
| `PurposeUserDelete`    | Account deletion confirmation. |
| `PurposePasswordReset` | Password reset flow.           |
| `PurposeAPIKey`        | Long-lived API access.         |
| `PurposeEmailVerify`   | Email verification.            |

License

MIT. See LICENSE for details.

Documentation

Index

Constants

View Source
const (
	PurposeLoginSession  = "login_session"  // User authentication session
	PurposeUserDelete    = "user_delete"    // Account deletion confirmation
	PurposePasswordReset = "password_reset" // Password reset flow
	PurposeAPIKey        = "api_key"        // Long-lived API access
	PurposeEmailVerify   = "email_verify"   // Email verification
)
View Source
const DateTimeLayout = time.RFC3339

Variables

View Source
var (
	ErrInitialisation              = errors.New("failed initialising token database")
	ErrInvalidPurpose              = errors.New("invalid purpose")
	ErrInvalidRow                  = errors.New("invalid database row")
	ErrInvalidUserId               = errors.New("invalid user ID")
	ErrSQLInjectionAttemptDetected = errors.New("SQL injection detected")
	ErrTokenDatabaseAlreadyExists  = errors.New("token database already exists")
	ErrTokenNotFound               = errors.New("token not found")
	ErrTokenNotValid               = errors.New("token is not valid")
)
View Source
var HashConfig hashwrapper.HashConfig = hashwrapper.HashConfig{
	Time:    uint32(1),
	Memory:  uint32(32),
	Threads: uint8(1),
	KeyLen:  uint32(4),
	SaltLen: 2,
}

Functions

func CleanupInvalidTokens

func CleanupInvalidTokens(tokenDB *dbwrapper.DBWrapper) (int64, error)

func InitDB

func InitDB(dbPath string) (*dbwrapper.DBWrapper, error)

func InitEncryptedDB

func InitEncryptedDB(dbPath string, dbKey string) (*dbwrapper.DBWrapper, error)

func IsInvalidPurpose

func IsInvalidPurpose(err error) bool

func IsInvalidUserId

func IsInvalidUserId(err error) bool

func IsTokenNotFound

func IsTokenNotFound(err error) bool

func IsTokenNotValid

func IsTokenNotValid(err error) bool

func IsValid

func IsValid(tokenDB *dbwrapper.DBWrapper, tokenInfo TokenInfo) (bool, error)

func NewErrInvalidPurpose

func NewErrInvalidPurpose(purpose string) error

func NewErrInvalidRow

func NewErrInvalidRow(missingColumn string) error

func NewErrInvalidUserId

func NewErrInvalidUserId(userID string) error

func NewErrTokenNotFound

func NewErrTokenNotFound(condition string) error

func RevokeAllTokensForUser

func RevokeAllTokensForUser(db *dbwrapper.DBWrapper, userID string) error

func RevokeToken

func RevokeToken(tokenDB *dbwrapper.DBWrapper, tokenID string) error

Types

type TokenDetails

type TokenDetails struct {
	TokenHash         string
	TokenID           uuid.UUID
	UserID            uuid.UUID
	Purpose           string
	CreatedAt         time.Time
	ExpiresAt         time.Time
	RevokedAt         sql.NullString
	DeviceFingerprint string
	UserAgent         string
	IsValid           bool
}

func GetAllTokensForUser

func GetAllTokensForUser(tokenDB *dbwrapper.DBWrapper, userID string) ([]*TokenDetails, error)

func GetTokenDetails

func GetTokenDetails(tokenDB *dbwrapper.DBWrapper, tokenInfo TokenInfo) (*TokenDetails, bool, error)

type TokenInfo

type TokenInfo struct {
	TokenID string
	Token   string
}

func AddToken

func AddToken(
	tokenDB *dbwrapper.DBWrapper,
	userID string,
	purpose string,
	lifetime time.Duration,
	deviceFingerprint string,
	userAgent string,
	allowOnMultipleDevices bool,
) (TokenInfo, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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