authy

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2018 License: MIT Imports: 14 Imported by: 0

README

Go Client for Authy API

A go library for using the Authy public API.

This API is not stable yet. Use it at your own risk.

Installation

If you don't have $GOPATH configured please type the following commands:

$ export GOPATH=$HOME/GoCode
$ mkdir -p $GOPATH/src
$ echo 'export GOPATH=$HOME/GoCode' >> ~/.bashrc

If you already have $GOPATH configured then install the package:

$ go get github.com/dcu/go-authy

Usage

To use this client you just need to import go-authy package and initialize it with your API KEY

import(
    "github.com/dcu/go-authy"
)
authyAPI := authy.NewAuthyAPI("#your_api_key")

Now that you have an Authy API object you can start sending requests.

Logger

By default, most operations and errors are logged to stderr. You can access authy.Logger to replace the logger. Example:

authy.Logger = log.New(...)

Creating Users

NOTE: User is matched based on cellphone and country code not e-mail. A cellphone is uniquely associated with an authy_id.

Creating users is very easy, you need to pass an email, a cellphone and a country code:

user, err := authyAPI.RegisterUser("new_user@email.com", 44, "405-342-5699", url.Values{})

in this case 44 is the country code(UK), use 1 for USA or Canada.

You can easily see if the user was created by calling user.Valid(). If request went right, you need to store the authy id in your database. Use user.Id to get this id in your database.

if user.Valid() {
    # store userResponse.User.Id in your user database
}

If something goes wrong user.Valid() will return false and you can see the errors using the following code

user.Errors

it returns a map[string]string explaining what went wrong with the request.

Verifying Tokens

To verify users you need the user id and a token. The token you get from the user through your login form.

verification, err := authyAPI.VerifyToken(authy-id, "token-entered-by-the-user", url.Values{"ip":{"<user ip>"}})

Once again you can use verification.Valid to verify whether the token was valid or not.

if verification.Valid() {
    # the user is valid
}

Requesting SMS Tokens

To request a SMS token you only need the user id.

sms, err := authyAPI.RequestSMS("authy-id", url.Values{})

As always, you can use sms.Valid() to verify if the token was sent. To be able to use this method you need to have activated the SMS plugin for your Authy App.

You should force this request to ensure the user will get a token even if it's using the Authy Mobile App.

Requesting token via phone call

To request a token via Phone Call you only need the user id.

phoneCall, err := authyAPI.RequestPhoneCall("authy-id", url.Values{"force":{"true"}})

As always, you can use phoneCall.Valid() to verify if the token was sent. To be able to use this method you need to have activated the Phone Call plugin for your Authy App.

You should force this request to ensure the user will get a token even if it's using the Authy App.

OneTouch

Sending an approval request

To send the push notification to a user use the method SendApprovalRequest which receives the Authy ID of the user, a message, the details to show to the user and any extra http param you want to send to the server.

details := authy.Details{
    "Type":      "SSH Server",
    "Server IP": serverIP,
    "User IP":   clientIP,
    "User":      os.Getenv("USER"),
}
approvalRequest, err := authyAPI.SendApprovalRequest(authyID, "Log to your ssh server", details, url.Values{})

Wait for approval request result

An easy way to get the response of the user is polling. The method WaitForApprovalRequest wraps all the polling code in just one method, use it as follows:

status, err := authyAPI.WaitForApprovalRequest(approvalRequest.UUID, 45, url.Values{})
if status == authy.OneTouchStatusApproved {
    // the request was approved.
}

Phone Verification

Start a phone verification

To start a phone verification use the following code:

verification, err := authyAPI.StartPhoneVerification(1, "555-555-5555",
authy.SMS)

Check phone verification

To check a phone verification use the following code:

verification, err := authyAPI.CheckPhoneVerification(1, "555-555-5555",
"000000")

if verification.Success {
}

Contributing

Get the code:

$ go get -u github.com/dcu/go-authy
$ cd $GOPATH/src/github.com/dcu/go-authy

and start coding.

Tests

To run the test just type:

make test
More...

You can fine the full API documentation in the official documentation page.

Documentation

Index

Constants

