-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
167 lines (132 loc) · 4.09 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
package main
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
type Shop struct {
Name string `json:"name"`
WebhookURL string `json:"webhookURL"`
PublicKey string `json:"publicKey"`
Description string `json:"description"`
}
var db *sql.DB
func getShops(w http.ResponseWriter, r *http.Request) {
log.Printf("Polling request received...Checking database....")
rows, err := db.Query("SELECT name, webhookURL, publicKey, description FROM shops")
if err != nil {
log.Printf("%v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var shops []Shop
for rows.Next() {
var shop Shop
var (
shopnameVar string
webhookURL string
PublicKey string
description string
)
if err := rows.Scan(&shopnameVar, &webhookURL, &PublicKey, &description); err != nil {
fmt.Printf("Error! %s key is %s\n", shopnameVar, webhookURL, PublicKey, description)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
shop.Name = shopnameVar
shop.WebhookURL = webhookURL
shop.PublicKey = PublicKey
shop.Description = description
log.Printf("attempting append of %s to shops array", shop.Name)
shops = append(shops, shop)
log.Printf("appending successful")
}
log.Printf("appending loop finished")
json.NewEncoder(w).Encode(shops)
}
func addShop(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
auth_server := os.Getenv("AUTH_SERVER")
req, _ := http.NewRequest("GET", auth_server+"/validate", nil)
req.Header.Add("Authorization", r.Header.Get("Authorization"))
resp, err := client.Do(req)
log.Printf("Checking authorization via Server")
if err != nil || resp.StatusCode != http.StatusOK {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var newShop Shop
json.NewDecoder(r.Body).Decode(&newShop)
log.Printf("Checking if shop already exists in database")
err = db.QueryRow("SELECT name FROM shops WHERE name = $1", newShop.Name).Scan(&newShop.Name)
if err != nil && err != sql.ErrNoRows {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err != sql.ErrNoRows {
w.Write([]byte("You are already part of federation"))
return
}
log.Printf("Inserting into database")
_, err = db.Exec("INSERT INTO shops (name, webhookURL, publicKey, description) VALUES ($1, $2, $3, $4)", newShop.Name, newShop.WebhookURL, newShop.PublicKey, newShop.Description)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("Select from Database")
rows, err := db.Query("SELECT name, webhookURL FROM shops")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
log.Printf("Check database...")
for rows.Next() {
var shop Shop
if err := rows.Scan(&shop.Name, &shop.WebhookURL); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
go sendWebhook(shop.WebhookURL, newShop)
}
json.NewEncoder(w).Encode(newShop)
log.Printf("Successfully added new shop")
}
func sendWebhook(webhookURL string, newShop Shop) {
jsonData, _ := json.Marshal(newShop)
resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
log.Printf("Failed to send webhook to %s: %v\n", webhookURL, err)
return
}
defer resp.Body.Close()
}
func main() {
err := godotenv.Load()
if err != nil {
panic("Error loading .env file")
}
dbUser := os.Getenv("DB_USER")
dbPassword := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
dbHost := os.Getenv("DB_HOST")
db, err = sql.Open("postgres", fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", dbHost, dbUser, dbPassword, dbName))
if err != nil {
log.Fatal(err)
}
defer db.Close()
router := mux.NewRouter()
router.HandleFunc("/shops", getShops).Methods("GET")
router.HandleFunc("/shops", addShop).Methods("POST")
port := os.Getenv("HUB_PORT")
log.Printf("Federation hub is running on port %s", port)
http.ListenAndServe(":"+port, router)
}