forked from baron/baron-sso
Merge pull request 'dev/sso-from-b5aed4f' (#34) from dev/sso-from-b5aed4f into main
Reviewed-on: ai-team/baron-sso#34
This commit is contained in:
@@ -1,18 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"baron-sso-backend/internal/handler"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/bwmarrin/snowflake"
|
||||
"baron-sso-backend/internal/handler"
|
||||
"baron-sso-backend/internal/logger"
|
||||
"baron-sso-backend/internal/repository"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/gofiber/fiber/v2/middleware/encryptcookie"
|
||||
"github.com/gofiber/fiber/v2/middleware/logger"
|
||||
"github.com/gofiber/fiber/v2/middleware/recover"
|
||||
"github.com/gofiber/fiber/v2/middleware/requestid"
|
||||
)
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
@@ -23,7 +26,27 @@ func getEnv(key, fallback string) string {
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 1. Initialize DB Connections
|
||||
// 0. Initialize Logger
|
||||
logger.Init(logger.Config{
|
||||
ServiceName: "baron-sso",
|
||||
Environment: getEnv("GO_ENV", "dev"),
|
||||
})
|
||||
|
||||
// Initialize Snowflake Node (Node 2 for Baron)
|
||||
node, err := snowflake.NewNode(2)
|
||||
if err != nil {
|
||||
slog.Error("Failed to initialize snowflake node", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// 1. Log Config on Startup
|
||||
slog.Info("Starting Baron SSO Backend",
|
||||
"frontend_url", getEnv("FRONTEND_URL", "http://ssologin.hmac.kr"),
|
||||
"redis_addr", getEnv("REDIS_ADDR", "redis:6379"),
|
||||
"descope_id", getEnv("DESCOPE_PROJECT_ID", "not-set"),
|
||||
)
|
||||
|
||||
// 2. Initialize DB Connections
|
||||
chHost := getEnv("CLICKHOUSE_HOST", "localhost")
|
||||
chPort, _ := strconv.Atoi(getEnv("CLICKHOUSE_PORT_NATIVE", "9000"))
|
||||
chUser := getEnv("CLICKHOUSE_USER", "default")
|
||||
@@ -32,8 +55,7 @@ func main() {
|
||||
|
||||
auditRepo, err := repository.NewClickHouseRepository(chHost, chPort, chUser, chPass, chDB)
|
||||
if err != nil {
|
||||
log.Printf("Warning: Failed to connect to ClickHouse: %v. Audit logs will fail.", err)
|
||||
// Proceeding mostly for Dev purposes, but in Prod should generally fail or fallback.
|
||||
slog.Warn("Failed to connect to ClickHouse. Audit logs will fail.", "error", err)
|
||||
}
|
||||
|
||||
// 2. Initialize Handlers
|
||||
@@ -43,10 +65,42 @@ func main() {
|
||||
// 3. Initialize Fiber
|
||||
app := fiber.New(fiber.Config{
|
||||
AppName: "Baron SSO Backend",
|
||||
DisableStartupMessage: true, // Clean logs
|
||||
})
|
||||
|
||||
// Middleware
|
||||
app.Use(logger.New())
|
||||
app.Use(requestid.New(requestid.Config{
|
||||
Generator: func() string {
|
||||
return node.Generate().String()
|
||||
},
|
||||
}))
|
||||
|
||||
// [Standardized] HTTP Request Logger Middleware using slog
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
start := time.Now()
|
||||
|
||||
// Handle request
|
||||
err := c.Next()
|
||||
|
||||
// Log after request
|
||||
latency := time.Since(start)
|
||||
|
||||
msg := "http_request"
|
||||
if err != nil {
|
||||
msg = "http_request_error"
|
||||
}
|
||||
|
||||
slog.Info(msg,
|
||||
"status", c.Response().StatusCode(),
|
||||
"method", c.Method(),
|
||||
"path", c.Path(),
|
||||
"latency", latency.String(),
|
||||
"ip", c.IP(),
|
||||
"req_id", c.GetRespHeader(fiber.HeaderXRequestID),
|
||||
)
|
||||
return err
|
||||
})
|
||||
|
||||
app.Use(recover.New())
|
||||
app.Use(cors.New(cors.Config{
|
||||
AllowOrigins: "*", // Adjust in production
|
||||
@@ -84,21 +138,52 @@ func main() {
|
||||
// Webhook for Descope Generic Email Gateway (Fake Email Strategy)
|
||||
auth.Post("/webhooks/descope-email", authHandler.HandleDescopeEmailRelay)
|
||||
|
||||
// Client Logging Route (For Debugging)
|
||||
// Client Logging Route (Standardized & Flattened)
|
||||
api.Post("/client-log", func(c *fiber.Ctx) error {
|
||||
type LogReq struct {
|
||||
Level string `json:"level"`
|
||||
Message string `json:"message"`
|
||||
Level string `json:"level"`
|
||||
Message string `json:"message"`
|
||||
Data map[string]interface{} `json:"data,omitempty"`
|
||||
}
|
||||
var req LogReq
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.SendStatus(fiber.StatusBadRequest)
|
||||
}
|
||||
log.Printf("[CLIENT-LOG] [%s] %s", req.Level, req.Message)
|
||||
|
||||
// Prepare attributes for flattening
|
||||
attrs := []any{
|
||||
slog.String("source", "client"),
|
||||
}
|
||||
for k, v := range req.Data {
|
||||
// Skip svc if it's already set by the global logger to avoid confusion,
|
||||
// or keep it as client_svc
|
||||
if k == "svc" {
|
||||
attrs = append(attrs, slog.Any("client_svc", v))
|
||||
} else {
|
||||
attrs = append(attrs, slog.Any(k, v))
|
||||
}
|
||||
}
|
||||
|
||||
// Map and log with correct level
|
||||
var level slog.Level
|
||||
switch req.Level {
|
||||
case "SEVERE", "ERROR":
|
||||
level = slog.LevelError
|
||||
case "WARNING", "WARN":
|
||||
level = slog.LevelWarn
|
||||
default:
|
||||
level = slog.LevelInfo
|
||||
}
|
||||
|
||||
slog.Log(c.Context(), level, req.Message, attrs...)
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
})
|
||||
|
||||
// Start Server
|
||||
port := getEnv("PORT", "3000")
|
||||
log.Fatal(app.Listen(":" + port))
|
||||
slog.Info("Server listening", "port", port)
|
||||
if err := app.Listen(":" + port); err != nil {
|
||||
slog.Error("Server failed to start", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ require (
|
||||
require (
|
||||
github.com/ClickHouse/ch-go v0.69.0 // indirect
|
||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||
github.com/bwmarrin/snowflake v0.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
|
||||
@@ -4,6 +4,8 @@ github.com/ClickHouse/clickhouse-go/v2 v2.42.0 h1:MdujEfIrpXesQUH0k0AnuVtJQXk6RZ
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.42.0/go.mod h1:riWnuo4YMVdajYll0q6FzRBomdyCrXyFY3VXeXczA8s=
|
||||
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
||||
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
|
||||
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
|
||||
@@ -39,8 +39,8 @@ type AuthHandler struct {
|
||||
DescopeClient *client.DescopeClient
|
||||
}
|
||||
|
||||
// Helper to generate secure random strings
|
||||
func generateSecureToken(length int) string {
|
||||
// GenerateSecureToken - Helper to generate secure random strings
|
||||
func GenerateSecureToken(length int) string {
|
||||
b := make([]byte, length)
|
||||
if _, err := crand.Read(b); err != nil {
|
||||
return ""
|
||||
@@ -126,36 +126,39 @@ func (h *AuthHandler) VerifySms(c *fiber.Ctx) error {
|
||||
func (h *AuthHandler) InitEnchantedLink(c *fiber.Ctx) error {
|
||||
var req domain.EnchantedLinkInitRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
log.Printf("[Enchanted] Body parse error: %v", err)
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid request body"})
|
||||
}
|
||||
|
||||
loginID := strings.ReplaceAll(req.LoginID, "-", "")
|
||||
loginID = strings.ReplaceAll(loginID, " ", "")
|
||||
|
||||
|
||||
// Generate secure tokens
|
||||
token := generateSecureToken(3)
|
||||
pendingRef := generateSecureToken(3)
|
||||
token := GenerateSecureToken(3)
|
||||
pendingRef := GenerateSecureToken(3)
|
||||
|
||||
log.Printf("[Enchanted] Initiating for %s. Token: %s, PendingRef: %s", loginID, token, pendingRef)
|
||||
|
||||
// Store in Redis
|
||||
h.RedisService.Set(prefixSession+pendingRef, fmt.Sprintf(`{"status":"%s"}`, statusPending), defaultExpiration)
|
||||
h.RedisService.Set(prefixToken+token, fmt.Sprintf(`{"pendingRef":"%s","loginId":"%s"}`, pendingRef, loginID), defaultExpiration)
|
||||
|
||||
// Send SMS
|
||||
// Frontend URL should be dynamic or env based
|
||||
frontendURL := os.Getenv("FRONTEND_URL")
|
||||
if frontendURL == "" {
|
||||
frontendURL = "http://ssologin.hmac.kr"
|
||||
}
|
||||
link := fmt.Sprintf("%s/verify/%s", frontendURL, token)
|
||||
content := fmt.Sprintf("[Baron SSO] 로그인 링크: %s", link)
|
||||
|
||||
log.Printf("[Enchanted] Sending link to %s", loginID)
|
||||
|
||||
log.Printf("[Enchanted] Sending SMS to %s via Naver Cloud", loginID)
|
||||
|
||||
if err := h.SmsService.SendSms(loginID, content); err != nil {
|
||||
log.Printf("[Enchanted] SMS Failed: %v", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to send SMS"})
|
||||
}
|
||||
|
||||
log.Printf("[Enchanted] SMS sent successfully to %s", loginID)
|
||||
return c.JSON(fiber.Map{
|
||||
"linkId": "SMS Sent",
|
||||
"pendingRef": pendingRef,
|
||||
@@ -179,6 +182,7 @@ func (h *AuthHandler) PollEnchantedLink(c *fiber.Ctx) error {
|
||||
json.Unmarshal([]byte(val), &data)
|
||||
|
||||
if data["status"] == statusSuccess {
|
||||
log.Printf("[Poll] Success for ref: %s", req.PendingRef)
|
||||
return c.JSON(fiber.Map{
|
||||
"sessionJwt": data["jwt"],
|
||||
"status": "ok",
|
||||
@@ -192,12 +196,16 @@ func (h *AuthHandler) PollEnchantedLink(c *fiber.Ctx) error {
|
||||
func (h *AuthHandler) VerifyMagicLink(c *fiber.Ctx) error {
|
||||
var req domain.MagicLinkVerifyRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
log.Printf("[Verify] Body parse error: %v", err)
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid request body"})
|
||||
}
|
||||
|
||||
log.Printf("[Verify] Attempting to verify token: %s", req.Token)
|
||||
|
||||
tokenKey := prefixToken + req.Token
|
||||
val, err := h.RedisService.Get(tokenKey)
|
||||
if err != nil || val == "" {
|
||||
log.Printf("[Verify] Token not found or expired in Redis: %s", req.Token)
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Invalid or expired token"})
|
||||
}
|
||||
|
||||
@@ -206,73 +214,68 @@ func (h *AuthHandler) VerifyMagicLink(c *fiber.Ctx) error {
|
||||
pendingRef := tokenData["pendingRef"]
|
||||
loginID := tokenData["loginId"]
|
||||
|
||||
log.Printf("[Verify] Token valid. LoginID: %s, PendingRef: %s", loginID, pendingRef)
|
||||
|
||||
// 1. Generate Descope Session Directly (Management SDK)
|
||||
if h.DescopeClient == nil {
|
||||
log.Printf("[Verify] Descope Client is nil!")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Descope Client not configured"})
|
||||
}
|
||||
|
||||
// Use GenerateEmbeddedLink to get a temporary token directly for the user.
|
||||
// This generates a token that will be exchanged for a real session.
|
||||
log.Printf("[Verify] Generating embedded link for %s", loginID)
|
||||
embeddedToken, err := h.DescopeClient.Management.User().GenerateEmbeddedLink(context.Background(), loginID, nil, 0)
|
||||
if err != nil {
|
||||
// If user does not exist, create it and retry
|
||||
if strings.Contains(err.Error(), "User not found") || strings.Contains(err.Error(), "E062108") {
|
||||
log.Printf("User %s not found. Creating new user...", loginID)
|
||||
|
||||
// Format LoginID for Descope (E.164 for phones)
|
||||
log.Printf("[Verify] User %s not found. Creating...", loginID)
|
||||
|
||||
descopeLoginID := loginID
|
||||
userObj := &descope.UserRequest{}
|
||||
|
||||
if strings.Contains(loginID, "@") {
|
||||
userObj.Email = loginID
|
||||
} else {
|
||||
// LoginID is likely a phone number
|
||||
if strings.HasPrefix(loginID, "010") {
|
||||
descopeLoginID = "+82" + loginID[1:]
|
||||
}
|
||||
userObj.Phone = descopeLoginID
|
||||
}
|
||||
|
||||
// Create user using the formatted LoginID
|
||||
_, errCreate := h.DescopeClient.Management.User().Create(context.Background(), descopeLoginID, userObj)
|
||||
if errCreate != nil {
|
||||
log.Printf("Failed to create user: %v", errCreate)
|
||||
log.Printf("[Verify] Failed to create user: %v", errCreate)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to create new user"})
|
||||
}
|
||||
|
||||
// Retry generating embedded token with the Descope LoginID
|
||||
|
||||
embeddedToken, err = h.DescopeClient.Management.User().GenerateEmbeddedLink(context.Background(), descopeLoginID, nil, 0)
|
||||
if err != nil {
|
||||
log.Printf("Failed to generate Descope Session after creation: %v", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to generate token for new user"})
|
||||
log.Printf("[Verify] Failed to generate token after creation: %v", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to generate upstream token"})
|
||||
}
|
||||
} else {
|
||||
log.Printf("Failed to generate Descope Session: %v", err)
|
||||
log.Printf("[Verify] Descope Error: %v", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to generate upstream token"})
|
||||
}
|
||||
}
|
||||
|
||||
// Exchange the Embedded Token for a real User Session JWT
|
||||
log.Printf("[Verify] Exchanging embedded token for session JWT")
|
||||
authInfo, err := h.DescopeClient.Auth.MagicLink().Verify(context.Background(), embeddedToken, nil)
|
||||
if err != nil {
|
||||
log.Printf("Failed to verify embedded token: %v", err)
|
||||
log.Printf("[Verify] Final verification failed: %v", err)
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to verify upstream token"})
|
||||
}
|
||||
sessionToken := authInfo.SessionToken.JWT
|
||||
|
||||
// Update Session in Redis for the polling client
|
||||
log.Printf("[Verify] Success! Updating Redis session: %s", pendingRef)
|
||||
sessionData, _ := json.Marshal(map[string]string{
|
||||
"status": statusSuccess,
|
||||
"jwt": sessionToken,
|
||||
})
|
||||
h.RedisService.Set(prefixSession+pendingRef, string(sessionData), defaultExpiration)
|
||||
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"token": sessionToken,
|
||||
"message": "Login successful",
|
||||
})
|
||||
}
|
||||
|
||||
// ProxyToDescope (Placeholder)
|
||||
func (h *AuthHandler) ProxyToDescope(c *fiber.Ctx, path string, payload interface{}) error {
|
||||
return c.Status(501).SendString("Descope Proxy Disabled")
|
||||
|
||||
49
backend/internal/logger/logger.go
Normal file
49
backend/internal/logger/logger.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Config holds the logger configuration
|
||||
type Config struct {
|
||||
ServiceName string
|
||||
Environment string // "dev", "local", "production"
|
||||
}
|
||||
|
||||
// Init initializes the global logger with slog.
|
||||
// It detects the environment to switch between TextHandler (dev) and JSONHandler (prod).
|
||||
func Init(cfg Config) {
|
||||
var handler slog.Handler
|
||||
|
||||
opts := &slog.HandlerOptions{
|
||||
// Default level
|
||||
Level: slog.LevelInfo,
|
||||
// Customize attributes (Time format)
|
||||
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
||||
if a.Key == slog.TimeKey {
|
||||
return slog.String(a.Key, a.Value.Time().Format("2006-01-02 15:04:05"))
|
||||
}
|
||||
return a
|
||||
},
|
||||
}
|
||||
|
||||
// Adjust level and format based on environment
|
||||
env := strings.ToLower(cfg.Environment)
|
||||
if env == "dev" || env == "local" || env == "development" {
|
||||
opts.Level = slog.LevelDebug
|
||||
handler = slog.NewTextHandler(os.Stdout, opts)
|
||||
} else {
|
||||
// Production defaults to JSON
|
||||
handler = slog.NewJSONHandler(os.Stdout, opts)
|
||||
}
|
||||
|
||||
// Create logger with common attributes
|
||||
logger := slog.New(handler).With(
|
||||
slog.String("svc", cfg.ServiceName),
|
||||
)
|
||||
|
||||
// Set as global default logger
|
||||
slog.SetDefault(logger)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ services:
|
||||
- .env
|
||||
environment:
|
||||
- APP_ENV=${APP_ENV:-development}
|
||||
- GO_ENV=${APP_ENV:-development}
|
||||
- COOKIE_SECRET=${COOKIE_SECRET}
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
- DESCOPE_PROJECT_ID=${DESCOPE_PROJECT_ID}
|
||||
@@ -39,14 +40,27 @@ services:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
container_name: baron_frontend
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- DESCOPE_PROJECT_ID=${DESCOPE_PROJECT_ID}
|
||||
- BACKEND_URL=${BACKEND_URL}
|
||||
- FRONTEND_URL=${FRONTEND_URL}
|
||||
- APP_ENV=${APP_ENV}
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-5000}:5000"
|
||||
networks:
|
||||
- baron_net
|
||||
depends_on:
|
||||
- backend
|
||||
command: >
|
||||
/bin/sh -c "mkdir -p /usr/share/nginx/html/assets &&
|
||||
echo \"DESCOPE_PROJECT_ID=$${DESCOPE_PROJECT_ID}\" > /usr/share/nginx/html/assets/.env &&
|
||||
echo \"BACKEND_URL=$${BACKEND_URL}\" >> /usr/share/nginx/html/assets/.env &&
|
||||
echo \"FRONTEND_URL=$${FRONTEND_URL}\" >> /usr/share/nginx/html/assets/.env &&
|
||||
echo \"APP_ENV=$${APP_ENV}\" >> /usr/share/nginx/html/assets/.env &&
|
||||
cp /usr/share/nginx/html/assets/.env /usr/share/nginx/html/.env &&
|
||||
nginx -g 'daemon off;'"
|
||||
|
||||
# Dummy service to wait for infra network if needed,
|
||||
# but essentially we assume infra is running.
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# ==========================================
|
||||
# Baron SSO - Unified Environment Configuration
|
||||
# ==========================================
|
||||
|
||||
# --- General System ---
|
||||
APP_ENV=development
|
||||
TZ=Asia/Seoul
|
||||
|
||||
# --- Infrastructure Ports ---
|
||||
DB_PORT=5432
|
||||
CLICKHOUSE_PORT_HTTP=8123
|
||||
CLICKHOUSE_PORT_NATIVE=9000
|
||||
BACKEND_PORT=3000
|
||||
FRONTEND_PORT=5000
|
||||
|
||||
# --- Database Credentials (PostgreSQL) ---
|
||||
DB_USER=baron
|
||||
DB_PASSWORD=password
|
||||
DB_NAME=baron_sso
|
||||
|
||||
# --- Backend Configuration ---
|
||||
# Must be 32 bytes. Generate with `openssl rand -hex 32`
|
||||
COOKIE_SECRET=super-secret-key-must-be-32-bytes!
|
||||
REDIS_ADDR=redis:6379
|
||||
|
||||
# --- Frontend Configuration ---
|
||||
# Descope Project ID (Required for Auth)
|
||||
DESCOPE_PROJECT_ID=P2t...your_descope_project_id
|
||||
|
||||
# --- Naver Cloud Services ---
|
||||
NAVER_CLOUD_ACCESS_KEY=ncp_iam_...
|
||||
NAVER_CLOUD_SECRET_KEY=ncp_iam_...
|
||||
NAVER_CLOUD_SERVICE_ID=ncp:sms:kr:...:...
|
||||
NAVER_SENDER_PHONE_NUMBER=...
|
||||
@@ -4,6 +4,7 @@ WORKDIR /app
|
||||
COPY . .
|
||||
# Get dependencies and build for web
|
||||
RUN flutter pub get
|
||||
RUN touch .env
|
||||
RUN flutter build web --release
|
||||
|
||||
# Stage 2: Serve with Nginx
|
||||
|
||||
@@ -99,19 +99,28 @@ class AuthProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> logError(String message) async {
|
||||
static Future<void> sendLog(String level, String message, {Map<String, dynamic>? data}) async {
|
||||
final url = Uri.parse('$_baseUrl/api/v1/client-log');
|
||||
try {
|
||||
await http.post(
|
||||
url,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'level': 'ERROR',
|
||||
'level': level,
|
||||
'message': message,
|
||||
if (data != null) 'data': data,
|
||||
}),
|
||||
);
|
||||
} catch (_) {
|
||||
// Ignore logging errors to prevent loops
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> logError(String message, {dynamic error, StackTrace? stackTrace}) async {
|
||||
final data = <String, dynamic>{};
|
||||
if (error != null) data['error'] = error.toString();
|
||||
if (stackTrace != null) data['stack'] = stackTrace.toString();
|
||||
|
||||
await sendLog('ERROR', message, data: data);
|
||||
}
|
||||
}
|
||||
|
||||
86
frontend/lib/core/services/logger_service.dart
Normal file
86
frontend/lib/core/services/logger_service.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:logging/logging.dart' as std_log;
|
||||
import 'package:logger/logger.dart' as pretty_log;
|
||||
import 'auth_proxy_service.dart';
|
||||
|
||||
/// Global Logger Service for Baron SSO Frontend
|
||||
class LoggerService {
|
||||
static final LoggerService _instance = LoggerService._internal();
|
||||
factory LoggerService() => _instance;
|
||||
|
||||
late final pretty_log.Logger _prettyLogger;
|
||||
|
||||
LoggerService._internal() {
|
||||
// 1. Initialize Pretty Logger for Dev
|
||||
_prettyLogger = pretty_log.Logger(
|
||||
printer: pretty_log.PrettyPrinter(
|
||||
methodCount: 0,
|
||||
errorMethodCount: 8,
|
||||
lineLength: 120,
|
||||
colors: true,
|
||||
printEmojis: true,
|
||||
dateTimeFormat: pretty_log.DateTimeFormat.onlyTimeAndSinceStart,
|
||||
),
|
||||
);
|
||||
|
||||
// 2. Configure Standard Logger (logging package)
|
||||
std_log.Logger.root.level = kReleaseMode ? std_log.Level.INFO : std_log.Level.ALL;
|
||||
|
||||
std_log.Logger.root.onRecord.listen((record) {
|
||||
if (kReleaseMode) {
|
||||
// [Production] Log as JSON
|
||||
_logJson(record);
|
||||
} else {
|
||||
// [Development] Log using Pretty Printer
|
||||
_logPretty(record);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Initialize the logger. Call this in main.dart
|
||||
static void init() {
|
||||
// Accessing the instance triggers the constructor
|
||||
LoggerService();
|
||||
std_log.Logger('BaronSSO').info('Logger initialized');
|
||||
}
|
||||
|
||||
void _logPretty(std_log.LogRecord record) {
|
||||
if (record.level >= std_log.Level.SEVERE) {
|
||||
_prettyLogger.e(record.message, error: record.error, stackTrace: record.stackTrace);
|
||||
} else if (record.level >= std_log.Level.WARNING) {
|
||||
_prettyLogger.w(record.message);
|
||||
} else if (record.level >= std_log.Level.INFO) {
|
||||
_prettyLogger.i(record.message);
|
||||
} else {
|
||||
_prettyLogger.d(record.message);
|
||||
}
|
||||
}
|
||||
|
||||
void _logJson(std_log.LogRecord record) {
|
||||
final logData = {
|
||||
'time': record.time.toUtc().toIso8601String(), // Use UTC for consistency
|
||||
'level': record.level.name,
|
||||
'msg': record.message,
|
||||
'svc': 'baron-frontend',
|
||||
if (record.error != null) 'error': record.error.toString(),
|
||||
if (record.stackTrace != null) 'stack': record.stackTrace.toString(),
|
||||
};
|
||||
|
||||
// 1. Print to Browser Console (F12)
|
||||
debugPrint(jsonEncode(logData));
|
||||
|
||||
// 2. Relay to Backend (Docker Terminal)
|
||||
if (record.level >= std_log.Level.INFO) {
|
||||
AuthProxyService.sendLog(
|
||||
record.level.name,
|
||||
record.message,
|
||||
data: {
|
||||
'client_time': record.time.toUtc().toIso8601String(),
|
||||
'logger': record.loggerName,
|
||||
if (record.error != null) 'error': record.error.toString(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:descope/descope.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
@@ -50,20 +51,17 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
}
|
||||
|
||||
Future<void> _verifyToken(String token) async {
|
||||
debugPrint("[Auth] Starting verification for token: $token");
|
||||
try {
|
||||
// Use Backend to verify the token (Backend-Driven Flow)
|
||||
// The backend will validate the local token, and then trigger Descope JWT generation.
|
||||
// This approves the pending session for the Polling device.
|
||||
await AuthProxyService.verifyMagicLink(token);
|
||||
|
||||
// Note: If this device (Mobile) also needs to login, we would need to
|
||||
// parse the response from verifyMagicLink which contains the JWT.
|
||||
// For now, we assume this action primarily approves the PC session.
|
||||
debugPrint("[Auth] Verification successful for token: $token");
|
||||
|
||||
if (mounted) {
|
||||
_showSuccessDialog();
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint("[Auth] Verification FAILED for token: $token. Error: $e");
|
||||
if (mounted) {
|
||||
_showError("Verification failed: $e");
|
||||
}
|
||||
@@ -97,6 +95,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
|
||||
final password = _passwordController.text;
|
||||
if (password.isNotEmpty) {
|
||||
debugPrint("[Auth] Attempting Email/Password login for: $email");
|
||||
try {
|
||||
final authResponse = await Descope.password.signIn(
|
||||
loginId: email,
|
||||
@@ -104,12 +103,14 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
);
|
||||
final session = DescopeSession.fromAuthenticationResponse(authResponse);
|
||||
Descope.sessionManager.manageSession(session);
|
||||
debugPrint("[Auth] Email login successful");
|
||||
if (mounted) _onLoginSuccess(session.sessionToken.jwt);
|
||||
} catch (e) {
|
||||
debugPrint("[Auth] Email login failed: $e");
|
||||
_showError("Email/Password Login Failed: $e");
|
||||
}
|
||||
} else {
|
||||
// Email Enchanted Link (Descope Standard)
|
||||
debugPrint("[Auth] Initiating Email Enchanted Link for: $email");
|
||||
_initiateDescopeLinkFlow(email, isSms: false);
|
||||
}
|
||||
}
|
||||
@@ -118,9 +119,8 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
final rawPhone = _phoneController.text.trim();
|
||||
if (rawPhone.isEmpty) return;
|
||||
|
||||
// Sanitize phone number
|
||||
String phone = rawPhone.replaceAll(RegExp(r'[-\s]'), '');
|
||||
// Ensure 010 format if needed, but backend handles it too
|
||||
debugPrint("[Auth] Initiating SMS Enchanted Link for: $phone");
|
||||
|
||||
try {
|
||||
if (mounted) {
|
||||
@@ -131,14 +131,14 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
);
|
||||
}
|
||||
|
||||
// 1. Init via Backend API (Not Descope SDK)
|
||||
// 1. Init via Backend API
|
||||
final initResponse = await AuthProxyService.initEnchantedLink(phone);
|
||||
final pendingRef = initResponse['pendingRef'];
|
||||
debugPrint("[Auth] SMS Sent. PendingRef: $pendingRef");
|
||||
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop(); // Close Loading
|
||||
|
||||
// Show Waiting Dialog
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
@@ -153,7 +153,8 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
const SizedBox(height: 16),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop(); // Allow canceling
|
||||
debugPrint("[Auth] Polling canceled by user");
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text("Cancel")
|
||||
)
|
||||
@@ -166,6 +167,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
_pollForSession(pendingRef);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint("[Auth] SMS initialization failed: $e");
|
||||
if (mounted && Navigator.canPop(context)) Navigator.of(context).pop();
|
||||
_showError("Failed to send SMS: $e");
|
||||
}
|
||||
@@ -174,6 +176,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
Future<void> _pollForSession(String pendingRef) async {
|
||||
int attempts = 0;
|
||||
const maxAttempts = 60; // 2 minutes
|
||||
debugPrint("[Auth] Starting poll for ref: $pendingRef");
|
||||
|
||||
while (attempts < maxAttempts && mounted) {
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
@@ -185,12 +188,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
if (result['status'] == 'ok') {
|
||||
final jwt = result['sessionJwt'];
|
||||
if (jwt != null) {
|
||||
// Note: Manually constructing DescopeSession can be complex due to abstract classes.
|
||||
// In a real production app, you should use the SDK's built-in exchange/verify methods.
|
||||
// For this prototype, we will proceed with the login success callback.
|
||||
// If session management is required immediately, we'd need to match the specific
|
||||
// SDK version's Token implementation.
|
||||
|
||||
debugPrint("[Auth] Polling SUCCESS. Token received.");
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop(); // Close Polling Dialog
|
||||
_onLoginSuccess(jwt);
|
||||
@@ -199,13 +197,12 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Polling error: $e");
|
||||
// Continue polling even on temporary network error?
|
||||
// Or break? Let's continue.
|
||||
debugPrint("[Auth] Polling error (attempt $attempts): $e");
|
||||
}
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
debugPrint("[Auth] Polling timed out for ref: $pendingRef");
|
||||
Navigator.of(context).pop(); // Close Polling Dialog
|
||||
_showError("Login timed out.");
|
||||
}
|
||||
@@ -276,6 +273,14 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
void _onLoginSuccess(String token) {
|
||||
if (!mounted) return;
|
||||
|
||||
// Record Audit Log
|
||||
AuditService.logEvent(
|
||||
userId: "unknown", // In real apps, parse token to get user ID
|
||||
eventType: "LOGIN_SUCCESS",
|
||||
status: "SUCCESS",
|
||||
details: "User logged in via Baron SSO",
|
||||
);
|
||||
|
||||
if (WebAuthIntegration.isPopup()) {
|
||||
WebAuthIntegration.sendLoginSuccess(token);
|
||||
_showError("Login Successful! You can close this window.");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
@@ -7,16 +8,38 @@ import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:flutter_web_plugins/url_strategy.dart';
|
||||
import 'features/auth/presentation/login_screen.dart';
|
||||
import 'features/dashboard/presentation/dashboard_screen.dart';
|
||||
import 'core/services/auth_proxy_service.dart';
|
||||
import 'core/services/logger_service.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
final _log = Logger('Main');
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
usePathUrlStrategy();
|
||||
|
||||
// 0. Initialize Logger
|
||||
LoggerService.init();
|
||||
|
||||
// 1. Global Error Handling
|
||||
FlutterError.onError = (details) {
|
||||
FlutterError.presentError(details);
|
||||
_log.severe("FLUTTER_ERROR", details.exception, details.stack);
|
||||
// Also send to backend if needed
|
||||
AuthProxyService.logError("FLUTTER_ERROR: ${details.exception}\n${details.stack}");
|
||||
};
|
||||
|
||||
PlatformDispatcher.instance.onError = (error, stack) {
|
||||
_log.severe("PLATFORM_ERROR", error, stack);
|
||||
AuthProxyService.logError("PLATFORM_ERROR: $error\n$stack");
|
||||
return true;
|
||||
};
|
||||
|
||||
// Load Env (Handling error if missing for now)
|
||||
try {
|
||||
await dotenv.load(fileName: ".env");
|
||||
} catch (e) {
|
||||
debugPrint("Warning: .env file not found.");
|
||||
_log.warning("Warning: .env file not found.");
|
||||
}
|
||||
|
||||
// Initialize Descope
|
||||
@@ -27,27 +50,40 @@ void main() async {
|
||||
try {
|
||||
await Descope.sessionManager.loadSession();
|
||||
} catch (e) {
|
||||
debugPrint("Failed to load session: $e");
|
||||
_log.warning("Failed to load session: $e");
|
||||
}
|
||||
|
||||
runApp(const ProviderScope(child: BaronSSOApp()));
|
||||
}
|
||||
|
||||
// Router Configuration
|
||||
final _routerLogger = Logger('Router');
|
||||
|
||||
final _router = GoRouter(
|
||||
initialLocation: '/',
|
||||
debugLogDiagnostics: true, // Enable diagnostic logs
|
||||
routes: [
|
||||
GoRoute(path: '/', builder: (context, state) => const LoginScreen()),
|
||||
GoRoute(
|
||||
path: '/',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to root (LoginScreen)");
|
||||
return const LoginScreen();
|
||||
}
|
||||
),
|
||||
GoRoute(
|
||||
path: '/verify/:token',
|
||||
builder: (context, state) {
|
||||
final token = state.pathParameters['token'];
|
||||
_routerLogger.info("Navigating to /verify with token: $token");
|
||||
return LoginScreen(verificationToken: token);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/dashboard',
|
||||
builder: (context, state) => const DashboardScreen(),
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /dashboard");
|
||||
return const DashboardScreen();
|
||||
},
|
||||
),
|
||||
],
|
||||
redirect: (context, state) {
|
||||
@@ -56,8 +92,16 @@ final _router = GoRouter(
|
||||
final path = state.uri.path;
|
||||
final isLoggingIn = path == '/' || path.startsWith('/verify/');
|
||||
|
||||
if (!isLoggedIn && !isLoggingIn) return '/';
|
||||
if (isLoggedIn && path == '/') return '/dashboard';
|
||||
_routerLogger.fine("Redirect check - Path: $path, IsLoggedIn: $isLoggedIn");
|
||||
|
||||
if (!isLoggedIn && !isLoggingIn) {
|
||||
_routerLogger.info("Not logged in, redirecting to /");
|
||||
return '/';
|
||||
}
|
||||
if (isLoggedIn && path == '/') {
|
||||
_routerLogger.info("Logged in, redirecting to /dashboard");
|
||||
return '/dashboard';
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
# Map ISO8601 time to "YYYY-MM-DD HH:mm:ss" format
|
||||
map $time_iso8601 $time_custom {
|
||||
"~^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})" "$1-$2-$3 $4:$5:$6";
|
||||
}
|
||||
|
||||
# Custom JSON Log Format matching Go slog
|
||||
log_format json_combined escape=json
|
||||
'{'
|
||||
'"time":"$time_custom",'
|
||||
'"level":"INFO",'
|
||||
'"msg":"http_access",'
|
||||
'"svc":"baron-frontend",'
|
||||
'"status":$status,'
|
||||
'"method":"$request_method",'
|
||||
'"path":"$request_uri",'
|
||||
'"latency":"${request_time}s",'
|
||||
'"ip":"$remote_addr",'
|
||||
'"forwarded_for":"$http_x_forwarded_for",'
|
||||
'"user_agent":"$http_user_agent"'
|
||||
'}';
|
||||
|
||||
server {
|
||||
listen 5000;
|
||||
include /etc/nginx/mime.types;
|
||||
|
||||
access_log /var/log/nginx/access.log json_combined;
|
||||
|
||||
# Backend API Proxy
|
||||
location /api {
|
||||
|
||||
@@ -39,8 +39,10 @@ dependencies:
|
||||
descope: ^0.9.11
|
||||
http: ^1.6.0
|
||||
google_fonts: ^6.3.3
|
||||
flutter_dotenv: ^6.0.0
|
||||
flutter_dotenv: ^5.1.0
|
||||
url_launcher: ^6.3.2
|
||||
logging: ^1.2.0
|
||||
logger: ^2.0.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
Reference in New Issue
Block a user