View Source
const (
	// SMS indicates the message will be delivered via SMS
	SMS = "sms"

	// Voice indicates the message will be delivered via phone call
	Voice = "call"
)

Variables

View Source
var (
	// Logger is the default logger of this package. You can override it with your own.
	Logger = log.New(os.Stderr, "[authy] ", log.LstdFlags)

	// DefaultTransport is the default transport struct for the HTTP client
	DefaultTransport = &http.Transport{
		Proxy:                 http.ProxyFromEnvironment,
		DialContext:           _Dialer.DialContext,
		MaxIdleConns:          128,
		IdleConnTimeout:       30 * time.Second,
		TLSHandshakeTimeout:   5 * time.Second,
		ExpectContinueTimeout: 3 * time.Second,
	}
)

Functions

This section is empty.

Types

type ApprovalRequest

type ApprovalRequest struct {
	HTTPResponse *http.Response

	Status   OneTouchStatus `json:"status"`
	UUID     string         `json:"uuid"`
	Notified bool           `json:"notified"`
}

ApprovalRequest is the approval request response.

func NewApprovalRequest

func NewApprovalRequest(response *http.Response) (*ApprovalRequest, error)

NewApprovalRequest returns an instance of ApprovalRequest.

func (*ApprovalRequest) Valid

func (request *ApprovalRequest) Valid() bool

Valid returns true if the approval request was valid.

type Authy

type Authy struct {
	APIKey  string
	BaseURL string
	Client  heimdall.Client
}

Authy contains credentials to connect to the Authy's API

func NewAuthyAPI

func NewAuthyAPI(apiKey string) *Authy

NewAuthyAPI returns an instance of Authy pointing to production.

func (*Authy) CheckPhoneVerification

func (authy *Authy) CheckPhoneVerification(countryCode int, phoneNumber string, verificationCode string, params url.Values) (*PhoneVerificationCheck, error)

CheckPhoneVerification checks the given verification code.

func (*Authy) DoRequest

func (authy *Authy) DoRequest(method string, path string, params url.Values) (*http.Response, error)

DoRequest performs a HTTP request to the Authy API

func (*Authy) FindApprovalRequest

func (authy *Authy) FindApprovalRequest(uuid string, params url.Values) (*ApprovalRequest, error)

FindApprovalRequest finds an approval request given its uuid.

func (*Authy) RegisterUser

func (authy *Authy) RegisterUser(email string, countryCode int, phoneNumber string, params url.Values) (*User, error)

RegisterUser register a new user given an email and phone number.

func (*Authy) RequestPhoneCall

func (authy *Authy) RequestPhoneCall(userID string, params url.Values) (*PhoneCallRequest, error)

RequestPhoneCall requests a phone call for the given user

func (*Authy) RequestSMS

func (authy *Authy) RequestSMS(userID string, params url.Values) (*SMSRequest, error)

RequestSMS requests a SMS for the given userID

func (*Authy) SendApprovalRequest

func (authy *Authy) SendApprovalRequest(userID string, message string, details Details, params url.Values) (*ApprovalRequest, error)

SendApprovalRequest sends a OneTouch's approval request to the given user.

func (*Authy) StartPhoneVerification

func (authy *Authy) StartPhoneVerification(countryCode int, phoneNumber string, via string, params url.Values) (*PhoneVerificationStart, error)

StartPhoneVerification starts the phone verification process.

func (*Authy) UserStatus

func (authy *Authy) UserStatus(id string, params url.Values) (*UserStatus, error)

UserStatus returns a set of data about a user.

func (*Authy) VerifyToken

func (authy *Authy) VerifyToken(userID string, token string, params url.Values) (*TokenVerification, error)

VerifyToken verifies the given token

func (*Authy) WaitForApprovalRequest

func (authy *Authy) WaitForApprovalRequest(uuid string, maxDuration time.Duration, params url.Values) (OneTouchStatus, error)

WaitForApprovalRequest waits until the status of an approval request has changed or times out.

type Details

type Details map[string]string

Details for OneTouch transaction

type OneTouchStatus

type OneTouchStatus string

OneTouchStatus is the type of the OneTouch statuses.

