aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorThibaut Horel <thibaut.horel@gmail.com>2018-12-26 13:20:57 -0500
committerThibaut Horel <thibaut.horel@gmail.com>2018-12-26 13:20:57 -0500
commited4f6fa1a785e14f39bda9715e3d081fb426ff36 (patch)
treeb3b9e4095281665a06b96e840133d563224c9fca
downloadid-ed4f6fa1a785e14f39bda9715e3d081fb426ff36.tar.gz
Initial commit
-rw-r--r--main.go46
-rw-r--r--store.go35
2 files changed, 81 insertions, 0 deletions
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..7d172b7
--- /dev/null
+++ b/main.go
@@ -0,0 +1,46 @@
+package main
+
+import (
+ "log"
+ "net/http"
+ "time"
+)
+
+type App struct {
+ SessionStore
+}
+
+func logMux(handler http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t := time.Now()
+ handler.ServeHTTP(w, r)
+ log.Println(r.Method, r.URL.Path, time.Since(t))
+ })
+}
+
+func (app *App) rootHandler(w http.ResponseWriter, r *http.Request) {
+ c, err := r.Cookie("id")
+ //log.Println(r.Header.Get("X-Original-URI"))
+ //log.Println(r.Host)
+ if err != nil {
+ w.WriteHeader(http.StatusUnauthorized)
+ } else {
+ if s, ok := app.Get(c.Value); ok {
+ w.Header().Set("X-Remote-User", s.UserId)
+ w.WriteHeader(http.StatusOK)
+ } else {
+ log.Println("Session does not exist:", c.Value)
+ w.WriteHeader(http.StatusForbidden)
+ }
+ }
+}
+
+func main() {
+ //log.SetFlags(log.LstdFlags)
+ store := NewPgStore()
+ app := &App{store}
+ http.HandleFunc("/", app.rootHandler)
+ if err := http.ListenAndServe(":8080", logMux(http.DefaultServeMux)); err != nil {
+ panic(err)
+ }
+}
diff --git a/store.go b/store.go
new file mode 100644
index 0000000..b744d88
--- /dev/null
+++ b/store.go
@@ -0,0 +1,35 @@
+package main
+
+import (
+ "database/sql"
+ "log"
+
+ _ "github.com/lib/pq"
+)
+
+type Session struct {
+ Id string
+ UserId string
+}
+
+type SessionStore interface {
+ Get(id string) (*Session, bool)
+}
+
+type PgSessionStore struct {
+ *sql.DB
+ cache map[string]*Session
+}
+
+func NewPgStore() *PgSessionStore {
+ db, err := sql.Open("postgres", "postgres://auth_master:pass@localhost/authdb")
+ if err != nil {
+ log.Panic(err)
+ }
+ return &PgSessionStore{db, make(map[string]*Session)}
+}
+
+func (store *PgSessionStore) Get(id string) (*Session, bool) {
+ s, ok := store.cache[id]
+ return s, ok
+}