-
Notifications
You must be signed in to change notification settings - Fork 1
/
admin.go
73 lines (66 loc) · 2.29 KB
/
admin.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
package zauth
import (
"net/http"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/liuzl/store"
"go.uber.org/zap"
"zliu.org/goutil"
)
func (m *Middleware) addAccountHandler(w http.ResponseWriter, r *http.Request) {
caddy.Log().Info("addAccountHandler",
zap.String("remote_addr", r.RemoteAddr),
zap.String("method", r.Method),
zap.String("host", r.Host),
zap.String("request_uri", r.RequestURI))
r.ParseForm()
uname := strings.TrimSpace(r.FormValue("uname"))
ak := goutil.GenerateRandomString(20)
sk := goutil.GenerateRandomString(40)
account := &Account{Uname: uname, AccessKey: ak, SecretKey: sk}
b, err := store.ObjectToBytes(account)
if err != nil {
caddy.Log().Fatal("fatal error", zap.Error(err))
}
err = m.getAuthDB().Put(ak, b)
caddy.Log().Info("new account",
zap.String("uname", uname), zap.String("ak", ak), zap.String("sk", sk))
ret := MakeResponse(err, "", account)
MustEncode(w, ret)
}
func (m *Middleware) getAllAccountsHandler(w http.ResponseWriter, r *http.Request) {
caddy.Log().Info("getAllAccountsHandler",
zap.String("remote_addr", r.RemoteAddr),
zap.String("method", r.Method),
zap.String("host", r.Host),
zap.String("request_uri", r.RequestURI))
var accounts []*Account
err := m.getAuthDB().ForEach(nil, func(key, value []byte) (bool, error) {
account := new(Account)
if e := store.BytesToObject(value, account); e != nil {
return false, e
}
accounts = append(accounts, account)
return true, nil
})
ret := MakeResponse(err, "", accounts)
MustEncode(w, ret)
}
func (m *Middleware) delAccountHandler(w http.ResponseWriter, r *http.Request) {
caddy.Log().Info("delAccountHandler",
zap.String("remote_addr", r.RemoteAddr),
zap.String("method", r.Method),
zap.String("host", r.Host),
zap.String("request_uri", r.RequestURI))
ak := strings.TrimSpace(r.FormValue("ak"))
err := m.getAuthDB().Delete(ak)
ret := MakeResponse(err, "", 1)
MustEncode(w, ret)
}
func (m *Middleware) admin() {
http.HandleFunc("/zauth/add_account", m.addAccountHandler)
http.HandleFunc("/zauth/get_all_accounts", m.getAllAccountsHandler)
http.HandleFunc("/zauth/del_account", m.delAccountHandler)
caddy.Log().Info("zauth admin server started", zap.String("listen", m.AuthAdminAddr))
caddy.Log().Error("zauth", zap.Error(http.ListenAndServe(m.AuthAdminAddr, nil)))
}