How to validate API key with function in Martini?

137 Views Asked by At

So I currently have a function that will take in a string APIKey to check it against my Mongo collection. If nothing is found (not authenticated), it returns false - if a user is found, it returns true. My problem, however, is I'm unsure how to integrate this with a Martini POST route. Here is my code:

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/go-martini/martini"
    _ "github.com/joho/godotenv/autoload"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type User struct {
    Name   string
    APIKey string
}

func validateAPIKey(users *mongo.Collection, APIKey string) bool {
    var user User

    filter := bson.D{{"APIKey", APIKey}}
    if err := users.FindOne(context.TODO(), filter).Decode(&user); err != nil {
        fmt.Printf("Found 0 results for API Key: %s\n", APIKey)
        return false
    }

    fmt.Printf("Found: %s\n", user.Name)
    return true
}

func uploadHandler() {

}

func main() {
    mongoURI := os.Getenv("MONGO_URI")
    mongoOptions := options.Client().ApplyURI(mongoURI)
    client, _ := mongo.Connect(context.TODO(), mongoOptions)
    defer client.Disconnect(context.TODO())
    if err := client.Ping(context.TODO(), nil); err != nil {
        log.Fatal(err, "Unable to access MongoDB server, exiting...")
    }

    // users := client.Database("sharex_api").Collection("authorized_users") // commented out when testing to ignore unused warnings

    m := martini.Classic()
    m.Post("/api/v1/upload", uploadHandler)

    m.RunOnAddr(":8085")
}

The validateAPIKey function works exactly as intended if tested alone, I am just unsure how I would run this function for a specific endpoint (in this case, /api/v1/upload).

0

There are 0 best solutions below