motp

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 5 Imported by: 0

README

motp

A fast, thread-safe, generic in-memory OTP (One-Time Password) manager for Go with automatic cleanup.

Features

  • Generic Payloads: Attach any custom metadata to your OTP using Go generics.
  • Thread-Safe: Safe for concurrent access across goroutines.
  • Auto-Purge: Background worker automatically cleans up expired tokens.
  • Customizable: Functional options to tweak code length, character set, and cleanup intervals.

Installation


go get github.com/vladevelops/motp

Quick Start

package main

import (
	"fmt"
	"time"

	"github.com/vladevelops/motp"
)

type SessionData struct {
	UserID string
}

func main() {
	// 1. Initialize the generic OTP store for SessionData
	otp := motp.NewMemoryOtp[SessionData]()

	// 2. Generate an OTP
	code, err := otp.GenerateOTP(motp.OtpData[SessionData]{
		Key:        "user_123",
		Expiration: time.Now().Add(5 * time.Minute),
		Data:       SessionData{UserID: "usr_42"},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("Generated OTP:", code)

	// 3. Verify / Check the OTP
	data, err := otp.CheckOTP("user_123", code)
	if err != nil {
		fmt.Println("Invalid or expired OTP:", err)
		return
	}
	fmt.Printf("OTP valid! User ID: %s\n", data.Data.UserID)

	// 4. Manually revoke or clear an OTP
	if err := otp.DeleteOTP("user_123"); err != nil {
		fmt.Println("Error deleting OTP:", err)
	}
}

API Reference

The NewMemoryOtp[T]() constructor returns a thread-safe MemoryOtp[T] interface exposing three core methods:


type MemoryOtp[T any] interface {
    GenerateOTP(otp_data OtpData[T]) (code string, err error)
    CheckOTP(key, code string) (ret_otp OtpData[T], err error)
    DeleteOTP(key string) error
}

Method Overview
GenerateOTP(otp_data OtpData[T]) (code string, err error)

Generates a random OTP code tied to the provided Key and stores it alongside your custom data payload T.

  • Errors: Returns an error if the key is empty, the expiration is already in the past, or code generation fails.
CheckOTP(key, code string) (ret_otp OtpData[T], err error)

Validates an incoming OTP code against the given lookup key.

  • On Success: Returns the original OtpData[T] struct (including your custom payload).
  • Errors: Returns an error if the key doesn't exist, the token has expired, or the provided code doesn't match.
DeleteOTP(key string) error

Manually removes an OTP entry from memory before its scheduled expiration. Useful for explicitly invalidating sessions, handling manual cancellations, or cleaning up after consumption.

License

MIT

Documentation

Overview

Package motp provides a thread-safe, generic in-memory OTP manager.

It supports customizable character sets, expiration windows, and automatic background purging of stale tokens.

Basic usage:

store := motp.NewMemoryOtp[MyData]()
code, err := store.GenerateOTP(data)

Index

Constants

This section is empty.

Variables

View Source
var ErrCodeNotFound = errors.New("code not present")

Functions

This section is empty.

Types

type MemoryOtp

type MemoryOtp[T any] interface {
	GenerateOTP(otp_data OtpData[T]) (code string, err error)
	CheckIsKeyPresent(key string) (is_present bool)
	CheckOTP(key, code string) (ret_otp OtpData[T], err error)
	DeleteOTP(key string) error
}

func NewMemoryOtp

func NewMemoryOtp[T any](confs ...OtpConf[T]) MemoryOtp[T]

NewMemoryOtp creates and initializes a new in-memory OTP manager.

By default, it is initialized with:

  • Code length: 7 digits
  • Alphabet: "0973546281" (numeric)
  • Cleanup interval: 15 seconds

Custom configuration can be applied by passing functional options (confs). On creation, it automatically spins up a background goroutine to periodically purge expired OTPs from memory.

Returns a thread-safe implementation of the MemoryOtp interface.

type OtpConf

type OtpConf[T any] func(*otp_manager[T])

func WithOTPAlphabet

func WithOTPAlphabet[T any](new_alphabet string) OtpConf[T]

WithOTPAlphabet configures the set of characters used when generating OTP codes.

If not specified, the manager defaults to "0973546281".

func WithOTPCleanupTime

func WithOTPCleanupTime[T any](new_time time.Duration) OtpConf[T]

WithOTPCleanupTime sets the interval at which the background purger runs to remove expired OTPs from memory.

If not specified, the manager defaults to cleaning up every 15 seconds.

func WithOTPLen

func WithOTPLen[T any](opt_len int) OtpConf[T]

WithOTPLen sets a custom length for generated OTP codes.

If not specified, the manager defaults to generating 7-character codes.

type OtpData

type OtpData[T any] struct {
	Key        string
	Expiration time.Time
	Code       string
	Data       T
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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