Skip to content

Instantly share code, notes, and snippets.

@vulcangz
Forked from alexedwards/main.go
Created July 15, 2019 09:47
Show Gist options
  • Save vulcangz/41b4313f88fc81fd7dfb41f15bdcf771 to your computer and use it in GitHub Desktop.
Save vulcangz/41b4313f88fc81fd7dfb41f15bdcf771 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