Mercurial > gemma
view pkg/controllers/token.go @ 471:1b08432a0e5d
Cosmetics.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Thu, 23 Aug 2018 10:11:50 +0200 |
parents | fc37e7072022 |
children | 2ac37419f593 |
line wrap: on
line source
package controllers import ( "encoding/json" "fmt" "log" "net/http" "gemma.intevation.de/gemma/pkg/auth" "gemma.intevation.de/gemma/pkg/models" ) func sendJSON(rw http.ResponseWriter, data interface{}) { rw.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(rw).Encode(data); err != nil { log.Printf("error: %v\n", err) } } func renew(rw http.ResponseWriter, req *http.Request) { token, _ := auth.GetToken(req) newToken, err := auth.ConnPool.Renew(token) switch { case err == auth.ErrNoSuchToken: http.NotFound(rw, req) return case err != nil: http.Error(rw, fmt.Sprintf("error: %v", err), http.StatusInternalServerError) return } session, _ := auth.GetSession(req) var result = struct { Token string `json:"token"` Expires int64 `json:"expires"` User string `json:"user"` Roles []string `json:"roles"` }{ Token: newToken, Expires: session.ExpiresAt, User: session.User, Roles: session.Roles, } sendJSON(rw, &result) } 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 login(rw http.ResponseWriter, req *http.Request) { var ( user = req.FormValue("user") password = req.FormValue("password") ) if !models.UserName(user).IsValid() || password == "" { http.Error(rw, "Invalid credentials", http.StatusBadRequest) return } token, session, err := auth.GenerateSession(user, password) if err != nil { http.Error(rw, fmt.Sprintf("error: %v", err), http.StatusUnauthorized) return } var result = struct { Token string `json:"token"` Expires int64 `json:"expires"` User string `json:"user"` Roles []string `json:"roles"` }{ Token: token, Expires: session.ExpiresAt, User: session.User, Roles: session.Roles, } sendJSON(rw, &result) }