var (
	// OneTouchStatusApproved is the approved status of an approval request
	OneTouchStatusApproved OneTouchStatus = "approved"

	// OneTouchStatusPending is the pending status of an approval request
	OneTouchStatusPending OneTouchStatus = "pending"

	// OneTouchStatusDenied is the denied status of an approval request
	OneTouchStatusDenied OneTouchStatus = "denied"

	// OneTouchStatusExpired is the expired status of an approval request
	OneTouchStatusExpired OneTouchStatus = "expired"
)

type PhoneCallRequest

type PhoneCallRequest struct {
	HTTPResponse *http.Response
	Message      string `json:"message"`
}

PhoneCallRequest encapsulates the response from the Authy API

func NewPhoneCallRequest

func NewPhoneCallRequest(response *http.Response) (*PhoneCallRequest, error)

NewPhoneCallRequest returns an instance of a PhoneCallRequest

func (*PhoneCallRequest) Valid

func (request *PhoneCallRequest) Valid() bool

Valid returns true if the request was valid.

type PhoneVerificationCheck

type PhoneVerificationCheck struct {
	HTTPResponse *http.Response
	Message      string `json:"message"`
	Success      bool   `json:"success"`
}

PhoneVerificationCheck encapsulates the response from the Authy API when checking a phone verification.

func NewPhoneVerificationCheck

func NewPhoneVerificationCheck(response *http.Response) (*PhoneVerificationCheck, error)

NewPhoneVerificationCheck receives a http request, parses the body and return an instance of PhoneVerification

type PhoneVerificationStart

type PhoneVerificationStart struct {
	HTTPResponse *http.Response
	UUID         string `json:"uuid"`
	Message      string `json:"message"`
	Success      bool   `json:"success"`
	Carrier      string `json:"carrier"`
}

PhoneVerificationStart encapsulates the response from the Authy API when requesting a phone verification.

func NewPhoneVerificationStart

func NewPhoneVerificationStart(response *http.Response) (*PhoneVerificationStart, error)

NewPhoneVerificationStart receives a http request, parses the body and return an instance of PhoneVerification

type SMSRequest

type SMSRequest struct {
	HTTPResponse *http.Response
	Message      string `json:"message"`
}

SMSRequest encapsulates the response from the Authy API when requesting a SMS

func NewSMSRequest

func NewSMSRequest(response *http.Response) (*SMSRequest, error)

NewSMSRequest returns an instance of SMSRequest

func (*SMSRequest) Valid

func (request *SMSRequest) Valid() bool

Valid returns true if the SMS was sent

type TokenVerification

type TokenVerification struct {
	HTTPResponse *http.Response
	Message      string      `json:"message"`
	Token        string      `json:"token"`
	Success      interface{} `json:"success"`
}

TokenVerification encapsulates the response from Authy API when verifying a token.

func NewTokenVerification

func NewTokenVerification(response *http.Response) (*TokenVerification, error)

NewTokenVerification creates an instance of a TokenVerification

func (*TokenVerification) Valid

func (verification *TokenVerification) Valid() bool

Valid returns true if the verification was valid.

type User

type User struct {
	HTTPResponse *http.Response
	ID           string
	UserData     struct {
		ID int `json:"id"`
	} `json:"user"`
	Errors  map[string]string `json:"errors"`
	Message string            `json:"message"`
}

User is an Authy User

func NewUser

func NewUser(httpResponse *http.Response) (*User, error)

NewUser returns an instance of User

func (*User) Valid

func (response *User) Valid() bool

Valid returns true if the user was created successfully

type UserStatus

type UserStatus struct {
	HTTPResponse *http.Response
	ID           string
	StatusData   struct {
		ID          int      `json:"authy_id"`
		Confirmed   bool     `json:"confirmed"`
		Registered  bool     `json:"registered"`
		Country     int      `json:"country_code"`
		PhoneNumber string   `json:"phone_number"`
		Devices     []string `json:"devices"`
	} `json:"status"`
	Message string `json:"message"`
	Success bool   `json:"success"`
}

UserStatus is a user with information loaded from Authy API

func NewUserStatus

func NewUserStatus(httpResponse *http.Response) (*UserStatus, error)

NewUserStatus returns an instance of UserStatus

Jump to

Keyboard shortcuts

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