-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
171 lines (136 loc) · 3.62 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
import (
"encoding/json"
"fmt"
"net/http"
"os"
jsonhandler "github.com/apex/log/handlers/json"
"github.com/aws/aws-sdk-go-v2/aws/endpoints"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/gorilla/mux"
"github.com/tj/go/http/response"
"github.com/unee-t/env"
"github.com/apex/log"
"github.com/apex/log/handlers/text"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type handler struct {
DSN string // e.g. "bugzilla:secret@tcp(auroradb.dev.unee-t.com:3306)/bugzilla?multiStatements=true&sql_mode=TRADITIONAL"
APIAccessToken string // e.g. O8I9svDTizOfLfdVA5ri
db *sql.DB
Code env.EnvCode
}
// APIKey is defined by the Table: user_api_keys https://s.natalian.org/2018-06-01/1527810246_2558x1406.png
type APIkey struct {
UserID string `json:"UserId"`
UserAPIkey string `json:"userApiKey"`
}
func init() {
if os.Getenv("UP_STAGE") == "" {
log.SetHandler(text.Default)
} else {
log.SetHandler(jsonhandler.Default)
}
}
// New setups the configuration assuming various parameters have been setup in the AWS account
func New() (h handler, err error) {
cfg, err := external.LoadDefaultAWSConfig(external.WithSharedConfigProfile("uneet-dev"))
if err != nil {
log.WithError(err).Fatal("setting up credentials")
return
}
cfg.Region = endpoints.ApSoutheast1RegionID
e, err := env.New(cfg)
if err != nil {
log.WithError(err).Warn("error getting AWS unee-t env")
}
var mysqlhost string
val, ok := os.LookupEnv("MYSQL_HOST")
if ok {
log.Infof("MYSQL_HOST overridden by local env: %s", val)
mysqlhost = val
} else {
mysqlhost = e.Udomain("auroradb")
}
h = handler{
DSN: fmt.Sprintf("%s:%s@tcp(%s:3306)/bugzilla?multiStatements=true&sql_mode=TRADITIONAL&collation=utf8mb4_unicode_520_ci",
e.GetSecret("MYSQL_USER"),
e.GetSecret("MYSQL_PASSWORD"),
mysqlhost),
APIAccessToken: e.GetSecret("API_ACCESS_TOKEN"),
Code: e.Code,
}
h.db, err = sql.Open("mysql", h.DSN)
if err != nil {
log.WithError(err).Fatal("error opening database")
return
}
return
}
func main() {
h, err := New()
if err != nil {
log.WithError(err).Fatal("error setting configuration")
return
}
defer h.db.Close()
addr := ":" + os.Getenv("PORT")
app := mux.NewRouter()
app.HandleFunc("/", h.enroll).Methods("POST")
app.HandleFunc("/", h.ping).Methods("GET")
if err := http.ListenAndServe(addr, env.Protect(app, h.APIAccessToken)); err != nil {
log.WithError(err).Fatal("error listening")
}
}
func (h handler) insert(credential APIkey) (err error) {
_, err = h.db.Exec(
`INSERT INTO user_api_keys (user_id,
api_key,
description
) VALUES (?,?,?)`,
credential.UserID,
credential.UserAPIkey,
"MEFE Access Key",
)
return
}
func (h handler) enroll(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var k APIkey
err := decoder.Decode(&k)
if err != nil {
log.WithError(err).Errorf("Input error")
response.BadRequest(w, "Invalid JSON")
return
}
defer r.Body.Close()
ctx := log.WithFields(log.Fields{
"APIkey": k,
})
ctx.Info("Decoded")
if k.UserAPIkey == "" {
response.BadRequest(w, "Missing UserAPIkey")
return
}
if k.UserID == "" {
response.BadRequest(w, "Missing UserID")
return
}
err = h.insert(k)
if err != nil {
log.WithError(err).Warnf("failed to insert")
response.BadRequest(w, "Failed to insert")
return
}
response.OK(w)
return
}
func (h handler) ping(w http.ResponseWriter, r *http.Request) {
err := h.db.Ping()
if err != nil {
log.WithError(err).Error("failed to ping database")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
fmt.Fprintf(w, "OK")
}