fathom/api/auth.go

81 lines
2.0 KiB
Go
Raw Normal View History

2016-11-22 21:33:50 +00:00
package api
import (
2016-12-11 13:50:01 +00:00
"encoding/json"
"github.com/dannyvankooten/ana/db"
"github.com/dannyvankooten/ana/models"
"github.com/gorilla/sessions"
"golang.org/x/crypto/bcrypt"
"net/http"
"os"
2016-11-22 21:33:50 +00:00
)
type Login struct {
2016-12-11 13:50:01 +00:00
Email string `json:"email"`
Password string `json:"password"`
}
var store = sessions.NewFilesystemStore("./storage/sessions/", []byte(os.Getenv("ANA_SECRET_KEY")))
// URL: POST /api/session
var LoginHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2016-12-11 13:50:01 +00:00
var l Login
json.NewDecoder(r.Body).Decode(&l)
2016-12-11 13:50:01 +00:00
// check login creds
var hashedPassword string
var u models.User
stmt, _ := db.Conn.Prepare("SELECT id, email, password FROM users WHERE email = ? LIMIT 1")
err := stmt.QueryRow(l.Email).Scan(&u.ID, &u.Email, &hashedPassword)
2016-12-11 13:50:01 +00:00
if err != nil || bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(l.Password)) != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
2016-12-11 13:50:01 +00:00
// TODO: Replace session filesystem store with DB store.
session, _ := store.Get(r, "auth")
session.Values["user_id"] = u.ID
err = session.Save(r, w)
checkError(err)
2016-12-11 13:50:01 +00:00
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("true"))
})
// URL: DELETE /api/session
var LogoutHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2016-12-11 13:50:01 +00:00
session, _ := store.Get(r, "auth")
if !session.IsNew {
session.Options.MaxAge = -1
session.Save(r, w)
}
2016-12-11 13:50:01 +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 {
2016-12-11 13:50:01 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "auth")
userID, ok := session.Values["user_id"]
2016-12-11 13:50:01 +00:00
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
2016-11-22 21:33:50 +00:00
2016-12-11 13:50:01 +00:00
// find user
var u models.User
stmt, _ := db.Conn.Prepare("SELECT id, email FROM users WHERE id = ? LIMIT 1")
err := stmt.QueryRow(userID).Scan(&u.ID, &u.Email)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
2016-11-22 21:33:50 +00:00
2016-12-11 13:50:01 +00:00
next.ServeHTTP(w, r)
})
2016-11-22 21:33:50 +00:00
}