otpgateway

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2019 License: MIT Imports: 5 Imported by: 0

README

OTP Gateway

OTP (One Time Password) Gateway is a standalone web app that provides a central gateway to verify user addresses such as e-mails and phone numbers or get a 2FA confirmations from thse addresses. An e-mail / SMTP verification provider is bundled and it is easy to write custom providers as Go plugins, for instance a plugin that uses Twilio to send out verification codes to phone numbers as text messages.

  • Use the built in web UI to easily integrate with existing applications
  • Use the HTTP/JSON APIs to build your own UI
  • Basic multi-tenancy with namespace+secret auth for seggregating

address otp email-otp

How does it work?

The application is agnostic of the address and the OTP or verification code involved. These are handled by provider plugins. Addresses are strings, for example, e-mail IDs, phone numbers, bank account numbers etc., and so are OTPs, for instance, 6 digit codes sent as SMSes or a penny value dropped to a bank account. The gateway pushes the OTP value to the user's target address and the user then has to view the OTP and enter it on the gateway's web view to complete the verification.

Providers

Providers are written as Go plugins that can be dynamically loaded into the gateway. An SMTP provider is bundled that enables e-mail address verifications by sending an OTP / verification link to user's e-mails. Refer to providers/smtp/smtp.go. To write a custom provider, copy the smtp plugin and change the methods to conform to the otpgateway.Provider interface and compile it as a go plugin (see the Makefile).

  • solsms - SMS provider for Solutions Infini (Indian gateway)

Usage

Download the latest release from the releases page or clone this repository and run make deps && make build. OTP Gateway requires a Redis installation.

  • Copy config.toml.sample to config.toml and edit the configuration
  • Run ./otpgateway --prov smtp.prov
Built in UI
  1. Generate an OTP for a user server side in your application: curl -u "myAppName:mySecret" -X PUT -d "to=john@doe.com&provider=smtp" localhost:9000/api/otp/uniqueIDForJohnDoe
  2. Use the OTPGateway() Javascript function (see the Javascript plugin section) to initiate the modal UI on your webpage. On receiving the Javascript callback, post it back to your application and confirm that the OTP is indeed verified: curl -u "myAppName:mySecret" -X POST localhost:9000/api/otp/uniqueIDForJohnDoe/status
Your own UI

Use the APIs described below to build your own UI.

API reference

List providers

curl localhost:9000/api/providers

{
  "status": "success",
  "data": ["smtp"]
}
Initiate an OTP for a user
curl -u "myAppName:mySecret" -X PUT -d "to=john@doe.com&provider=smtp&extra={\"yes\": true}" localhost:9000/api/otp/uniqueIDForJohnDoe
param description
:id (optional) A unique ID for the user being verified. If this is not provided, an random ID is generated and returned. It's good to send this as a permanent ID for your existing users to prevent users from indefinitely trying to generate OTPs. For instance, if your user's ID is 123 and you're verifying the user's e-mail, a simple ID can be MD5("email.123"). Important. The ID is only unique per namespace and not per provider.
provider ID of the provider plugin to use for verification. The bundled e-mail provider's ID is "smtp".
to (optional) The address of the user to verify, for instance, an e-mail ID for the "smtp" provider. If this is left blank, a view is displayed to collect the address from the user.
channel_description (optional) Description to show to the user on the OTP verification page. If left empty, it'll show the default description or help text from the provider plugin.
address_description (optional) Description to show to the user on the address collection page. If left empty, it'll show the default description or help text from the provider plugin.
otp (optional) The OTP or code to send to the user for verification. If this is left empty, a random OTP is generated and sent
extra (optional) An extra payload (JSON string) that will be returned with the OTP
{
  "status": "success",
  "data": {
    "namespace": "myAppName",
    "id": "uniqueIDForJohnDoe",
    "to": "john@doe.com",
    "channel_description": "",
    "address_description": "",
    "extra": { "yes": true },
    "provider": "smtp",
    "otp": "354965",
    "max_attempts": 5,
    "attempts": 5,
    "closed": false,
    "ttl": 300,
    "url": "http://localhost:9000/otp/myAppName/uniqueIDForJohnDoe"
  }
}
Validate an OTP entered by the user

Every incorrect validation here increments the attempts before further attempts are blocked. curl -u "myAppName:mySecret" -X POST -d "action=check&otp=354965" localhost:9000/api/otp/uniqueIDForJohnDoe

{
  "status": "success",
  "data": {
    "namespace": "myAppName",
    "id": "uniqueIDForJohnDoe",
    "to": "john@doe.com",
    "channel_description": "",
    "address_description": "",
    "extra": { "yes": true },
    "provider": "smtp",
    "otp": "354965",
    "max_attempts": 5,
    "attempts": 5,
    "closed": false,
    "ttl": 300,
    "url": "http://localhost:9000/otp/myAppName/uniqueIDForJohnDoe"
  }
}
Check whether an OTP request is verified

This is used to confirm verification after a callback from the built in UI flow. curl -u "myAppName:mySecret" -X POST localhost:9000/api/otp/uniqueIDForJohnDoe/status

{
  "status": "success",
  "data": {
    "namespace": "myAppName",
    "id": "uniqueIDForJohnDoe",
    "to": "john@doe.com",
    "channel_description": "",
    "address_description": "",
    "extra": { "yes": true },
    "provider": "smtp",
    "otp": "354965",
    "max_attempts": 5,
    "attempts": 5,
    "closed": false,
    "ttl": 300
  }
}

or an error such as

{ "status": "error", "message": "OTP not verified" }

Javascript plugin

