fathom/pkg/api/auth.go

96 lines
2.0 KiB
Go
Raw Normal View History

2016-11-22 21:33:50 +00:00
package api
import (
2017-01-25 16:11:35 +00:00
"context"
2016-12-11 13:50:01 +00:00
"encoding/json"
2016-12-24 13:09:24 +00:00
"net/http"
"os"
2016-12-11 13:50:01 +00:00
"github.com/gorilla/sessions"
"github.com/usefathom/fathom/pkg/datastore"
2016-12-11 13:50:01 +00:00
"golang.org/x/crypto/bcrypt"
2016-11-22 21:33:50 +00:00
)
2017-01-25 16:11:35 +00:00
type key int
const (
userKey key = 0
)
2016-12-24 13:09:24 +00:00
type login struct {
2016-12-11 13:50:01 +00:00
Email string `json:"email"`
Password string `json:"password"`
}
var store = sessions.NewCookieStore([]byte(os.Getenv("FATHOM_SECRET")))
// URL: POST /api/session
var LoginHandler = HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
2016-12-11 13:50:01 +00:00
// check login creds
var l login
json.NewDecoder(r.Body).Decode(&l)
2017-01-25 16:11:35 +00:00
2018-04-25 11:45:21 +00:00
// find user with given email
2017-01-25 16:11:35 +00:00
u, err := datastore.GetUserByEmail(l.Email)
2018-04-25 11:45:21 +00:00
if err != nil && err != datastore.ErrNoResults {
return err
}
// compare pwd
2018-04-25 11:45:21 +00:00
if err == datastore.ErrNoResults || bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(l.Password)) != nil {
2016-12-11 13:50:01 +00:00
w.WriteHeader(http.StatusUnauthorized)
return respond(w, envelope{Error: "invalid_credentials"})
2016-12-11 13:50:01 +00:00
}
2016-12-11 13:50:01 +00:00
session, _ := store.Get(r, "auth")
session.Values["user_id"] = u.ID
err = session.Save(r, w)
if err != nil {
return err
}
return respond(w, envelope{Data: true})
})
// URL: DELETE /api/session
var LogoutHandler = HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
2016-12-11 13:50:01 +00:00
session, _ := store.Get(r, "auth")
if !session.IsNew {
session.Options.MaxAge = -1
err := session.Save(r, w)
if err != nil {
return err
}
2016-12-11 13:50:01 +00:00
}
return respond(w, envelope{Data: true})
})
/* middleware */
2016-11-22 21:33:50 +00:00
func Authorize(next http.Handler) http.Handler {
2016-12-11 13:50:01 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2018-05-10 20:21:44 +00:00
session, err := store.Get(r, "auth")
if err != nil {
return
}
2016-12-11 13:50:01 +00:00
userID, ok := session.Values["user_id"]
2018-04-25 11:45:21 +00:00
if session.IsNew || !ok {
2016-12-11 13:50:01 +00:00
w.WriteHeader(http.StatusUnauthorized)
return
}
2016-11-22 21:33:50 +00:00
2016-12-11 13:50:01 +00:00
// find user
2017-01-25 16:11:35 +00:00
u, err := datastore.GetUser(userID.(int64))
2016-12-11 13:50:01 +00:00
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
2016-11-22 21:33:50 +00:00
2017-01-25 16:11:35 +00:00
ctx := context.WithValue(r.Context(), userKey, u)
next.ServeHTTP(w, r.WithContext(ctx))
2016-12-11 13:50:01 +00:00
})
2016-11-22 21:33:50 +00:00
}