Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created January 28, 2018 11:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alexedwards/6eac2f19b9b5c064ca90f756c32f94cc to your computer and use it in GitHub Desktop.
Save alexedwards/6eac2f19b9b5c064ca90f756c32f94cc to your computer and use it in GitHub Desktop.
RequireLogin middleware
var sessionManager = scs.NewCookieManager("...")
func RequireLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := sessionManager.Load(r)
userID, err := session.GetInt("userID")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if userID == 0 {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
validUser := CheckUserID(userID)
if !validUser {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
next.ServeHTTP(w, r)
})
}
func CheckUserID(userID int) bool {
// Check your database to make sure the provided ID is valid.
return true // or false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment