-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
52 lines (45 loc) · 1.04 KB
/
auth.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
package main
import (
"os"
"github.com/gin-gonic/gin"
)
var (
adminUsername = os.Getenv("ADMIN_USERNAME")
adminPassword = os.Getenv("ADMIN_PASSWORD")
)
func init() {
assertBadPassword()
}
var protectPrivate gin.HandlerFunc = func(c *gin.Context) {
path := c.Request.URL.Path
if isLikePrivatePath(path) && !isLoggedIn(c) {
c.Status(404)
c.Abort()
}
}
var checkAuth gin.HandlerFunc = func(c *gin.Context) {
if !isLoggedIn(c) {
c.JSON(401, errorRes{"Login required"})
c.Abort()
}
}
func authApis(r *gin.Engine) {
r.POST("/api/login", ratelimitLoginApi(), func(c *gin.Context) {
json := &loginReq{}
_ = c.BindJSON(json)
if json.Username == adminUsername && json.Password == adminPassword {
setUser(c, json.Username)
c.JSON(200, successRes{})
} else {
c.JSON(400, errorRes{"Wrong username or password"})
securityLog(c, "Failed attempt to login")
}
})
r.GET("/api/session", checkAuth, func(c *gin.Context) {
c.JSON(200, getConfigRes())
})
}
func isLoggedIn(c *gin.Context) bool {
_, ok := getUser(c)
return ok
}