Files
kotosoft-id/kotosoft-id-backend/cmd/main.go
T

88 lines
2.3 KiB
Go

package main
import (
"context"
"encoding/json"
"log"
"github.com/dusiburg/kotosoft-id/internal/config"
"github.com/dusiburg/kotosoft-id/internal/db"
"github.com/dusiburg/kotosoft-id/internal/handlers"
http "github.com/dusiburg/kotosoft-id/internal/http"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/dusiburg/kotosoft-id/internal/repositories"
"github.com/dusiburg/kotosoft-id/internal/services"
)
func main() {
cfg, err := config.New()
if err != nil {
log.Fatalf("config: %v", err)
}
postgres, err := db.ConnectPostgres(cfg.Postgres.URL)
if err != nil {
log.Fatalf("postgres: %v", err)
}
if err := db.RunMigrations(cfg.Postgres.MigrationFilePath, postgres.Pool); err != nil {
log.Fatalf("migrations: %v", err)
}
redis, err := db.ConnectRedis(cfg.Redis.URL)
if err != nil {
log.Fatalf("redis: %v", err)
}
userRepo := repositories.NewUserRepository(postgres.Pool)
oauthRepo := repositories.NewOAuthRepository(postgres.Pool)
if err := seedClient(context.Background(), oauthRepo, cfg.Client); err != nil {
log.Fatalf("seed client: %v", err)
}
svc := services.New(
userRepo,
oauthRepo,
redis.Client,
services.TokenConfig{
AccessTTL: cfg.Tokens.AccessTTL,
RefreshTTL: cfg.Tokens.RefreshTTL,
},
)
limiter := services.NewRateLimiter(redis.Client)
authHandler := handlers.NewAuthHandler(svc)
oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL)
consentHandler := handlers.NewConsentHandler(svc)
clientHandler := handlers.NewClientHandler(svc)
router := http.NewRouter(authHandler, oauthHandler, consentHandler, clientHandler, svc, oauthRepo, limiter)
log.Printf("starting server on %s", cfg.Server.Addr)
if err := router.Run(cfg.Server.Addr); err != nil {
log.Fatalf("server: %v", err)
}
}
func seedClient(ctx context.Context, repo *repositories.OAuthRepository, cfg config.Client) error {
hashedSecret, err := services.HashClientSecret(cfg.Secret)
if err != nil {
return err
}
redirectURIsJSON, _ := json.Marshal(cfg.RedirectURIs)
grantTypesJSON, _ := json.Marshal(cfg.GrantTypes)
scopesJSON, _ := json.Marshal(cfg.Scopes)
return repo.UpsertClient(ctx, models.OAuthClient{
ClientID: cfg.ID,
ClientSecret: hashedSecret,
Name: cfg.Name,
RedirectURIs: redirectURIsJSON,
GrantTypes: grantTypesJSON,
Scopes: scopesJSON,
Trusted: true,
})
}