api access controll
This commit is contained in:
parent
668de8188d
commit
a4b947a9b6
49
api/lib.go
49
api/lib.go
|
@ -18,31 +18,38 @@ func jsonOutput(w http.ResponseWriter,data interface{}){
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
|
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
|
||||||
|
w.Header().Set("Access-Control-Allow-Headers","Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
||||||
w.Write(js)
|
w.Write(js)
|
||||||
}
|
}
|
||||||
func BasicAuth(h httprouter.Handle, pass []byte) httprouter.Handle {
|
func BasicAuth(h httprouter.Handle, pass []byte) httprouter.Handle {
|
||||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||||
const basicAuthPrefix string = "Basic "
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
|
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
|
||||||
|
w.Header().Set("Access-Control-Allow-Headers","Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
||||||
|
|
||||||
// Get the Basic Authentication credentials
|
const basicAuthPrefix string = "Basic "
|
||||||
auth := r.Header.Get("Authorization")
|
|
||||||
if strings.HasPrefix(auth, basicAuthPrefix) {
|
|
||||||
// Check credentials
|
|
||||||
payload, err := base64.StdEncoding.DecodeString(auth[len(basicAuthPrefix):])
|
|
||||||
if err == nil {
|
|
||||||
pair := bytes.SplitN(payload, []byte(":"), 2)
|
|
||||||
if len(pair) == 2 &&
|
|
||||||
bytes.Equal(pair[1], pass) {
|
|
||||||
|
|
||||||
// Delegate request to the given handle
|
// Get the Basic Authentication credentials
|
||||||
h(w, r, ps)
|
auth := r.Header.Get("Authorization")
|
||||||
return
|
if strings.HasPrefix(auth, basicAuthPrefix) {
|
||||||
}
|
// Check credentials
|
||||||
}
|
payload, err := base64.StdEncoding.DecodeString(auth[len(basicAuthPrefix):])
|
||||||
}
|
if err == nil {
|
||||||
|
pair := bytes.SplitN(payload, []byte(":"), 2)
|
||||||
|
if len(pair) == 2 &&
|
||||||
|
bytes.Equal(pair[1], pass) {
|
||||||
|
|
||||||
// Request Basic Authentication otherwise
|
// Delegate request to the given handle
|
||||||
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
|
h(w, r, ps)
|
||||||
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request Basic Authentication otherwise
|
||||||
|
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
|
||||||
|
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue