credentials.go raw

   1  /*
   2   * Copyright 2017 Baidu, Inc.
   3   *
   4   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
   5   * except in compliance with the License. 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 distributed under the
  10   * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  11   * either express or implied. See the License for the specific language governing permissions
  12   * and limitations under the License.
  13   */
  14  
  15  // credentials.go - the credentials data structure definition
  16  
  17  // Package auth implements the authorization functionality for BCE.
  18  // It use the BCE access key ID and secret access key with the specific sign algorithm to generate
  19  // the authorization string. It also supports the temporary authorization by the STS token.
  20  package auth
  21  
  22  import "errors"
  23  
  24  // BceCredentials define the data structure for authorization
  25  type BceCredentials struct {
  26  	AccessKeyId     string // access key id to the service
  27  	SecretAccessKey string // secret access key to the service
  28  	SessionToken    string // session token generate by the STS service
  29  }
  30  
  31  func (b *BceCredentials) String() string {
  32  	str := "ak: " + b.AccessKeyId + ", sk: " + b.SecretAccessKey
  33  	if len(b.SessionToken) != 0 {
  34  		return str + ", sessionToken: " + b.SessionToken
  35  	}
  36  	return str
  37  }
  38  
  39  func NewBceCredentials(ak, sk string) (*BceCredentials, error) {
  40  	if len(ak) == 0 {
  41  		return nil, errors.New("accessKeyId should not be empty")
  42  	}
  43  	if len(sk) == 0 {
  44  		return nil, errors.New("secretKey should not be empty")
  45  	}
  46  
  47  	return &BceCredentials{ak, sk, ""}, nil
  48  }
  49  
  50  func NewSessionBceCredentials(ak, sk, token string) (*BceCredentials, error) {
  51  	if len(token) == 0 {
  52  		return nil, errors.New("sessionToken should not be empty")
  53  	}
  54  
  55  	result, err := NewBceCredentials(ak, sk)
  56  	if err != nil {
  57  		return nil, err
  58  	}
  59  	result.SessionToken = token
  60  
  61  	return result, nil
  62  }
  63