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) {
|
func Whoami(w http.ResponseWriter, r *http.Request) {
|
||||||
user, ok := r.Context().Value(userKey{}).(*User)
|
user, ok := r.Context().Value(userKey{}).(*User)
|
||||||
if !ok {
|
if !ok || user == nil {
|
||||||
w.Write([]byte("undefined"))
|
// Anonymous user
|
||||||
return
|
w.Write([]byte("anonymous"))
|
||||||
} else {
|
|
||||||
w.Write([]byte(user.Name))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
w.Write([]byte(user.Name))
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoginCtx(next http.Handler) http.Handler {
|
func LoginCtx(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
var user *User
|
// Try to retrieve username from context
|
||||||
var err error
|
username, ok := r.Context().Value(usernameKey).(string)
|
||||||
|
if !ok || username == "" {
|
||||||
if username := r.Context().Value(usernameKey).(string); username != "" {
|
// No username provided, assume it's an anonymous user
|
||||||
user, err = dbGetUserByName(username)
|
next.ServeHTTP(w, r)
|
||||||
} else {
|
|
||||||
render.Render(w, r, ErrNotFound)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Lookup user in the database
|
||||||
|
user, err := dbGetUserByName(username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// If user is specified and not found, throw an error
|
||||||
render.Render(w, r, ErrNotFound)
|
render.Render(w, r, ErrNotFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user