github.com/cs3org/reva/v2@v2.27.7/pkg/token/manager/demo/demo.go (about) 1 // Copyright 2018-2021 CERN 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // In applying this license, CERN does not waive the privileges and immunities 16 // granted to it by virtue of its status as an Intergovernmental Organization 17 // or submit itself to any jurisdiction. 18 19 package demo 20 21 import ( 22 "bytes" 23 "context" 24 "encoding/base64" 25 "encoding/gob" 26 27 auth "github.com/cs3org/go-cs3apis/cs3/auth/provider/v1beta1" 28 user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" 29 "github.com/cs3org/reva/v2/pkg/token" 30 "github.com/cs3org/reva/v2/pkg/token/manager/registry" 31 "github.com/pkg/errors" 32 ) 33 34 func init() { 35 registry.Register("demo", New) 36 } 37 38 // New returns a new token manager. 39 func New(m map[string]interface{}) (token.Manager, error) { 40 mngr := manager{} 41 return &mngr, nil 42 } 43 44 type manager struct{} 45 46 type claims struct { 47 User *user.User `json:"user"` 48 Scope map[string]*auth.Scope `json:"scope"` 49 } 50 51 func (m *manager) MintToken(ctx context.Context, u *user.User, scope map[string]*auth.Scope) (string, error) { 52 token, err := encode(&claims{u, scope}) 53 if err != nil { 54 return "", errors.Wrap(err, "error encoding user") 55 } 56 return token, nil 57 } 58 59 func (m *manager) DismantleToken(ctx context.Context, token string) (*user.User, map[string]*auth.Scope, error) { 60 c, err := decode(token) 61 if err != nil { 62 return nil, nil, errors.Wrap(err, "error decoding claims") 63 } 64 return c.User, c.Scope, nil 65 } 66 67 // from https://stackoverflow.com/questions/28020070/golang-serialize-and-deserialize-back 68 // go binary encoder 69 func encode(c *claims) (string, error) { 70 b := bytes.Buffer{} 71 e := gob.NewEncoder(&b) 72 err := e.Encode(c) 73 if err != nil { 74 return "", err 75 } 76 return base64.StdEncoding.EncodeToString(b.Bytes()), nil 77 } 78 79 // from https://stackoverflow.com/questions/28020070/golang-serialize-and-deserialize-back 80 // go binary decoder 81 func decode(token string) (*claims, error) { 82 c := &claims{} 83 by, err := base64.StdEncoding.DecodeString(token) 84 if err != nil { 85 return nil, err 86 } 87 b := bytes.Buffer{} 88 b.Write(by) 89 d := gob.NewDecoder(&b) 90 err = d.Decode(&c) 91 if err != nil { 92 return nil, err 93 } 94 return c, nil 95 }