Browse Source

auth middleware

sunguroku 5 năm trước cách đây
mục cha
commit
65ab4ec439
2 tập tin đã thay đổi với 91 bổ sung0 xóa
  1. 54 0
      internal/auth/auth.go
  2. 37 0
      server/router/middleware/auth.go

+ 54 - 0
internal/auth/auth.go

@@ -0,0 +1,54 @@
+package main
+
+import (
+	"fmt"
+	"net/http"
+
+	"github.com/gorilla/sessions"
+)
+
+var (
+	key   = []byte("secret") // change to os.Getenv("SESSION_KEY")
+	store = sessions.NewCookieStore(key)
+)
+
+func secret(w http.ResponseWriter, r *http.Request) {
+	session, _ := store.Get(r, "cookie-name")
+	fmt.Println(session.Values["authenticated"])
+
+	// 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!")
+}
+
+func login(w http.ResponseWriter, r *http.Request) {
+	session, _ := store.Get(r, "cookie-name")
+
+	// Authentication goes here
+	// ...
+
+	// Set user as authenticated
+	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)
+}

+ 37 - 0
server/router/middleware/auth.go

@@ -0,0 +1,37 @@
+package middleware
+
+import (
+	"net/http"
+
+	"github.com/gorilla/sessions"
+)
+
+var (
+	key   = []byte("secret") // change to os.Getenv("SESSION_KEY")
+	store = sessions.NewCookieStore(key)
+)
+
+// ContentTypeJSON sets the content type for requests to application/json
+func authenticate(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if isLoggedIn(r) {
+			next.ServeHTTP(w, r)
+		} else {
+			http.Error(w, http.StatusText(403), 403)
+			return
+		}
+
+		return
+	})
+}
+
+// Helpers
+
+func isLoggedIn(r *http.Request) bool {
+	session, _ := store.Get(r, "session-id")
+
+	if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
+		return false
+	}
+	return true
+}