forked from P-E-D-L/proclone
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauthorization.go
More file actions
81 lines (70 loc) · 2.02 KB
/
authorization.go
File metadata and controls
81 lines (70 loc) · 2.02 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
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
package middleware
import (
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
// authRequired provides authentication middleware for ensuring that a user is logged in.
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 AdminRequired(c *gin.Context) {
session := sessions.Default(c)
id := session.Get("id")
if id == nil {
c.String(http.StatusUnauthorized, "Unauthorized")
c.Abort()
return
}
isAdmin := session.Get("isAdmin")
if isAdmin == nil || !isAdmin.(bool) {
c.String(http.StatusForbidden, "Admin access required")
c.Abort()
return
}
c.Next()
}
func GetUser(c *gin.Context) string {
userID := sessions.Default(c).Get("id")
if userID != nil {
return userID.(string)
}
return ""
}
func Logout(c *gin.Context) {
session := sessions.Default(c)
id := session.Get("id")
if id == nil {
c.JSON(http.StatusOK, gin.H{"message": "No session."})
return
}
session.Delete("id")
if err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Successfully logged out!"})
}
func CORSMiddleware(fqdn string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "application/json; text/event-stream")
c.Writer.Header().Set("Access-Control-Allow-Origin", fqdn)
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Origin")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
}
c.Next()
}
}