github.com/cs3org/reva/v2@v2.27.7/pkg/siteacc/credentials/credentials.go (about)

     1  // Copyright 2018-2020 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 credentials
    20  
    21  import (
    22  	"github.com/cs3org/reva/v2/pkg/siteacc/credentials/crypto"
    23  	"github.com/pkg/errors"
    24  )
    25  
    26  // Credentials stores and en-/decrypts credentials
    27  type Credentials struct {
    28  	ID     string `json:"id"`
    29  	Secret string `json:"secret"`
    30  }
    31  
    32  // Get decrypts and retrieves the stored credentials.
    33  func (creds *Credentials) Get(passphrase string) (string, string, error) {
    34  	id, err := crypto.DecodeString(creds.ID, passphrase)
    35  	if err != nil {
    36  		return "", "", errors.Wrap(err, "unable to decode ID")
    37  	}
    38  	secret, err := crypto.DecodeString(creds.Secret, passphrase)
    39  	if err != nil {
    40  		return "", "", errors.Wrap(err, "unable to decode secret")
    41  	}
    42  	return id, secret, nil
    43  }
    44  
    45  // Set encrypts and sets new credentials.
    46  func (creds *Credentials) Set(id, secret string, passphrase string) error {
    47  	if s, err := crypto.EncodeString(id, passphrase); err == nil {
    48  		creds.ID = s
    49  	} else {
    50  		return errors.Wrap(err, "unable to encode ID")
    51  	}
    52  	if s, err := crypto.EncodeString(secret, passphrase); err == nil {
    53  		creds.Secret = s
    54  	} else {
    55  		return errors.Wrap(err, "unable to encode secret")
    56  	}
    57  	return nil
    58  }
    59  
    60  // IsValid checks whether the credentials are valid.
    61  func (creds *Credentials) IsValid() bool {
    62  	return len(creds.ID) > 0 && len(creds.Secret) > 0
    63  }
    64  
    65  // Clear resets the credentials.
    66  func (creds *Credentials) Clear() {
    67  	creds.ID = ""
    68  	creds.Secret = ""
    69  }