changeset 126:89cf2e7672ff

Implemented an explicit token deletion under endpoint /api/logout.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 28 Jun 2018 13:09:38 +0200
parents a98a282f00e1
children 44794c641277
files auth/connection.go cmd/tokenserver/main.go
diffstat 2 files changed, 32 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/auth/connection.go	Thu Jun 28 12:21:36 2018 +0200
+++ b/auth/connection.go	Thu Jun 28 13:09:38 2018 +0200
@@ -3,6 +3,7 @@
 import (
 	"database/sql"
 	"errors"
+	"log"
 	"time"
 )
 
@@ -81,6 +82,26 @@
 	}
 }
 
+func (cp *ConnectionPool) Delete(token string) bool {
+	res := make(chan bool)
+	cp.cmds <- func(cp *ConnectionPool) {
+		conn, found := cp.conns[token]
+		if !found {
+			res <- false
+			return
+		}
+		delete(cp.conns, token)
+		if conn.db != nil {
+			if err := conn.db.Close(); err != nil {
+				log.Printf("warn: %v\n", err)
+			}
+			conn.db = nil
+		}
+		res <- true
+	}
+	return <-res
+}
+
 func (cp *ConnectionPool) Add(token, user, password string) *Connection {
 	res := make(chan *Connection)
 
--- a/cmd/tokenserver/main.go	Thu Jun 28 12:21:36 2018 +0200
+++ b/cmd/tokenserver/main.go	Thu Jun 28 13:09:38 2018 +0200
@@ -10,6 +10,16 @@
 	"gemma.intevation.de/gemma/auth"
 )
 
+func logout(rw http.ResponseWriter, req *http.Request) {
+	token, _ := auth.GetToken(req)
+	deleted := auth.ConnPool.Delete(token)
+	if !deleted {
+		http.NotFound(rw, req)
+	}
+	rw.Header().Set("Content-Type", "text/plain")
+	fmt.Fprintln(rw, "token deleted")
+}
+
 func token(rw http.ResponseWriter, req *http.Request) {
 	user := req.FormValue("user")
 	password := req.FormValue("password")
@@ -22,7 +32,6 @@
 	}
 
 	rw.Header().Set("Content-Type", "text/plain")
-
 	fmt.Fprintf(rw, "%s\n", token)
 }
 
@@ -34,6 +43,7 @@
 	mux := http.NewServeMux()
 	mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(p))))
 	mux.HandleFunc("/api/token", token)
+	mux.Handle("/api/logout", auth.JWTMiddleware(http.HandlerFunc(token)))
 
 	addr := fmt.Sprintf("%s:%d", *host, *port)
 	log.Fatalln(http.ListenAndServe(addr, mux))