Compare commits

...

2 Commits

Author SHA1 Message Date
14c78536de use login context with newmessage 2025-04-07 22:18:54 -04:00
32bfd109b9 add user identification 2025-04-07 22:08:46 -04:00
3 changed files with 52 additions and 7 deletions

View File

@@ -36,6 +36,12 @@ func Start() {
panic("oh no")
})
r.Route("/whoami", func(r chi.Router) {
r.Use(SessionAuthMiddleware)
r.Use(LoginCtx)
r.Get("/", Whoami)
})
r.Route("/messages", func(r chi.Router) {
r.Use(SessionAuthMiddleware) // Protect with authentication
@@ -46,7 +52,10 @@ func Start() {
r.Delete("/", DeleteMessage)
r.Post("/edit", EditMessage)
})
r.Post("/new", NewMessage)
r.Route("/new", func(r chi.Router) {
r.Use(LoginCtx)
r.Post("/", NewMessage)
})
})
r.Route("/users", func(r chi.Router) {

View File

@@ -115,11 +115,14 @@ func NewMessage(w http.ResponseWriter, r *http.Request) {
return
}
userID := r.FormValue("user_id")
if userID == "" {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
// userID := r.FormValue("user_id")
//if userID == "" {
// http.Error(w, "Invalid user ID", http.StatusBadRequest)
// return
//}
var user = r.Context().Value(userKey{}).(*User)
body := r.FormValue("body")
if body == "" {
@@ -129,7 +132,7 @@ func NewMessage(w http.ResponseWriter, r *http.Request) {
msg := Message{
ID: newMessageID(),
UserID: userID,
UserID: user.ID,
Body: body,
Timestamp: time.Now(),
Edited: time.Time{},

View File

@@ -30,6 +30,39 @@ func UserCtx(next http.Handler) http.Handler {
})
}
func Whoami(w http.ResponseWriter, r *http.Request) {
user, ok := r.Context().Value(userKey{}).(*User)
if !ok {
w.Write([]byte("undefined"))
return
} else {
w.Write([]byte(user.Name))
return
}
}
func LoginCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var user *User
var err error
if username := r.Context().Value(usernameKey).(string); username != "" {
user, err = dbGetUserByName(username)
} else {
render.Render(w, r, ErrNotFound)
return
}
if err != nil {
render.Render(w, r, ErrNotFound)
return
}
ctx := context.WithValue(r.Context(), userKey{}, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetUser(w http.ResponseWriter, r *http.Request) {
user, ok := r.Context().Value(userKey{}).(*User)
if !ok || user == nil {