The gateway comes with a Javascript plugin that enables easy integration of the verification flow into existing application. Once a server side call to generate an OTP is made and a namespace and id are obtained, calling OTPGateway() opens the verification UI in a modal popup, and once the user finishes the verification, gives you a callback.

<!-- The id #otpgateway-script is required for the script to work //-->
<script
  id="otpgateway-script"
  src="http://localhost:9000/static/otp.js"
></script>
<script>
  // 1. Make an Ajax call to the server to generate and send an OTP and return the
  // the :namespace and :id for the OTP.
  // 2. Invoke the verification UI for the user with the namespace and id values,
  // and a callback which is triggered when the user finishes the flow.
  OTPGateway(
    namespaceVal,
    idVal,
    function(nm, id) {
      console.log("finished", nm, id);

      // 3. Post the namespace and id to your server that will make the
      // status request to the gateway and on success, update the user's
      // address in your records as it's now verified.
    },
    function() {
      console.log("cancelled");
    }
  );
</script>

Licensed under the MIT license.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotExist = errors.New("the OTP does not exist")

ErrNotExist is thrown when an OTP (requested by namespace / ID) does not exist.

Functions

This section is empty.

Types

type NewProvider

type NewProvider func(jsonCfg []byte) (Provider, error)

NewProvider represents an initialisation function that takes an arbitrary JSON encoded configuration set and returns an instance of a Provider.

type OTP

type OTP struct {
	Namespace   string          `redis:"namespace" json:"namespace"`
	ID          string          `redis:"id" json:"id"`
	To          string          `redis:"to" json:"to"`
	ChannelDesc string          `redis:"channel_description" json:"channel_description"`
	AddressDesc string          `redis:"address_description" json:"address_description"`
	Extra       json.RawMessage `redis:"extra" json:"extra"`
	Provider    string          `redis:"provider" json:"provider"`
	OTP         string          `redis:"otp" json:"otp"`
	MaxAttempts int             `redis:"max_attempts" json:"max_attempts"`
	Attempts    int             `redis:"attempts" json:"attempts"`
	Closed      bool            `redis:"closed" json:"closed"`
	TTL         time.Duration   `redis:"-" json:"-"`
	TTLSeconds  float64         `redis:"-" json:"ttl"`
}

OTP contains the information about an OTP.

type Provider

type Provider interface {
	// ID returns the name of the Provider.
	ID() string

	// ChannelName returns the name of the channel the provider is
	// validating, for example "SMS" or "E-mail". This is displayed on
	// web views.
	ChannelName() string

	// ChannelDesc returns the help text that is shown to the end users describing
	// how the Provider handles OTP verification.
	// Eg: "We've sent a 6 digit code to your phone. Enter that here to verify
	//      your phone number"
	ChannelDesc() string

	// AddressName returns the name or label of the address for this provider.
	// For example "E-mail" for an e-mail provider or "Phone number" for an SMS provider.
	AddressName() string

	// AddressDesc returns the help text that is shown to the end users when
	// they're asked to enter their addresses (eg: e-mail or phone), if the OTP
	// registered without an address.
	AddressDesc() string

	// ValidateAddress validates the 'to' address the Provider
	// is supposed to send the OTP to, for instance, an e-mail
	// or a phone number.
	ValidateAddress(to string) error

	// Push pushes a message. Depending on the the Provider,
	// implementation, this can either cause the message to
	// be sent immediately or be queued waiting for a Flush().
	Push(to, subject string, body []byte) error

	// MaxAddressLen returns the maximum allowed length of the 'to' address.
	MaxAddressLen() int

	// MaxOTPLen returns the maximum allowed length of the OTP value.
	MaxOTPLen() int

	// MaxBodyLen returns the maximum permitted length of the text
	// that can be sent by the Provider.
	MaxBodyLen() int
}

Provider is an interface for a generic messaging backend, for instance, e-mail, SMS etc.

type ProviderConf

type ProviderConf struct {
	Template string `mapstructure:"template"`
	Subject  string `mapstructure:"subject"`
	Config   string `mapstructure:"config"`
}

ProviderConf represents the common confoguration types for a Provider.

type RedisConf

type RedisConf struct {
	Host      string        `mapstructure:"host"`
	Port      int           `mapstructure:"port"`
	Username  string        `mapstructure:"username"`
	Password  string        `mapstructure:"password"`
	MaxActive int           `mapstructure:"max_active"`
	MaxIdle   int           `mapstructure:"max_idle"`
	Timeout   time.Duration `mapstructure:"timeout"`
	KeyPrefix string        `mapstructure:"key_prefix"`
}

RedisConf contains Redis configuration fields.

type Store

type Store interface {
	// Set sets an OTP against an ID. Every Set() increments the attempts
	// count against the ID that was initially set.
	Set(namespace, id string, otp OTP) (OTP, error)

	// SetAddress sets (updates) the address on an existing OTP.
	SetAddress(namespace, id, address string) error

	// Check checks the attempt count and TTL duration against an ID.
	// Passing counter=true increments the attempt counter.
	Check(namespace, id string, counter bool) (OTP, error)

	// Close closes an OTP and marks it as done (verified).
	// After this, the OTP has to expire after a TTL or be deleted.
	Close(namespace, id string) error

	// Delete deletes the OTP saved against a given ID.
	Delete(namespace, id string) error
}

Store represents a storage backend where OTP data is stored.

func NewRedisStore

func NewRedisStore(c RedisConf) Store

NewRedisStore returns a Redis implementation of store.

Directories

Path Synopsis
providers

Jump to

Keyboard shortcuts

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