Skip to content

Commit

Permalink
Merge pull request tkeel-io#21 from uptutu/feat/authuser
Browse files Browse the repository at this point in the history
feat: parse token get auth user info
  • Loading branch information
uptutu authored Mar 1, 2022
2 parents 216ac6e + d0ce8d3 commit e3b612f
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 0 deletions.
108 changes: 108 additions & 0 deletions auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package auth

import (
"context"
"encoding/json"
"io/ioutil"
"net/http"

"github.com/pkg/errors"
"github.com/tkeel-io/kit"
"github.com/tkeel-io/kit/log"
transportHTTP "github.com/tkeel-io/kit/transport/http"
)

const (
//_AuthTokenURL string = "http://192.168.123.11:30707/apis/security/v1/oauth/authenticate"
_AuthTokenURL string = "http://localhost:3500/v1.0/invoke/keel/method/apis/security/v1/oauth/authenticate"
_Authorization string = "Authenticate"
)

type User struct {
ID string `json:"id"`
TenantID string `json:"tenant_id"`
Token string `json:"token"`
}

func Authenticate(token interface{}) (*User, error) {
tokenStr := ""
switch t := token.(type) {
case string:
tokenStr = t
case context.Context:
val, ok := transportHTTP.HeaderFromContext(t)[_Authorization]
if !ok || len(tokenStr) == 0 {
return nil, errors.New("invalid Authenticate")
}
tokenStr = val[0]
default:
return nil, errors.New("invalid token type")
}
if tokenStr == "" {
return nil, errors.New("token is empty")
}

req, err := http.NewRequest("GET", _AuthTokenURL, nil)
if nil != err {
return nil, err
}
req.Header.Add(_Authorization, tokenStr)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Error("error ", err)
return nil, err
}
defer resp.Body.Close()
body, err := getBody(resp)
if nil != err {
log.Error("error parse token, ", err)
return nil, err
}

var response kit.Response
if err = json.Unmarshal(body, &response); nil != err {
log.Error("resp Unmarshal error, ", err)
return nil, err
}

if response.Code == "io.tkeel.SUCCESS" {
return nil, errors.New(response.Msg)
}

respData, ok := response.Data.(map[string]interface{})
if !ok {
log.Error("resp data is not map[string]interface{}")
return nil, errors.New("resp data is not map[string]interface{}")
}

id, ok := respData["user_id"].(string)
if !ok {
return nil, errors.New("parse token user_id data error")
}

tenantId, ok := respData["tenant_id"].(string)
if !ok {
return nil, errors.New("parse token tenant_id data error")
}

return &User{
ID: id,
TenantID: tenantId,
Token: tokenStr,
}, nil
}

func getBody(resp *http.Response) ([]byte, error) {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error("error ReadAll", err)
return body, err
}

log.Debug("receive resp, ", string(body))
if resp.StatusCode != 200 {
log.Error("bad status ", resp.StatusCode)
return body, errors.New(resp.Status)
}
return body, nil
}
16 changes: 16 additions & 0 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package auth

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestAuthenticate(t *testing.T) {
token := "Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ0a2VlbCIsImV4cCI6MTY0NjEyMTk0Nywic3ViIjoidXNyLTIzNDgwMmM5YWQwY2NjOGUxYTViYWQ0NWZiNmMifQ.EUvVpq_ITnTZgJhH1KlUIzPReCU-IUnFN5FritWn2Co3GRhvTVDboR2xM7J4T2EIjI-5eq3dZrGOsSudx86_sA"
auth, err := Authenticate(token)
assert.NoError(t, err)
fmt.Printf("%+v\n", auth)
assert.NotEmpty(t, auth)
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ require (
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)

require github.com/pkg/errors v0.8.1

require (
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
Expand Down
7 changes: 7 additions & 0 deletions type.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package kit

type Response struct {
Code string `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}

0 comments on commit e3b612f

Please sign in to comment.