Skip to content

Commit 738686b

Browse files
committed
Code cleanup, use HTTP POST header for api key
1 parent dec457d commit 738686b

File tree

5 files changed

+107
-33
lines changed

5 files changed

+107
-33
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.19
55
require (
66
github.com/go-chi/chi/v5 v5.0.7
77
github.com/google/uuid v1.3.0
8+
go.mongodb.org/mongo-driver v1.10.2
89
)
910

1011
require (
@@ -16,7 +17,6 @@ require (
1617
github.com/xdg-go/scram v1.1.1 // indirect
1718
github.com/xdg-go/stringprep v1.0.3 // indirect
1819
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
19-
go.mongodb.org/mongo-driver v1.10.2 // indirect
2020
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
2121
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
2222
golang.org/x/text v0.3.7 // indirect

go.sum

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
23
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
34
github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8=
45
github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
56
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
67
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
8+
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
79
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
810
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
911
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@@ -16,9 +18,12 @@ github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6f
1618
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
1719
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
1820
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
21+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
1922
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
2023
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
24+
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
2125
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
26+
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
2227
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
2328
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
2429
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
@@ -43,8 +48,10 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
4348
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
4449
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
4550
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
51+
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
4652
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
4753
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
4854
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
4955
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
56+
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
5057
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

handler.go

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package main
2+
3+
import (
4+
"Learning/license"
5+
"context"
6+
"encoding/json"
7+
"github.com/go-chi/chi/v5"
8+
"go.mongodb.org/mongo-driver/bson"
9+
"go.mongodb.org/mongo-driver/bson/primitive"
10+
"go.mongodb.org/mongo-driver/mongo"
11+
"net/http"
12+
)
13+
14+
type HandlerContext struct {
15+
apiKey string
16+
collection *mongo.Collection
17+
}
18+
19+
func (ctx *HandlerContext) allUnusedKeys(writer http.ResponseWriter, request *http.Request) {
20+
ctx.getKeysWithFilter(writer, request, bson.M{"owner": nil})
21+
}
22+
23+
func (ctx *HandlerContext) allKeys(writer http.ResponseWriter, request *http.Request) {
24+
ctx.getKeysWithFilter(writer, request, nil)
25+
}
26+
27+
func (ctx *HandlerContext) getKeysWithFilter(writer http.ResponseWriter, request *http.Request, filter primitive.M) {
28+
if !ctx.checkApiKey(request.Header.Get("api-key")) {
29+
writer.WriteHeader(http.StatusUnauthorized)
30+
return
31+
}
32+
33+
var cursor *mongo.Cursor
34+
var err error
35+
if filter == nil {
36+
cursor, err = ctx.collection.Find(context.TODO(), bson.D{})
37+
} else {
38+
cursor, err = ctx.collection.Find(context.TODO(), filter)
39+
}
40+
41+
if err != nil {
42+
panic(err)
43+
}
44+
45+
var results []bson.M
46+
if err = cursor.All(context.TODO(), &results); err != nil {
47+
panic(err)
48+
}
49+
50+
err = json.NewEncoder(writer).Encode(results)
51+
}
52+
53+
func (ctx *HandlerContext) registerKey(writer http.ResponseWriter, request *http.Request) {
54+
if !ctx.checkApiKey(request.Header.Get("api-key")) {
55+
writer.WriteHeader(http.StatusUnauthorized)
56+
return
57+
}
58+
59+
licenseKey := license.GenerateKey()
60+
_, err := ctx.collection.InsertOne(context.TODO(), licenseKey)
61+
if err != nil {
62+
return
63+
}
64+
65+
err = json.NewEncoder(writer).Encode(licenseKey)
66+
if err != nil {
67+
return
68+
}
69+
}
70+
71+
func (ctx *HandlerContext) validateKey(writer http.ResponseWriter, request *http.Request) {
72+
key := chi.URLParam(request, "key")
73+
var licenseKey bson.D
74+
if err := ctx.collection.FindOne(context.TODO(), bson.M{"_id": key}).Decode(&licenseKey); err != nil {
75+
_, _ = writer.Write([]byte("false"))
76+
return
77+
}
78+
_, _ = writer.Write([]byte("true"))
79+
}
80+
81+
func (ctx *HandlerContext) checkApiKey(apiKey string) (valid bool) {
82+
return ctx.apiKey == apiKey
83+
}

license/license.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ func GenerateKey() License {
1111

1212
type License struct {
1313
Key string `json:"id" bson:"_id"`
14+
Owner string `json:"owner" bson:"owner"`
1415
CreationDate time.Time `json:"creation_date" bson:"creation_date"`
1516
Disabled bool `json:"disabled" bson:"disabled"`
1617
}

main.go

Lines changed: 15 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
package main
22

33
import (
4-
"Learning/license"
54
"context"
6-
"encoding/json"
7-
"fmt"
85
"github.com/go-chi/chi/v5"
9-
"go.mongodb.org/mongo-driver/bson"
106
"go.mongodb.org/mongo-driver/mongo"
117
"go.mongodb.org/mongo-driver/mongo/options"
128
"go.mongodb.org/mongo-driver/mongo/readpref"
139
"log"
1410
"net/http"
11+
"os"
1512
)
1613

1714
func main() {
15+
if len(os.Args) < 2 {
16+
log.Fatal("You didn't set an api key.")
17+
}
18+
1819
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
1920
if err != nil {
2021
panic(err)
@@ -24,41 +25,23 @@ func main() {
2425
panic(err)
2526
}
2627

27-
collection = client.Database("default").Collection("licenses")
28+
defer client.Disconnect(context.TODO())
2829

29-
router := chi.NewRouter()
30-
router.Get("/create/{key}", registerKey)
31-
router.Get("/validate/{key}", validateKey)
30+
collection := client.Database("default").Collection("licenses")
3231

33-
err = http.ListenAndServe(":3000", router)
34-
if err != nil {
35-
return
36-
}
37-
}
32+
handlerContext := HandlerContext{apiKey: os.Args[1], collection: collection}
3833

39-
var collection *mongo.Collection
34+
router := chi.NewRouter()
4035

41-
var licenses = make(map[string]license.License)
36+
router.Get("/validate/{key}", handlerContext.validateKey)
4237

43-
func registerKey(writer http.ResponseWriter, request *http.Request) {
44-
licenseKey := license.GenerateKey()
45-
_, err := collection.InsertOne(context.TODO(), licenseKey)
46-
if err != nil {
47-
return
48-
}
38+
// Requires API key
39+
router.Post("/create", handlerContext.registerKey)
40+
router.Post("/all", handlerContext.allKeys)
41+
router.Post("/unused", handlerContext.allUnusedKeys)
4942

50-
licenses[licenseKey.Key] = licenseKey
51-
err = json.NewEncoder(writer).Encode(licenseKey)
43+
err = http.ListenAndServe(":3000", router)
5244
if err != nil {
5345
return
5446
}
5547
}
56-
57-
func validateKey(writer http.ResponseWriter, request *http.Request) {
58-
key := chi.URLParam(request, "key")
59-
var licenseKey bson.D
60-
if err := collection.FindOne(context.TODO(), bson.M{"_id": key}).Decode(&licenseKey); err != nil {
61-
log.Fatal(err)
62-
}
63-
fmt.Println(licenseKey)
64-
}

0 commit comments

Comments
 (0)