changeset 127:44794c641277

Implemented explicit token renewal under endpoint /api/renew.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 28 Jun 2018 13:39:14 +0200
parents 89cf2e7672ff
children 441a8ee637c5
files auth/connection.go cmd/tokenserver/main.go
diffstat 2 files changed, 45 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/auth/connection.go	Thu Jun 28 13:09:38 2018 +0200
+++ b/auth/connection.go	Thu Jun 28 13:39:14 2018 +0200
@@ -102,6 +102,35 @@
 	return <-res
 }
 
+func (cp *ConnectionPool) Replace(
+	token string,
+	replace func(string, string) (string, error)) (string, error) {
+
+	type res struct {
+		token string
+		err   error
+	}
+
+	resCh := make(chan res)
+
+	cp.cmds <- func(cp *ConnectionPool) {
+		conn, found := cp.conns[token]
+		if !found {
+			resCh <- res{err: ErrNoSuchToken}
+			return
+		}
+		newToken, err := replace(conn.user, conn.password)
+		if err == nil {
+			delete(cp.conns, token)
+			cp.conns[newToken] = conn
+		}
+		resCh <- res{token: newToken, err: err}
+	}
+
+	r := <-resCh
+	return r.token, r.err
+}
+
 func (cp *ConnectionPool) Add(token, user, password string) *Connection {
 	res := make(chan *Connection)
 
--- a/cmd/tokenserver/main.go	Thu Jun 28 13:09:38 2018 +0200
+++ b/cmd/tokenserver/main.go	Thu Jun 28 13:39:14 2018 +0200
@@ -10,11 +10,27 @@
 	"gemma.intevation.de/gemma/auth"
 )
 
+func renew(rw http.ResponseWriter, req *http.Request) {
+	token, _ := auth.GetToken(req)
+	newToken, err := auth.ConnPool.Replace(token, auth.GenerateToken)
+	switch {
+	case err == auth.ErrNoSuchToken:
+		http.NotFound(rw, req)
+		return
+	case err != nil:
+		http.Error(rw, fmt.Sprintf("error: %v", err), http.StatusInternalServerError)
+		return
+	}
+	rw.Header().Set("Content-Type", "text/plain")
+	fmt.Fprintf(rw, "%s\n", newToken)
+}
+
 func logout(rw http.ResponseWriter, req *http.Request) {
 	token, _ := auth.GetToken(req)
 	deleted := auth.ConnPool.Delete(token)
 	if !deleted {
 		http.NotFound(rw, req)
+		return
 	}
 	rw.Header().Set("Content-Type", "text/plain")
 	fmt.Fprintln(rw, "token deleted")