fathom/api/auth.go

47 lines
1.1 KiB
Go
Raw Normal View History

2016-11-22 21:33:50 +00:00
package api
import (
"net/http"
"github.com/gorilla/sessions"
"os"
2016-11-22 21:33:50 +00:00
)
var store = sessions.NewFilesystemStore( "./storage/sessions/", []byte(os.Getenv("ANA_SECRET_KEY")))
// 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")
if ! session.IsNew {
session.Options.MaxAge = -1
session.Save(r, w)
}
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) {
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 {
w.WriteHeader(http.StatusUnauthorized)
2016-11-22 21:33:50 +00:00
return
}
2016-11-22 21:33:50 +00:00
next.ServeHTTP(w, r)
2016-11-22 21:33:50 +00:00
})
}