Mercurial > gemma
view cmd/tokenserver/main.go @ 142:edce32db775a vue-gettext
merge with default
author | Thomas Junk <thomas.junk@intevation.de> |
---|---|
date | Mon, 02 Jul 2018 09:37:15 +0200 |
parents | 441a8ee637c5 |
children | 0c56c56a1c44 |
line wrap: on
line source
package main import ( "flag" "fmt" "log" "net/http" "path/filepath" "gemma.intevation.de/gemma/auth" ) func sysAdmin(rw http.ResponseWriter, req *http.Request) { claims, _ := auth.GetClaims(req) rw.Header().Set("Content-Type", "text/plain") fmt.Fprintf(rw, "%s is a sys_admin\n", claims.User) } 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") } func token(rw http.ResponseWriter, req *http.Request) { user := req.FormValue("user") password := req.FormValue("password") token, err := auth.GenerateToken(user, password) if 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", token) } func main() { port := flag.Int("port", 8000, "port to listen at.") host := flag.String("host", "localhost", "host to listen at.") flag.Parse() p, _ := filepath.Abs("./web") 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))) mux.Handle("/api/renew", auth.JWTMiddleware(http.HandlerFunc(renew))) mux.Handle("/api/sys_admin", auth.JWTMiddleware( auth.ClaimsChecker(http.HandlerFunc(sysAdmin), auth.HasRole("sys_admin")))) addr := fmt.Sprintf("%s:%d", *host, *port) log.Fatalln(http.ListenAndServe(addr, mux)) }