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