41 lines
824 B
Go
41 lines
824 B
Go
package routing
|
|
|
|
import (
|
|
"lishwist/db"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/Teajey/sqlstore"
|
|
)
|
|
|
|
type Context struct {
|
|
store *sqlstore.Store
|
|
}
|
|
|
|
func NewContext(store *sqlstore.Store) *Context {
|
|
return &Context{
|
|
store,
|
|
}
|
|
}
|
|
|
|
func (ctx *Context) ExpectUser(next func(*db.User, http.ResponseWriter, *http.Request)) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
session, _ := ctx.store.Get(r, "lishwist_user")
|
|
username, ok := session.Values["username"].(string)
|
|
if !ok {
|
|
log.Println("Failed to get username")
|
|
http.Error(w, "", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
user, err := db.GetUserByName(username)
|
|
if err != nil {
|
|
log.Printf("Failed to get user: %s\n", err)
|
|
http.Error(w, "", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
next(user, w, r)
|
|
})
|
|
}
|