-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthentication.go
More file actions
47 lines (41 loc) · 1.19 KB
/
authentication.go
File metadata and controls
47 lines (41 loc) · 1.19 KB
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
package main
import (
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func authRequired(c *gin.Context) {
session := sessions.Default(c)
id := session.Get("id")
if id == nil {
c.String(http.StatusUnauthorized, "Unauthorized")
c.Abort()
return
}
c.Next()
}
func getUUID() string {
return uuid.NewString()
}
func initCookies(router *gin.Engine) {
uuid := getUUID()
store := cookie.NewStore([]byte(uuid))
router.Use(sessions.Sessions("session", store))
}
func basicAuth(c *gin.Context) {
session := sessions.Default(c)
user, pass, hasAuth := c.Request.BasicAuth()
if hasAuth && user == tomlConf.AdminUsername && pass == tomlConf.AdminPassword {
session.Set("id", user)
if err := session.Save(); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to save session."})
return
}
c.Redirect(http.StatusSeeOther, "/topology")
} else {
c.Header("WWW-Authenticate", "Basic realm=Restricted")
c.AbortWithStatus(http.StatusUnauthorized)
}
}