harness-drone/handler/api/auth/auth.go
2019-02-19 15:56:41 -08:00

46 lines
1.4 KiB
Go

// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
package auth
import (
"net/http"
"github.com/drone/drone/handler/api/request"
"github.com/drone/drone/logger"
"github.com/drone/drone/core"
)
// HandleAuthentication returns an http.HandlerFunc middlewrae that authenticates
// the http.Request and errors if the account cannot be authenticated.
func HandleAuthentication(session core.Session) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := logger.FromContext(ctx)
user, err := session.Get(r)
// this block of code checks the error message and user
// returned from the session, including some edge cases,
// to prevent a session from being falsely created.
if err != nil || user == nil || user.ID == 0 {
next.ServeHTTP(w, r)
log.Debugln("api: guest access")
return
}
if user.Machine {
log = log.WithField("user.machine", user.Machine)
}
if user.Admin {
log = log.WithField("user.admin", user.Admin)
}
log = log.WithField("user.login", user.Login)
ctx = logger.WithContext(ctx, log)
next.ServeHTTP(w, r.WithContext(
request.WithUser(ctx, user),
))
})
}
}