-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
111 lines (100 loc) · 2.43 KB
/
http.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
package main
import (
"errors"
"net/http"
"time"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"gopkg.in/mgo.v2/bson"
)
type login struct {
Username string `form:"username" json:"username" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func runHTTPServer(listenAddr, secretKey, rootPwd string) {
r := gin.Default()
if rootPwd != "" {
logger.Warning("Root password is enabled!")
}
rootUser := User{
UID: 0, GID: 0,
Username: "root",
Name: "Root Admin",
IsActive: true,
IsAdmin: true,
}
jwtMidware := &jwt.GinJWTMiddleware{
Realm: "TUNA",
Key: []byte(secretKey),
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
Authenticator: func(c *gin.Context) (interface{}, error) {
var loginVals login
if err := c.ShouldBind(&loginVals); err != nil {
return "", jwt.ErrMissingLoginValues
}
username := loginVals.Username
password := loginVals.Password
if rootPwd != "" {
if username == "root" && rootPwd == password {
c.Set("user", rootUser)
return username, nil
}
}
m := getMongo()
defer m.Close()
users := m.FindUsers(bson.M{"username": username}, "")
if len(users) != 1 {
return username, errors.New("Wrong user or password")
}
user := users[0]
if !user.Authenticate(password) {
return "", errors.New("Wrong user or password")
}
c.Set("user", user)
return username, nil
},
Authorizator: func(data interface{}, c *gin.Context) bool {
username, ok := data.(string)
if !ok {
return false
}
if username == "root" {
c.Set("user", rootUser)
return true
}
m := getMongo()
defer m.Close()
users := m.FindUsers(bson.M{"username": username}, "")
if len(users) != 1 {
return false
}
user := users[0]
if !user.IsActive {
return false
}
c.Set("user", user)
return true
},
}
r.POST("/login", jwtMidware.LoginHandler)
api := r.Group("/api/v1")
api.Use(jwtMidware.MiddlewareFunc())
{
api.GET("/refresh_token", jwtMidware.RefreshHandler)
api.POST("/admin/passwd", apiUpdatePassowrd)
api.GET("/users/", apiListUsers)
}
httpServer := &http.Server{
Addr: listenAddr,
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
go func() {
logger.Noticef("HTTP Serving on: %s", listenAddr)
if err := httpServer.ListenAndServe(); err != nil {
logger.Panic(err.Error())
}
}()
}