From 701626881eb1a0609a18cd86555f8b13d8db2bc8 Mon Sep 17 00:00:00 2001 From: Brad Rydzewski Date: Sun, 12 Apr 2015 23:15:28 -0700 Subject: [PATCH] ability to create a token --- server/login.go | 2 +- server/session/session.go | 4 ++-- server/token.go | 27 ++++++++++++++++++++++----- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/server/login.go b/server/login.go index 162090c2..62fcae5a 100644 --- a/server/login.go +++ b/server/login.go @@ -111,7 +111,7 @@ func GetLogin(c *gin.Context) { Login: u.Login, Issued: time.Now().UTC().Unix(), } - tokenstr, err := session.GenerateToken(c.Request, token) + tokenstr, err := session.GenerateToken(token) if err != nil { log.Errorf("cannot create token for %s. %s", u.Login, err) c.Redirect(303, "/login#error=internal_error") diff --git a/server/session/session.go b/server/session/session.go index 5b178db1..072515ce 100644 --- a/server/session/session.go +++ b/server/session/session.go @@ -12,7 +12,7 @@ import ( ) type Session interface { - GenerateToken(*http.Request, *common.Token) (string, error) + GenerateToken(*common.Token) (string, error) GetLogin(*http.Request) *common.Token } @@ -37,7 +37,7 @@ func New(s *settings.Session) Session { // GenerateToken generates a JWT token for the user session // that can be appended to the #access_token segment to // facilitate client-based OAuth2. -func (s *session) GenerateToken(r *http.Request, t *common.Token) (string, error) { +func (s *session) GenerateToken(t *common.Token) (string, error) { token := jwt.New(jwt.GetSigningMethod("HS256")) token.Claims["user"] = t.Login token.Claims["kind"] = t.Kind diff --git a/server/token.go b/server/token.go index 882c6b01..23bfe2c7 100644 --- a/server/token.go +++ b/server/token.go @@ -3,14 +3,31 @@ package server import ( "github.com/gin-gonic/gin" - // "github.com/drone/drone/common" + "github.com/drone/drone/common" ) -// POST /api/user/tokens +// POST /api/user/tokens/:label func PostToken(c *gin.Context) { - // 1. generate a unique, random password - // 2. take a hash of the password, and store in the database - // 3. return the random password to the UI and instruct the user to copy it + store := ToDatastore(c) + sess := ToSession(c) + user := ToUser(c) + label := c.Params.ByName("label") + + token := &common.Token{} + token.Label = label + token.Login = user.Login + token.Kind = common.TokenUser + + err := store.InsertToken(token) + if err != nil { + c.Fail(400, err) + } + + jwt, err := sess.GenerateToken(token) + if err != nil { + c.Fail(400, err) + } + c.String(200, jwt) } // DELETE /api/user/tokens/:label