-
-
Save vulcangz/41b4313f88fc81fd7dfb41f15bdcf771 to your computer and use it in GitHub Desktop.
RequireLogin middleware
This file contains 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