Select Git revision
-
Steffen Schneider authoredSteffen Schneider authored
auth.go 2.41 KiB
/*
This file is part of SystemTestPortal.
Copyright (C) 2017 Institute of Software Technology, University of Stuttgart
SystemTestPortal is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SystemTestPortal is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SystemTestPortal. If not, see <http://www.gnu.org/licenses/>.
*/
package middleware
import (
"log"
"net/http"
"github.com/urfave/negroni"
"gitlab.com/stp-team/systemtestportal-webapp/domain/user"
"gitlab.com/stp-team/systemtestportal-webapp/web/errors"
)
// UserKey is used to retrieve the currently signed in user from
// the request context (nil if no user is signed in).
const UserKey = "user"
const (
badCookieTitle = "Invalid cookie!"
badCookie = "It seems the cookie you send in your request " +
"has spoiled. This only happens in really rare cases. " +
"If this error persists please <a href='" +
"https://www.howtogeek.com/111925/delete-cookies-in-" +
"the-five-most-popular-web-browsers-in-windows/'>remove your cookies</a>" +
" for this site."
)
// SessionHandler is used to get the user that corresponds to a request.
type SessionHandler interface {
// GetCurrent gets the user that hold the session. If there is no
// user session the returned user will be nil.
GetCurrent(r *http.Request) (*user.User, error)
}
// Auth returns a middleware that will check the user session
// for the signed in user.
// The retrieved user will be written into the request
// context with the key "user"
func Auth(session SessionHandler) negroni.HandlerFunc {
if session == nil {
log.Panic("Given session handler must not be nil!")
}
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
u, err := session.GetCurrent(r)
if err != nil {
errors.ConstructStd(http.StatusBadRequest, badCookieTitle, badCookie, r).
WithLog("Auth: Couldn't get user information out of request.").
WithStackTrace(1).
WithCause(err).
WithRequestDump(r).
Respond(w)
return
}
AddToContext(r, UserKey, u)
next(w, r)
}
}