This repository has been archived by the owner on Jan 29, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
171 lines (133 loc) · 3.24 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package main
/**
* Go packages
*/
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"time"
)
/**
* Vendor packages
*/
import (
"github.com/dgrijalva/jwt-go"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Resource : http response for authenticated property
type Resource struct {
ID string `json:"id"`
Type string `json:"type"`
Resource bson.M `json:"resource"`
}
// AuthenticationRequest : http request for authentication
type AuthenticationRequest struct {
Token string `json:"token"`
}
func createDatabaseClient() (*mongo.Client, error) {
mongoURI := os.Getenv("MONGODB_URI")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
cancel()
if err != nil {
return nil, err
}
return client, nil
}
func extractJwtToken(req *http.Request) (string, error) {
var token string
var request AuthenticationRequest
if req.Body == nil {
return token, errors.New("no request body found")
}
err := json.NewDecoder(req.Body).Decode(&request)
if err != nil {
return token, err
}
token = request.Token
return token, nil
}
func getCollectionName(_type string) string {
switch _type {
case "user":
return "users"
case "vm":
return "vms"
default:
return _type + "s"
}
}
func handleError(w http.ResponseWriter, e error) {
http.Error(w, e.Error(), 500)
}
func fetchResourceFromToken(tokenString string) (Resource, error) {
var resource Resource
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_KEY")), nil
})
if err != nil {
return resource, err
}
resourceID := fmt.Sprintf("%v", claims["id"])
resourceType := fmt.Sprintf("%v", claims["type"])
fmt.Println("authenticated", resourceType, resourceID)
document, err := fetchDocument(getCollectionName(resourceType), resourceID)
if err != nil {
return resource, err
}
resource = Resource{ID: resourceID, Type: resourceType, Resource: document}
return resource, nil
}
func fetchDocument(_collection string, id string) (bson.M, error) {
client, err := createDatabaseClient()
result := bson.M{}
filter := bson.M{"info.id": &id}
collection := client.Database("cryb").Collection(_collection)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err = collection.FindOne(ctx, filter).Decode(&result)
cancel()
if err != nil {
return result, err
}
return result, nil
}
func authenticate(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
fmt.Fprintf(w, "method not acceptable\n")
return
}
tokenString, err := extractJwtToken(req)
if err != nil {
handleError(w, err)
return
}
resource, err := fetchResourceFromToken(tokenString)
if err != nil {
handleError(w, err)
return
}
out, err := json.Marshal(resource)
if err != nil {
handleError(w, err)
return
}
fmt.Fprintf(w, string(out))
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file!")
}
http.HandleFunc("/", authenticate)
fmt.Println("listening on :4500")
http.ListenAndServe(":4500", nil)
}