This repository has been archived by the owner on Apr 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
367 lines (302 loc) · 9.87 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/runwayapp/air-traffic-control/internal/middlewares"
token "github.com/runwayapp/air-traffic-control/internal/utils"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"github.com/google/uuid"
"github.com/joho/godotenv"
)
var db *sql.DB
type Command struct {
Id string
Organization string
Repository string
Name string
Data string
Created_at string
Updated_at string
}
type CommandResponse struct {
Id string `json:"id"`
Organization string `json:"organization"`
Repository string `json:"repository"`
Name string `json:"name"`
Data map[string]interface{} `json:"data"`
Created_at string `json:"created_at"`
Updated_at string `json:"updated_at"`
}
type AuthRequest struct {
Login string `json:"login"`
}
func main() {
var err error
// log env on startup just incase
if os.Getenv("ENV") != "" {
log.Printf("ENV Detected on Startup: %s", os.Getenv("ENV"))
}
// Load in the `.env` file only in development
if os.Getenv("ENV") != "production" {
err = godotenv.Load()
if err != nil {
log.Fatal("failed to load env", err)
}
}
log.Printf("ENV: %s", os.Getenv("ENV"))
// Open a connection to the database
db, err = sql.Open("mysql", os.Getenv("DSN"))
if err != nil {
log.Fatal("failed to open db connection", err)
}
if err := db.Ping(); err != nil {
log.Printf("ERROR: failed to ping / connect to database: %v", err)
}
log.Println("successfully connected to database")
// Build router & define routes
router := gin.Default()
// Recovery middleware recovers from any panics and writes a 500 if there was one.
router.Use(gin.Recovery())
protected := router.Group("/api/v1")
protected.Use(middlewares.JwtAuthMiddleware())
protected.GET("/:org/:repo/commands", GetRepoCommands)
protected.GET("/:org/:repo/commands/:commandId", GetSingleCommand)
protected.POST("/:org/:repo/commands", CreateCommand)
protected.PUT("/:org/:repo/commands/:commandId", UpdateCommand)
protected.DELETE("/:org/:repo/commands/:commandId", DeleteCommand)
apiKeyProtection := router.Group("/api/v1")
apiKeyProtection.Use(middlewares.ApiKeyAuthMiddleware())
apiKeyProtection.POST("/auth", Auth)
// add ping endpoint
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
router.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "air-traffic-control application",
})
})
// Run the router
router.Run()
}
func Auth(c *gin.Context) {
var authRequest AuthRequest
err := c.BindJSON(&authRequest)
if err != nil {
msg, _ := fmt.Printf("(Auth) c.BindJSON %s", err)
panic(msg)
}
if authRequest.Login == "" {
c.JSON(http.StatusBadRequest, gin.H{"message": "login is required"})
return
}
token, err := token.GenerateToken(authRequest.Login)
if err != nil {
msg, _ := fmt.Printf("(Auth) token.GenerateToken %s", err)
panic(msg)
}
c.JSON(http.StatusOK, gin.H{"message": "ok", "token": token})
}
func GetRepoCommands(c *gin.Context) {
org := c.Param("org")
org = strings.ReplaceAll(org, "/", "")
repo := c.Param("repo")
repo = strings.ReplaceAll(repo, "/", "")
query := `SELECT * FROM commands WHERE organization = ? AND repository = ?`
res, err := db.Query(query, org, repo)
defer res.Close()
if err != nil {
msg, _ := fmt.Printf("(GetCommands) db.Query %s", err)
panic(msg)
}
commands := []CommandResponse{}
for res.Next() {
var commandResponse CommandResponse
var command Command
err := res.Scan(&command.Id, &command.Organization, &command.Repository, &command.Name, &command.Data, &command.Created_at, &command.Updated_at)
if err != nil {
msg, _ := fmt.Printf("(GetCommands) res.Scan %s", err)
panic(msg)
}
// ensure the data is valid json before appending
var data map[string]interface{}
err = json.Unmarshal([]byte(command.Data), &data)
if err != nil {
msg, _ := fmt.Printf("(GetCommands) json.Unmarshal %s", err)
panic(msg)
}
commandResponse.Id = command.Id
commandResponse.Organization = command.Organization
commandResponse.Repository = command.Repository
commandResponse.Name = command.Name
commandResponse.Created_at = command.Created_at
commandResponse.Updated_at = command.Updated_at
commandResponse.Data = data
commands = append(commands, commandResponse)
}
c.JSON(http.StatusOK, commands)
}
func GetSingleCommand(c *gin.Context) {
org := c.Param("org")
org = strings.ReplaceAll(org, "/", "")
repo := c.Param("repo")
repo = strings.ReplaceAll(repo, "/", "")
commandId := c.Param("commandId")
commandId = strings.ReplaceAll(commandId, "/", "")
var commandResponse CommandResponse
var command Command
query := `SELECT * FROM commands WHERE id = ? AND organization = ? AND repository = ?`
err := db.QueryRow(query, commandId, org, repo).Scan(&command.Id, &command.Organization, &command.Repository, &command.Name, &command.Data, &command.Created_at, &command.Updated_at)
if err != nil {
msg, _ := fmt.Printf("(GetSingleCommand) db.Exec %s", err)
panic(msg)
}
// ensure the data is valid json before appending
var data map[string]interface{}
err = json.Unmarshal([]byte(command.Data), &data)
if err != nil {
msg, _ := fmt.Printf("(GetCommands) json.Unmarshal %s", err)
panic(msg)
}
commandResponse.Id = command.Id
commandResponse.Organization = command.Organization
commandResponse.Repository = command.Repository
commandResponse.Name = command.Name
commandResponse.Created_at = command.Created_at
commandResponse.Updated_at = command.Updated_at
commandResponse.Data = data
c.JSON(http.StatusOK, commandResponse)
}
func CreateCommand(c *gin.Context) {
id := uuid.New().String()
org := c.Param("org")
org = strings.ReplaceAll(org, "/", "")
repo := c.Param("repo")
repo = strings.ReplaceAll(repo, "/", "")
var newCommand Command
err := c.BindJSON(&newCommand)
if err != nil {
msg, _ := fmt.Printf("(CreateCommand) c.BindJSON %s", err)
panic(msg)
}
// add values to the new command
newCommand.Id = id
newCommand.Organization = org
newCommand.Repository = repo
// check required params
if newCommand.Organization == "" || newCommand.Repository == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "organization and repository are required params"})
return
}
// Check all required inputs
if newCommand.Name == "" || newCommand.Data == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "organization, repository, name, and data are required"})
return
}
query := `INSERT INTO commands (id, organization, repository, name, data) VALUES (?, ?, ?, ?, ?)`
res, err := db.Exec(query, newCommand.Id, newCommand.Organization, newCommand.Repository, newCommand.Name, newCommand.Data)
if err != nil {
msg, _ := fmt.Printf("(CreateCommand) db.Exec %s", err)
panic(msg)
}
_, err = res.LastInsertId()
if err != nil {
msg, _ := fmt.Printf("(CreateCommand) res.LastInsertId %s", err)
panic(msg)
}
var commandResponse CommandResponse
// ensure the data is valid json before appending
var data map[string]interface{}
err = json.Unmarshal([]byte(newCommand.Data), &data)
if err != nil {
msg, _ := fmt.Printf("(GetCommands) json.Unmarshal %s", err)
panic(msg)
}
commandResponse.Id = newCommand.Id
commandResponse.Organization = newCommand.Organization
commandResponse.Repository = newCommand.Repository
commandResponse.Name = newCommand.Name
commandResponse.Created_at = newCommand.Created_at
commandResponse.Updated_at = newCommand.Updated_at
commandResponse.Data = data
c.JSON(http.StatusOK, commandResponse)
}
func UpdateCommand(c *gin.Context) {
var updates Command
err := c.BindJSON(&updates)
if err != nil {
msg, _ := fmt.Printf("(UpdateCommand) c.BindJSON %s", err)
panic(msg)
}
org := c.Param("org")
org = strings.ReplaceAll(org, "/", "")
repo := c.Param("repo")
repo = strings.ReplaceAll(repo, "/", "")
commandId := c.Param("commandId")
commandId = strings.ReplaceAll(commandId, "/", "")
// check all required inputs
if updates.Name == "" || updates.Data == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "name and data are required"})
return
}
query := `UPDATE commands SET name = ?, data = ? WHERE id = ? AND organization = ? AND repository = ?`
result, err := db.Exec(query, updates.Name, updates.Data, commandId, org, repo)
if err != nil {
msg, _ := fmt.Printf("(UpdateCommand) db.Exec %s", err)
panic(msg)
}
// if no rows were affected, return an error
rowsAffected, err := result.RowsAffected()
if err != nil {
msg, _ := fmt.Printf("(DeleteCommand) result.RowsAffected %s", err)
panic(msg)
}
if rowsAffected == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "command not found"})
return
}
c.Status(http.StatusOK)
}
func DeleteCommand(c *gin.Context) {
org := c.Param("org")
org = strings.ReplaceAll(org, "/", "")
repo := c.Param("repo")
repo = strings.ReplaceAll(repo, "/", "")
commandId := c.Param("commandId")
commandId = strings.ReplaceAll(commandId, "/", "")
// if an org or repo is not provided, return an error
if org == "" || repo == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "org and repo are required"})
return
}
// if a commandId is not provided, return an error
if commandId == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "commandId is required"})
return
}
query := `DELETE FROM commands WHERE id = ? AND organization = ? AND repository = ?`
result, err := db.Exec(query, commandId, org, repo)
if err != nil {
msg, _ := fmt.Printf("(DeleteCommand) db.Exec %s", err)
panic(msg)
}
// if no rows were affected, return an error
rowsAffected, err := result.RowsAffected()
if err != nil {
msg, _ := fmt.Printf("(DeleteCommand) result.RowsAffected %s", err)
panic(msg)
}
if rowsAffected == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "command not found"})
return
}
c.Status(http.StatusOK)
}