github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/generate/generate.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Copyright 2016 The Gogs Authors. All rights reserved.
     7  // Copyright 2016 The GitBundle Authors. All rights reserved.
     8  // Use of this source code is governed by a MIT-style
     9  // license that can be found in the LICENSE file.
    10  
    11  package generate
    12  
    13  import (
    14  	"crypto/rand"
    15  	"encoding/base64"
    16  	"io"
    17  	"time"
    18  
    19  	"github.com/gitbundle/modules/util"
    20  
    21  	"github.com/golang-jwt/jwt/v4"
    22  )
    23  
    24  // NewInternalToken generate a new value intended to be used by INTERNAL_TOKEN.
    25  func NewInternalToken() (string, error) {
    26  	secretBytes := make([]byte, 32)
    27  	_, err := io.ReadFull(rand.Reader, secretBytes)
    28  	if err != nil {
    29  		return "", err
    30  	}
    31  
    32  	secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)
    33  
    34  	now := time.Now()
    35  
    36  	var internalToken string
    37  	internalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    38  		"nbf": now.Unix(),
    39  	}).SignedString([]byte(secretKey))
    40  	if err != nil {
    41  		return "", err
    42  	}
    43  
    44  	return internalToken, nil
    45  }
    46  
    47  // NewJwtSecret generates a new value intended to be used for JWT secrets.
    48  func NewJwtSecret() ([]byte, error) {
    49  	bytes := make([]byte, 32)
    50  	_, err := io.ReadFull(rand.Reader, bytes)
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  	return bytes, nil
    55  }
    56  
    57  // NewJwtSecretBase64 generates a new base64 encoded value intended to be used for JWT secrets.
    58  func NewJwtSecretBase64() (string, error) {
    59  	bytes, err := NewJwtSecret()
    60  	if err != nil {
    61  		return "", err
    62  	}
    63  	return base64.RawURLEncoding.EncodeToString(bytes), nil
    64  }
    65  
    66  // NewSecretKey generate a new value intended to be used by SECRET_KEY.
    67  func NewSecretKey() (string, error) {
    68  	secretKey, err := util.CryptoRandomString(32)
    69  	if err != nil {
    70  		return "", err
    71  	}
    72  
    73  	return secretKey, nil
    74  }