|
| 1 | +// Copyright 2016 The Gogs Authors. All rights reserved. |
| 2 | +// Copyright 2016 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 | +package generate |
| 7 | + |
| 8 | +import ( |
| 9 | + "crypto/rand" |
| 10 | + "encoding/base64" |
| 11 | + "io" |
| 12 | + "math/big" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/dgrijalva/jwt-go" |
| 16 | +) |
| 17 | + |
| 18 | +// GetRandomString generate random string by specify chars. |
| 19 | +func GetRandomString(n int) (string, error) { |
| 20 | + const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" |
| 21 | + |
| 22 | + buffer := make([]byte, n) |
| 23 | + max := big.NewInt(int64(len(alphanum))) |
| 24 | + |
| 25 | + for i := 0; i < n; i++ { |
| 26 | + index, err := randomInt(max) |
| 27 | + if err != nil { |
| 28 | + return "", err |
| 29 | + } |
| 30 | + |
| 31 | + buffer[i] = alphanum[index] |
| 32 | + } |
| 33 | + |
| 34 | + return string(buffer), nil |
| 35 | +} |
| 36 | + |
| 37 | +// NewInternalToken generate a new value intended to be used by INTERNAL_TOKEN. |
| 38 | +func NewInternalToken() (string, error) { |
| 39 | + secretBytes := make([]byte, 32) |
| 40 | + _, err := io.ReadFull(rand.Reader, secretBytes) |
| 41 | + if err != nil { |
| 42 | + return "", err |
| 43 | + } |
| 44 | + |
| 45 | + secretKey := base64.RawURLEncoding.EncodeToString(secretBytes) |
| 46 | + |
| 47 | + now := time.Now() |
| 48 | + |
| 49 | + var internalToken string |
| 50 | + internalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ |
| 51 | + "nbf": now.Unix(), |
| 52 | + }).SignedString([]byte(secretKey)) |
| 53 | + if err != nil { |
| 54 | + return "", err |
| 55 | + } |
| 56 | + |
| 57 | + return internalToken, nil |
| 58 | +} |
| 59 | + |
| 60 | +// NewLfsJwtSecret generate a new value intended to be used by LFS_JWT_SECRET. |
| 61 | +func NewLfsJwtSecret() (string, error) { |
| 62 | + JWTSecretBytes := make([]byte, 32) |
| 63 | + _, err := io.ReadFull(rand.Reader, JWTSecretBytes) |
| 64 | + if err != nil { |
| 65 | + return "", err |
| 66 | + } |
| 67 | + |
| 68 | + JWTSecretBase64 := base64.RawURLEncoding.EncodeToString(JWTSecretBytes) |
| 69 | + return JWTSecretBase64, nil |
| 70 | +} |
| 71 | + |
| 72 | +// NewSecretKey generate a new value intended to be used by SECRET_KEY. |
| 73 | +func NewSecretKey() (string, error) { |
| 74 | + secretKey, err := GetRandomString(64) |
| 75 | + if err != nil { |
| 76 | + return "", err |
| 77 | + } |
| 78 | + |
| 79 | + return secretKey, nil |
| 80 | +} |
| 81 | + |
| 82 | +func randomInt(max *big.Int) (int, error) { |
| 83 | + rand, err := rand.Int(rand.Reader, max) |
| 84 | + if err != nil { |
| 85 | + return 0, err |
| 86 | + } |
| 87 | + |
| 88 | + return int(rand.Int64()), nil |
| 89 | +} |
0 commit comments