-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
377 lines (323 loc) · 9.32 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
368
369
370
371
372
373
374
375
376
377
package main
import (
"embed"
"encoding/json"
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"html/template"
"isley/config"
"isley/handlers"
"isley/logger"
"isley/model"
"isley/routes"
"isley/utils"
"isley/watcher"
"net/http"
"os"
"strconv"
"strings"
"time"
)
//go:embed model/migrations/*.sql web/templates/* web/static/**/* utils/fonts/* VERSION
var embeddedFiles embed.FS
func main() {
// Initialize logger
logger.InitLogger()
// Set version
version := fmt.Sprintf("Isley %s", getVersion())
logger.Log.Info("Starting application version:", version)
// Define the port
port := os.Getenv("ISLEY_PORT")
if port == "" {
port = "8080" // Default port if environment variable PORT is not set
}
model.MigrateDB()
model.InitDB()
// Initialize translation service
utils.Init("en")
// Initialize default admin credentials if not present
present, err := handlers.ExistsSetting("auth_username")
if err != nil {
logger.Log.WithError(err).Error("Error checking if default admin credentials are present")
} else {
if !present {
handlers.UpdateSetting("auth_username", "admin")
hashedPassword, _ := utils.HashPassword("isley")
handlers.UpdateSetting("auth_password", hashedPassword)
handlers.UpdateSetting("force_password_change", "true")
}
}
// Start the sensor watcher
watcher.PruneSensorData()
go watcher.Watch()
// Set up Gin router
r := gin.Default()
funcMap := template.FuncMap{
"upper": strings.ToUpper, // Define the 'upper' function
"default": func(val interface{}, def string) string {
if str, ok := val.(string); ok && str != "" {
return str
}
return def
},
"json": func(v interface{}) string {
a, err := json.Marshal(v)
if err != nil {
logger.Log.WithError(err).Error("Error marshalling JSON")
return ""
}
return string(a)
},
"formatStringDateTimeLocal": func(t string) string {
parsedTime, err := time.Parse(time.RFC3339, t)
if err != nil {
return "" // Return empty if parsing fails
}
return parsedTime.Format("2006-01-02T15:04")
},
"formatDateTimeLocal": func(t time.Time) string {
return t.Format("2006-01-02T15:04")
},
"toLocalTimeString": func(t time.Time) string {
if err != nil {
return "" // Fallback to the original string if parsing fails
}
return t.In(time.Local).Format("01/02/2006 03:04 PM")
},
"formatDate": func(t time.Time) string {
return t.Format("01/02/2006")
},
"formatDateTime": func(t time.Time) string { return t.Format("01/02/2006 03:04 PM") },
"formatDateISO": func(t time.Time) string {
return t.Format("2006-01-02")
},
"formatStringDate": func(t string) string {
tm, err := time.Parse(time.RFC3339, t)
if err != nil {
logger.Log.WithFields(logrus.Fields{
"input": t,
"error": err,
}).Error("Error parsing date")
return t
}
return tm.Format("01/02/2006")
},
"toInt": func(value interface{}) int {
switch v := value.(type) {
case string:
intVal, err := strconv.Atoi(v)
if err != nil {
logger.Log.WithFields(logrus.Fields{
"input": v,
"error": err,
}).Error("Error converting string to int")
return 0
}
return intVal
case float64:
return int(v)
case int:
return v
default:
logger.Log.WithField("input", value).Warn("Unhandled type in toInt conversion")
return 0
}
},
"preview": func(t string) string {
if len(t) > 100 {
return t[:100] + "..."
}
return t
},
"now": func() time.Time {
return time.Now()
},
}
// Attach FuncMap and ParseFS
templ := template.Must(template.New("").Funcs(funcMap).ParseFS(embeddedFiles, "web/templates/**/*"))
// Set HTML templates in Gin
r.SetHTMLTemplate(templ)
// Load settings (PollingInterval, ACIEnabled, etc.)
handlers.LoadSettings()
r.Static("/uploads", "./uploads")
r.GET("/static/*filepath", func(c *gin.Context) {
filePath := fmt.Sprintf("web/static%s", c.Param("filepath"))
data, err := embeddedFiles.ReadFile(filePath)
if err != nil {
c.Status(http.StatusNotFound)
return
}
http.ServeContent(c.Writer, c.Request, filePath, time.Now().In(time.Local), strings.NewReader(string(data)))
})
r.GET("/fonts/*filepath", func(c *gin.Context) {
filePath := fmt.Sprintf("utils/fonts%s", c.Param("filepath"))
data, err := embeddedFiles.ReadFile(filePath)
if err != nil {
c.Status(http.StatusNotFound)
return
}
http.ServeContent(c.Writer, c.Request, filePath, time.Now().In(time.Local), strings.NewReader(string(data)))
})
// Initialize session store
store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("isley_session", store))
// Public routes
r.GET("/login", func(c *gin.Context) {
lang := utils.GetLanguage(c)
translations := utils.TranslationService.GetTranslations(lang)
c.HTML(http.StatusOK, "views/login.html", gin.H{
"lcl": translations,
"languages": utils.AvailableLanguages,
"currentLanguage": lang,
})
})
r.POST("/login", func(c *gin.Context) {
handleLogin(c)
})
r.GET("/logout", func(c *gin.Context) {
handleLogout(c)
})
r.GET("/favicon.ico", func(c *gin.Context) {
// Open the favicon from the embedded filesystem
faviconData, err := embeddedFiles.ReadFile("web/static/img/favicon.ico")
if err != nil {
c.String(500, "Failed to load favicon")
return
}
// Write the favicon data to the response
c.Data(200, "image/x-icon", faviconData)
})
guestMode := false
if config.GuestMode == 1 {
guestMode = true
}
if guestMode {
routes.AddBasicRoutes(r.Group("/"), version)
}
protected := r.Group("/")
protected.Use(AuthMiddleware())
{
protected.Use(ForcePasswordChangeMiddleware())
protected.GET("/change-password", func(c *gin.Context) {
lang := utils.GetLanguage(c)
translations := utils.TranslationService.GetTranslations(lang)
c.HTML(http.StatusOK, "views/change-password.html", gin.H{
"lcl": translations,
"languages": utils.AvailableLanguages,
"currentLanguage": lang,
})
})
protected.POST("/change-password", func(c *gin.Context) {
handleChangePassword(c)
})
routes.AddProtectedRotues(protected, version)
if !guestMode {
routes.AddBasicRoutes(protected, version)
}
}
apiProtected := r.Group("/")
apiProtected.Use(AuthMiddlewareApi())
{
routes.AddProtectedApiRoutes(apiProtected)
}
// Start the server
logger.Log.Fatal(r.Run(":" + port))
logger.Log.Info("Server started on port %s", port)
}
func handleLogin(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
storedUsername, _ := handlers.GetSetting("auth_username")
storedPasswordHash, _ := handlers.GetSetting("auth_password")
forcePasswordChange, _ := handlers.GetSetting("force_password_change")
if username != storedUsername || !utils.CheckPasswordHash(password, storedPasswordHash) {
c.HTML(http.StatusUnauthorized, "views/login.html", gin.H{
"Error": "Invalid username or password",
})
return
}
session := sessions.Default(c)
session.Set("logged_in", true)
session.Set("force_password_change", forcePasswordChange == "true")
session.Save()
if forcePasswordChange == "true" {
c.Redirect(http.StatusFound, "/change-password")
return
}
c.Redirect(http.StatusFound, "/")
}
func handleLogout(c *gin.Context) {
session := sessions.Default(c)
session.Clear()
session.Save()
c.Redirect(http.StatusFound, "/login")
}
func handleChangePassword(c *gin.Context) {
newPassword := c.PostForm("new_password")
confirmPassword := c.PostForm("confirm_password")
if newPassword != confirmPassword {
c.HTML(http.StatusBadRequest, "views/change-password.html", gin.H{
"Error": "Passwords do not match",
})
return
}
hashedPassword, _ := utils.HashPassword(newPassword)
handlers.UpdateSetting("auth_password", hashedPassword)
handlers.UpdateSetting("force_password_change", "false")
session := sessions.Default(c)
session.Set("force_password_change", false)
session.Save()
c.Redirect(http.StatusFound, "/")
}
func AuthMiddlewareApi() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
loggedIn := session.Get("logged_in")
if loggedIn == nil || !loggedIn.(bool) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
c.Next()
}
}
// Middleware to enforce authentication
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
loggedIn := session.Get("logged_in")
if loggedIn == nil || !loggedIn.(bool) {
c.Redirect(http.StatusFound, "/login")
c.Abort()
return
}
c.Next()
}
}
// Middleware to enforce password change
func ForcePasswordChangeMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
forcePasswordChange := session.Get("force_password_change")
// Allow access to /change-password (both GET and POST) if force password change is required
if forcePasswordChange != nil && forcePasswordChange.(bool) {
if c.FullPath() != "/change-password" {
c.Redirect(http.StatusFound, "/change-password")
c.Abort()
return
}
}
c.Next()
}
}
func getVersion() string {
// Read the VERSION file from the embedded filesystem
data, err := embeddedFiles.ReadFile("VERSION")
if err != nil {
return "dev" // fallback to "dev" for local builds
}
return strings.TrimSpace(string(data))
}