prompt 1,2,3
This commit is contained in:
55
internal/app/app.go
Normal file
55
internal/app/app.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"trustcontact/internal/config"
|
||||
"trustcontact/internal/db"
|
||||
apphttp "trustcontact/internal/http"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/gofiber/fiber/v2/middleware/session"
|
||||
)
|
||||
|
||||
func NewApp(cfg *config.Config) (*fiber.App, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is nil")
|
||||
}
|
||||
|
||||
app := fiber.New()
|
||||
|
||||
app.Use(cors.New(cors.Config{
|
||||
AllowOrigins: strings.Join(cfg.CORS.Origins, ","),
|
||||
AllowHeaders: strings.Join(cfg.CORS.Headers, ","),
|
||||
AllowMethods: strings.Join(cfg.CORS.Methods, ","),
|
||||
AllowCredentials: cfg.CORS.Credentials,
|
||||
}))
|
||||
|
||||
store := session.New(session.Config{
|
||||
CookieHTTPOnly: true,
|
||||
CookieSecure: cfg.Env == config.EnvProd,
|
||||
})
|
||||
|
||||
database, err := db.Open(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open db: %w", err)
|
||||
}
|
||||
|
||||
if cfg.AutoMigrate {
|
||||
if err := db.Migrate(database); err != nil {
|
||||
return nil, fmt.Errorf("migrate db: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.SeedEnabled && cfg.Env == config.EnvDevelop {
|
||||
if err := db.Seed(database); err != nil {
|
||||
return nil, fmt.Errorf("seed db: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
apphttp.RegisterRoutes(app, store, database, cfg)
|
||||
|
||||
return app, nil
|
||||
}
|
||||
24
internal/auth/passwords.go
Normal file
24
internal/auth/passwords.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package auth
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
func HashPassword(plain string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
func ComparePassword(hash string, plain string) (bool, error) {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain))
|
||||
if err != nil {
|
||||
if err == bcrypt.ErrMismatchedHashAndPassword {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
33
internal/auth/tokens.go
Normal file
33
internal/auth/tokens.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
)
|
||||
|
||||
const tokenBytes = 32
|
||||
|
||||
func NewToken() (string, error) {
|
||||
buf := make([]byte, tokenBytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func HashToken(plainToken string) string {
|
||||
sum := sha256.Sum256([]byte(plainToken))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func VerifyTokenExpiresAt(now time.Time) time.Time {
|
||||
return now.UTC().Add(24 * time.Hour)
|
||||
}
|
||||
|
||||
func ResetTokenExpiresAt(now time.Time) time.Time {
|
||||
return now.UTC().Add(1 * time.Hour)
|
||||
}
|
||||
198
internal/config/config.go
Normal file
198
internal/config/config.go
Normal file
@@ -0,0 +1,198 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
const (
|
||||
EnvDevelop = "develop"
|
||||
EnvProd = "prod"
|
||||
|
||||
DBDriverSQLite = "sqlite"
|
||||
DBDriverPostgres = "postgres"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AppName string
|
||||
Env string
|
||||
Port string
|
||||
BaseURL string
|
||||
BuildHash string
|
||||
|
||||
DBDriver string
|
||||
SQLitePath string
|
||||
PostgresDSN string
|
||||
|
||||
CORS CORSConfig
|
||||
|
||||
SessionKey string
|
||||
|
||||
SMTP SMTPConfig
|
||||
|
||||
EmailSinkDir string
|
||||
|
||||
AutoMigrate bool
|
||||
SeedEnabled bool
|
||||
}
|
||||
|
||||
type CORSConfig struct {
|
||||
Origins []string
|
||||
Headers []string
|
||||
Methods []string
|
||||
Credentials bool
|
||||
}
|
||||
|
||||
type SMTPConfig struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
From string
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
if err := godotenv.Load(); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, fmt.Errorf("load .env: %w", err)
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
AppName: envOrDefault("APP_NAME", "trustcontact"),
|
||||
Env: envOrDefault("APP_ENV", EnvDevelop),
|
||||
Port: envOrDefault("APP_PORT", "3000"),
|
||||
BaseURL: envOrDefault("APP_BASE_URL", "http://localhost:3000"),
|
||||
BuildHash: envOrDefault("APP_BUILD_HASH", "dev"),
|
||||
DBDriver: envOrDefault("DB_DRIVER", DBDriverSQLite),
|
||||
SQLitePath: envOrDefault("DB_SQLITE_PATH", "data/app.sqlite3"),
|
||||
PostgresDSN: strings.TrimSpace(os.Getenv("DB_POSTGRES_DSN")),
|
||||
CORS: CORSConfig{
|
||||
Origins: envListOrDefault("CORS_ORIGINS", []string{"http://localhost:3000"}),
|
||||
Headers: envListOrDefault("CORS_HEADERS", []string{"Origin", "Content-Type", "Accept", "Authorization", "HX-Request"}),
|
||||
Methods: envListOrDefault("CORS_METHODS", []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}),
|
||||
Credentials: envBoolOrDefault("CORS_CREDENTIALS", true),
|
||||
},
|
||||
SessionKey: envOrDefault("SESSION_KEY", "change-me-in-prod"),
|
||||
EmailSinkDir: envOrDefault("EMAIL_SINK_DIR", "data/email-sink"),
|
||||
AutoMigrate: envBoolOrDefault("AUTO_MIGRATE", true),
|
||||
SeedEnabled: envBoolOrDefault("SEED_ENABLED", false),
|
||||
SMTP: SMTPConfig{
|
||||
Host: envOrDefault("SMTP_HOST", "localhost"),
|
||||
Port: envIntOrDefault("SMTP_PORT", 1025),
|
||||
Username: strings.TrimSpace(os.Getenv("SMTP_USERNAME")),
|
||||
Password: strings.TrimSpace(os.Getenv("SMTP_PASSWORD")),
|
||||
From: envOrDefault("SMTP_FROM", "noreply@example.test"),
|
||||
},
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) Validate() error {
|
||||
if c.AppName == "" {
|
||||
return errors.New("APP_NAME is required")
|
||||
}
|
||||
|
||||
switch c.Env {
|
||||
case EnvDevelop, EnvProd:
|
||||
default:
|
||||
return fmt.Errorf("APP_ENV must be one of [%s,%s]", EnvDevelop, EnvProd)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(c.Port) == "" {
|
||||
return errors.New("APP_PORT is required")
|
||||
}
|
||||
|
||||
switch c.DBDriver {
|
||||
case DBDriverSQLite:
|
||||
if strings.TrimSpace(c.SQLitePath) == "" {
|
||||
return errors.New("DB_SQLITE_PATH is required when DB_DRIVER=sqlite")
|
||||
}
|
||||
case DBDriverPostgres:
|
||||
if strings.TrimSpace(c.PostgresDSN) == "" {
|
||||
return errors.New("DB_POSTGRES_DSN is required when DB_DRIVER=postgres")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("DB_DRIVER must be one of [%s,%s]", DBDriverSQLite, DBDriverPostgres)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(c.SessionKey) == "" {
|
||||
return errors.New("SESSION_KEY is required")
|
||||
}
|
||||
|
||||
if c.SMTP.Port <= 0 {
|
||||
return errors.New("SMTP_PORT must be > 0")
|
||||
}
|
||||
|
||||
if strings.TrimSpace(c.EmailSinkDir) == "" {
|
||||
return errors.New("EMAIL_SINK_DIR is required")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func envOrDefault(key, fallback string) string {
|
||||
value := strings.TrimSpace(os.Getenv(key))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func envBoolOrDefault(key string, fallback bool) bool {
|
||||
value := strings.TrimSpace(os.Getenv(key))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
func envIntOrDefault(key string, fallback int) int {
|
||||
value := strings.TrimSpace(os.Getenv(key))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
func envListOrDefault(key string, fallback []string) []string {
|
||||
value := strings.TrimSpace(os.Getenv(key))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
parts := strings.Split(value, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
clean := strings.TrimSpace(part)
|
||||
if clean != "" {
|
||||
out = append(out, clean)
|
||||
}
|
||||
}
|
||||
|
||||
if len(out) == 0 {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
57
internal/db/db.go
Normal file
57
internal/db/db.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"trustcontact/internal/config"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
gormlogger "gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func Open(cfg *config.Config) (*gorm.DB, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("config is nil")
|
||||
}
|
||||
|
||||
gormCfg := &gorm.Config{Logger: newLogger(cfg.Env)}
|
||||
|
||||
switch cfg.DBDriver {
|
||||
case config.DBDriverSQLite:
|
||||
if err := ensureSQLiteDir(cfg.SQLitePath); err != nil {
|
||||
return nil, fmt.Errorf("prepare sqlite dir: %w", err)
|
||||
}
|
||||
return gorm.Open(sqlite.Open(cfg.SQLitePath), gormCfg)
|
||||
case config.DBDriverPostgres:
|
||||
return gorm.Open(postgres.Open(cfg.PostgresDSN), gormCfg)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported db driver: %s", cfg.DBDriver)
|
||||
}
|
||||
}
|
||||
|
||||
func newLogger(env string) gormlogger.Interface {
|
||||
level := gormlogger.Warn
|
||||
if env == config.EnvDevelop {
|
||||
level = gormlogger.Info
|
||||
}
|
||||
|
||||
return gormlogger.Default.LogMode(level)
|
||||
}
|
||||
|
||||
func ensureSQLiteDir(sqlitePath string) error {
|
||||
dir := filepath.Dir(sqlitePath)
|
||||
if dir == "." || dir == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
return os.MkdirAll(dir, 0o755)
|
||||
}
|
||||
|
||||
func nowUTC() time.Time {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
15
internal/db/migrate.go
Normal file
15
internal/db/migrate.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"trustcontact/internal/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func Migrate(database *gorm.DB) error {
|
||||
return database.AutoMigrate(
|
||||
&models.User{},
|
||||
&models.EmailVerificationToken{},
|
||||
&models.PasswordResetToken{},
|
||||
)
|
||||
}
|
||||
76
internal/db/seed.go
Normal file
76
internal/db/seed.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"trustcontact/internal/auth"
|
||||
"trustcontact/internal/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func Seed(database *gorm.DB) error {
|
||||
passwordHash, err := auth.HashPassword("password")
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash seed password: %w", err)
|
||||
}
|
||||
|
||||
seedUsers := []models.User{
|
||||
{
|
||||
Email: "admin@example.com",
|
||||
Role: models.RoleAdmin,
|
||||
EmailVerified: true,
|
||||
PasswordHash: passwordHash,
|
||||
},
|
||||
{
|
||||
Email: "user@example.com",
|
||||
Role: models.RoleUser,
|
||||
EmailVerified: true,
|
||||
PasswordHash: passwordHash,
|
||||
},
|
||||
{
|
||||
Email: "demo1@example.com",
|
||||
Role: models.RoleUser,
|
||||
EmailVerified: true,
|
||||
PasswordHash: passwordHash,
|
||||
},
|
||||
{
|
||||
Email: "demo2@example.com",
|
||||
Role: models.RoleUser,
|
||||
EmailVerified: true,
|
||||
PasswordHash: passwordHash,
|
||||
},
|
||||
{
|
||||
Email: "demo3@example.com",
|
||||
Role: models.RoleUser,
|
||||
EmailVerified: true,
|
||||
PasswordHash: passwordHash,
|
||||
},
|
||||
}
|
||||
|
||||
for _, user := range seedUsers {
|
||||
if err := upsertUser(database, user); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertUser(database *gorm.DB, user models.User) error {
|
||||
result := database.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "email"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"role",
|
||||
"email_verified",
|
||||
"password_hash",
|
||||
"updated_at",
|
||||
}),
|
||||
}).Create(&user)
|
||||
if result.Error != nil {
|
||||
return fmt.Errorf("seed user %s: %w", user.Email, result.Error)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
15
internal/http/router.go
Normal file
15
internal/http/router.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"trustcontact/internal/config"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/session"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func RegisterRoutes(app *fiber.App, _ *session.Store, _ *gorm.DB, _ *config.Config) {
|
||||
app.Get("/healthz", func(c *fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
})
|
||||
}
|
||||
21
internal/models/auth_tokens.go
Normal file
21
internal/models/auth_tokens.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type EmailVerificationToken struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
UserID uint `gorm:"not null;index"`
|
||||
TokenHash string `gorm:"size:64;uniqueIndex;not null"`
|
||||
ExpiresAt time.Time `gorm:"not null;index"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type PasswordResetToken struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
UserID uint `gorm:"not null;index"`
|
||||
TokenHash string `gorm:"size:64;uniqueIndex;not null"`
|
||||
ExpiresAt time.Time `gorm:"not null;index"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
18
internal/models/user.go
Normal file
18
internal/models/user.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
RoleAdmin = "admin"
|
||||
RoleUser = "user"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Email string `gorm:"size:320;uniqueIndex;not null"`
|
||||
PasswordHash string `gorm:"size:255;not null"`
|
||||
EmailVerified bool `gorm:"not null;default:false"`
|
||||
Role string `gorm:"size:32;index;not null;default:user"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
Reference in New Issue
Block a user