package api import ( "bytes" "encoding/base64" "encoding/json" "net/http" "strings" "github.com/astaxie/session" "github.com/julienschmidt/httprouter" ) type JsonResult struct { Data interface{} `json:"data"` Session struct { Login interface{} `json:"login"` Profil map[string]interface{} `json:"profil"` } `json:"session"` } func JsonOutput(sessions *session.Manager, w http.ResponseWriter, r *http.Request, data interface{}) { sess := sessions.SessionStart(w, r) result := JsonResult{Data: data} result.Session.Login = sess.Get("login") js, err := json.Marshal(result) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", 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.Header().Set("Access-Control-Allow-Credentials", "true") w.Write(js) } func BasicAuth(h httprouter.Handle, pass []byte) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { if origin := r.Header.Get("Origin"); origin != "" { w.Header().Set("Access-Control-Allow-Origin", 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.Header().Set("Access-Control-Allow-Credentials", "true") const basicAuthPrefix string = "Basic " // Get the Basic Authentication credentials 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 h(w, r, ps) return } } } // Request Basic Authentication otherwise w.Header().Set("WWW-Authenticate", "Basic realm=Restricted") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) } }