forked from wisepythagoras/pos-system
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
198 lines (161 loc) · 6.52 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
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"strconv"
"github.com/asaskevich/EventBus"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
// parseConfig parses the configuration either from the same folder, or
// from an explicit path.
func parseConfig(customConfig *string) (*Config, error) {
if customConfig == nil || len(*customConfig) == 0 {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
} else {
viper.SetConfigFile(*customConfig)
}
var config Config
// Try to read the configuration file.
if err := viper.ReadInConfig(); err != nil {
return nil, err
}
// Default config.
viper.SetDefault("server.port", 8088)
// Parse the configuration into the config object.
err := viper.Unmarshal(&config)
if err != nil {
return nil, err
}
return &config, nil
}
func authHandler(isAdmin bool, configAuthToken string) gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
userCookie := session.Get("user")
xAuthToken := c.GetHeader("x-auth-token")
if (userCookie == nil || userCookie == "") && xAuthToken != configAuthToken {
c.AbortWithStatus(http.StatusForbidden)
} else {
if isAdmin && xAuthToken != configAuthToken {
user := &UserStruct{}
json.Unmarshal([]byte(userCookie.(string)), &user)
// Prevent anyone who is not logged in to view this page.
if user == nil || !user.IsAdmin {
c.AbortWithStatus(http.StatusForbidden)
return
}
}
c.Next()
}
}
}
func main() {
customConfig := flag.String("config", "", "The path to a custom config file")
flag.Parse()
db, err := ConnectDB()
if err != nil {
panic(err)
}
config, err := parseConfig(customConfig)
if err != nil {
fmt.Println(err.Error())
return
}
bus := EventBus.New()
// Instanciate all of the route handlers here.
productHandlers := &ProductHandlers{
DB: db,
Bus: bus,
}
orderHandlers := &OrderHandlers{
DB: db,
Bus: bus,
Config: config,
}
userHandlers := &UserHandlers{
DB: db,
Config: config,
}
stationHandlers := &StationHandlers{
DB: db,
Config: config,
}
// Start listeningfor messages and send them to the clients, if there are any.
productHandlers.StartWSHandler()
adminAuthToken := config.Admin.Token
router := gin.Default()
router.LoadHTMLGlob("templates/*")
// Apply the sessions middleware.
store := cookie.NewStore([]byte(config.Secret))
router.Use(sessions.Sessions("mysession", store))
// Set the static/public path.
router.Use(static.Serve("/", static.LocalFile("./public", false)))
router.Any("/", func(c *gin.Context) {
session := sessions.Default(c)
userCookie := session.Get("user")
if userCookie == nil || userCookie == "" {
c.Redirect(http.StatusMovedPermanently, "/login")
return
}
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "POS",
"admin": false,
})
})
router.GET("/admin", authHandler(true, adminAuthToken), func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Admin",
"admin": true,
})
})
router.POST("/login", userHandlers.Login)
router.GET("/login", userHandlers.LoginPage)
router.GET("/logout", userHandlers.Logout)
router.GET("/api/user", authHandler(false, adminAuthToken), userHandlers.GetLoggedInUser)
router.POST("/api/user", authHandler(true, adminAuthToken), userHandlers.Create)
router.DELETE("/api/user/:userId", authHandler(true, adminAuthToken), userHandlers.Delete)
router.GET("/api/users", authHandler(true, adminAuthToken), userHandlers.List)
router.GET("/api/orders/earnings", authHandler(true, adminAuthToken), orderHandlers.GetTotalEarnings)
router.GET("/api/orders/earnings/:day", authHandler(true, adminAuthToken), orderHandlers.EarningsPerDay)
router.GET("/api/orders/totals/export", authHandler(true, adminAuthToken), orderHandlers.ExportTotalEarnings)
router.GET("/api/orders", authHandler(false, adminAuthToken), orderHandlers.GetOrders)
router.GET("/api/orders/past_year", authHandler(true, adminAuthToken), orderHandlers.OrdersPastYear)
router.POST("/api/order", authHandler(false, adminAuthToken), orderHandlers.CreateOrder)
router.GET("/api/order/:orderId", authHandler(false, adminAuthToken), orderHandlers.FetchOrder)
router.GET("/api/order/:orderId/receipt/:printerId", authHandler(false, adminAuthToken), orderHandlers.PrintReceipt)
router.GET("/api/order/:orderId/pub", orderHandlers.PublicOrder)
router.GET("/api/order/:orderId/qrcode", authHandler(false, adminAuthToken), orderHandlers.OrderQRCode)
router.PUT("/api/order/:orderId/product/:productId/:state", authHandler(false, adminAuthToken), orderHandlers.UpdateFulfilled)
router.DELETE("/api/order/:orderId", authHandler(true, adminAuthToken), orderHandlers.ToggleOrder)
router.POST("/api/product", authHandler(true, adminAuthToken), productHandlers.CreateProduct)
router.GET("/api/products", authHandler(false, adminAuthToken), productHandlers.ListProducts)
router.PUT("/api/product/:productId", authHandler(false, adminAuthToken), productHandlers.UpdateProduct)
router.DELETE("/api/product/:productId", authHandler(false, adminAuthToken), productHandlers.ToggleDiscontinued)
router.PUT("/api/product/type", authHandler(true, adminAuthToken), productHandlers.CreateProductType)
router.GET("/api/product/types", productHandlers.ListProductTypes)
router.POST("/api/station", authHandler(true, adminAuthToken), stationHandlers.CreateStation)
router.POST("/api/station/:stationId/:productId", authHandler(true, adminAuthToken), stationHandlers.AddProductToStation)
router.DELETE("/api/station/:stationId/:productId", authHandler(true, adminAuthToken), stationHandlers.RemoveProductFromStation)
router.GET("/api/station/:stationId", authHandler(false, adminAuthToken), stationHandlers.Station)
router.DELETE("/api/station/:stationId", authHandler(true, adminAuthToken), stationHandlers.Delete)
router.GET("/api/stations", authHandler(false, adminAuthToken), stationHandlers.Stations)
router.GET("/api/printers", func(c *gin.Context) {
c.JSON(http.StatusOK, &ApiResponse{
Data: config.Printers,
Success: true,
})
})
// The websocket and streaming endpoints.
router.GET("/api/products/ws", authHandler(false, adminAuthToken), productHandlers.ProductUpdateWS)
router.GET("/api/products/stream", authHandler(false, adminAuthToken), productHandlers.ProductUpdateStream)
router.GET("/api/orders/stream", authHandler(false, adminAuthToken), orderHandlers.OrderStream)
router.Run(":" + strconv.Itoa(config.Server.Port))
}