Created
January 28, 2018 11:32
-
-
Save alexedwards/6eac2f19b9b5c064ca90f756c32f94cc to your computer and use it in GitHub Desktop.
RequireLogin middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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