authExample.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package sessionstore
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/gorilla/sessions"
  6. )
  7. var (
  8. key = []byte("secret") // change to os.Getenv("SESSION_KEY")
  9. store = sessions.NewCookieStore(key)
  10. )
  11. func secret(w http.ResponseWriter, r *http.Request) {
  12. session, _ := store.Get(r, "cookie-name")
  13. fmt.Println(session.Values["authenticated"])
  14. // Check if user is authenticated
  15. if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
  16. http.Error(w, "Forbidden", http.StatusForbidden)
  17. return
  18. }
  19. // Print secret message
  20. fmt.Fprintln(w, "The cake is a lie!")
  21. }
  22. func login(w http.ResponseWriter, r *http.Request) {
  23. session, _ := store.Get(r, "cookie-name")
  24. // Authentication goes here
  25. // ...
  26. // Set user as authenticated
  27. session.Values["authenticated"] = true
  28. session.Save(r, w)
  29. }
  30. func logout(w http.ResponseWriter, r *http.Request) {
  31. session, _ := store.Get(r, "cookie-name")
  32. // Revoke users authentication
  33. session.Values["authenticated"] = false
  34. session.Save(r, w)
  35. }
  36. func main() {
  37. http.HandleFunc("/secret", secret)
  38. http.HandleFunc("/login", login)
  39. http.HandleFunc("/logout", logout)
  40. http.ListenAndServe(":8080", nil)
  41. }