| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package auth
- import (
- "encoding/json"
- "net"
- "net/http"
- "strings"
- "quickip/internal/config"
- "quickip/internal/model"
- )
- func Middleware(cfg config.Config, next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if !allowedSource(r.RemoteAddr) {
- writeJSON(w, http.StatusForbidden, model.APIResponse{Code: 1003, Message: "来源 IP 不允许", Data: nil})
- return
- }
- password := r.Header.Get("X-Admin-Password")
- if password == "" {
- writeJSON(w, http.StatusUnauthorized, model.APIResponse{Code: 1001, Message: "缺少密码", Data: nil})
- return
- }
- if password != cfg.AdminPassword {
- writeJSON(w, http.StatusUnauthorized, model.APIResponse{Code: 1002, Message: "密码错误", Data: nil})
- return
- }
- next.ServeHTTP(w, r)
- })
- }
- func allowedSource(remoteAddr string) bool {
- host, _, err := net.SplitHostPort(remoteAddr)
- if err != nil {
- host = remoteAddr
- }
- ip := net.ParseIP(strings.TrimSpace(host))
- if ip == nil {
- return false
- }
- _, subnet, _ := net.ParseCIDR("169.254.0.0/16")
- return subnet.Contains(ip)
- }
- func writeJSON(w http.ResponseWriter, status int, payload model.APIResponse) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- _ = json.NewEncoder(w).Encode(payload)
- }
|