Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
ichtrojan committed Sep 8, 2024
0 parents commit c8775bf
Show file tree
Hide file tree
Showing 4 changed files with 268 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Shege LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
74 changes: 74 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# FastOTP API Client for Go

This Go package provides a client for interacting with the FastOTP API.

## Installation

```bash
go get -u github.com/ShegeHQ/fastotp
```

## Usage

```go
package main

import (
"fmt"
"log"

"github.com/ShegeHQ/fastotp"
)

func main() {
// Initialize the client with your API key
client := fastotp.Init("your_api_key")

// Generate OTP
generateReq := fastotp.GenerateOTPRequest{
Type: "alpha_numeric",
Identifier: "user123",
Delivery: map[string]string{"email": "[email protected]"},
Validity: 5,
TokenLength: 6,
}

generateResp, err := client.GenerateOTP(generateReq)
if err != nil {
log.Fatalf("Error generating OTP: %v", err)
}

fmt.Printf("Generated OTP: %+v\n", generateResp.OTP)

// Validate OTP
validateReq := fastotp.ValidateOTPRequest{
Identifier: "user123",
Token: "123456",
}

validateResp, err := client.ValidateOTP(validateReq)
if err != nil {
log.Fatalf("Error validating OTP: %v", err)
}

fmt.Printf("Validated OTP: %+v\n", validateResp.OTP)

// Get OTP details
otpID := generateResp.OTP.ID
otpDetails, err := client.GetOTP(otpID)
if err != nil {
log.Fatalf("Error fetching OTP details: %v", err)
}

fmt.Printf("OTP Details: %+v\n", otpDetails.OTP)
}
```

## Configuration

**ApiKey:** Your FastOTP API key.

## Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, feel free to open an issue or
submit a pull request.
172 changes: 172 additions & 0 deletions fastotp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package fastotp

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)

type Client struct {
BaseURL string
APIKey string
Client *http.Client
}

func Init(apiKey string) *Client {
return &Client{
BaseURL: "https://api.fastotp.co",
APIKey: apiKey,
Client: &http.Client{Timeout: 10 * time.Second},
}
}

type OTP struct {
ID string `json:"id"`
Identifier string `json:"identifier"`
Type string `json:"type"`
Status string `json:"status"`
DeliveryMethods []string `json:"delivery_methods"`
DeliveryDetails map[string]interface{} `json:"delivery_details"`
ExpiresAt string `json:"expires_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}

type GenerateOTPRequest struct {
Type string `json:"type"`
Identifier string `json:"identifier"`
Delivery map[string]string `json:"delivery"`
Validity int `json:"validity"`
TokenLength int `json:"token_length"`
}

type GenerateOTPResponse struct {
OTP OTP `json:"otp"`
}

type ValidateOTPRequest struct {
Identifier string `json:"identifier"`
Token string `json:"token"`
}

type ValidateOTPResponse struct {
OTP OTP `json:"otp"`
}

type ErrorResponse struct {
Message string `json:"message"`
Errors map[string]interface{} `json:"errors,omitempty"`
}

func (c *Client) GenerateOTP(req GenerateOTPRequest) (*GenerateOTPResponse, error) {
url := fmt.Sprintf("%s/generate", c.BaseURL)

jsonData, err := json.Marshal(req)
if err != nil {
return nil, err
}

request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}

request.Header.Set("Content-Type", "application/json")
request.Header.Set("x-api-key", c.APIKey)

response, err := c.Client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
return nil, parseErrorResponse(response)
}

var otpResponse GenerateOTPResponse
if err := json.NewDecoder(response.Body).Decode(&otpResponse); err != nil {
return nil, err
}

return &otpResponse, nil
}

func (c *Client) ValidateOTP(req ValidateOTPRequest) (*ValidateOTPResponse, error) {
url := fmt.Sprintf("%s/validate", c.BaseURL)

jsonData, err := json.Marshal(req)
if err != nil {
return nil, err
}

request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}

request.Header.Set("Content-Type", "application/json")
request.Header.Set("x-api-key", c.APIKey)

response, err := c.Client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
return nil, parseErrorResponse(response)
}

var otpResponse ValidateOTPResponse
if err := json.NewDecoder(response.Body).Decode(&otpResponse); err != nil {
return nil, err
}

return &otpResponse, nil
}

func (c *Client) GetOTP(id string) (*GenerateOTPResponse, error) {
url := fmt.Sprintf("%s/%s", c.BaseURL, id)

request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}

request.Header.Set("x-api-key", c.APIKey)

response, err := c.Client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
return nil, parseErrorResponse(response)
}

var otpResponse GenerateOTPResponse
if err := json.NewDecoder(response.Body).Decode(&otpResponse); err != nil {
return nil, err
}

return &otpResponse, nil
}

func parseErrorResponse(response *http.Response) error {
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}

var errResp ErrorResponse
if err := json.Unmarshal(body, &errResp); err != nil {
return fmt.Errorf("error parsing response: %v", err)
}

return fmt.Errorf("error: %s, details: %v", errResp.Message, errResp.Errors)
}

0 comments on commit c8775bf

Please sign in to comment.