Automating SMS Verification Codes with Go and Exolve API

August 16, 2024, 5:52 am
In the digital age, security is paramount. Two-factor authentication (2FA) has become a standard practice for safeguarding user accounts. One effective method of implementing 2FA is through SMS verification codes. This article explores how to create a simple yet powerful SMS verification code generator using Go and the Exolve API.

**The Challenge of Security**

Imagine a locked door. A key is needed to enter. In the online world, passwords are keys. But what if someone steals your key? This is where 2FA comes into play. It adds an extra layer of security, ensuring that even if someone has your password, they cannot access your account without a second key—often sent via SMS.

**Choosing the Right Tools**

To build our SMS verification system, we will use the Go programming language and the Exolve SMS API. Exolve simplifies the process of sending SMS messages, making it an ideal choice for our project. They even offer a trial balance, allowing us to test the service without upfront costs.

**Getting Started with Exolve**

First, we need to register on the Exolve website. This grants us access to a personal dashboard where we can manage our settings and utilize various features. The next step is to create an application within our account. This action generates API keys, which are essential for authenticating our requests to the Exolve API.

Once we have our API keys, we can purchase a phone number for sending SMS messages. Exolve provides a selection of numbers, and we can choose one based on our needs.

**Understanding the SMS API**

The Exolve API offers several methods, but we will focus on two key functionalities: sending SMS messages and retrieving message logs.

1. **SendSMS Method**: This method allows us to send an SMS message. We will make a POST request, specifying the sender's number, the recipient's number, and the message content.

2. **GetList Method**: This method retrieves data about sent and received SMS messages. It helps us keep track of our communications.

**Building the SMS Generator**

Now, let’s dive into the code. We will create a web application in Go that utilizes the Exolve API to send verification codes to users. The project structure will look like this:

```
/project-folder
├── main.go # Go server file
├── static # Folder for static files
└── index.html # HTML file
```

**Setting Up the Server**

In `main.go`, we will set up our server. We will import necessary packages, including those for handling HTTP requests, JSON encoding, and random number generation.

```go
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"sync"
"time"
"golang.org/x/time/rate"
)
```

We define a structure for our SMS request, which includes the sender's number, recipient's number, and the message text.

**Creating the Main Function**

The main function sets up the HTTP routes. The root URL serves the HTML page, while the `/send` URL handles SMS sending requests.

```go
func main() {
http.HandleFunc("/", serveHome)
http.HandleFunc("/send", rateLimit(handleSendSMS))
log.Println("Server started on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
```

**Handling Requests**

The `serveHome` function loads the HTML template, providing a user-friendly interface for inputting phone numbers. The `handleSendSMS` function processes the form submission, generates a verification code, and sends it via SMS.

```go
func handleSendSMS(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
err := r.ParseForm()
if err != nil {
http.Error(w, "Failed to parse form", 400)
return
}
number := r.FormValue("number")
code := generateCode(8)
message := fmt.Sprintf("Your verification code is: %s", code)
if err := sendSMS(number, message); err != nil {
log.Printf("Failed to send SMS: %v", err)
http.Error(w, "Failed to send SMS", 500)
return
}
fmt.Fprintf(w, "SMS with code sent to %s", number)
}
```

**Generating the Code**

The `generateCode` function creates a random alphanumeric code of a specified length. This code serves as the verification key sent to the user.

```go
func generateCode(length int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
rand.Seed(time.Now().UnixNano())
b := make([]rune, length)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
```

**Sending the SMS**

The `sendSMS` function constructs the request to the Exolve API, sending the SMS message to the specified number.

```go
func sendSMS(destination, message string) error {
requestData := SMSRequest{
Number: "YOUR_NUMBER", // Replace with your purchased number
Destination: destination,
Text: message,
}
jsonData, err := json.Marshal(requestData)
if err != nil {
return err
}
req, err := http.NewRequest("POST", "https://api.exolve.ru/messaging/v1/SendSMS", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer your_API_key") // Replace with your API key
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to send SMS: received status code %d", resp.StatusCode)
}
return nil
}
```

**Creating the HTML Interface**

The `index.html` file provides a simple form for users to enter their phone numbers. It includes basic styling for a clean look.

```html





Request SMS Code




Enter your phone number:







```

**Running the Application**

To run the application, navigate to the project folder in your command line and execute:

```bash
go run main.go
```

Visit `http://localhost:8080` in your browser. Enter a phone number and click "Send Code." You should receive an SMS with your verification code.

**Enhancements and Future Steps**

While this application is functional, there are several enhancements to consider. Implementing logging for better error tracking is crucial. Additionally, using environment variables to store sensitive information like API keys is a best practice.

Improving the user interface and adding features like message templates or a database for tracking sent messages could enhance the application further.

**Conclusion**

Creating an SMS verification code generator using Go and the Exolve API is a straightforward process. This tool not only enhances security but also improves user experience. With the right tools and a bit of coding, you can build a robust verification system that keeps your users safe.