allow LoginCtx to handle anonymous users
This commit is contained in:
25
api/user.go
25
api/user.go
@@ -32,28 +32,29 @@ 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))
|
||||
if !ok || user == nil {
|
||||
// Anonymous user
|
||||
w.Write([]byte("anonymous"))
|
||||
return
|
||||
}
|
||||
|
||||
w.Write([]byte(user.Name))
|
||||
}
|
||||
|
||||
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)
|
||||
// Try to retrieve username from context
|
||||
username, ok := r.Context().Value(usernameKey).(string)
|
||||
if !ok || username == "" {
|
||||
// No username provided, assume it's an anonymous user
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Lookup user in the database
|
||||
user, err := dbGetUserByName(username)
|
||||
if err != nil {
|
||||
// If user is specified and not found, throw an error
|
||||
render.Render(w, r, ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
Reference in New Issue
Block a user