2016-11-22 21:33:50 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2016-11-23 14:51:19 +00:00
|
|
|
"github.com/gorilla/sessions"
|
2016-11-25 15:30:38 +00:00
|
|
|
"os"
|
2016-11-22 21:33:50 +00:00
|
|
|
)
|
|
|
|
|
2016-11-25 15:30:38 +00:00
|
|
|
var store = sessions.NewFilesystemStore( "./storage/sessions/", []byte(os.Getenv("ANA_SECRET_KEY")))
|
2016-11-23 14:51:19 +00:00
|
|
|
|
|
|
|
// URL: POST /api/session
|
|
|
|
var Login = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
session, _ := store.Get(r, "auth")
|
|
|
|
session.Values["user"] = "Danny"
|
|
|
|
err := session.Save(r, w)
|
|
|
|
checkError(err)
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Write([]byte("true"))
|
|
|
|
})
|
|
|
|
|
|
|
|
// URL: DELETE /api/session
|
|
|
|
var Logout = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
session, _ := store.Get(r, "auth")
|
2016-11-25 15:30:38 +00:00
|
|
|
if ! session.IsNew {
|
|
|
|
session.Options.MaxAge = -1
|
|
|
|
session.Save(r, w)
|
|
|
|
}
|
2016-11-23 14:51:19 +00:00
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Write([]byte("true"))
|
|
|
|
})
|
|
|
|
|
|
|
|
/* middleware */
|
2016-11-22 21:33:50 +00:00
|
|
|
func Authorize(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2016-11-25 15:30:38 +00:00
|
|
|
session, _ := store.Get(r, "auth")
|
2016-11-22 21:33:50 +00:00
|
|
|
|
2016-11-23 15:29:07 +00:00
|
|
|
if _, ok := session.Values["user"]; !ok {
|
2016-11-23 14:51:19 +00:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2016-11-22 21:33:50 +00:00
|
|
|
return
|
2016-11-23 14:51:19 +00:00
|
|
|
}
|
2016-11-22 21:33:50 +00:00
|
|
|
|
2016-11-23 14:51:19 +00:00
|
|
|
next.ServeHTTP(w, r)
|
2016-11-22 21:33:50 +00:00
|
|
|
})
|
|
|
|
}
|