github.com/greenpau/go-authcrunch@v1.1.4/pkg/ids/store.go (about)

     1  // Copyright 2022 Paul Greenberg greenpau@outlook.com
     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  package ids
    16  
    17  import (
    18  	"encoding/json"
    19  
    20  	"github.com/greenpau/go-authcrunch/pkg/authn/enums/operator"
    21  	"github.com/greenpau/go-authcrunch/pkg/authn/icons"
    22  	"github.com/greenpau/go-authcrunch/pkg/errors"
    23  	"github.com/greenpau/go-authcrunch/pkg/ids/ldap"
    24  	"github.com/greenpau/go-authcrunch/pkg/ids/local"
    25  	"github.com/greenpau/go-authcrunch/pkg/requests"
    26  	"go.uber.org/zap"
    27  )
    28  
    29  // IdentityStore represents identity store.
    30  type IdentityStore interface {
    31  	GetRealm() string
    32  	GetName() string
    33  	GetKind() string
    34  	GetConfig() map[string]interface{}
    35  	Configure() error
    36  	Configured() bool
    37  	Request(operator.Type, *requests.Request) error
    38  	GetLoginIcon() *icons.LoginIcon
    39  }
    40  
    41  // NewIdentityStore returns IdentityStore instance.
    42  func NewIdentityStore(cfg *IdentityStoreConfig, logger *zap.Logger) (IdentityStore, error) {
    43  	var st IdentityStore
    44  	var err error
    45  
    46  	if logger == nil {
    47  		return nil, errors.ErrIdentityStoreConfigureLoggerNotFound
    48  	}
    49  
    50  	if err := cfg.Validate(); err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	b, _ := json.Marshal(cfg.Params)
    55  
    56  	switch cfg.Kind {
    57  	case "local":
    58  		config := &local.Config{}
    59  		if err := json.Unmarshal(b, config); err != nil {
    60  			return nil, errors.ErrIdentityStoreNewConfig.WithArgs(cfg.Params, err)
    61  		}
    62  		config.Name = cfg.Name
    63  		st, err = local.NewIdentityStore(config, logger)
    64  	case "ldap":
    65  		config := &ldap.Config{}
    66  		if err := json.Unmarshal(b, config); err != nil {
    67  			return nil, errors.ErrIdentityStoreNewConfig.WithArgs(cfg.Params, err)
    68  		}
    69  		config.Name = cfg.Name
    70  		st, err = ldap.NewIdentityStore(config, logger)
    71  	}
    72  
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  
    77  	return st, nil
    78  }