Files
EdgeCommon/pkg/serverconfigs/http_auth_method_basic.go

66 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-05-17 18:28:59 +08:00
// Copyright 2021 GoEdge CDN goedge.cdn@gmail.com. All rights reserved.
2021-06-17 21:18:05 +08:00
package serverconfigs
import (
"encoding/json"
"net/http"
)
// HTTPAuthBasicMethodUser BasicAuth中的用户
type HTTPAuthBasicMethodUser struct {
Username string `json:"username"`
Password string `json:"password"`
}
func (this *HTTPAuthBasicMethodUser) Validate(password string) (bool, error) {
return this.Password == password, nil
2021-06-17 21:18:05 +08:00
}
// HTTPAuthBasicMethod BasicAuth方法定义
type HTTPAuthBasicMethod struct {
2022-08-30 11:24:07 +08:00
HTTPAuthBaseMethod
Users []*HTTPAuthBasicMethodUser `json:"users"`
Realm string `json:"realm"`
Charset string `json:"charset"`
2021-06-17 21:18:05 +08:00
userMap map[string]*HTTPAuthBasicMethodUser // username => *User
}
func NewHTTPAuthBasicMethod() *HTTPAuthBasicMethod {
return &HTTPAuthBasicMethod{}
}
2022-08-30 11:24:07 +08:00
func (this *HTTPAuthBasicMethod) Init(params map[string]any) error {
2021-06-17 21:18:05 +08:00
this.userMap = map[string]*HTTPAuthBasicMethodUser{}
paramsJSON, err := json.Marshal(params)
if err != nil {
return err
}
err = json.Unmarshal(paramsJSON, this)
if err != nil {
return err
}
for _, user := range this.Users {
this.userMap[user.Username] = user
}
return nil
}
2022-08-30 11:24:07 +08:00
func (this *HTTPAuthBasicMethod) Filter(req *http.Request, doSubReq func(subReq *http.Request) (status int, err error), formatter func(string) string) (ok bool, newURI string, uriChanged bool, err error) {
2021-06-17 21:18:05 +08:00
username, password, ok := req.BasicAuth()
if !ok {
2022-08-30 11:24:07 +08:00
return false, "", false, nil
2021-06-17 21:18:05 +08:00
}
user, ok := this.userMap[username]
if !ok {
2022-08-30 11:24:07 +08:00
return false, "", false, nil
2021-06-17 21:18:05 +08:00
}
2022-08-30 11:24:07 +08:00
ok, err = user.Validate(password)
return ok, "", false, err
2021-06-17 21:18:05 +08:00
}