Inital commit
This commit is contained in:
parent
4f6382818b
commit
be643d3252
|
@ -0,0 +1,59 @@
|
||||||
|
// sessions.go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gorilla/sessions"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
|
||||||
|
key = []byte("super-secret-key")
|
||||||
|
store = sessions.NewCookieStore(key)
|
||||||
|
//store := gormstore.New(gorm.Open(...), []byte("secret"))
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
func secret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
session, _ := store.Get(r, "cookie-name")
|
||||||
|
|
||||||
|
// Check if user is authenticated
|
||||||
|
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
|
||||||
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print secret message
|
||||||
|
fmt.Fprintln(w, "The cake is a lie!")
|
||||||
|
fmt.Println(session.Values)
|
||||||
|
}
|
||||||
|
|
||||||
|
func login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
session, _ := store.Get(r, "cookie-name")
|
||||||
|
|
||||||
|
// Authentication goes here
|
||||||
|
// ...
|
||||||
|
|
||||||
|
// Set user as authenticated
|
||||||
|
session.Values["user"] = "test"
|
||||||
|
session.Values["authenticated"] = true
|
||||||
|
session.Save(r, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
func logout(w http.ResponseWriter, r *http.Request) {
|
||||||
|
session, _ := store.Get(r, "cookie-name")
|
||||||
|
|
||||||
|
// Revoke users authentication
|
||||||
|
session.Values["authenticated"] = false
|
||||||
|
session.Save(r, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
http.HandleFunc("/secret", secret)
|
||||||
|
http.HandleFunc("/login", login)
|
||||||
|
http.HandleFunc("/logout", logout)
|
||||||
|
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
Loading…
Reference in New Issue