Exemple #1
0
// basicAuthHandlerFunc is a middleware function to authenticate HTTP requests.
func (s *svc) basicAuthHandlerFunc(handler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		log := keys.MustGetLog(r)

		// try to get token from cookie
		authCookie, err := r.Cookie("ClawIO_Token")
		if err == nil {
			user, err := s.authenticator.CreateUserFromToken(authCookie.Value)
			if err == nil {
				r = keys.SetUser(r, user)
				log.WithField("user", user.Username).Info("authenticated request")
				handler(w, r)
				return
			}
			log.WithError(err).Warn("token is not valid anymore")
		} else {
			log.WithError(err).Warn("cookie is not valid")
		}

		// try to get credentials using basic auth
		username, password, ok := r.BasicAuth()
		if !ok {
			log.Warn("basic auth not provided")
			w.Header().Set("WWW-Authenticate", "Basic Realm='ClawIO credentials'")
			w.WriteHeader(http.StatusUnauthorized)
			return
		}

		// try to authenticate user with username and password
		token, err := s.authenticationController.Authenticate(username, password)
		if err != nil {
			log.WithError(err).Warn("unauthorized")
			w.Header().Set("WWW-Authenticate", "Basic Realm='ClawIO credentials'")
			w.WriteHeader(http.StatusUnauthorized)
			return
		}

		// save token into cookie for further requests
		cookie := &http.Cookie{}
		cookie.Name = "ClawIO_Token"
		cookie.Value = token
		http.SetCookie(w, cookie)

		user, err := s.authenticator.CreateUserFromToken(token)
		if err == nil {
			keys.SetUser(r, user)
			log.WithField("user", user.Username).Info("authenticated request")
			handler(w, r)
			return
		}

		log.WithError(err).Error("token is not valid after being generated in the same request")
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
}
Exemple #2
0
// JWTHandlerFunc is a middleware function to authenticate HTTP requests.
func (a *Authenticator) JWTHandlerFunc(handler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		log := keys.MustGetLog(r)
		token := a.getTokenFromRequest(r)
		user, err := a.CreateUserFromToken(token)
		if err != nil {
			log.Warn("unauthorized")
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}
		r = keys.SetUser(r, user)
		log.WithField("user", user.Username).Info("authenticated request")
		handler(w, r)
	}
}
Exemple #3
0
func (o *testObject) wrapAuthenticatedRequest(w *httptest.ResponseRecorder, r *http.Request, handler http.Handler) {
	keys.SetLog(r, logrus.WithField("test", "test"))
	keys.SetUser(r, o.user)
	handler.ServeHTTP(w, r)
}