github.com/cnotch/ipchub@v1.1.0/provider/auth/json.go (about)

     1  // Copyright (c) 2019,CAOHONGJU All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package auth
     6  
     7  import (
     8  	"encoding/json"
     9  	"fmt"
    10  	"io/ioutil"
    11  	"os"
    12  	"path/filepath"
    13  
    14  	"github.com/cnotch/ipchub/utils"
    15  )
    16  
    17  // JSON json 提供者
    18  var JSON = &jsonProvider{}
    19  
    20  type jsonProvider struct {
    21  	filePath string
    22  }
    23  
    24  func (p *jsonProvider) Name() string {
    25  	return "json"
    26  }
    27  
    28  func (p *jsonProvider) Configure(config map[string]interface{}) error {
    29  	path, ok := config["file"]
    30  	if ok {
    31  		switch v := path.(type) {
    32  		case string:
    33  			p.filePath = v
    34  		default:
    35  			return fmt.Errorf("invalid user config, file attr: %v", path)
    36  		}
    37  	} else {
    38  		p.filePath = "users.json"
    39  	}
    40  
    41  	if !filepath.IsAbs(p.filePath) {
    42  		exe, err := os.Executable()
    43  		if err != nil {
    44  			return err
    45  		}
    46  		p.filePath = filepath.Join(filepath.Dir(exe), p.filePath)
    47  	}
    48  
    49  	return nil
    50  }
    51  
    52  func (p *jsonProvider) LoadAll() ([]*User, error) {
    53  	path := p.filePath
    54  	if _, err := os.Stat(path); err != nil {
    55  		if os.IsNotExist(err) {
    56  			return []*User{{
    57  				Name:     "admin",
    58  				Password: "admin",
    59  				Admin:    true}}, nil
    60  		}
    61  		return nil, err
    62  	}
    63  
    64  	// 从文件读
    65  	b, err := ioutil.ReadFile(path)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  
    70  	var users []*User
    71  	if err := json.Unmarshal(b, &users); err != nil {
    72  		return nil, err
    73  	}
    74  
    75  	return users, nil
    76  }
    77  
    78  func (p *jsonProvider) Flush(full []*User, saves []*User, removes []*User) error {
    79  	return utils.EncodeJSONFile(p.filePath, full)
    80  }