generate jwt private key

This commit is contained in:
celogeek 2022-05-26 23:58:43 +02:00
parent e6210640db
commit ff3931f083
Signed by: celogeek
GPG Key ID: E6B7BDCFC446233A

View File

@ -2,11 +2,13 @@ package photosapi
import ( import (
"context" "context"
"crypto/ed25519"
"errors" "errors"
"math/rand" "math/rand"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
"path/filepath"
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -19,13 +21,15 @@ var (
) )
type Service struct { type Service struct {
Gin *gin.Engine Gin *gin.Engine
DB *gorm.DB DB *gorm.DB
Config *ServiceConfig Config *ServiceConfig
StorageTmp *Storage StorageTmp *Storage
StorageUpload *Storage StorageUpload *Storage
LogOk *Logger LogOk *Logger
LogErr *Logger LogErr *Logger
SessionKey ed25519.PrivateKey
SessionKeyValidation ed25519.PublicKey
} }
type ServiceConfig struct { type ServiceConfig struct {
@ -34,14 +38,34 @@ type ServiceConfig struct {
StorePath string StorePath string
} }
func GetOrGenerateKey(storePath string) ed25519.PrivateKey {
p := filepath.Join(storePath, "photo.key")
key, err := os.ReadFile(p)
if errors.Is(err, os.ErrNotExist) {
_, key, err = ed25519.GenerateKey(nil)
if err != nil {
panic(err)
}
err = os.WriteFile(p, key, 0600)
if err != nil {
panic(err)
}
}
return key
}
func New(config *ServiceConfig) *Service { func New(config *ServiceConfig) *Service {
key := GetOrGenerateKey(config.StorePath)
pubKey := key.Public().(ed25519.PublicKey)
return &Service{ return &Service{
Gin: gin.New(), Gin: gin.New(),
Config: config, Config: config,
StorageTmp: NewStorage(config.StorePath, "tmp"), StorageTmp: NewStorage(config.StorePath, "tmp"),
StorageUpload: NewStorage(config.StorePath, "upload"), StorageUpload: NewStorage(config.StorePath, "upload"),
LogOk: &Logger{os.Stdout, "Photos"}, LogOk: &Logger{os.Stdout, "Photos"},
LogErr: &Logger{os.Stderr, "Photos"}, LogErr: &Logger{os.Stderr, "Photos"},
SessionKey: key,
SessionKeyValidation: pubKey,
} }
} }
@ -78,7 +102,6 @@ func (s *Service) Run() error {
s.PrepareStore() s.PrepareStore()
s.SetupRoutes() s.SetupRoutes()
s.SetupDB() s.SetupDB()
go s.SessionCleaner()
srv := &http.Server{ srv := &http.Server{
Addr: s.Config.Listen, Addr: s.Config.Listen,