file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
internal/repository/monitor.go
Go
package repository import ( "context" "github.com/jackc/pgx/v5" "github.com/yorukot/starker/internal/models" ) // GetMonitorsByNodeID gets monitors that use the specified node as source func GetMonitorsByNodeID(ctx context.Context, tx pgx.Tx, nodeID string) ([]models.Monitor, error) { query := ` SELECT id, collection_id, "from", name, to_ip, to_name, created_at, updated_at FROM monitors WHERE "from" = $1 ` rows, err := tx.Query(ctx, query, nodeID) if err != nil { return nil, err } defer rows.Close() var monitors []models.Monitor for rows.Next() { var monitor models.Monitor err := rows.Scan( &monitor.ID, &monitor.CollectionID, &monitor.From, &monitor.Name, &monitor.ToIP, &monitor.ToName, &monitor.CreatedAt, &monitor.UpdatedAt, ) if err != nil { return nil, err } monitors = append(monitors, monitor) } return monitors, nil } // GetAllMonitors gets all monitors from the database func GetAllMonitors(ctx context.Context, tx pgx.Tx) ([]models.Monitor, error) { query := ` SELECT id, collection_id, "from", name, to_ip, to_name, created_at, updated_at FROM monitors ORDER BY name ` rows, err := tx.Query(ctx, query) if err != nil { return nil, err } defer rows.Close() var monitors []models.Monitor for rows.Next() { var monitor models.Monitor err := rows.Scan( &monitor.ID, &monitor.CollectionID, &monitor.From, &monitor.Name, &monitor.ToIP, &monitor.ToName, &monitor.CreatedAt, &monitor.UpdatedAt, ) if err != nil { return nil, err } monitors = append(monitors, monitor) } return monitors, nil } // GetMonitorsByCollectionID gets monitors that belong to the specified collection func GetMonitorsByCollectionID(ctx context.Context, tx pgx.Tx, collectionID string) ([]models.Monitor, error) { query := ` SELECT id, collection_id, "from", name, to_ip, to_name, created_at, updated_at FROM monitors WHERE collection_id = $1 ` rows, err := tx.Query(ctx, query, collectionID) if err != nil { return nil, err } defer rows.Close() var monitors []models.Monitor for rows.Next() { var monitor models.Monitor err := rows.Scan( &monitor.ID, &monitor.CollectionID, &monitor.From, &monitor.Name, &monitor.ToIP, &monitor.ToName, &monitor.CreatedAt, &monitor.UpdatedAt, ) if err != nil { return nil, err } monitors = append(monitors, monitor) } return monitors, nil } // CreateMonitor creates a new monitor in the database func CreateMonitor(ctx context.Context, tx pgx.Tx, monitor models.Monitor) error { query := ` INSERT INTO monitors (id, collection_id, "from", name, to_ip, to_name, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ` _, err := tx.Exec(ctx, query, monitor.ID, monitor.CollectionID, monitor.From, monitor.Name, monitor.ToIP, monitor.ToName, monitor.CreatedAt, monitor.UpdatedAt) return err } // GetMonitorByID gets a monitor by its ID from the database func GetMonitorByID(ctx context.Context, tx pgx.Tx, monitorID string) (*models.Monitor, error) { query := ` SELECT id, collection_id, "from", name, to_ip, to_name, created_at, updated_at FROM monitors WHERE id = $1 ` var monitor models.Monitor err := tx.QueryRow(ctx, query, monitorID).Scan( &monitor.ID, &monitor.CollectionID, &monitor.From, &monitor.Name, &monitor.ToIP, &monitor.ToName, &monitor.CreatedAt, &monitor.UpdatedAt, ) if err != nil { if err == pgx.ErrNoRows { return nil, nil // Monitor not found } return nil, err } return &monitor, nil } // UpdateMonitor updates an existing monitor in the database func UpdateMonitor(ctx context.Context, tx pgx.Tx, monitor models.Monitor) error { query := ` UPDATE monitors SET collection_id = $2, name = $3, to_ip = $4, to_name = $5, updated_at = $6 WHERE id = $1 ` _, err := tx.Exec(ctx, query, monitor.ID, monitor.CollectionID, monitor.Name, monitor.ToIP, monitor.ToName, monitor.UpdatedAt) return err }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/repository/node.go
Go
package repository import ( "context" "github.com/jackc/pgx/v5" "github.com/yorukot/starker/internal/models" ) // GetNodeByIP gets a node by IP address func GetNodeByIP(ctx context.Context, tx pgx.Tx, ip string) (*models.Node, error) { query := ` SELECT id, ip, name, token, created_at, updated_at FROM nodes WHERE ip = $1 ` var node models.Node err := tx.QueryRow(ctx, query, ip).Scan( &node.ID, &node.IP, &node.Name, &node.Token, &node.CreatedAt, &node.UpdatedAt, ) if err != nil { if err == pgx.ErrNoRows { return nil, nil } return nil, err } return &node, nil } // GetNodes gets all nodes func GetNodes(ctx context.Context, tx pgx.Tx) ([]models.Node, error) { query := ` SELECT id, ip, name, token, created_at, updated_at FROM nodes ` rows, err := tx.Query(ctx, query) if err != nil { return nil, err } defer rows.Close() var nodes []models.Node for rows.Next() { var node models.Node err := rows.Scan(&node.ID, &node.IP, &node.Name, &node.Token, &node.CreatedAt, &node.UpdatedAt) if err != nil { return nil, err } nodes = append(nodes, node) } return nodes, nil } // GetNodeByID gets a node by ID func GetNodeByID(ctx context.Context, tx pgx.Tx, id string) (*models.Node, error) { query := ` SELECT id, ip, name, token, created_at, updated_at FROM nodes WHERE id = $1 ` var node models.Node err := tx.QueryRow(ctx, query, id).Scan( &node.ID, &node.IP, &node.Name, &node.Token, &node.CreatedAt, &node.UpdatedAt, ) if err != nil { if err == pgx.ErrNoRows { return nil, nil } return nil, err } return &node, nil } // CreateNode creates a new node in the database func CreateNode(ctx context.Context, tx pgx.Tx, node models.Node) error { query := ` INSERT INTO nodes (id, ip, name, token, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6) ` _, err := tx.Exec(ctx, query, node.ID, node.IP, node.Name, node.Token, node.CreatedAt, node.UpdatedAt) return err } // UpdateNode updates a node in the database func UpdateNode(ctx context.Context, tx pgx.Tx, node models.Node) error { query := ` UPDATE nodes SET name = $2, updated_at = $3 WHERE id = $1 ` _, err := tx.Exec(ctx, query, node.ID, node.Name, node.UpdatedAt) return err } // DeleteNode deletes a node from the database func DeleteNode(ctx context.Context, tx pgx.Tx, id string) error { query := `DELETE FROM nodes WHERE id = $1` _, err := tx.Exec(ctx, query, id) return err }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/repository/ping.go
Go
package repository import ( "context" "github.com/jackc/pgx/v5" "github.com/yorukot/starker/internal/models" ) // CreatePing creates a new ping record in the database func CreatePing(ctx context.Context, tx pgx.Tx, ping *models.Ping) error { query := ` INSERT INTO pings (ping_id, node_id, time, latency_ms, packet_loss) VALUES ($1, $2, $3, $4, $5) ` _, err := tx.Exec(ctx, query, ping.PingID, ping.NodeID, ping.Time, ping.LatencyMs, ping.PacketLoss) return err }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/repository/transaction.go
Go
package repository import ( "context" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "go.uber.org/zap" ) // StartTransaction return a tx func StartTransaction(db *pgxpool.Pool, ctx context.Context) (pgx.Tx, error) { tx, err := db.Begin(ctx) if err != nil { return nil, err } return tx, nil } // DeferRollback rollback the transaction func DeferRollback(tx pgx.Tx, ctx context.Context) { if err := tx.Rollback(ctx); err != nil { zap.L().Error("Failed to rollback transaction", zap.Error(err)) } } // TODO: Return the err and it should handle the error // CommitTransaction commit the transaction func CommitTransaction(tx pgx.Tx, ctx context.Context) { if err := tx.Commit(ctx); err != nil { zap.L().Error("Failed to commit transaction", zap.Error(err)) } }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/router/auth.go
Go
package router import ( "github.com/go-chi/chi/v5" "github.com/yorukot/starker/internal/handler" "github.com/yorukot/starker/internal/handler/auth" ) // AuthRouter sets up the authentication routes func AuthRouter(r chi.Router, app *handler.App) { authHandler := auth.AuthHandler{ DB: app.DB, } r.Route("/auth", func(r chi.Router) { r.Post("/login", authHandler.Login) }) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/router/collection.go
Go
package router import ( "github.com/go-chi/chi/v5" "github.com/yorukot/starker/internal/handler" "github.com/yorukot/starker/internal/handler/collection" "github.com/yorukot/starker/internal/middleware" ) func CollectionRouter(r chi.Router, app *handler.App) { collectionHandler := collection.CollectionHandler{ DB: app.DB, } r.Route("/collections", func(r chi.Router) { r.Get("/", collectionHandler.GetCollections) r.Group(func(r chi.Router) { r.Use(middleware.AuthRequiredMiddleware) r.Post("/", collectionHandler.CreateCollection) r.Patch("/{collectionID}", collectionHandler.UpdateCollection) r.Delete("/{collectionID}", collectionHandler.DeleteCollection) }) }) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/router/monitor.go
Go
package router import ( "github.com/go-chi/chi/v5" "github.com/yorukot/starker/internal/handler" "github.com/yorukot/starker/internal/handler/monitor" "github.com/yorukot/starker/internal/middleware" ) // MonitorRouter sets up the monitor routes func MonitorRouter(r chi.Router, app *handler.App) { monitorHandler := monitor.MonitorHandler{ DB: app.DB, } r.Route("/monitors", func(r chi.Router) { r.Post("/{monitorID}/ping", monitorHandler.PingMonitor) r.Get("/{monitorID}", monitorHandler.GetMonitor) r.Group(func(r chi.Router) { r.Use(middleware.AuthRequiredMiddleware) r.Post("/", monitorHandler.CreateMonitor) r.Patch("/{monitorID}", monitorHandler.UpdateMonitor) r.Delete("/{monitorID}", monitorHandler.DeleteMonitor) }) }) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/router/node.go
Go
package router import ( "github.com/go-chi/chi/v5" "github.com/yorukot/starker/internal/handler" "github.com/yorukot/starker/internal/handler/node" "github.com/yorukot/starker/internal/middleware" ) // NodeRouter sets up the node routes func NodeRouter(r chi.Router, app *handler.App) { nodeHandler := node.NodeHandler{ DB: app.DB, } r.Route("/nodes", func(r chi.Router) { r.Get("/", nodeHandler.GetNodes) r.Route("/monitors/{nodeID}", func(r chi.Router) { MonitorRouter(r, app) }) r.Group(func(r chi.Router) { r.Use(middleware.AuthRequiredMiddleware) r.Post("/", nodeHandler.CreateNode) r.Patch("/{nodeID}", nodeHandler.UpdateNode) r.Delete("/{nodeID}", nodeHandler.DeleteNode) }) }) }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/service/authsvc/auth.go
Go
package authsvc import ( "context" "net/http" "time" "github.com/go-playground/validator/v10" "github.com/yorukot/starker/internal/config" "github.com/yorukot/starker/internal/models" "github.com/yorukot/starker/pkg/encrypt" ) // LoginRequest is the request body for the login endpoint type LoginRequest struct { Email string `json:"email" validate:"required,email,max=255"` Password string `json:"password" validate:"required,min=8,max=255"` } // LoginValidate validate the login request func LoginValidate(loginRequest LoginRequest) error { return validator.New().Struct(loginRequest) } func GenerateAccessToken(ctx context.Context, email string) (string, error) { JWTSecret := encrypt.JWTSecret{ Secret: config.Env().JWTSecretKey, } accessToken, err := JWTSecret.GenerateAccessToken(config.Env().AppName, email, time.Now().Add(time.Duration(config.Env().AccessTokenExpiresAt)*time.Second)) if err != nil { return "", err } return accessToken, nil } func GenerateAccessTokenCookie(accessToken string) (http.Cookie, error) { accessTokenCookie := http.Cookie{ Name: models.CookieNameAccessToken, Value: accessToken, Expires: time.Now().Add(time.Duration(config.Env().AccessTokenExpiresAt) * time.Second), HttpOnly: true, Secure: true, } return accessTokenCookie, nil }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/service/collectionsvc/collection.go
Go
package collectionsvc import ( "time" "github.com/go-playground/validator/v10" "github.com/segmentio/ksuid" "github.com/yorukot/starker/internal/models" ) // CreateCollectionRequest is the request body for the create collection endpoint type CreateCollectionRequest struct { Name string `json:"name" validate:"required,max=255"` ParentCollectionID *string `json:"parent_collection_id,omitempty"` } // CreateCollectionValidate validates the create collection request func CreateCollectionValidate(request CreateCollectionRequest) error { return validator.New().Struct(request) } // GenerateCollection generates a collection from the create request func GenerateCollection(request CreateCollectionRequest) models.Collection { return models.Collection{ ID: ksuid.New().String(), Name: request.Name, ParentCollectionID: request.ParentCollectionID, CreatedAt: time.Now(), UpdatedAt: time.Now(), } } // UpdateCollectionRequest is the request body for the update collection endpoint type UpdateCollectionRequest struct { Name *string `json:"name,omitempty" validate:"omitempty,max=255"` ParentCollectionID *string `json:"parent_collection_id,omitempty"` } // UpdateCollectionValidate validates the update collection request func UpdateCollectionValidate(request UpdateCollectionRequest) error { return validator.New().Struct(request) } // CollectionWithDetails represents a collection with its children and monitors type CollectionWithDetails struct { models.Collection Children []CollectionWithDetails `json:"children,omitempty"` Monitors []models.Monitor `json:"monitors,omitempty"` } // BuildHierarchicalCollections builds a hierarchical structure of collections with their monitors func BuildHierarchicalCollections(collections []models.Collection, monitors []models.Monitor) []CollectionWithDetails { // Create maps for efficient lookups collectionMap := make(map[string]*CollectionWithDetails) monitorsByCollection := make(map[string][]models.Monitor) // Group monitors by collection ID for _, monitor := range monitors { monitorsByCollection[monitor.CollectionID] = append(monitorsByCollection[monitor.CollectionID], monitor) } // Create collection details map for _, collection := range collections { collectionMap[collection.ID] = &CollectionWithDetails{ Collection: collection, Children: []CollectionWithDetails{}, Monitors: monitorsByCollection[collection.ID], } if collectionMap[collection.ID].Monitors == nil { collectionMap[collection.ID].Monitors = []models.Monitor{} } } // Build hierarchical structure var rootCollections []CollectionWithDetails for _, collection := range collections { if collection.ParentCollectionID == nil { // Root collection rootCollections = append(rootCollections, *collectionMap[collection.ID]) } else { // Child collection - add to parent's children if parent, exists := collectionMap[*collection.ParentCollectionID]; exists { parent.Children = append(parent.Children, *collectionMap[collection.ID]) } } } return rootCollections }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/service/monitorsvc/monitor.go
Go
package monitorsvc import ( "time" "github.com/go-playground/validator/v10" "github.com/segmentio/ksuid" "github.com/yorukot/starker/internal/models" ) // CreateMonitorRequest is the request body for creating a monitor type CreateMonitorRequest struct { CollectionID string `json:"collection_id" validate:"required"` Name string `json:"name" validate:"required,max=255"` ToIP string `json:"to_ip" validate:"required,ip"` ToName *string `json:"to_name,omitempty" validate:"omitempty,max=255"` } // CreateMonitorValidate validates the create monitor request func CreateMonitorValidate(request CreateMonitorRequest) error { return validator.New().Struct(request) } // GenerateMonitor generates a new monitor from the request func GenerateMonitor(request CreateMonitorRequest, nodeID string) models.Monitor { monitorID := ksuid.New().String() now := time.Now() monitor := models.Monitor{ ID: monitorID, CollectionID: request.CollectionID, From: nodeID, Name: request.Name, ToIP: request.ToIP, ToName: request.ToName, CreatedAt: now, UpdatedAt: now, } return monitor } // UpdateMonitorRequest is the request body for updating a monitor type UpdateMonitorRequest struct { CollectionID *string `json:"collection_id,omitempty" validate:"omitempty"` Name *string `json:"name,omitempty" validate:"omitempty,max=255"` ToIP *string `json:"to_ip,omitempty" validate:"omitempty,ip"` ToName *string `json:"to_name,omitempty" validate:"omitempty,max=255"` } // UpdateMonitorValidate validates the update monitor request func UpdateMonitorValidate(request UpdateMonitorRequest) error { return validator.New().Struct(request) } // ApplyMonitorUpdates applies updates to an existing monitor func ApplyMonitorUpdates(existingMonitor models.Monitor, updateRequest UpdateMonitorRequest) models.Monitor { updatedMonitor := existingMonitor updatedMonitor.UpdatedAt = time.Now() if updateRequest.CollectionID != nil { updatedMonitor.CollectionID = *updateRequest.CollectionID } if updateRequest.Name != nil { updatedMonitor.Name = *updateRequest.Name } if updateRequest.ToIP != nil { updatedMonitor.ToIP = *updateRequest.ToIP } if updateRequest.ToName != nil { updatedMonitor.ToName = updateRequest.ToName } return updatedMonitor } // +----------------------------------------------+ // | Ping Service Functions | // +----------------------------------------------+ // PingRequest is the request body for executing a ping type PingRequest struct { Timestamp int64 `json:"timestamp" validate:"required"` // Unix timestamp when the ping was performed by the node LatencyMs *float32 `json:"latency_ms,omitempty" validate:"omitempty,min=0"` // Ping latency in milliseconds (nil if packet loss) PacketLoss bool `json:"packet_loss"` // Whether packet loss occurred } // ValidatePingRequest validates the ping request func ValidatePingRequest(request PingRequest) error { return validator.New().Struct(request) } // ValidateMonitorToken validates that the provided Bearer token matches the node's authentication token func ValidateMonitorToken(node *models.Node, bearerToken string) bool { return node.Token == bearerToken } // GeneratePing creates a new ping record from the monitor and ping request func GeneratePing(monitor *models.Monitor, request PingRequest) *models.Ping { pingID := ksuid.New().String() // Use the timestamp from the node machine pingTime := time.Unix(request.Timestamp, 0) ping := &models.Ping{ PingID: pingID, NodeID: monitor.From, Time: pingTime, PacketLoss: request.PacketLoss, } // Only set latency if there's no packet loss if !request.PacketLoss && request.LatencyMs != nil { ping.LatencyMs = request.LatencyMs } return ping }
yorukot/Houng
1
Go
yorukot
Yorukot
internal/service/nodesvc/node.go
Go
package nodesvc import ( "fmt" "time" "github.com/go-playground/validator/v10" "github.com/segmentio/ksuid" "github.com/yorukot/starker/internal/models" "github.com/yorukot/starker/pkg/encrypt" ) // CreateNodeRequest is the request body for creating a node type CreateNodeRequest struct { IP string `json:"ip" validate:"required,ip"` Name *string `json:"name,omitempty" validate:"omitempty,max=255"` } // UpdateNodeRequest is the request body for updating a node type UpdateNodeRequest struct { Name *string `json:"name,omitempty" validate:"omitempty,max=255"` } // CreateNodeValidate validates the create node request func CreateNodeValidate(request CreateNodeRequest) error { return validator.New().Struct(request) } // UpdateNodeValidate validates the update node request func UpdateNodeValidate(request UpdateNodeRequest) error { return validator.New().Struct(request) } // GenerateNode generates a new node from the request func GenerateNode(request CreateNodeRequest) (models.Node, error) { nodeID := ksuid.New().String() // Generate a secure token for the node token, err := encrypt.GenerateRandomString(32) if err != nil { return models.Node{}, fmt.Errorf("failed to generate node token: %w", err) } node := models.Node{ ID: nodeID, IP: request.IP, Name: request.Name, Token: token, CreatedAt: time.Now(), UpdatedAt: time.Now(), } return node, nil }
yorukot/Houng
1
Go
yorukot
Yorukot
migrations/1_initialize_schema.up.sql
SQL
CREATE SCHEMA IF NOT EXISTS "public"; CREATE TABLE "public"."nodes" ( "id" character varying(27) NOT NULL, "ip" text NOT NULL, "name" text, "token" text NOT NULL, "updated_at" timestamp NOT NULL, "created_at" timestamp NOT NULL, PRIMARY KEY ("id") ); CREATE TABLE "public"."collections" ( "id" character varying(27) NOT NULL, "name" text NOT NULL, "parent_collection_id" character varying(27), "updated_at" timestamp NOT NULL, "created_at" timestamp NOT NULL, PRIMARY KEY ("id") ); CREATE TABLE "public"."pings" ( "ping_id" character varying(27) NOT NULL, "monitor_id" character varying(27) NOT NULL, "time" timestamp NOT NULL, "latency_ms" real UNIQUE, "packet_loss" boolean NOT NULL, PRIMARY KEY ("ping_id", "monitor_id", "time") ); CREATE TABLE "public"."monitors" ( "id" character varying(27) NOT NULL, "collection_id" character varying(27) NOT NULL, "node_id" character varying(27) NOT NULL, "name" text NOT NULL, "to_ip" text NOT NULL, "to_name" text NOT NULL, "updated_at" timestamp NOT NULL, "created_at" timestamp NOT NULL, PRIMARY KEY ("id") ); -- Foreign key constraints -- Schema: public ALTER TABLE "public"."monitors" ADD CONSTRAINT "fk_monitors_collection_id_collections_id" FOREIGN KEY("collection_id") REFERENCES "public"."collections"("id"); ALTER TABLE "public"."monitors" ADD CONSTRAINT "fk_monitors_node_id_nodes_id" FOREIGN KEY("node_id") REFERENCES "public"."nodes"("id"); ALTER TABLE "public"."pings" ADD CONSTRAINT "fk_pings_monitor_id_monitors_id" FOREIGN KEY("monitor_id") REFERENCES "public"."monitors"("id");
yorukot/Houng
1
Go
yorukot
Yorukot
pkg/encrypt/argon.go
Go
package encrypt import ( "crypto/rand" "crypto/subtle" "encoding/base64" "fmt" "strings" "golang.org/x/crypto/argon2" ) // params is the parameters for the Argon2id hash type params struct { memory uint32 iterations uint32 parallelism uint8 saltLength uint32 keyLength uint32 } // CreateArgon2idHash generate a Argon2id hash for the password func CreateArgon2idHash(password string) (string, error) { p := &params{ memory: 128 * 1024, iterations: 15, parallelism: 4, saltLength: 16, keyLength: 32, } salt := make([]byte, p.saltLength) if _, err := rand.Read(salt); err != nil { return "", fmt.Errorf("failed to generate salt: %w", err) } hash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength) b64Salt := base64.RawStdEncoding.EncodeToString(salt) b64Hash := base64.RawStdEncoding.EncodeToString(hash) encodedHash := fmt.Sprintf("$argon2id$v=19$t=%d$m=%d$p=%d$%s$%s", p.iterations, p.memory, p.parallelism, b64Salt, b64Hash) return encodedHash, nil } // ComparePasswordAndHash compare the password and the hash func ComparePasswordAndHash(password, encodedHash string) (match bool, err error) { p, salt, hash, err := decodeHash(encodedHash) if err != nil { return false, err } otherHash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength) // Use subtle.ConstantTimeCompare to avoid timing attacks if subtle.ConstantTimeCompare(hash, otherHash) == 1 { return true, nil } return false, nil } // decodeHash decode the hash func decodeHash(encodedHash string) (p *params, salt, hash []byte, err error) { vals := strings.Split(encodedHash, "$") if len(vals) != 8 { return nil, nil, nil, fmt.Errorf("invalid hash") } var version int _, err = fmt.Sscanf(vals[2], "v=%d", &version) if err != nil { return nil, nil, nil, err } if version != argon2.Version { return nil, nil, nil, fmt.Errorf("incompatible version") } p = &params{} _, err = fmt.Sscanf(vals[3], "t=%d", &p.iterations) if err != nil { return nil, nil, nil, err } _, err = fmt.Sscanf(vals[4], "m=%d", &p.memory) if err != nil { return nil, nil, nil, err } _, err = fmt.Sscanf(vals[5], "p=%d", &p.parallelism) if err != nil { return nil, nil, nil, err } salt, err = base64.RawStdEncoding.Strict().DecodeString(vals[6]) if err != nil { return nil, nil, nil, err } p.saltLength = uint32(len(salt)) hash, err = base64.RawStdEncoding.Strict().DecodeString(vals[7]) if err != nil { return nil, nil, nil, err } p.keyLength = uint32(len(hash)) return p, salt, hash, nil }
yorukot/Houng
1
Go
yorukot
Yorukot
pkg/encrypt/gnerator.go
Go
package encrypt import ( "crypto/rand" "encoding/base64" "fmt" "math/big" "github.com/segmentio/ksuid" ) // GenerateSecureRefreshToken generate a secure refresh token func GenerateSecureRefreshToken() (string, error) { bytes := make([]byte, 256) // 256-bit _, err := rand.Read(bytes) if err != nil { return "", fmt.Errorf("failed to generate token: %w", err) } return ksuid.New().String() + "_" + base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(bytes), nil } // GenerateRandomString generate a random string func GenerateRandomString(length int) (string, error) { const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" result := make([]byte, length) for i := 0; i < length; i++ { num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset)))) if err != nil { return "", err } result[i] = charset[num.Int64()] } return string(result), nil }
yorukot/Houng
1
Go
yorukot
Yorukot
pkg/encrypt/jwt_token.go
Go
package encrypt import ( "time" "github.com/golang-jwt/jwt/v5" ) // JWTSecret is the secret for the JWT // We doing this because this make the function more testable type JWTSecret struct { Secret string } // AccessTokenClaims is the claims for the access token type AccessTokenClaims struct { Issuer string `json:"iss"` Subject string `json:"sub"` ExpiresAt int64 `json:"exp"` IssuedAt int64 `json:"iat"` } // GenerateAccessToken generate an access token func (j *JWTSecret) GenerateAccessToken(issuer string, subject string, expiresAt time.Time) (string, error) { claims := AccessTokenClaims{ Issuer: issuer, Subject: subject, ExpiresAt: expiresAt.Unix(), IssuedAt: time.Now().Unix(), } // TODO: Maybe need a way to covert the struct to map token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "iss": claims.Issuer, "sub": claims.Subject, "exp": claims.ExpiresAt, "iat": claims.IssuedAt, }) return token.SignedString([]byte(j.Secret)) } // ValidateAccessTokenAndGetClaims validate the access token and get the claims func (j *JWTSecret) ValidateAccessTokenAndGetClaims(token string) (bool, AccessTokenClaims, error) { claims := jwt.MapClaims{} _, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) { return []byte(j.Secret), nil }) if err != nil { if err == jwt.ErrTokenInvalidClaims { return false, AccessTokenClaims{}, nil } return false, AccessTokenClaims{}, err } // TODO: Maybe need a more clean way to covert the map to struct issuer, ok := claims["iss"].(string) if !ok { return false, AccessTokenClaims{}, nil } subject, ok := claims["sub"].(string) if !ok { return false, AccessTokenClaims{}, nil } expiresAt, ok := claims["exp"].(float64) if !ok { return false, AccessTokenClaims{}, nil } issuedAt, ok := claims["iat"].(float64) if !ok { return false, AccessTokenClaims{}, nil } accessTokenClaims := AccessTokenClaims{ Issuer: issuer, Subject: subject, ExpiresAt: int64(expiresAt), IssuedAt: int64(issuedAt), } return true, accessTokenClaims, nil }
yorukot/Houng
1
Go
yorukot
Yorukot
pkg/logger/logger.go
Go
package logger import ( "os" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/yorukot/starker/internal/config" ) // InitLogger initialize the logger func InitLogger() { appEnv := os.Getenv("APP_ENV") var logger *zap.Logger if appEnv == string(config.AppEnvDev) { devConfig := zap.NewDevelopmentConfig() devConfig.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder logger, _ = devConfig.Build() } else { logger = zap.Must(zap.NewProduction()) } zap.ReplaceGlobals(logger) zap.L().Info("Logger initialized") defer logger.Sync() }
yorukot/Houng
1
Go
yorukot
Yorukot
pkg/response/response.go
Go
package response import ( "encoding/json" "net/http" ) // ErrorResponse is the response for an error type ErrorResponse struct { Message string `json:"message"` ErrCode string `json:"err_code"` } // SuccessResponse is the response for a success type SuccessResponse struct { Message string `json:"message"` Data any `json:"data"` } // RespondWithError responds with an error message func RespondWithError(w http.ResponseWriter, statusCode int, message, errCode string) { w.WriteHeader(statusCode) json.NewEncoder(w).Encode(ErrorResponse{ Message: message, ErrCode: errCode, }) } // RespondWithJSON responds with a JSON object func RespondWithJSON(w http.ResponseWriter, statusCode int, message string, data interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(statusCode) json.NewEncoder(w).Encode(SuccessResponse{ Message: message, Data: data, }) } // RespondWithData responds with a JSON object func RespondWithData(w http.ResponseWriter, data interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(data) }
yorukot/Houng
1
Go
yorukot
Yorukot
index.js
JavaScript
const app = require('express')(); const path = require('path'); const fs = require('fs'); const kill = require('tree-kill'); const proccess = require('child_process'); app.get('/', function(req, res) { var curl = req.headers['user-agent'].split("/"); let powerPoop = true; if (curl[1].split(")").length == 2) if (curl[1].split(")")[1] == " WindowsPowerShell") powerPoop = false; if (curl[0] != "curl" && powerPoop) { res.redirect(302, 'https://github.com/Mr-Bossman/ascii-live.git'); } else if (!powerPoop) { res.write("\r\nPlease use 'curl.exe -sN' instead...\r\n"); res.end(); } else { ff = proccess.spawn('./display', ['rick.txt', '5']); res.write(" if which aplay >/dev/null; then\n\ if which curl >/dev/null; then\n\ (curl -s https://keroserene.net/lol/roll.s16 | aplay &> /dev/null)&\n\ elif which wget >/dev/null; then\n\ (wget -q -O - https://keroserene.net/lol/roll.s16 | aplay &> /dev/null)&\n\ fi\n\ elif which paplay >/dev/null; then\n\ if which curl >/dev/null; then\n\ (curl -s https://keroserene.net/lol/roll.s16 | paplay &> /dev/null)&\n\ elif which wget >/dev/null; then\n\ (wget -q -O - https://keroserene.net/lol/roll.s16 | paplay &> /dev/null)&\n\ fi\n\ elif which afplay >/dev/null; then\n\ if which curl >/dev/null; then\n\ (curl -s https://keroserene.net/lol/roll.s16 > /tmp/roll.wav 2>/dev/null; afplay /tmp/roll.wav &> /dev/null)&\n\ elif which wget >/dev/null; then\n\ (wget -q -O - https://keroserene.net/lol/roll.s16 > /tmp/roll.wav 2>/dev/null; afplay /tmp/roll.wav &> /dev/null)&\n\ fi\n\ elif which play >/dev/null; then\n\ if which curl >/dev/null; then\n\ (curl -s https://keroserene.net/lol/roll.gsm > /tmp/roll.wav 2>/dev/null; play /tmp/roll.wav &> /dev/null)&\n\ elif which wget >/dev/null; then\n\ (wget -q -O - https://keroserene.net/lol/roll.gsm > /tmp/roll.wav 2>/dev/null; play /tmp/roll.wav &> /dev/null)&\n\ fi\n\ fi\n\ cat - \n"); res.write("curl -s https://www.python.org/ftp/python/3.9.6/python-3.9.6-embed-amd64.zip -o %temp%/py.zip\r\npowershell -Command \"Expand-Archive -Force %temp%/py.zip %temp%/python_tmp\"\r\ncurl -s https://rick.jachan.dev/win.py > %temp%/win.py\r\n%temp%/python_tmp/python.exe %temp%/win.py\r\n"); const banner = "Hey did you know you can add sound by `curl.exe -sN http://rick.jachan.dev | cmd.exe` or `curl -sN http://rick.jachan.dev | bash`." const end = "\033[2J\u001b[26H" + banner + "\033[0H"; ff.stdout.on("data", function(data) { res.write(data.toString().replace("\033[2J\033[0H",end).replace("\033[0m","\033[0m\n\n" + "\r".repeat(4096))); }); res.on('close', function() { if (!ff.killed) kill(ff.pid); }); } }); app.get('/win.py', function(req, res) { res.write(fs.readFileSync(path.join(__dirname, "./win.py")).toString().replace(/\n/g, '\r\n')); res.end(); }); app.listen(80);
yorukot/RickASCII
0
JavaScript
yorukot
Yorukot
win.py
Python
import sys import os import signal import subprocess def signal_handler(sig, frame): os.kill(id.pid, signal.SIGINT) os.system("cls") sys.exit(0) signal.signal(signal.SIGINT, signal_handler) id = subprocess.Popen(["powershell","-Command","&{$PlayWav=New-Object System.Media.SoundPlayer('https://keroserene.net/lol/roll.s16'); $PlayWav.LoadAsync(); $PlayWav.playsync()}"]) os.system("") while(True): print(sys.stdin.read(1),end="")
yorukot/RickASCII
0
JavaScript
yorukot
Yorukot
backend/cmd/main.go
Go
package main import ( "net/http" "github.com/go-chi/chi/v5" chiMiddleware "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" _ "github.com/joho/godotenv/autoload" httpSwagger "github.com/swaggo/http-swagger" "go.uber.org/zap" "github.com/yorukot/blind-party/internal/config" "github.com/yorukot/blind-party/internal/middleware" "github.com/yorukot/blind-party/internal/router" "github.com/yorukot/blind-party/pkg/logger" "github.com/yorukot/blind-party/pkg/response" ) // @version 1.0 // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email support@swagger.io // @license.name MIT // @license.url https://opensource.org/licenses/MIT func main() { logger.InitLogger() _, err := config.InitConfig() if err != nil { zap.L().Fatal("Error initializing config", zap.Error(err)) return } r := chi.NewRouter() r.Use(cors.Handler(cors.Options{ AllowedOrigins: []string{"http://localhost:5173", "https://localhost:5173", "http://100.64.0.100:5173", "https://yorukot.github.io", "https://eclectic-sawine-7dd6a4.netlify.app", "https://bgayp.netlify.app", "https://frank-kam.itch.io"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token", "X-Requested-With", "Upgrade", "Connection", "Sec-WebSocket-Key", "Sec-WebSocket-Version", "Sec-WebSocket-Protocol"}, ExposedHeaders: []string{"Link"}, AllowCredentials: true, MaxAge: 300, })) r.Use(middleware.ZapLoggerMiddleware(zap.L())) r.Use(chiMiddleware.StripSlashes) setupRouter(r) zap.L().Info("Starting server on http://localhost:" + config.Env().Port) zap.L().Info("Environment: " + string(config.Env().AppEnv)) err = http.ListenAndServe(":"+config.Env().Port, r) if err != nil { zap.L().Fatal("Failed to start server", zap.Error(err)) } } // setupRouter sets up the router func setupRouter(r chi.Router) { r.Route("/api", func(r chi.Router) { router.GameRouter(r) }) if config.Env().AppEnv == config.AppEnvDev { r.Get("/swagger/*", httpSwagger.WrapHandler) } r.Get("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) }) // Not found handler r.NotFound(func(w http.ResponseWriter, r *http.Request) { response.RespondWithError(w, http.StatusNotFound, "Not Found", "NOT_FOUND") }) r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) { response.RespondWithError(w, http.StatusMethodNotAllowed, "Method Not Allowed", "METHOD_NOT_ALLOWED") }) zap.L().Info("Router setup complete") }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/config/env.go
Go
package config import ( "sync" "github.com/caarlos0/env/v10" "go.uber.org/zap" ) type AppEnv string const ( AppEnvDev AppEnv = "dev" AppEnvProd AppEnv = "prod" ) // EnvConfig holds all environment variables for the application type EnvConfig struct { Port string `env:"PORT" envDefault:"8080"` Debug bool `env:"DEBUG" envDefault:"false"` AppEnv AppEnv `env:"APP_ENV" envDefault:"prod"` AppName string `env:"APP_NAME" envDefault:"stargo"` MinPlayers int `env:"MIN_PLAYERS" envDefault:"4"` MaxPlayers int `env:"MAX_PLAYERS" envDefault:"16"` } var ( appConfig *EnvConfig once sync.Once ) // loadConfig loads and validates all environment variables func loadConfig() (*EnvConfig, error) { cfg := &EnvConfig{} if err := env.Parse(cfg); err != nil { return nil, err } return cfg, nil } // InitConfig initializes the config only once func InitConfig() (*EnvConfig, error) { var err error once.Do(func() { appConfig, err = loadConfig() zap.L().Info("Config loaded") }) return appConfig, err } // Env returns the config. Panics if not initialized. func Env() *EnvConfig { if appConfig == nil { zap.L().Panic("config not initialized — call InitConfig() first") } return appConfig }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/game_life_cyle.go
Go
package game import ( "log" "time" "github.com/yorukot/blind-party/internal/schema" ) func (h *GameHandler) GameLifeCycle(game *schema.Game) { defer func() { if game.Ticker != nil { game.Ticker.Stop() } log.Printf("Game %s lifecycle ended", game.ID) }() log.Printf("Starting game lifecycle for game %s", game.ID) // Main game loop for { log.Printf("Game %s main loop tick", game.ID) select { case <-game.StopTicker: log.Printf("Game %s received stop signal", game.ID) return case client := <-game.Register: h.handleClientRegister(game, client) case client := <-game.Unregister: h.handleClientUnregister(game, client) case message := <-game.Broadcast: h.broadcastToClients(game, message) default: // Handle game state progression h.processGameState(game) time.Sleep(60 * time.Millisecond) } } } // handleClientRegister processes new WebSocket client connections func (h *GameHandler) handleClientRegister(game *schema.Game, client *schema.WebSocketClient) { game.Mu.Lock() defer game.Mu.Unlock() game.Clients[client.Username] = client // Determine joined round number joinedRound := 0 if game.CurrentRound != nil { joinedRound = game.CurrentRound.Number } // Create a new player object for this client player := &schema.Player{ Name: client.Username, Position: schema.Position{X: 10.0, Y: 10.0}, // Default center position IsSpectator: false, IsEliminated: false, JoinedRound: joinedRound, LastUpdate: time.Now(), LastValidPosition: schema.Position{X: 10.0, Y: 10.0}, LastMoveTime: time.Now(), MovementSpeed: game.Config.BaseMovementSpeed, Stats: schema.PlayerStats{ RoundsSurvived: 0, FinalPosition: 0, }, } // Add player to the game game.Players[client.Username] = player game.PlayerCount++ game.AliveCount++ log.Printf("Client %s registered to game %s (Player count: %d)", client.Username, game.ID, game.PlayerCount) // Send current game state to newly connected client gameState := h.createGameStateMessage(game) game.Broadcast <- gameState } // handleClientUnregister processes WebSocket client disconnections func (h *GameHandler) handleClientUnregister(game *schema.Game, client *schema.WebSocketClient) { game.Mu.Lock() defer game.Mu.Unlock() if _, exists := game.Clients[client.Username]; exists { // Remove client delete(game.Clients, client.Username) close(client.Send) // Remove player if it exists if player, playerExists := game.Players[client.Username]; playerExists { delete(game.Players, client.Username) game.PlayerCount-- // Only decrement alive count if player wasn't eliminated if !player.IsEliminated { game.AliveCount-- } } log.Printf("Client %s unregistered from game %s (Player count: %d)", client.Username, game.ID, game.PlayerCount) // Check if no players remain and stop the game if game.PlayerCount == 0 { log.Printf("No players remaining, stopping game %s", game.ID) go func() { game.StopTicker <- true }() return // Don't broadcast since game is stopping } // Broadcast updated game state to remaining clients via the broadcast channel updatedGameState := h.createGameStateMessage(game) game.Broadcast <- updatedGameState } } // broadcastToClients sends a message to all connected clients func (h *GameHandler) broadcastToClients(game *schema.Game, message interface{}) { game.Mu.RLock() defer game.Mu.RUnlock() for userID, client := range game.Clients { select { case client.Send <- message: default: // Client's send channel is full, close it close(client.Send) delete(game.Clients, userID) log.Printf("Removed unresponsive client %s from game %s", userID, game.ID) } } } // createGameStateMessage creates a complete game state message for clients func (h *GameHandler) createGameStateMessage(game *schema.Game) map[string]interface{} { // Update players list for JSON serialization game.PlayersList = make([]*schema.Player, 0, len(game.Players)) for _, player := range game.Players { game.PlayersList = append(game.PlayersList, player) } // Convert map data to array format for JSON game.MapArray = make([][]int, 20) for i := range game.MapArray { game.MapArray[i] = make([]int, 20) for j := range game.MapArray[i] { game.MapArray[i][j] = int(game.Map[i][j]) } } // Create a safe game state without channels return map[string]interface{}{ "event": "game_update", "data": map[string]interface{}{ "game_id": game.ID, "created_at": game.CreatedAt, "started_at": game.StartedAt, "ended_at": game.EndedAt, "phase": game.Phase, "current_round": game.CurrentRound, "map": game.MapArray, "round": game.CurrentRound, "round_number": game.RoundNumber, "players": game.PlayersList, "player_count": game.PlayerCount, "countdown_seconds": game.Countdown, "alive_count": game.AliveCount, "config": game.Config, }, } } // +=====================================================+ // | GAME TICK LOGIC | // +=====================================================+ // processGameState handles the main game logic progression func (h *GameHandler) processGameState(game *schema.Game) { game.Mu.Lock() defer game.Mu.Unlock() switch game.Phase { case schema.PreGame: h.handlePreGamePhase(game) case schema.InGame: h.handleInGamePhase(game) log.Print("Processed InGame phase") case schema.Settlement: // h.handleSettlementPhase(game) } game.LastTick = time.Now() log.Printf("Game %s state processed (Phase: %s)", game.ID, game.Phase) game.Broadcast <- h.createGameStateMessage(game) }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/get_game_state.go
Go
package game import ( "net/http" "github.com/go-chi/chi/v5" "github.com/yorukot/blind-party/pkg/response" ) // GetGameState returns the current state of a specific game func (h *GameHandler) GetGameState(w http.ResponseWriter, r *http.Request) { // Extract gameID from URL parameters gameID := chi.URLParam(r, "gameID") if gameID == "" { response.RespondWithError(w, http.StatusBadRequest, "Game ID is required", "MISSING_GAME_ID") return } // Look up the game in GameData map game, exists := h.GameData[gameID] if !exists { response.RespondWithError(w, http.StatusNotFound, "Game not found", "GAME_NOT_FOUND") return } // Return the game state response.RespondWithData(w, game) }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/handler.go
Go
package game import "github.com/yorukot/blind-party/internal/schema" type GameHandler struct { GameData map[string]*schema.Game }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/in_game.go
Go
package game import ( "log" "math/rand" "time" "github.com/yorukot/blind-party/internal/schema" ) func getRandomColor() schema.WoolColor { colors := []schema.WoolColor{ schema.White, // 0 schema.Orange, // 1 schema.Magenta, // 2 schema.LightBlue, // 3 schema.Yellow, // 4 schema.Lime, // 5 schema.Pink, // 6 schema.Gray, // 7 schema.LightGray, // 8 schema.Cyan, // 9 schema.Purple, // 10 schema.Blue, // 11 schema.Brown, // 12 schema.Green, // 13 schema.Red, // 14 schema.Black, // 15 } return colors[rand.Intn(len(colors))] } // generateRandomMap creates a new random map with all 16 colors func (h *GameHandler) generateRandomMap(game *schema.Game) { for y := 0; y < game.Config.MapHeight; y++ { for x := 0; x < game.Config.MapWidth; x++ { game.Map[y][x] = getRandomColor() } } log.Printf("Generated new random map for game %s", game.ID) } // removeNonTargetColors removes all blocks except the target color, turning them to Air func (h *GameHandler) removeNonTargetColors(game *schema.Game, targetColor schema.WoolColor) { for y := 0; y < game.Config.MapHeight; y++ { for x := 0; x < game.Config.MapWidth; x++ { if game.Map[y][x] != targetColor { game.Map[y][x] = schema.Air } } } log.Printf("Removed all non-target colors except %d from game %s", targetColor, game.ID) } // calculateRoundDuration returns the rush duration based on round number func (h *GameHandler) calculateRoundDuration(roundNumber int) float64 { // Progressive timing: starts at 20.0s and decreases to 80% each round // Based on game.md requirement for decreasing countdown each round baseDuration := 20.0 minDuration := 1.2 // Calculate duration as 80% of previous round (exponential decay) duration := baseDuration for i := 1; i < roundNumber; i++ { duration *= 0.8 } if duration < minDuration { duration = minDuration } return duration } func (h *GameHandler) eliminatePlayer(game *schema.Game, player *schema.Player) { if player.IsEliminated { return } player.IsEliminated = true now := time.Now() player.Stats.EliminatedAt = &now player.Stats.RoundsSurvived = game.CurrentRound.Number - 1 // Count alive players for final position aliveCount := 0 for _, p := range game.Players { if !p.IsEliminated { aliveCount++ } } player.Stats.FinalPosition = aliveCount } // startNewRound initializes and starts a new round in the game func (h *GameHandler) startNewRound(game *schema.Game) { game.RoundNumber++ // Step 1: Generate a new map (per game.md requirement) h.generateRandomMap(game) // Step 2: Determine target color (per game.md requirement) targetColor := getRandomColor() // Step 3: Calculate progressive round duration (per game.md step 6) rushDuration := h.calculateRoundDuration(game.RoundNumber) game.CurrentRound = &schema.Round{ Number: game.RoundNumber, Phase: schema.ColorCall, StartTime: time.Now(), EndTime: nil, ColorToShow: targetColor, RushDuration: rushDuration, } // Set countdown to rush duration (per game.md step 3) game.Countdown = &rushDuration log.Printf("Started round %d for game %s with target color %d and duration %.1fs", game.RoundNumber, game.ID, targetColor, rushDuration) // Broadcast new round start game.Broadcast <- map[string]any{ "event": "game_update", "data": map[string]any{ "round_number": game.RoundNumber, "target_color": targetColor, "countdown": rushDuration, "map": h.convertMapToArray(game), }, } } // convertMapToArray converts the map to array format for JSON func (h *GameHandler) convertMapToArray(game *schema.Game) [][]int { mapArray := make([][]int, game.Config.MapHeight) for i := range mapArray { mapArray[i] = make([]int, game.Config.MapWidth) for j := range mapArray[i] { mapArray[i][j] = int(game.Map[i][j]) } } return mapArray } func (h *GameHandler) handleInGamePhase(game *schema.Game) { // Ensure there is a current round if game.CurrentRound == nil { h.startNewRound(game) return } switch game.CurrentRound.Phase { case schema.ColorCall: h.handleColorCallPhase(game) case schema.EliminationCheck: h.handleEliminationCheckPhase(game) } } func (h *GameHandler) handleColorCallPhase(game *schema.Game) { // Update countdown timer (per game.md step 3) if game.Countdown == nil { game.Countdown = &game.CurrentRound.RushDuration } else { *game.Countdown -= time.Since(game.LastTick).Seconds() } // Broadcast countdown update game.Broadcast <- map[string]any{ "event": "game_update", "data": map[string]any{ "countdown_seconds": game.Countdown, "target_color": game.CurrentRound.ColorToShow, }, } // When countdown reaches 0, transition to elimination phase if game.Countdown == nil || *game.Countdown <= 0 { // Step 4: Remove all blocks except target color (per game.md requirement) h.removeNonTargetColors(game, game.CurrentRound.ColorToShow) // Broadcast map change game.Broadcast <- map[string]any{ "event": "game_update", "data": map[string]any{ "map": h.convertMapToArray(game), "blocks_removed": true, }, } game.CurrentRound.Phase = schema.EliminationCheck game.Countdown = nil log.Printf("Round %d countdown finished, removed non-target blocks for game %s", game.CurrentRound.Number, game.ID) } } func (h *GameHandler) handleEliminationCheckPhase(game *schema.Game) { eliminatedPlayers := []string{} // Step 5: Check each non-eliminated player's position (per game.md requirement) for _, player := range game.Players { if player.IsEliminated { continue } // Convert player position to map coordinates // Player positions are 1-based, map is 0-based // Add 0.5 adjustment for proper block center alignment x := int(player.Position.X + 0.5) y := int(player.Position.Y + 0.5) // Bounds checking if x < 0 || x >= game.Config.MapWidth || y < 0 || y >= game.Config.MapHeight { // Player is out of bounds, eliminate them h.eliminatePlayer(game, player) eliminatedPlayers = append(eliminatedPlayers, player.Name) log.Printf("Player %s eliminated (out of bounds) at position (%.1f, %.1f)", player.Name, player.Position.X, player.Position.Y) continue } // Check if player is standing on Air (eliminated) or wrong color blockUnder := game.Map[y][x] blockName := "Unknown" targetName := "Unknown" // Convert block values to readable names for debugging if blockUnder == schema.Air { blockName = "Air" } else if blockUnder >= 0 && blockUnder <= 15 { colorNames := []string{"White", "Orange", "Magenta", "LightBlue", "Yellow", "Lime", "Pink", "Gray", "LightGray", "Cyan", "Purple", "Blue", "Brown", "Green", "Red", "Black"} blockName = colorNames[blockUnder] } if game.CurrentRound.ColorToShow >= 0 && game.CurrentRound.ColorToShow <= 15 { colorNames := []string{"White", "Orange", "Magenta", "LightBlue", "Yellow", "Lime", "Pink", "Gray", "LightGray", "Cyan", "Purple", "Blue", "Brown", "Green", "Red", "Black"} targetName = colorNames[game.CurrentRound.ColorToShow] } log.Printf("Player %s at position (%.2f, %.2f) -> adjusted (%.2f, %.2f) -> map[%d][%d] = %s(%d), target: %s(%d)", player.Name, player.Position.X, player.Position.Y, player.Position.X+0.5, player.Position.Y+0.5, y, x, blockName, blockUnder, targetName, game.CurrentRound.ColorToShow) if blockUnder == schema.Air || blockUnder != game.CurrentRound.ColorToShow { h.eliminatePlayer(game, player) eliminatedPlayers = append(eliminatedPlayers, player.Name) if blockUnder == schema.Air { log.Printf("Player %s eliminated (standing on Air) at position (%.1f, %.1f)", player.Name, player.Position.X, player.Position.Y) } else { log.Printf("Player %s eliminated (wrong block: %s, target: %s) at position (%.1f, %.1f)", player.Name, blockName, targetName, player.Position.X, player.Position.Y) } } else { log.Printf("Player %s survives round %d - standing on correct block %s", player.Name, game.CurrentRound.Number, blockName) } } // Broadcast elimination results if len(eliminatedPlayers) > 0 { game.Broadcast <- map[string]any{ "event": "game_update", "data": map[string]any{ "eliminated_players": eliminatedPlayers, "round_number": game.CurrentRound.Number, "target_color": game.CurrentRound.ColorToShow, }, } } // End the current round now := time.Now() game.CurrentRound.EndTime = &now // Count remaining alive players aliveCount := 0 for _, player := range game.Players { if !player.IsEliminated { aliveCount++ } } game.AliveCount = aliveCount // Check if game should end (per game.md step 7) if aliveCount <= 1 { game.Phase = schema.Settlement game.EndedAt = &now // Find winner if there's exactly one player left var winnerID string for _, player := range game.Players { if !player.IsEliminated { winnerID = player.Name break } } game.Broadcast <- map[string]any{ "event": "game_update", "data": map[string]any{ "winner_id": winnerID, "end_time": now, "total_rounds": game.RoundNumber, "alive_count": aliveCount, }, } log.Printf("Game %s ended after %d rounds with winner: %s", game.ID, game.RoundNumber, winnerID) } else { // Continue to next round (per game.md step 7) log.Printf("Round %d completed for game %s, %d players remaining", game.CurrentRound.Number, game.ID, aliveCount) // Broadcast round end game.Broadcast <- map[string]any{ "event": "game_update", "data": map[string]any{ "round_number": game.CurrentRound.Number, "alive_count": aliveCount, "next_round_in": 2.0, // 2 second break between rounds }, } // Clear current round and start next one after brief delay game.CurrentRound = nil game.Countdown = nil // Add small delay before next round starts (simulating rest period) go func() { time.Sleep(2 * time.Second) h.startNewRound(game) }() } }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/new_game.go
Go
package game import ( "math/rand" "net/http" "strconv" "time" "github.com/yorukot/blind-party/internal/schema" "github.com/yorukot/blind-party/pkg/response" ) func (h *GameHandler) NewGame(w http.ResponseWriter, r *http.Request) { // Generate a new 6-digit game ID var gameID string for { // Generate random number between 100000 and 999999 randomNum := rand.Intn(900000) + 100000 gameID = strconv.Itoa(randomNum) // Check if the game ID already exists if _, exists := h.GameData[gameID]; !exists { break } } // Create a new game instance now := time.Now() game := &schema.Game{ ID: gameID, CreatedAt: now, Phase: schema.PreGame, // Initialize maps and slices Players: make(map[string]*schema.Player), PlayersList: make([]*schema.Player, 0), PlayerCount: 0, AliveCount: 0, // WebSocket management Clients: make(map[string]*schema.WebSocketClient), Broadcast: make(chan interface{}, 256), Register: make(chan *schema.WebSocketClient, 256), Unregister: make(chan *schema.WebSocketClient, 256), // Round CurrentRound: nil, RoundNumber: 0, // Configuration Config: schema.GameConfig{ MapWidth: 20, MapHeight: 20, CountdownSequence: []int{30, 25, 20, 15, 10, 8, 6, 4, 3, 2}, SpectatorOnlyRounds: 2, // Timing Progression (rush phase duration by round ranges) TimingProgression: []schema.TimingRange{ {StartRound: 1, EndRound: 3, Duration: 4.0}, {StartRound: 4, EndRound: 6, Duration: 3.5}, {StartRound: 7, EndRound: 9, Duration: 3.0}, {StartRound: 10, EndRound: 12, Duration: 2.5}, {StartRound: 13, EndRound: 15, Duration: 2.0}, }, // Movement & Anti-cheat BaseMovementSpeed: 4.0, MaxMovementSpeed: 5.0, LagCompensationMs: 50, PositionUpdateHz: 10, TimerUpdateHz: 20, }, // Generate random map data Map: generateRandomMap(), // Synchronization StopTicker: make(chan bool), } // Convert map to array for JSON serialization game.MapArray = mapToArray(game.Map) // Store the game in GameData map h.GameData[gameID] = game // Start the game lifecycle in a separate goroutine go h.GameLifeCycle(game) // Respond with the game ID response.RespondWithData( w, map[string]string{"game_id": gameID}, ) } // generateRandomMap creates a 20x20 map with equal distribution of 16 wool colors func generateRandomMap() schema.MapData { var mapData schema.MapData // Create a list of all possible positions positions := make([]struct{ x, y int }, 0, 400) // 20*20 = 400 total blocks for i := 0; i < 20; i++ { // height (rows) for j := 0; j < 20; j++ { // width (columns) positions = append(positions, struct{ x, y int }{j, i}) } } // Shuffle positions for random distribution rand.Shuffle(len(positions), func(i, j int) { positions[i], positions[j] = positions[j], positions[i] }) // Distribute colors evenly: 16 colors * 25 blocks = 400 total blocks (perfect distribution) blocksPerColor := 25 // 400 / 16 = 25 blocks per color posIndex := 0 for color := 0; color < 16; color++ { // Assign blocks for this color for block := 0; block < blocksPerColor; block++ { pos := positions[posIndex] mapData[pos.y][pos.x] = schema.WoolColor(color) posIndex++ } } return mapData } // mapToArray converts the 2D map array to a format suitable for JSON serialization func mapToArray(mapData schema.MapData) [][]int { result := make([][]int, 20) // height = 20 for i := 0; i < 20; i++ { result[i] = make([]int, 20) // width = 20 for j := 0; j < 20; j++ { result[i][j] = int(mapData[i][j]) } } return result }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/pre_game.go
Go
package game import ( "log" "math/rand" "time" "github.com/yorukot/blind-party/internal/config" "github.com/yorukot/blind-party/internal/schema" ) // handlePreGamePhase manages the pre-game waiting phase func (h *GameHandler) handlePreGamePhase(game *schema.Game) { log.Printf("Game %s is in PreGame phase with %d players", game.ID, game.PlayerCount) // Get player limits from configuration cfg := config.Env() minPlayers := cfg.MinPlayers maxPlayers := cfg.MaxPlayers // Validate player count is within bounds if game.PlayerCount > maxPlayers { log.Printf("Game %s exceeded maximum players (%d), rejecting new connections", game.ID, maxPlayers) return } // Start game if we have minimum players if game.PlayerCount >= minPlayers { log.Printf("Game %s starting with minimum players (%d)", game.ID, game.PlayerCount) h.startGamePreparation(game) } } // startGamePreparation begins the 5-second preparation phase func (h *GameHandler) startGamePreparation(game *schema.Game) { log.Printf("Game %s entering preparation phase with %d players", game.ID, game.PlayerCount) if game.Countdown == nil { countdown := float64(5) game.Countdown = &countdown game.LastTick = time.Now() } else { // Subtract elapsed time since last tick elapsed := time.Since(game.LastTick).Seconds() *game.Countdown -= elapsed game.LastTick = time.Now() } if game.Countdown == nil || *game.Countdown <= 0 { h.startGame(game) return } } // startGame transitions from PreGame to InGame phase func (h *GameHandler) startGame(game *schema.Game) { now := time.Now() game.StartedAt = &now game.Phase = schema.InGame // Assign spawn positions to all players h.assignSpawnPositions(game) // Initialize player statistics and movement tracking h.initializeAllPlayerStats(game) log.Printf("Game %s started with %d players", game.ID, game.PlayerCount) // Broadcast game start with full game state game.Broadcast <- map[string]interface{}{ "event": "game_update", "data": map[string]interface{}{ "phase": game.Phase, "game_id": game.ID, "players": game.PlayersList, "map": game.MapArray, }, } } // assignSpawnPositions assigns random spawn positions to all players on valid colored blocks func (h *GameHandler) assignSpawnPositions(game *schema.Game) { // Collect all valid spawn positions (any colored block, not Air) validPositions := make([]schema.Position, 0) for y := 0; y < game.Config.MapHeight; y++ { for x := 0; x < game.Config.MapWidth; x++ { if game.Map[y][x] != schema.Air { // Not Air block // Use 1-based coordinate system (1-20 range) with 2 decimal precision validPositions = append(validPositions, schema.Position{ X: float64(x+1) + 0.5, // Block coordinates: 1.5, 2.5, ..., 20.5 Y: float64(y+1) + 0.5, }) } } } // Shuffle positions for random assignment rand.Shuffle(len(validPositions), func(i, j int) { validPositions[i], validPositions[j] = validPositions[j], validPositions[i] }) // Assign positions to players positionIndex := 0 for _, player := range game.Players { if positionIndex < len(validPositions) { player.Position = validPositions[positionIndex] player.LastValidPosition = player.Position positionIndex++ log.Printf("Player %s (%s) spawned at position (%.1f, %.1f)", player.Name, player.Name, player.Position.X, player.Position.Y) } } } // initializeAllPlayerStats initializes statistics and movement tracking for all players func (h *GameHandler) initializeAllPlayerStats(game *schema.Game) { now := time.Now() for _, player := range game.Players { // Initialize movement tracking player.LastUpdate = now player.LastMoveTime = now player.MovementSpeed = game.Config.BaseMovementSpeed // Initialize statistics player.Stats = schema.PlayerStats{ RoundsSurvived: 0, TotalDistance: 0, FinalPosition: 0, } log.Printf("Initialized stats for player %s (%s)", player.Name, player.Name) } }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/settlement.go
Go
package game
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/handler/game/websocket.go
Go
package game import ( "fmt" "log" "strconv" "time" "github.com/go-chi/chi/v5" "golang.org/x/net/websocket" "github.com/yorukot/blind-party/internal/schema" ) // ConnectWebSocket handles WebSocket connections for a specific game func (h *GameHandler) ConnectWebSocket(ws *websocket.Conn) { defer ws.Close() // Get gameID from URL path req := ws.Request() gameID := chi.URLParam(req, "gameID") if gameID == "" { log.Println("No gameID provided in WebSocket connection") return } // Get game instance game, exists := h.GameData[gameID] if !exists { log.Printf("Game %s not found", gameID) return } // Extract username from query parameters username := req.URL.Query().Get("username") if username == "" { log.Println("No username provided in WebSocket connection") return } // Make sure the username is unique in the game for _, player := range game.Players { if player.Name == username { log.Printf("Username %s already taken in game %s", username, gameID) return } } // Create WebSocket client client := &schema.WebSocketClient{ Conn: ws, Username: username, Token: "", // No token needed Send: make(chan interface{}, 256), Connected: time.Now(), } // Register client with the game game.Register <- client // Handle client disconnection defer func() { game.Unregister <- client }() // Start goroutine to handle sending messages to client go func() { defer ws.Close() for message := range client.Send { if err := websocket.JSON.Send(ws, message); err != nil { log.Printf("Error sending message to client %s: %v", username, err) return } } }() // Read messages from client (handle player updates) for { var message map[string]interface{} err := websocket.JSON.Receive(ws, &message) if err != nil { log.Printf("WebSocket read error for user %s (username: %s): %v", username, username, err) break } // Handle different message types if msgType, exists := message["event"]; exists { switch msgType { case "player_update": log.Printf("Received player update from user %s", username) h.handlePlayerUpdate(game, username, message) case "ping": // Respond to ping with pong client.Send <- map[string]interface{}{ "event": "pong", } default: log.Printf("Unknown message type from user %s: %s", username, msgType) } } } } // handlePlayerUpdate processes player position updates from WebSocket clients func (h *GameHandler) handlePlayerUpdate(game *schema.Game, username string, message map[string]interface{}) { game.Mu.Lock() defer game.Mu.Unlock() // Find the player player, exists := game.Players[username] if !exists { log.Printf("Player update from unknown user %s", username) return } // Don't update eliminated or spectator players if player.IsEliminated || player.IsSpectator { log.Printf("Skipping position update for user %s: player is %s", username, func() string { if player.IsEliminated { return "eliminated" } return "spectator" }()) return } // Don't allow position updates during elimination phase if game.CurrentRound != nil && game.CurrentRound.Phase == schema.EliminationCheck { log.Printf("Skipping position update for user %s: game is in elimination phase", username) return } // Extract position data data, hasData := message["player"].(map[string]interface{}) if !hasData { log.Printf("Invalid message format from user %s: missing or invalid 'player' field. Message: %+v", username, message) return } log.Printf("Received position data from user %s: %+v", username, data) newPosition := player.Position // Extract new position coordinates if posX, exists := data["pos_x"]; exists { if x, err := parseFloat(posX); err == nil { newPosition.X = x log.Printf("Updated X position for user %s: %.2f", username, x) } else { log.Printf("Invalid X coordinate from user %s: %v (error: %v)", username, posX, err) } } if posY, exists := data["pos_y"]; exists { if y, err := parseFloat(posY); err == nil { newPosition.Y = y log.Printf("Updated Y position for user %s: %.2f", username, y) } else { log.Printf("Invalid Y coordinate from user %s: %v (error: %v)", username, posY, err) } } log.Printf("Handling position update for user %s, x: %.1f, y: %.1f", username, newPosition.X, newPosition.Y) // Update player position (validation moved to game lifecycle) player.Position = newPosition // Update last update time player.LastUpdate = time.Now() game.Players[username] = player } // parseFloat attempts to convert various numeric types to float64 func parseFloat(value interface{}) (float64, error) { switch v := value.(type) { case float64: return v, nil case float32: return float64(v), nil case int: return float64(v), nil case int32: return float64(v), nil case int64: return float64(v), nil case string: return strconv.ParseFloat(v, 64) default: return 0, fmt.Errorf("cannot convert %T to float64", value) } }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/middleware/logger.go
Go
package middleware import ( "net/http" "time" "github.com/fatih/color" "github.com/google/uuid" "go.uber.org/zap" "github.com/yorukot/blind-party/internal/config" ) // ZapLoggerMiddleware is a middleware that logs the incoming request and the response time func ZapLoggerMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestID := uuid.New().String() start := time.Now() next.ServeHTTP(w, r) logger.Info(GenerateDiffrentColorForMethod(r.Method)+" request completed", zap.String("request_id", requestID), zap.String("path", r.URL.Path), zap.String("user_agent", r.UserAgent()), zap.String("remote_addr", r.RemoteAddr), zap.Duration("duration", time.Since(start)), ) }) } } // GenerateDiffrentColorForMethod generate a different color for the method func GenerateDiffrentColorForMethod(method string) string { if config.Env().AppEnv == config.AppEnvDev { switch method { case "GET": return color.GreenString(method) case "POST": return color.BlueString(method) case "PUT": return color.YellowString(method) case "PATCH": return color.MagentaString(method) case "DELETE": return color.RedString(method) case "OPTIONS": return color.CyanString(method) case "HEAD": return color.WhiteString(method) default: return method } } return method }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/router/game.go
Go
package router import ( "github.com/go-chi/chi/v5" "golang.org/x/net/websocket" "github.com/yorukot/blind-party/internal/handler/game" "github.com/yorukot/blind-party/internal/schema" ) // GameRouter sets up the game routes func GameRouter(r chi.Router) { gameHandler := &game.GameHandler{ GameData: make(map[string]*schema.Game), } r.Route("/game", func(r chi.Router) { r.Post("/", gameHandler.NewGame) r.Get("/{gameID}/state", gameHandler.GetGameState) r.Route("/{gameID}", func(r chi.Router) { r.Handle("/ws", websocket.Handler(gameHandler.ConnectWebSocket)) }) }) }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/internal/schema/game.go
Go
package schema import ( "sync" "time" "golang.org/x/net/websocket" ) // WoolColor represents the 16 wool colors in Minecraft type WoolColor int const ( White WoolColor = iota // 0 Orange // 1 Magenta // 2 LightBlue // 3 Yellow // 4 Lime // 5 Pink // 6 Gray // 7 LightGray // 8 Cyan // 9 Purple // 10 Blue // 11 Brown // 12 Green // 13 Red // 14 Black // 15 Air // 16 ) // GamePhase represents the current phase of the game type GamePhase string const ( PreGame GamePhase = "pre-game" InGame GamePhase = "in-game" Settlement GamePhase = "settlement" ) // RoundPhase represents the phase within a round type RoundPhase string const ( ColorCall RoundPhase = "color-call" EliminationCheck RoundPhase = "elimination-check" ) // Position represents x,y coordinates type Position struct { X float64 `json:"pos_x"` Y float64 `json:"pos_y"` } // Player represents a player in the game type Player struct { Name string `json:"name"` Position Position `json:"position"` // For JSON marshaling IsSpectator bool `json:"is_spectator"` IsEliminated bool `json:"is_eliminated"` JoinedRound int `json:"joined_round"` LastUpdate time.Time `json:"-"` // Movement validation LastValidPosition Position `json:"-"` LastMoveTime time.Time `json:"-"` MovementSpeed float64 `json:"-"` // blocks per second // Stats for settlement Stats PlayerStats `json:"-"` } // PlayerStats tracks player performance type PlayerStats struct { RoundsSurvived int `json:"rounds_survived"` TotalDistance float64 `json:"total_distance"` EliminatedAt *time.Time `json:"eliminated_at,omitempty"` FinalPosition int `json:"final_position"` } // Round represents a single round in the game type Round struct { Number int `json:"round_number"` Phase RoundPhase `json:"phase"` StartTime time.Time `json:"start_time"` EndTime *time.Time `json:"end_time,omitempty"` ColorToShow WoolColor `json:"color_to_show"` RushDuration float64 `json:"rush_duration"` // Variable timing by round } // MapData represents the 20x20 game map type MapData [20][20]WoolColor // WebSocketClient represents a connected WebSocket client type WebSocketClient struct { Conn *websocket.Conn Username string Token string Send chan interface{} Connected time.Time } // GameConfig holds configuration for the game type GameConfig struct { MapWidth int `json:"map_width"` // 20 MapHeight int `json:"map_height"` // 20 CountdownSequence []int `json:"countdown_sequence"` // [30, 25, 20, 15, 10, 8, 6, 4, 3, 2] SpectatorOnlyRounds int `json:"spectator_only_rounds"` // Last 2 rounds // Timing Progression (rush phase duration by round ranges) TimingProgression []TimingRange `json:"timing_progression"` // Scoring Configuration SurvivalPointsPerRound int `json:"survival_points_per_round"` // 10 EliminationBonusMultiplier int `json:"elimination_bonus_multiplier"` // 5 SpeedBonusThreshold float64 `json:"speed_bonus_threshold"` // 1.0 second PerfectBonusThreshold float64 `json:"perfect_bonus_threshold"` // 2.0 seconds SpeedBonusPoints int `json:"speed_bonus_points"` // 2 PerfectBonusPoints int `json:"perfect_bonus_points"` // 50 FinalWinnerBonus int `json:"final_winner_bonus"` // 100 EnduranceBonus int `json:"endurance_bonus"` // 200 StreakBonuses map[int]int `json:"streak_bonuses"` // {3: 30, 5: 75, 10: 200} // Movement & Anti-cheat BaseMovementSpeed float64 `json:"base_movement_speed"` // 4.0 blocks/second MaxMovementSpeed float64 `json:"max_movement_speed"` // 5.0 blocks/second LagCompensationMs int `json:"lag_compensation_ms"` // 100ms PositionUpdateHz int `json:"position_update_hz"` // 10 Hz TimerUpdateHz int `json:"timer_update_hz"` // 20 Hz // Map Changes MapChangeRounds []int `json:"map_change_rounds"` // Rounds when colors are removed ColorsToRemoveEach int `json:"colors_to_remove_each"` // Number of colors to remove per change } // TimingRange defines rush duration for specific round ranges type TimingRange struct { StartRound int `json:"start_round"` EndRound int `json:"end_round"` Duration float64 `json:"duration"` // in seconds } // Game represents the main game structure type Game struct { // Basic Information ID string `json:"game_id"` CreatedAt time.Time `json:"created_at"` StartedAt *time.Time `json:"started_at,omitempty"` EndedAt *time.Time `json:"ended_at,omitempty"` // Game State Phase GamePhase `json:"phase"` CurrentRound *Round `json:"current_round,omitempty"` RoundNumber int `json:"round_number"` Map MapData `json:"-"` // Use MapToArray() for JSON MapArray [][]int `json:"map"` // Flattened map for JSON Countdown *float64 `json:"countdown_seconds,omitempty"` // Players Players map[string]*Player `json:"-"` PlayersList []*Player `json:"players"` // For JSON marshaling PlayerPositionHistory map[string]Position `json:"-"` // For movement validation PlayerCount int `json:"player_count"` AliveCount int `json:"alive_count"` // WebSocket Management Clients map[string]*WebSocketClient `json:"-"` Broadcast chan interface{} `json:"-"` Register chan *WebSocketClient `json:"-"` Unregister chan *WebSocketClient `json:"-"` // Configuration Config GameConfig `json:"config"` // Synchronization Mu sync.RWMutex Ticker *time.Ticker StopTicker chan bool LastTick time.Time `json:"-"` LastPositionBroadcast time.Time `json:"-"` // Tracks when positions were last broadcast }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/pkg/logger/logger.go
Go
package logger import ( "os" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/yorukot/blind-party/internal/config" ) // InitLogger initialize the logger func InitLogger() { appEnv := os.Getenv("APP_ENV") var logger *zap.Logger if appEnv == string(config.AppEnvDev) { devConfig := zap.NewDevelopmentConfig() devConfig.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder logger, _ = devConfig.Build() } else { logger = zap.Must(zap.NewProduction()) } zap.ReplaceGlobals(logger) zap.L().Info("Logger initialized") defer logger.Sync() }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
backend/pkg/response/response.go
Go
package response import ( "encoding/json" "net/http" ) // ErrorResponse is the response for an error type ErrorResponse struct { Message string `json:"message"` ErrCode string `json:"err_code"` } // SuccessResponse is the response for a success type SuccessResponse struct { Message string `json:"message"` Data any `json:"data"` } // RespondWithError responds with an error message func RespondWithError(w http.ResponseWriter, statusCode int, message, errCode string) { w.WriteHeader(statusCode) json.NewEncoder(w).Encode(ErrorResponse{ Message: message, ErrCode: errCode, }) } // RespondWithJSON responds with a JSON object func RespondWithJSON(w http.ResponseWriter, statusCode int, message string, data interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(statusCode) json.NewEncoder(w).Encode(SuccessResponse{ Message: message, Data: data, }) } // RespondWithData responds with a JSON object func RespondWithData(w http.ResponseWriter, data interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(data) }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/eslint.config.js
JavaScript
import prettier from 'eslint-config-prettier'; import { fileURLToPath } from 'node:url'; import { includeIgnoreFile } from '@eslint/compat'; import js from '@eslint/js'; import svelte from 'eslint-plugin-svelte'; import { defineConfig } from 'eslint/config'; import globals from 'globals'; import ts from 'typescript-eslint'; import svelteConfig from './svelte.config.js'; const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url)); export default defineConfig( includeIgnoreFile(gitignorePath), js.configs.recommended, ...ts.configs.recommended, ...svelte.configs.recommended, prettier, ...svelte.configs.prettier, { languageOptions: { globals: { ...globals.browser, ...globals.node } }, rules: { // typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects. // see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors 'no-undef': 'off' } }, { files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'], languageOptions: { parserOptions: { projectService: true, extraFileExtensions: ['.svelte'], parser: ts.parser, svelteConfig } } } );
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/app.css
CSS
@import 'tailwindcss'; /* Custom Minecraft Font Imports */ @font-face { font-family: 'Minecraft'; src: url('./lib/assets/fonts/MinecraftRegular-Bmg3.otf') format('opentype'); font-weight: 400; font-style: normal; font-display: swap; } @font-face { font-family: 'Minecraft'; src: url('./lib/assets/fonts/MinecraftBold-nMK1.otf') format('opentype'); font-weight: 700; font-style: normal; font-display: swap; } @font-face { font-family: 'Minecraft'; src: url('./lib/assets/fonts/MinecraftItalic-R8Mo.otf') format('opentype'); font-weight: 400; font-style: italic; font-display: swap; } @font-face { font-family: 'Minecraft'; src: url('./lib/assets/fonts/MinecraftBoldItalic-1y1e.otf') format('opentype'); font-weight: 700; font-style: italic; font-display: swap; } /* Global font configuration */ html { font-family: 'Minecraft', 'Courier New', 'Lucida Console', monospace; } /* Pixel-perfect rendering utilities */ .pixelated { image-rendering: pixelated; image-rendering: -moz-crisp-edges; image-rendering: crisp-edges; } .pixel-text { font-family: 'Minecraft', 'Courier New', 'Lucida Console', monospace; text-rendering: optimizeSpeed; -webkit-font-smoothing: none; -moz-osx-font-smoothing: grayscale; } /* Game-specific text styles */ .game-text { font-family: 'Minecraft', 'Courier New', 'Lucida Console', monospace; text-shadow: 2px 2px 0px rgba(0, 0, 0, 0.8); letter-spacing: 0.1em; }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/app.d.ts
TypeScript
// See https://svelte.dev/docs/kit/types#app.d.ts // for information about these interfaces declare global { namespace App { // interface Error {} // interface Locals {} // interface PageData {} // interface PageState {} // interface Platform {} } } export {};
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/app.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> %sveltekit.head% </head> <body data-sveltekit-preload-data="hover"> <div style="display: contents">%sveltekit.body%</div> </body> </html>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/api/http.ts
TypeScript
import { PUBLIC_API_BASE_URL } from '$env/static/public'; /** * Response type for creating a new game */ export interface CreateGameResponse { game_id: string; } /** * Base API error interface */ export interface ApiError { message: string; status: number; details?: unknown; } /** * Custom error class for API errors */ export class HttpApiError extends Error { constructor( public status: number, message: string, public details?: unknown ) { super(message); this.name = 'HttpApiError'; } } /** * HTTP API client configuration */ class HttpApiClient { private readonly baseUrl: string; constructor() { this.baseUrl = PUBLIC_API_BASE_URL; if (!this.baseUrl) { throw new Error('PUBLIC_API_BASE_URL environment variable is not set'); } } /** * Make a HTTP request with proper error handling */ private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> { const url = `${this.baseUrl}${endpoint}`; try { const response = await fetch(url, { headers: { 'Content-Type': 'application/json', ...options.headers }, ...options }); if (!response.ok) { const errorData = await response.text(); let errorMessage = `HTTP ${response.status}: ${response.statusText}`; try { const parsedError = JSON.parse(errorData); errorMessage = parsedError.message || errorMessage; } catch { // If parsing fails, use the raw text or default message errorMessage = errorData || errorMessage; } throw new HttpApiError(response.status, errorMessage, errorData); } const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { return await response.json(); } // If response is not JSON, return empty object return {} as T; } catch (error) { if (error instanceof HttpApiError) { throw error; } // Network or other errors throw new HttpApiError( 0, `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`, error ); } } /** * Creates a new game instance * * @returns Promise resolving to the game creation response * @throws HttpApiError if the request fails */ async createGame(): Promise<CreateGameResponse> { return this.request<CreateGameResponse>('/api/game/', { method: 'POST' }); } /** * Get the base URL being used by the client */ getBaseUrl(): string { return this.baseUrl; } } /** * Singleton HTTP API client instance */ export const httpApi = new HttpApiClient(); /** * Convenience function to create a new game */ export async function createGame(): Promise<CreateGameResponse> { return httpApi.createGame(); }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/api/websocket.ts
TypeScript
import { PUBLIC_WS_BASE_URL } from '$env/static/public'; import type { GameStateResponse } from '../types/game.js'; /** * WebSocket connection states */ export type ConnectionState = | 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'error'; /** * WebSocket message types that can be received from the server */ export type WebSocketMessage = | { event: 'game_update'; data: GameStateResponse } | { type: 'error'; data: { message: string; code?: string } } | { type: 'ping' } | { type: 'pong' }; /** * WebSocket message types that can be sent to the server */ export type OutgoingWebSocketMessage = | { event: 'player_update'; player: { pos_x: number; pos_y: number } } | { type: 'ping' } | { type: 'pong' }; /** * WebSocket client configuration options */ export interface WebSocketClientOptions { /** Auto-reconnect on connection loss (default: true) */ autoReconnect?: boolean; /** Maximum number of reconnection attempts (default: 5) */ maxReconnectAttempts?: number; /** Delay between reconnection attempts in ms (default: 1000) */ reconnectDelay?: number; /** Ping interval in ms to keep connection alive (default: 30000) */ pingInterval?: number; } /** * Event listeners for WebSocket client */ export interface WebSocketEventListeners { onStateChange?: (state: ConnectionState) => void; onGameUpdate?: (gameState: GameStateResponse) => void; onError?: (error: string) => void; onMessage?: (message: WebSocketMessage) => void; } /** * WebSocket API client for game connections */ export class WebSocketGameClient { private ws: WebSocket | null = null; private state: ConnectionState = 'disconnected'; private reconnectAttempts = 0; private reconnectTimer: number | null = null; private pingTimer: number | null = null; private readonly baseUrl: string; private gameId: string | null = null; private username: string | null = null; private readonly options: Required<WebSocketClientOptions>; private readonly listeners: WebSocketEventListeners = {}; constructor(options: WebSocketClientOptions = {}) { this.baseUrl = PUBLIC_WS_BASE_URL; if (!this.baseUrl) { throw new Error('PUBLIC_WS_BASE_URL environment variable is not set'); } this.options = { autoReconnect: true, maxReconnectAttempts: 5, reconnectDelay: 1000, pingInterval: 30000, ...options }; } /** * Connect to a specific game */ async connect(gameId: string, username: string): Promise<void> { if (this.state === 'connected' || this.state === 'connecting') { throw new Error('WebSocket is already connected or connecting'); } this.gameId = gameId; this.username = username; this.reconnectAttempts = 0; return this.establishConnection(); } /** * Disconnect from the current game */ disconnect(): void { this.clearTimers(); this.setState('disconnected'); if (this.ws) { this.ws.close(1000, 'Client disconnect'); this.ws = null; } this.gameId = null; this.username = null; } /** * Send a message to the server */ send(message: OutgoingWebSocketMessage): void { if (this.state !== 'connected' || !this.ws) { throw new Error('WebSocket is not connected'); } this.ws.send(JSON.stringify(message)); } /** * Send player position update to the server */ sendPlayerUpdate(pos_x: number, pos_y: number): void { this.send({ event: 'player_update', player: { pos_x: pos_x, pos_y: pos_y } }); } /** * Get current connection state */ getState(): ConnectionState { return this.state; } /** * Get current game ID */ getGameId(): string | null { return this.gameId; } /** * Get current username */ getUsername(): string | null { return this.username; } /** * Add event listeners */ on<K extends keyof WebSocketEventListeners>( event: K, listener: NonNullable<WebSocketEventListeners[K]> ): void { this.listeners[event] = listener; } /** * Remove event listeners */ off<K extends keyof WebSocketEventListeners>(event: K): void { delete this.listeners[event]; } /** * Establish WebSocket connection */ private async establishConnection(): Promise<void> { if (!this.gameId || !this.username) { throw new Error('Game ID and username are required'); } this.setState('connecting'); const wsUrl = `${this.baseUrl}/api/game/${this.gameId}/ws?username=${encodeURIComponent(this.username)}`; try { this.ws = new WebSocket(wsUrl); this.setupWebSocketEventHandlers(); // Wait for connection to open or fail await new Promise<void>((resolve, reject) => { const ws = this.ws; if (!ws) { reject(new Error('Failed to initialise WebSocket')); return; } const socket = ws; let timeout = 0; function cleanup() { window.clearTimeout(timeout); socket.removeEventListener('open', handleOpen); socket.removeEventListener('error', handleError); } function handleOpen() { cleanup(); resolve(); } function handleError() { cleanup(); reject(new Error('WebSocket connection failed')); } timeout = window.setTimeout(() => { cleanup(); reject(new Error('Connection timeout')); }, 10000); socket.addEventListener('open', handleOpen, { once: true }); socket.addEventListener('error', handleError, { once: true }); }); } catch (error) { this.setState('error'); this.listeners.onError?.( error instanceof Error ? error.message : 'Unknown connection error' ); if ( this.options.autoReconnect && this.reconnectAttempts < this.options.maxReconnectAttempts ) { this.scheduleReconnect(); } throw error; } } /** * Setup WebSocket event handlers */ private setupWebSocketEventHandlers(): void { if (!this.ws) return; this.ws.onopen = () => { this.setState('connected'); this.reconnectAttempts = 0; this.startPingTimer(); }; this.ws.onclose = (event) => { this.clearTimers(); if (event.code === 1000) { // Normal closure this.setState('disconnected'); } else if ( this.options.autoReconnect && this.reconnectAttempts < this.options.maxReconnectAttempts ) { this.setState('reconnecting'); this.scheduleReconnect(); } else { this.setState('error'); this.listeners.onError?.(`Connection closed unexpectedly (code: ${event.code})`); } }; this.ws.onerror = () => { this.setState('error'); this.listeners.onError?.('WebSocket error occurred'); }; this.ws.onmessage = (event) => { try { const message: WebSocketMessage = JSON.parse(event.data); this.handleMessage(message); } catch { this.listeners.onError?.('Failed to parse WebSocket message'); } }; } /** * Handle incoming WebSocket messages */ private handleMessage(message: WebSocketMessage): void { this.listeners.onMessage?.(message); // Handle messages with 'event' property (server format) if ('event' in message) { switch (message.event) { case 'game_update': this.listeners.onGameUpdate?.(message.data); break; } return; } // Handle messages with 'type' property (client/server communication) if ('type' in message) { switch (message.type) { case 'error': this.listeners.onError?.(message.data.message); break; case 'ping': this.send({ type: 'pong' }); break; case 'pong': // Server acknowledged our ping break; } } } /** * Set connection state and notify listeners */ private setState(newState: ConnectionState): void { if (this.state !== newState) { this.state = newState; this.listeners.onStateChange?.(newState); } } /** * Schedule reconnection attempt */ private scheduleReconnect(): void { this.reconnectAttempts++; this.reconnectTimer = window.setTimeout(() => { if (this.gameId && this.username) { this.establishConnection().catch(() => { // Error handling is done in establishConnection }); } }, this.options.reconnectDelay * this.reconnectAttempts); } /** * Start ping timer to keep connection alive */ private startPingTimer(): void { this.pingTimer = window.setInterval(() => { if (this.state === 'connected') { this.send({ type: 'ping' }); } }, this.options.pingInterval); } /** * Clear all timers */ private clearTimers(): void { if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null; } } } /** * Create a new WebSocket game client instance */ export function createWebSocketClient(options?: WebSocketClientOptions): WebSocketGameClient { return new WebSocketGameClient(options); }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/game/countdown-overlay.svelte
Svelte
<script lang="ts"> interface Props { /** Current second(s) remaining in the final countdown window. */ remainingSeconds: number; /** Allow the parent to explicitly toggle visibility. */ visible?: boolean; /** Maximum countdown window the overlay should cover. */ windowSize?: number; /** Optional headline text displayed above the timer. */ label?: string; /** Supporting message displayed below the timer. */ message?: string; /** Accent colour used for borders, glow and the radial progress ring. */ fillColor?: string; } let { remainingSeconds, visible = true, windowSize = 5, label = 'Final Countdown', message = 'Round ending soon — get ready!', fillColor = '#fef08a' }: Props = $props(); /** Clamp the timer so visuals stay within the configured window. */ let clamped = $derived(Math.max(Math.min(remainingSeconds, windowSize), 0)); let shouldRender = $derived( visible && remainingSeconds > 0 && remainingSeconds <= windowSize && Number.isFinite(remainingSeconds) ); let intRemaining = $derived(Math.ceil(clamped)); let progress = $derived(windowSize > 0 ? clamped / windowSize : 0); let overlayStyle = $derived.by(() => { const safeProgress = Math.min(Math.max(progress, 0), 1); const intensity = 0.12 + (1 - safeProgress) * 0.18; const glow = `box-shadow: 0 22px 68px color-mix(in srgb, ${fillColor} ${(intensity * 100).toFixed(0)}%, transparent);`; const borderColor = `color-mix(in srgb, var(--overlay-accent) 65%, rgba(148, 163, 184, 0.34))`; const backgroundGradient = 'linear-gradient(145deg, ' + `color-mix(in srgb, var(--overlay-accent) 28%, rgba(30, 27, 75, 0.45)) 0%, ` + `color-mix(in srgb, var(--overlay-accent) 14%, rgba(15, 23, 42, 0.35)) 45%, ` + `rgba(2, 6, 23, 0.50) 100%)`; return `--overlay-accent: ${fillColor}; ${glow} border-color: ${borderColor}; background: ${backgroundGradient};`; }); let labelStyle = $derived(`color: color-mix(in srgb, var(--overlay-accent) 80%, white 20%);`); let numberStyle = $derived( 'color: color-mix(in srgb, var(--overlay-accent) 92%, white 8%); ' + 'text-shadow: 6px 6px 0 rgba(0,0,0,0.45);' ); let messageStyle = $derived( 'color: color-mix(in srgb, var(--overlay-accent) 75%, rgba(255,255,255,0.85));' ); </script> {#if shouldRender} <div class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center"> <div class="relative flex flex-col items-center gap-6 rounded-[32px] border-4 px-12 py-10 text-center text-white shadow-[0_18px_60px_rgba(0,0,0,0.4)]" style={overlayStyle} > <span class="font-minecraft text-[0.85rem] tracking-[0.4em] uppercase drop-shadow-[3px_3px_0_rgba(0,0,0,0.4)]" style={labelStyle} > {label} </span> <div class="relative flex h-40 w-40 items-center justify-center"> {#key intRemaining} <span class="countdown-number font-minecraft text-8xl" style={numberStyle}> {intRemaining} </span> {/key} </div> <p class="text-sm font-medium drop-shadow-[2px_2px_0_rgba(0,0,0,0.4)]" style={messageStyle} > {message} </p> </div> </div> {/if} <style> .countdown-number { animation: overlay-pop 1s cubic-bezier(0.21, 1.12, 0.59, 1) forwards; } @keyframes overlay-breathe { 0%, 100% { transform: scale(0.98); box-shadow: 0 0 12px rgba(248, 250, 252, 0.2); } 50% { transform: scale(1.02); box-shadow: 0 0 26px rgba(248, 250, 252, 0.32); } } @keyframes overlay-pop { 0% { opacity: 0; transform: scale(0.7); filter: blur(6px); } 35% { opacity: 1; transform: scale(1.1); filter: blur(0px); } 55% { transform: scale(0.95); } 100% { transform: scale(1); } } </style>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/game/game-board-panel.svelte
Svelte
<script lang="ts"> import { onMount } from 'svelte'; import GameBoard from './game-board.svelte'; import type { PlayerOnBoard } from '$lib/types/player'; interface Props { mapSize: number; gameMap?: number[][]; targetSize?: number; minTileSize?: number; maxTileSize?: number; players?: PlayerOnBoard[]; selfPlayer?: PlayerOnBoard | null; } let { mapSize, gameMap = [], targetSize = 560, minTileSize = 10, maxTileSize = 48, players = [], selfPlayer = null }: Props = $props(); let container: HTMLElement | null = null; let containerWidth = $state(targetSize); let safeMapSize = $derived.by(() => Math.max(1, Math.floor(mapSize ?? 1))); let effectiveTargetSize = $derived.by(() => Math.max(minTileSize * safeMapSize, Math.min(containerWidth, targetSize)) ); let computedTileSize = $derived.by(() => { const tile = Math.floor(effectiveTargetSize / safeMapSize); return Math.max(minTileSize, Math.min(maxTileSize, tile)); }); onMount(() => { if (!container) { return; } const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { if (entry.target !== container) { continue; } const width = entry.contentBoxSize?.[0]?.inlineSize ?? entry.contentRect.width; containerWidth = Math.max(width, minTileSize * safeMapSize); } }); resizeObserver.observe(container); containerWidth = container.clientWidth; return () => { resizeObserver.disconnect(); }; }); </script> <section bind:this={container} class="flex w-full items-center justify-center rounded-3xl border-4 border-black bg-slate-950/90 p-4 shadow-[0_16px_0px_rgba(0,0,0,0.55)] backdrop-blur" > <GameBoard mapSize={safeMapSize} {gameMap} tileSize={computedTileSize} {players} {selfPlayer} /> </section>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/game/game-board.svelte
Svelte
<script lang="ts"> import { onMount } from 'svelte'; import type { PlayerOnBoard } from '$lib/types/player'; import { BLOCK_TEXTURE_NAMES } from '$lib/constants/block-textures'; /** * Canvas-based renderer for the Blind Party map. * Displays the game map data. */ interface Props { mapSize: number; gameMap?: number[][]; tileSize?: number; players?: PlayerOnBoard[]; selfPlayer?: PlayerOnBoard | null; } let { mapSize, gameMap = [], tileSize = 32, players = [], selfPlayer = null }: Props = $props(); // Use centralized block texture names to dynamically import textures const textureUrls = BLOCK_TEXTURE_NAMES.map((name) => { const modules = import.meta.glob('$lib/assets/blocks/*.png', { as: 'url', eager: true }); const path = `/src/lib/assets/blocks/${name}.png`; return modules[path] as string; }).filter(Boolean); let normalizedMapSize = $derived.by(() => Math.max(1, Math.floor(mapSize ?? 0))); let safeTileSize = $derived.by(() => Math.max(8, Math.floor(tileSize ?? 0) || 32)); let cssSize = $derived(normalizedMapSize * safeTileSize); let canvas: HTMLCanvasElement | null = null; let devicePixelRatio = $state(1); let texturesReady = $state(false); let mapGrid = $state<number[][]>([]); let blockImages: HTMLImageElement[] = []; const clampToBoard = (value: number, size: number) => Math.min(Math.max(value, 0), size - 1); const mapPlayerToToken = (player: PlayerOnBoard, isSelf = false) => { const x = clampToBoard(player.position.x, normalizedMapSize); const y = clampToBoard(player.position.y, normalizedMapSize); return { id: player.id, name: player.name, status: player.status, accent: player.accent, x, y, left: (x + 0.5) * safeTileSize, top: (y + 0.5) * safeTileSize, isSelf }; }; let otherPlayerTokens = $derived( players .filter((player) => player.status !== 'eliminated') .map((player) => mapPlayerToToken(player)) ); let selfPlayerToken = $derived.by(() => { if (!selfPlayer || selfPlayer.status === 'eliminated') { return null; } return mapPlayerToToken(selfPlayer, true); }); $effect(() => { if (!import.meta.env.DEV) { return; } console.debug('[GameBoard] tokens derived', { otherPlayers: otherPlayerTokens.map((token) => ({ id: token.id, x: token.x, y: token.y })), self: selfPlayerToken ? { id: selfPlayerToken.id, x: selfPlayerToken.x, y: selfPlayerToken.y } : null }); }); let playerDiameter = $derived( Math.min(safeTileSize, Math.max(16, Math.round(safeTileSize * 0.85))) ); const getPlayerClasses = (status: PlayerOnBoard['status'], isSelf: boolean) => { if (isSelf) { return 'ring-4 ring-amber-300/90 ring-offset-2 ring-offset-black'; } if (status === 'spectating') { return 'opacity-80'; } return ''; }; $effect(() => { // Use provided map data if (gameMap && gameMap.length > 0) { mapGrid = gameMap; } else { // Clear map if no data is available mapGrid = []; } }); function createImage(url: string) { return new Promise<HTMLImageElement>((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); img.onerror = (event) => reject(event); img.src = url; }); } function draw(grid: number[][], tile: number, ratio: number) { if (!canvas || !texturesReady || !grid.length) { return; } const context = canvas.getContext('2d'); if (!context) { return; } // Reset the transform before drawing to keep scaling consistent. context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, canvas.width, canvas.height); context.scale(ratio, ratio); for (let y = 0; y < grid.length; y += 1) { for (let x = 0; x < grid[y].length; x += 1) { const textureIndex = grid[y][x] % blockImages.length; const texture = blockImages[textureIndex]; if (texture) { context.drawImage(texture, x * tile, y * tile, tile, tile); } else { context.fillStyle = '#000'; context.fillRect(x * tile, y * tile, tile, tile); } } } } onMount(() => { let cancelled = false; function updateDevicePixelRatio() { devicePixelRatio = window.devicePixelRatio || 1; } updateDevicePixelRatio(); const handleResize = () => { updateDevicePixelRatio(); draw(mapGrid, safeTileSize, devicePixelRatio); }; window.addEventListener('resize', handleResize); Promise.all(textureUrls.map((url) => createImage(url))) .then((images) => { if (cancelled) { return; } blockImages = images; texturesReady = true; draw(mapGrid, safeTileSize, devicePixelRatio); }) .catch((error) => { console.error('Failed to load block textures', error); }); return () => { cancelled = true; window.removeEventListener('resize', handleResize); }; }); let scaledCanvasSize = $derived(Math.round(cssSize * devicePixelRatio)); $effect(() => { if (!texturesReady) { return; } draw(mapGrid, safeTileSize, devicePixelRatio); }); </script> <div class="relative inline-block rounded-lg border-4 border-black bg-slate-900 p-2 shadow-xl"> <div class="relative"> <canvas bind:this={canvas} class="block-map h-auto w-full" width={scaledCanvasSize} height={scaledCanvasSize} style={`width: ${cssSize}px; height: ${cssSize}px;`} ></canvas> <div class="player-layer pointer-events-none absolute top-0 left-0" style={`width: ${cssSize}px; height: ${cssSize}px;`} > {#if selfPlayerToken} <div class={`player-token absolute flex items-center justify-center rounded-full border-2 border-black bg-gradient-to-br ${selfPlayerToken.accent} text-white shadow-[3px_3px_0_rgba(0,0,0,0.6)] transition-transform duration-150 ease-out ${getPlayerClasses( selfPlayerToken.status, true )}`} style={`width: ${playerDiameter}px; height: ${playerDiameter}px; left: ${selfPlayerToken.left}px; top: ${selfPlayerToken.top}px; transform: translate(-50%, -50%);`} aria-label={`${selfPlayerToken.name} (You)`} > <span class="font-minecraft text-xs tracking-widest drop-shadow-[1px_1px_0_rgba(0,0,0,0.65)]" > {selfPlayerToken.name.slice(0, 1).toUpperCase()} </span> </div> {/if} {#each otherPlayerTokens as player (player.id)} <div class={`player-token absolute flex items-center justify-center rounded-full border-2 border-black bg-gradient-to-br ${player.accent} text-white shadow-[3px_3px_0_rgba(0,0,0,0.6)] transition-transform duration-150 ease-out ${getPlayerClasses( player.status, false )}`} style={`width: ${playerDiameter}px; height: ${playerDiameter}px; left: ${player.left}px; top: ${player.top}px; transform: translate(-50%, -50%);`} aria-label={`${player.name} (${player.status})`} > <span class="font-minecraft text-xs tracking-widest drop-shadow-[1px_1px_0_rgba(0,0,0,0.65)]" > {player.name.slice(0, 1).toUpperCase()} </span> </div> {/each} </div> </div> </div> <style> .block-map { image-rendering: pixelated; image-rendering: crisp-edges; display: block; } .player-token { text-rendering: optimizeSpeed; -webkit-font-smoothing: none; -moz-osx-font-smoothing: grayscale; } </style>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/game/game-status-bar.svelte
Svelte
<script lang="ts"> interface Props { label: string; displayText: string; progress: number; fillColor?: string; borderColor?: string; } let { label, displayText, progress, fillColor = '#22c55e', borderColor }: Props = $props(); // Clamp progress between 0 and 100 let clampedProgress = $derived(Math.max(0, Math.min(100, progress))); let resolvedBorderColor = $derived(borderColor ?? fillColor); let containerStyle = $derived.by(() => { const frameColor = `color-mix(in srgb, ${resolvedBorderColor} 55%, rgba(15, 23, 42, 0.52))`; const backgroundGradient = 'linear-gradient(135deg, rgba(2, 6, 23, 0.95) 0%, ' + `color-mix(in srgb, ${fillColor} 12%, rgba(15, 23, 42, 0.82)) 38%, ` + `rgba(2, 6, 23, 0.92) 100%)`; return `--countdown-bar-fill: ${fillColor}; border-color: ${frameColor}; background: ${backgroundGradient};`; }); let fillStyle = $derived.by(() => { const barGradient = 'linear-gradient(270deg, ' + `color-mix(in srgb, var(--countdown-bar-fill) 96%, white 4%) 0%, ` + `color-mix(in srgb, var(--countdown-bar-fill) 78%, rgba(0, 0, 0, 0.08)) 100%)`; return `width: ${clampedProgress}%; background: ${barGradient}; box-shadow: inset 0 -4px 0 rgba(0,0,0,0.35);`; }); let labelStyle = $derived( `color: color-mix(in srgb, var(--countdown-bar-fill) 82%, white 18%);` ); let timeStyle = $derived( 'color: color-mix(in srgb, var(--countdown-bar-fill) 94%, white 6%); ' + 'text-shadow: 2px 2px 0 rgba(0,0,0,0.7);' ); </script> <section class="relative w-full rounded-3xl border-4 p-4 shadow-[8px_8px_0_0_rgba(0,0,0,0.6)]" style={containerStyle} > <div class="flex items-center justify-between text-xs tracking-[0.3em] uppercase"> <span class="font-minecraft text-sm drop-shadow-[2px_2px_0_rgba(0,0,0,0.7)]" style={labelStyle} > {label} </span> <span class="font-minecraft text-base drop-shadow-[2px_2px_0_rgba(0,0,0,0.7)]" style={timeStyle} > {displayText} </span> </div> <div class="relative mt-3 h-6 w-full overflow-hidden rounded-2xl border-2 border-black/70 bg-slate-900 shadow-[inset_0_0_0_2px_rgba(0,0,0,0.8)]" > <div class="h-full transition-[width] duration-1000 ease-linear" style={fillStyle}></div> <div class="pointer-events-none absolute inset-0" style="background-image: repeating-linear-gradient(0deg, rgba(255,255,255,0.18) 0px, rgba(255,255,255,0.18) 2px, transparent 2px, transparent 4px); mix-blend-mode: screen;" ></div> </div> <div class="pointer-events-none absolute inset-0 rounded-3xl border-2 border-black/60"></div> </section>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/game/player-movement-controls.svelte
Svelte
<script lang="ts"> import { onMount } from 'svelte'; import { playerState, type Direction } from '$lib/player-state.svelte.js'; interface Props { disabled?: boolean; } let { disabled = false }: Props = $props(); function handlePointerDown(direction: Direction, event: PointerEvent) { if (disabled) { return; } event.preventDefault(); playerState.triggerMove(direction); } function handlePointerEnd(direction: Direction, event: PointerEvent) { if (disabled) { return; } event.preventDefault(); playerState.clearDirection(direction); } onMount(() => { function handleKeyDown(event: KeyboardEvent) { if (disabled) { return; } playerState.handleKeyDown(event); } function handleKeyUp(event: KeyboardEvent) { playerState.handleKeyUp(event); } window.addEventListener('keydown', handleKeyDown); window.addEventListener('keyup', handleKeyUp); return () => { window.removeEventListener('keydown', handleKeyDown); window.removeEventListener('keyup', handleKeyUp); playerState.clearPressedKeys(); }; }); </script> <section class="movement-panel w-full rounded-3xl border-4 border-black bg-slate-950/85 px-6 py-8 text-blue-100 shadow-[0_16px_0px_rgba(0,0,0,0.55)] backdrop-blur" aria-label="Player movement controls" > <div class="flex flex-col items-center gap-6"> <div class="flex w-full flex-col items-start justify-between gap-2 sm:flex-row sm:items-center" > <h2 class="font-minecraft text-xl tracking-[0.35em] text-cyan-200 uppercase"> Movement </h2> <p class="text-xs tracking-[0.3em] text-blue-200/70 uppercase"> Use Arrow Keys or WASD </p> </div> <div class="grid w-full max-w-sm grid-cols-3 grid-rows-3 gap-3"> <div></div> <button type="button" class={`inline-flex h-16 w-16 items-center justify-center rounded-2xl border-3 border-black text-xs tracking-wider text-blue-100 uppercase transition-all duration-100 ease-in-out ${ playerState.activeDirections.has('up') ? 'translate-y-0.5 bg-gradient-to-br from-red-400/60 to-red-600/80 text-orange-50 shadow-[2px_2px_0_rgba(0,0,0,0.6)]' : 'bg-gradient-to-br from-blue-400/40 to-blue-600/75 shadow-[4px_4px_0_rgba(0,0,0,0.55)] hover:shadow-[3px_3px_0_rgba(0,0,0,0.6)]' } focus-visible:outline-3 focus-visible:outline-offset-2 focus-visible:outline-white/85`} onpointerdown={(event) => handlePointerDown('up', event)} onpointerup={(event) => handlePointerEnd('up', event)} onpointerleave={(event) => handlePointerEnd('up', event)} onpointercancel={(event) => handlePointerEnd('up', event)} aria-label="Move up" > <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="h-5 w-5 drop-shadow-[2px_2px_0_rgba(0,0,0,0.4)]" > <path d="M12 5.5 5 13h4v6h6v-6h4z" /> </svg> </button> <div></div> <button type="button" class={`inline-flex h-16 w-16 items-center justify-center rounded-2xl border-3 border-black text-xs tracking-wider text-blue-100 uppercase transition-all duration-100 ease-in-out ${ playerState.activeDirections.has('left') ? 'translate-y-0.5 bg-gradient-to-br from-red-400/60 to-red-600/80 text-orange-50 shadow-[2px_2px_0_rgba(0,0,0,0.6)]' : 'bg-gradient-to-br from-blue-400/40 to-blue-600/75 shadow-[4px_4px_0_rgba(0,0,0,0.55)] hover:shadow-[3px_3px_0_rgba(0,0,0,0.6)]' } focus-visible:outline-3 focus-visible:outline-offset-2 focus-visible:outline-white/85`} onpointerdown={(event) => handlePointerDown('left', event)} onpointerup={(event) => handlePointerEnd('left', event)} onpointerleave={(event) => handlePointerEnd('left', event)} onpointercancel={(event) => handlePointerEnd('left', event)} aria-label="Move left" > <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="h-5 w-5 drop-shadow-[2px_2px_0_rgba(0,0,0,0.4)]" > <path d="M5.5 12 13 19v-4h6v-6h-6V5z" /> </svg> </button> <button type="button" class="pointer-events-none inline-flex h-16 w-16 items-center justify-center rounded-2xl border-3 border-black bg-slate-900/80 text-blue-200/50 opacity-50 shadow-none" disabled aria-hidden="true" > <span class="text-[0.6rem] tracking-[0.3em] uppercase">Move</span> </button> <button type="button" class={`inline-flex h-16 w-16 items-center justify-center rounded-2xl border-3 border-black text-xs tracking-wider text-blue-100 uppercase transition-all duration-100 ease-in-out ${ playerState.activeDirections.has('right') ? 'translate-y-0.5 bg-gradient-to-br from-red-400/60 to-red-600/80 text-orange-50 shadow-[2px_2px_0_rgba(0,0,0,0.6)]' : 'bg-gradient-to-br from-blue-400/40 to-blue-600/75 shadow-[4px_4px_0_rgba(0,0,0,0.55)] hover:shadow-[3px_3px_0_rgba(0,0,0,0.6)]' } focus-visible:outline-3 focus-visible:outline-offset-2 focus-visible:outline-white/85`} onpointerdown={(event) => handlePointerDown('right', event)} onpointerup={(event) => handlePointerEnd('right', event)} onpointerleave={(event) => handlePointerEnd('right', event)} onpointercancel={(event) => handlePointerEnd('right', event)} aria-label="Move right" > <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="h-5 w-5 drop-shadow-[2px_2px_0_rgba(0,0,0,0.4)]" > <path d="M18.5 12 11 5v4H5v6h6v4z" /> </svg> </button> <div></div> <button type="button" class={`inline-flex h-16 w-16 items-center justify-center rounded-2xl border-3 border-black text-xs tracking-wider text-blue-100 uppercase transition-all duration-100 ease-in-out ${ playerState.activeDirections.has('down') ? 'translate-y-0.5 bg-gradient-to-br from-red-400/60 to-red-600/80 text-orange-50 shadow-[2px_2px_0_rgba(0,0,0,0.6)]' : 'bg-gradient-to-br from-blue-400/40 to-blue-600/75 shadow-[4px_4px_0_rgba(0,0,0,0.55)] hover:shadow-[3px_3px_0_rgba(0,0,0,0.6)]' } focus-visible:outline-3 focus-visible:outline-offset-2 focus-visible:outline-white/85`} onpointerdown={(event) => handlePointerDown('down', event)} onpointerup={(event) => handlePointerEnd('down', event)} onpointerleave={(event) => handlePointerEnd('down', event)} onpointercancel={(event) => handlePointerEnd('down', event)} aria-label="Move down" > <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="h-5 w-5 drop-shadow-[2px_2px_0_rgba(0,0,0,0.4)]" > <path d="M12 18.5 19 11h-4V5H9v6H5z" /> </svg> </button> <div></div> </div> <p class="text-xs text-blue-200/60"> Tap or press directions to queue moves. Multiple keys can be pressed simultaneously. Keyboard input works even when the buttons are not focused. </p> </div> </section> <style> .movement-panel { text-rendering: optimizeSpeed; -webkit-font-smoothing: none; -moz-osx-font-smoothing: grayscale; } </style>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/game/player-roster.svelte
Svelte
<script lang="ts"> import { flip } from 'svelte/animate'; import { slide } from 'svelte/transition'; import type { PlayerStatus, PlayerSummary } from '$lib/types/player'; type RosterPlayer = PlayerSummary & { is_eliminated?: boolean; is_spectator?: boolean; }; interface Props { players: RosterPlayer[]; selfPlayer?: RosterPlayer | null; } let { players = $bindable(), selfPlayer = null }: Props = $props(); let selfPlayerId = $derived(selfPlayer?.id ?? null); const statusOrder: Record<PlayerStatus, number> = { ingame: 0, eliminated: 1, spectating: 2 }; function resolveStatus(player: RosterPlayer): PlayerStatus { if (player.is_spectator) { return 'spectating'; } if (player.is_eliminated) { return 'eliminated'; } return player.status; } let otherPlayersSorted = $derived.by(() => players .filter((player) => player.id !== selfPlayerId) .toSorted((a, b) => { const statusDiff = statusOrder[resolveStatus(a)] - statusOrder[resolveStatus(b)]; if (statusDiff !== 0) return statusDiff; return a.name.localeCompare(b.name); }) ); let sortedPlayers = $derived.by(() => selfPlayer ? [selfPlayer, ...otherPlayersSorted] : otherPlayersSorted ); let totalPlayers = $derived(sortedPlayers.length); let activePlayers = $derived.by( () => sortedPlayers.filter((player) => resolveStatus(player) === 'ingame').length ); let inactivePlayers = $derived.by( () => sortedPlayers.filter((player) => resolveStatus(player) !== 'ingame').length ); </script> <aside class="w-full max-w-full space-y-6 rounded-3xl border-4 border-black bg-slate-950/85 p-6 shadow-[0_12px_0px_rgba(0,0,0,0.55)] backdrop-blur transition-all duration-300 lg:max-w-sm" > <div class="space-y-1"> <h2 class="font-minecraft text-2xl tracking-wide text-cyan-300 uppercase">Players</h2> <p class="text-sm text-blue-100/70"> Players sync in real-time once the lobby is live. Showing sample roster for styling. </p> </div> <div class="flex items-center justify-between rounded-lg border-2 border-black bg-gradient-to-r from-emerald-500/20 via-transparent to-cyan-500/20 px-4 py-3 text-xs tracking-[0.25em] text-blue-100/60 uppercase" > <span>{activePlayers} active</span> <span>{totalPlayers} total</span> </div> <div class="space-y-3"> {#each sortedPlayers as player, index (player.id)} {@const playerStatus = resolveStatus(player)} <div animate:flip={{ duration: 300, easing: (t) => t * (2 - t) }}> <!-- Separator between active and inactive players --> {#if index > 0 && resolveStatus(sortedPlayers[index - 1]) === 'ingame' && playerStatus !== 'ingame' && activePlayers > 0 && inactivePlayers > 0} <div class="mb-3 h-px bg-gradient-to-r from-transparent via-slate-600/50 to-transparent" transition:slide={{ duration: 300, axis: 'y' }} ></div> {/if} <div class={`pixel-card flex items-center justify-between gap-3 rounded-xl border-2 border-black px-4 py-3 shadow-[4px_4px_0px_rgba(0,0,0,0.6)] transition-all duration-500 ease-in-out ${ player.id === selfPlayerId ? 'bg-slate-900/90 ring-4 ring-amber-300/90 ring-offset-2 ring-offset-black' : playerStatus === 'ingame' ? 'bg-slate-900/80' : 'bg-slate-900/50 opacity-75' }`} > <div class="flex items-center gap-3"> <span class={`relative h-10 w-10 rounded-lg border-2 border-black bg-gradient-to-br ${player.accent} shadow-[2px_2px_0px_rgba(0,0,0,0.5)] transition-all duration-500 ease-in-out ${playerStatus !== 'ingame' ? 'grayscale' : ''}`} ></span> <div> <p class={`font-minecraft text-lg tracking-wide uppercase transition-all duration-500 ease-in-out ${ playerStatus !== 'ingame' ? 'text-yellow-100/70' : 'text-yellow-100' }`} > {player.name} </p> {#if player.id === selfPlayerId} <p class="text-xs tracking-[0.25em] text-amber-200/80 uppercase transition-all duration-500 ease-in-out" > You </p> {:else if playerStatus === 'eliminated'} <p class="text-xs tracking-[0.25em] text-rose-300/70 uppercase transition-all duration-500 ease-in-out" > Eliminated </p> {:else if playerStatus === 'ingame'} <p class="text-xs tracking-[0.25em] text-emerald-200/80 uppercase transition-all duration-500 ease-in-out" > On Mission </p> {:else if playerStatus === 'spectating'} <p class="text-xs tracking-[0.25em] text-blue-100/70 uppercase transition-all duration-500 ease-in-out" > Spectating </p> {/if} </div> </div> </div> </div> {/each} </div> </aside> <style> .pixel-card { text-rendering: optimizeSpeed; -webkit-font-smoothing: none; -moz-osx-font-smoothing: grayscale; transition: transform 0.15s ease; } .pixel-card:hover { transform: translateY(-2px); } </style>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/game/target-block-icon.svelte
Svelte
<script lang="ts"> import { BLOCK_TEXTURE_NAMES } from '$lib/constants/block-textures'; interface Props { targetBlock: number; } let { targetBlock }: Props = $props(); // Use centralized block texture names to get the correct texture const textureUrls = BLOCK_TEXTURE_NAMES.map((name) => { const modules = import.meta.glob('$lib/assets/blocks/*.png', { as: 'url', eager: true }); const path = `/src/lib/assets/blocks/${name}.png`; return modules[path] as string; }).filter(Boolean); let blockTexturePath = $derived.by(() => { const textureIndex = Math.min(targetBlock, textureUrls.length - 1); return textureUrls[textureIndex] || textureUrls[0]; }); </script> <div class="absolute top-4 right-4 z-10 flex flex-col items-center gap-2 rounded-xl border-4 border-black bg-slate-900/50 p-3 opacity-90 shadow-[4px_4px_0_rgba(0,0,0,0.4)]" > <div class="text-center"> <p class="font-minecraft text-xs tracking-wider text-yellow-300 uppercase drop-shadow-[2px_2px_0_rgba(0,0,0,0.7)]" > Target </p> </div> <div class="relative"> <img src={blockTexturePath} alt="Target block texture" class="h-12 w-12 rounded border-2 border-black shadow-[2px_2px_0_rgba(0,0,0,0.6)]" style="image-rendering: pixelated; image-rendering: crisp-edges;" /> <div class="absolute inset-0 rounded border border-white/20"></div> </div> </div>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/ui/join-form.svelte
Svelte
<script lang="ts"> import logo from '$lib/assets/blind-party.png'; import PixelButton from '$lib/components/ui/pixel-button.svelte'; import PixelInput from '$lib/components/ui/pixel-input.svelte'; interface Props { params: { gameId: string; }; username: string; isConnecting: boolean; connectionError: string | null; connectionState: string; onJoin: () => void; } let { params, username = $bindable(), isConnecting, connectionError, connectionState, onJoin }: Props = $props(); </script> <div class="flex min-h-screen flex-col items-center justify-center p-8"> <div class="flex w-full max-w-md flex-col items-center space-y-8"> <header class="text-center"> <img src={logo} alt="Blind Party Logo" class="pixelated h-auto w-[24rem]" /> <h1 class="font-minecraft text-3xl tracking-wider text-yellow-300 uppercase drop-shadow-[4px_4px_0px_rgba(0,0,0,0.65)]" > Game: <span class="text-white">{params.gameId}</span> </h1> </header> <div class="w-full space-y-4"> <PixelInput bind:value={username} placeholder="Enter your username" maxlength={20} /> {#if connectionError} <p class="text-sm text-red-400">{connectionError}</p> {/if} <PixelButton disabled={!username.trim() || isConnecting} onclick={onJoin}> {isConnecting ? 'Joining...' : 'Join Game'} </PixelButton> <div class="text-center"> <p class="text-sm text-slate-400"> Connection: <span class="text-blue-300">{connectionState}</span> </p> </div> </div> <style> .pixelated { image-rendering: pixelated; image-rendering: -moz-crisp-edges; image-rendering: crisp-edges; } </style> </div> </div>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/ui/pixel-button.svelte
Svelte
<script lang="ts"> interface Props { variant?: 'primary' | 'secondary'; disabled?: boolean; onclick?: () => void; children: import('svelte').Snippet; } let { variant = 'primary', disabled = false, onclick, children }: Props = $props(); </script> <button class=" pixel-button w-full {variant === 'primary' ? 'bg-gradient-to-b from-green-400 to-green-600 hover:from-green-300 hover:to-green-500' : 'bg-gradient-to-b from-blue-400 to-blue-600 hover:from-blue-300 hover:to-blue-500'} font-minecraft pixel-text border-4 border-black px-6 py-3 text-xl font-bold tracking-wider text-white uppercase transition-all duration-150 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50 " style=" box-shadow: inset -4px -4px 0px rgba(0,0,0,0.3), inset 4px 4px 0px rgba(255,255,255,0.3), 4px 4px 8px rgba(0,0,0,0.4); text-shadow: 2px 2px 0px rgba(0,0,0,0.5); " {disabled} {onclick} > {@render children()} </button> <style> .pixel-button { text-rendering: optimizeSpeed; -webkit-font-smoothing: none; -moz-osx-font-smoothing: grayscale; } .pixel-button:hover:not(:disabled) { animation: pixel-bounce 0.6s ease-in-out infinite alternate; } .pixel-button:active:not(:disabled) { box-shadow: inset -2px -2px 0px rgba(0, 0, 0, 0.3), inset 2px 2px 0px rgba(255, 255, 255, 0.3), 2px 2px 4px rgba(0, 0, 0, 0.4); } @keyframes pixel-bounce { 0% { transform: translateY(0px); } 100% { transform: translateY(-2px); } } </style>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/components/ui/pixel-input.svelte
Svelte
<script lang="ts"> interface Props { value?: string; placeholder?: string; maxlength?: number; } let { value = $bindable(''), placeholder = '', maxlength }: Props = $props(); </script> <input bind:value {placeholder} {maxlength} class=" pixel-input font-minecraft pixel-text w-full border-4 border-gray-600 bg-gray-800 px-4 py-3 text-center text-xl font-bold tracking-wider text-white uppercase transition-colors duration-200 placeholder:font-bold placeholder:text-gray-500 focus:border-cyan-400 focus:outline-none " style=" box-shadow: inset -4px -4px 0px rgba(0,0,0,0.3), inset 4px 4px 0px rgba(255,255,255,0.1), 4px 4px 0px rgba(0,0,0,0.4); " /> <style> .pixel-input { text-rendering: optimizeSpeed; -webkit-font-smoothing: none; -moz-osx-font-smoothing: grayscale; } .pixel-input:focus { animation: pixel-glow 1s ease-in-out infinite alternate; } @keyframes pixel-glow { from { box-shadow: inset -4px -4px 0px rgba(0, 0, 0, 0.3), inset 4px 4px 0px rgba(255, 255, 255, 0.1), 4px 4px 0px rgba(0, 0, 0, 0.4), 0 0 0 0 rgba(6, 182, 212, 0.7); } to { box-shadow: inset -4px -4px 0px rgba(0, 0, 0, 0.3), inset 4px 4px 0px rgba(255, 255, 255, 0.1), 4px 4px 0px rgba(0, 0, 0, 0.4), 0 0 0 4px rgba(6, 182, 212, 0.3); } } </style>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/constants/block-textures.ts
TypeScript
export enum WoolColor { White = 0, Orange = 1, Magenta = 2, LightBlue = 3, Yellow = 4, Lime = 5, Pink = 6, Gray = 7, LightGray = 8, Cyan = 9, Purple = 10, Blue = 11, Brown = 12, Green = 13, Red = 14, Black = 15, Air = 16 } export const BLOCK_TEXTURE_NAMES = [ 'white_wool', 'orange_wool', 'magenta_wool', 'light_blue_wool', 'yellow_wool', 'lime_wool', 'pink_wool', 'gray_wool', 'light_gray_wool', 'cyan_wool', 'purple_wool', 'blue_wool', 'brown_wool', 'green_wool', 'red_wool', 'black_wool' ] as const; export type BlockType = (typeof BLOCK_TEXTURE_NAMES)[number];
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/index.ts
TypeScript
// place files you want to import through the `$lib` alias in this folder.
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/player-state.svelte.ts
TypeScript
import type { PlayerOnBoard, PlayerPosition } from '$lib/types/player'; import type { WebSocketGameClient } from '$lib/api/websocket'; import { SvelteSet } from 'svelte/reactivity'; export type Direction = 'up' | 'down' | 'left' | 'right'; /** * Simplified player state management for WebSocket-based movement */ class PlayerState { activeDirections = $state<SvelteSet<Direction>>(new SvelteSet()); position = $state<PlayerPosition>({ x: 0, y: 0 }); playerId = $state<string | null>(null); private pressedKeys = new Set<string>(); private wsClient: WebSocketGameClient | null = null; private lastSyncedPosition: PlayerPosition = { x: 0, y: 0 }; private isInitialized = false; // Smooth movement physics private velocity = { x: 0, y: 0 }; private readonly ACCELERATION = 0.8; // Units per frame squared private readonly MAX_SPEED = 0.15; // Maximum velocity per frame private readonly FRICTION = 0.85; // Friction coefficient (0-1) private animationFrameId: number | null = null; private lastUpdateTime = 0; private lastPositionSent = { x: 0, y: 0 }; private readonly POSITION_SEND_INTERVAL = 100; // Send position every 100ms private lastPositionSentTime = 0; private keyDirectionMap: Record<string, Direction> = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right', w: 'up', s: 'down', a: 'left', d: 'right' }; private getDirectionFromKey(key: string): Direction | undefined { if (!key) { return undefined; } if (this.keyDirectionMap[key]) { return this.keyDirectionMap[key]; } const normalized = key.toLowerCase(); return this.keyDirectionMap[normalized]; } /** * Set the WebSocket client for sending position updates */ setWebSocketClient(client: WebSocketGameClient | null): void { this.wsClient = client; } /** * Start moving in a direction (smooth acceleration) */ triggerMove(direction: Direction): void { this.activeDirections.add(direction); this.startMovementLoop(); } /** * Stop moving in a direction */ clearDirection(direction: Direction): void { this.activeDirections.delete(direction); // Movement loop will handle deceleration when no directions are active } /** * Start the smooth movement animation loop */ private startMovementLoop(): void { if (this.animationFrameId !== null) { return; // Already running } this.lastUpdateTime = performance.now(); this.updateMovement(); } /** * Update player position with smooth physics */ private updateMovement = (): void => { const currentTime = performance.now(); const deltaTime = Math.min(currentTime - this.lastUpdateTime, 32) / 16.67; // Cap at ~60fps, normalize to 60fps this.lastUpdateTime = currentTime; // Calculate target velocity based on active directions const targetVelocity = { x: 0, y: 0 }; if (this.activeDirections.has('left')) targetVelocity.x -= 1; if (this.activeDirections.has('right')) targetVelocity.x += 1; if (this.activeDirections.has('up')) targetVelocity.y -= 1; if (this.activeDirections.has('down')) targetVelocity.y += 1; // Normalize diagonal movement const magnitude = Math.sqrt( targetVelocity.x * targetVelocity.x + targetVelocity.y * targetVelocity.y ); if (magnitude > 0) { targetVelocity.x = (targetVelocity.x / magnitude) * this.MAX_SPEED; targetVelocity.y = (targetVelocity.y / magnitude) * this.MAX_SPEED; } // Apply acceleration towards target velocity const accel = this.ACCELERATION * deltaTime; this.velocity.x += (targetVelocity.x - this.velocity.x) * accel; this.velocity.y += (targetVelocity.y - this.velocity.y) * accel; // Apply friction when no input if (magnitude === 0) { this.velocity.x *= Math.pow(this.FRICTION, deltaTime); this.velocity.y *= Math.pow(this.FRICTION, deltaTime); } // Update position this.position = { x: this.position.x + this.velocity.x * deltaTime, y: this.position.y + this.velocity.y * deltaTime }; // Send position update to server if enough time has passed and position changed significantly this.maybeSendPositionUpdate(); // Continue loop if there's movement or velocity const isMoving = this.activeDirections.size > 0 || Math.abs(this.velocity.x) > 0.001 || Math.abs(this.velocity.y) > 0.001; if (isMoving) { this.animationFrameId = requestAnimationFrame(this.updateMovement); } else { this.animationFrameId = null; // Send final position when stopped this.sendPositionUpdateNow(); } }; /** * Send position update to server if enough time has passed */ private maybeSendPositionUpdate(): void { const now = performance.now(); if (now - this.lastPositionSentTime < this.POSITION_SEND_INTERVAL) { return; } // Check if position changed significantly const distance = Math.abs(this.position.x - this.lastPositionSent.x) + Math.abs(this.position.y - this.lastPositionSent.y); if (distance > 0.1) { // Send if moved more than 0.1 units this.sendPositionUpdateNow(); } } /** * Send current position to server immediately */ private sendPositionUpdateNow(): void { if (this.wsClient && this.wsClient.getState() === 'connected') { const roundedX = Math.round(this.position.x * 100) / 100; const roundedY = Math.round(this.position.y * 100) / 100; this.wsClient.sendPlayerUpdate(roundedX, roundedY); // Track what we sent to avoid conflicts with server updates this.lastSyncedPosition = { x: roundedX, y: roundedY }; this.lastPositionSent = { x: roundedX, y: roundedY }; this.lastPositionSentTime = performance.now(); } } handleKeyDown(event: KeyboardEvent): void { const direction = this.getDirectionFromKey(event.key); if (!direction) { return; } if (this.pressedKeys.has(event.key)) { event.preventDefault(); return; } this.pressedKeys.add(event.key); event.preventDefault(); this.triggerMove(direction); } handleKeyUp(event: KeyboardEvent): void { const direction = this.getDirectionFromKey(event.key); this.pressedKeys.delete(event.key); if (!direction) { return; } this.clearDirection(direction); } clearPressedKeys(): void { this.pressedKeys.clear(); this.activeDirections.clear(); this.stopMovementLoop(); } /** * Update position from server game state * Only sync if this is the first time or if the server position differs significantly from what we sent */ syncWithServer(player: PlayerOnBoard | null): void { if (!player) { this.playerId = null; this.position = { x: 0, y: 0 }; this.lastSyncedPosition = { x: 0, y: 0 }; this.isInitialized = false; return; } // First time initialization if (!this.isInitialized || this.playerId !== player.id) { this.playerId = player.id; this.position = { x: player.position.x, y: player.position.y }; this.lastSyncedPosition = { x: player.position.x, y: player.position.y }; this.isInitialized = true; return; } // Check if server position differs significantly from what we last synced // This handles cases where the server may have corrected our position const distance = Math.abs(player.position.x - this.lastSyncedPosition.x) + Math.abs(player.position.y - this.lastSyncedPosition.y); if (distance > 2) { // Only sync if position differs by more than 2 units this.position = { x: player.position.x, y: player.position.y }; this.lastSyncedPosition = { x: player.position.x, y: player.position.y }; } } /** * Stop the movement animation loop */ private stopMovementLoop(): void { if (this.animationFrameId !== null) { cancelAnimationFrame(this.animationFrameId); this.animationFrameId = null; } } /** * Reset player state */ reset(): void { this.stopMovementLoop(); this.activeDirections.clear(); this.position = { x: 0, y: 0 }; this.playerId = null; this.pressedKeys.clear(); this.wsClient = null; this.lastSyncedPosition = { x: 0, y: 0 }; this.isInitialized = false; this.velocity = { x: 0, y: 0 }; this.lastUpdateTime = 0; this.lastPositionSent = { x: 0, y: 0 }; this.lastPositionSentTime = 0; } } export const playerState = new PlayerState();
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/types/game.ts
TypeScript
import type { PlayerSummary } from './player.js'; /** * Game phase enumeration representing the current state of the game */ export type GamePhase = 'pre-game' | 'in-game' | 'settlement'; /** * Player position coordinates in the game grid */ export interface GamePlayerPosition { pos_x: number; pos_y: number; } /** * Player object as received from the game state API */ export interface GamePlayer { name: string; position: GamePlayerPosition; is_spectator: boolean; is_eliminated: boolean; } /** * Main game state response structure from the API */ export interface GameStateResponse { game_id: string; phase: GamePhase; map: number[][]; players: GamePlayer[]; countdown_seconds: number | null; target_color: number; } /** * Extended game state with additional client-side properties */ export interface GameState extends GameStateResponse { /** Timestamp when the state was last updated */ lastUpdated?: number; /** Whether this is the current player's game */ isCurrentPlayerGame?: boolean; } /** * Game events that can occur during gameplay */ export type GameEvent = | { type: 'player_joined'; player: GamePlayer } | { type: 'player_left'; playerName: string } | { type: 'player_moved'; player: GamePlayer } | { type: 'player_eliminated'; playerName: string } | { type: 'phase_changed'; newPhase: GamePhase; countdown?: number } | { type: 'game_ended'; winners: string[] }; /** * Convert API GamePlayer to internal PlayerSummary format */ export function gamePlayerToPlayerSummary(gamePlayer: GamePlayer): PlayerSummary { return { id: gamePlayer.name, // Using name as ID since API doesn't provide separate ID name: gamePlayer.name, status: gamePlayer.is_spectator ? 'spectating' : gamePlayer.is_eliminated ? 'eliminated' : 'ingame', accent: '', // Default accent, can be set elsewhere position: { x: gamePlayer.position.pos_x, y: gamePlayer.position.pos_y } }; } /** * Convert internal PlayerSummary to API GamePlayer format */ export function playerSummaryToGamePlayer(player: PlayerSummary): GamePlayer { return { name: player.name, position: { pos_x: player.position?.x ?? 0, pos_y: player.position?.y ?? 0 }, is_spectator: player.status === 'spectating', is_eliminated: player.status === 'eliminated' }; } /** * Type guard to check if a phase is valid */ export function isValidGamePhase(phase: string): phase is GamePhase { return ['pre-game', 'in-game', 'settlement'].includes(phase); } /** * Get display name for game phase */ export function getPhaseDisplayName(phase: GamePhase): string { switch (phase) { case 'pre-game': return 'Waiting to Start'; case 'in-game': return 'Playing'; case 'settlement': return 'Game Over'; } }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/lib/types/player.ts
TypeScript
export type PlayerStatus = 'spectating' | 'ingame' | 'eliminated'; export interface PlayerPosition { /** * Zero-based column index within the game board grid. */ x: number; /** * Zero-based row index within the game board grid. */ y: number; } export interface PlayerSummary { id: string; name: string; status: PlayerStatus; accent: string; /** * Optional grid coordinate for rendering on the game board. */ position?: PlayerPosition; } export interface PlayerOnBoard extends PlayerSummary { position: PlayerPosition; }
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/routes/+layout.svelte
Svelte
<script lang="ts"> import favicon from '$lib/assets/favicon.svg'; import '../app.css'; let { children } = $props(); export const prerender = true; </script> <svelte:head> <link rel="icon" href={favicon} /> </svelte:head> {@render children?.()}
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/routes/+page.svelte
Svelte
<script lang="ts"> import { goto } from '$app/navigation'; import logo from '$lib/assets/blind-party.png'; import PixelButton from '../lib/components/ui/pixel-button.svelte'; import PixelInput from '../lib/components/ui/pixel-input.svelte'; import { createGame as apiCreateGame, HttpApiError } from '$lib/api/http'; let gameId = $state(''); let isCreating = $state(false); let createError = $state<string | null>(null); function joinGame() { if (gameId.trim()) { goto(`/game/${gameId.trim()}`); } } async function createGame() { isCreating = true; createError = null; try { const response = await apiCreateGame(); goto(`/game/${response.game_id}`); } catch (error) { if (error instanceof HttpApiError) { createError = error.message; } else { createError = error instanceof Error ? error.message : 'Failed to create game'; } } finally { isCreating = false; } } </script> <div class="flex min-h-screen flex-col items-center justify-center bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900 p-8" > <div class="flex w-full max-w-md flex-col items-center space-y-8"> <img src={logo} alt="Blind Party Logo" class="pixelated h-auto w-[32rem]" /> <div class="w-full space-y-4"> <PixelInput bind:value={gameId} placeholder="Enter Game ID" maxlength={10} /> <PixelButton variant="primary" disabled={!gameId.trim()} onclick={joinGame}> Join Game </PixelButton> <div class="flex items-center justify-center"> <div class="h-px flex-1 bg-slate-600"></div> <span class="px-4 text-sm text-slate-400">OR</span> <div class="h-px flex-1 bg-slate-600"></div> </div> <PixelButton variant="secondary" disabled={isCreating} onclick={createGame}> {isCreating ? 'Creating...' : 'Create New Game'} </PixelButton> {#if createError} <p class="text-center text-sm text-red-400">{createError}</p> {/if} </div> </div> </div> <style> .pixelated { image-rendering: pixelated; image-rendering: -moz-crisp-edges; image-rendering: crisp-edges; } </style>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/src/routes/game/[gameId]/+page.svelte
Svelte
<script lang="ts"> import { PUBLIC_API_BASE_URL, PUBLIC_WS_BASE_URL } from '$env/static/public'; import { createWebSocketClient, type WebSocketGameClient } from '$lib/api/websocket'; import CountdownOverlay from '$lib/components/game/countdown-overlay.svelte'; import GameBoardPanel from '$lib/components/game/game-board-panel.svelte'; import GameStatusBar from '$lib/components/game/game-status-bar.svelte'; import PlayerMovementControls from '$lib/components/game/player-movement-controls.svelte'; import PlayerRoster from '$lib/components/game/player-roster.svelte'; import TargetBlockIcon from '$lib/components/game/target-block-icon.svelte'; import JoinForm from '$lib/components/ui/join-form.svelte'; import { playerState } from '$lib/player-state.svelte.js'; import type { GameStateResponse, GameState } from '$lib/types/game'; import { gamePlayerToPlayerSummary } from '$lib/types/game'; import type { PlayerOnBoard, PlayerSummary } from '$lib/types/player'; import { onDestroy } from 'svelte'; interface Props { params: { gameId: string; }; } let { params }: Props = $props(); let isJoined = $state(false); let username = $state(''); let isConnecting = $state(false); let connectionError = $state<string | null>(null); let connectionState = $state('disconnected'); // WebSocket client let wsClient: WebSocketGameClient | null = null; // Game state from WebSocket let gameState = $state<GameState>({ game_id: '', phase: 'pre-game', players: [], map: [], countdown_seconds: null, target_color: 0, lastUpdated: Date.now() }); // Derived values for UI let players = $derived(gameState.players.map(gamePlayerToPlayerSummary)); let mapSize = $derived(Math.max(gameState.map.length || 10, gameState.map[0]?.length || 10)); let gameMap = $derived(gameState.map); let remainingSeconds = $derived(gameState.countdown_seconds || 0); // Player-specific derived values let selfPlayerSummary = $derived(players.find((p) => p.name === username) || null); // Use local player state position for immediate movement feedback let selfPlayerOnBoard = $derived.by(() => { if (!selfPlayerSummary || !selfPlayerSummary.position) { return null; } // Create player object with local position from playerState return { ...selfPlayerSummary, position: playerState.position } as PlayerOnBoard; }); let otherPlayersOnBoard = $derived( players.filter((p) => p.name !== username && p.position) as PlayerOnBoard[] ); function createWebSocketGameClient() { return createWebSocketClient({ autoReconnect: true, maxReconnectAttempts: 5, reconnectDelay: 1000, pingInterval: 30000 }); } function setupEventHandlers(client: WebSocketGameClient) { client.on('onStateChange', (state) => { connectionState = state; if (state === 'connected') { isJoined = true; } }); client.on('onGameUpdate', (updatedGameState) => { // Merge the updated state with existing state, keeping client-side properties gameState = { ...gameState, ...updatedGameState, lastUpdated: Date.now() }; // Sync player position with server const selfPlayerSummary = updatedGameState.players .map(gamePlayerToPlayerSummary) .find((p) => p.name === username); const selfPlayerOnBoard = selfPlayerSummary && selfPlayerSummary.position ? (selfPlayerSummary as PlayerOnBoard) : null; if (selfPlayerOnBoard) { playerState.syncWithServer(selfPlayerOnBoard); } }); client.on('onError', (error) => { connectionError = error; isConnecting = false; }); } async function joinGame() { if (!username.trim()) { connectionError = 'Please enter a username'; return; } isConnecting = true; connectionError = null; try { // Initialize WebSocket client wsClient = createWebSocketGameClient(); // Set up event listeners setupEventHandlers(wsClient); // Connect WebSocket client to player state playerState.setWebSocketClient(wsClient); // Connect to the game await wsClient.connect(params.gameId, username.trim()); console.log('[Game] WebSocket connected, initializing player state'); } catch (error) { connectionError = error instanceof Error ? error.message : 'Failed to connect to game'; isConnecting = false; } finally { isConnecting = false; } } // Cleanup on component destroy onDestroy(() => { if (wsClient) { wsClient.disconnect(); } playerState.reset(); }); </script> <div class="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900 text-white"> {#if !isJoined} <JoinForm {params} bind:username {isConnecting} {connectionError} {connectionState} onJoin={joinGame} /> {:else} <!-- Game interface --> <div class="mx-auto flex max-w-6xl flex-col gap-10 px-4 py-10 sm:px-6 sm:py-12"> <header class="flex flex-col gap-3 text-center lg:text-left"> <p class="text-sm tracking-[0.35em] text-blue-200/80 uppercase"> Blind Party - {username} </p> <h1 class="font-minecraft text-3xl tracking-wider text-yellow-300 uppercase drop-shadow-[4px_4px_0px_rgba(0,0,0,0.65)] sm:text-4xl" > Game ID: <span class="text-white">{params.gameId}</span> </h1> <p class="text-base text-blue-100/80"> {#if connectionState === 'connected'} Connected to game server - {gameState.phase} {:else} Connection status: {connectionState} {/if} </p> </header> {#if gameState.phase === 'pre-game'} <GameStatusBar label="Waiting for Players" displayText="{players.length}/4" progress={(players.length / 4) * 100} fillColor="#f59e0b" /> {:else if gameState.phase === 'in-game'} <GameStatusBar label="Game In Progress" displayText={remainingSeconds > 0 ? `${remainingSeconds}s` : 'Active'} progress={remainingSeconds > 0 ? (remainingSeconds / 30) * 100 : 100} fillColor="#3b82f6" /> {:else if gameState.phase === 'settlement'} <GameStatusBar label="Game Ended" displayText="Final Results" progress={100} fillColor="#10b981" /> {:else} <GameStatusBar label="Game Status" displayText="Ready" progress={100} fillColor="#22c55e" /> {/if} {#if remainingSeconds > 0} <CountdownOverlay {remainingSeconds} /> {/if} <div class="flex flex-col gap-8 lg:flex-row"> <div class="relative"> <GameBoardPanel {mapSize} {gameMap} players={otherPlayersOnBoard} selfPlayer={selfPlayerOnBoard} /> {#if gameState.phase === 'in-game'} <TargetBlockIcon targetBlock={gameState.target_color} /> {/if} </div> <!-- Show movement controls between board and roster on mobile --> <div class="lg:hidden"> <PlayerMovementControls /> </div> <PlayerRoster {players} selfPlayer={selfPlayerSummary} /> </div> <!-- Keep the original controls visible only on large screens (desktop) --> <div class="hidden lg:block"> <PlayerMovementControls /> </div> </div> {/if} </div>
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/svelte.config.js
JavaScript
import adapter from '@sveltejs/adapter-static'; import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: vitePreprocess(), kit: { adapter: adapter({ fallback: '404.html' }), paths: { base: process.argv.includes('dev') ? '' : process.env.BASE_PATH } } }; export default config;
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/tailwind.config.js
JavaScript
/** @type {import('tailwindcss').Config} */ export default { content: ['./src/**/*.{html,js,svelte,ts}'], theme: { extend: { fontFamily: { minecraft: ['Minecraft', 'Courier New', 'Lucida Console', 'monospace'], pixel: ['Minecraft', 'Courier New', 'Lucida Console', 'monospace'], mono: ['Minecraft', 'Courier New', 'Lucida Console', 'monospace'] } } }, plugins: [] };
yorukot/blind-party
3
Svelte
yorukot
Yorukot
frontend/vite.config.ts
TypeScript
import tailwindcss from '@tailwindcss/vite'; import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [tailwindcss(), sveltekit()] });
yorukot/blind-party
3
Svelte
yorukot
Yorukot
main.go
Go
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" "time" "github.com/joho/godotenv" "golang.org/x/net/html" ) const ( announcementURL = "https://www.csie.ntnu.edu.tw/index.php/category/news/announcement/" checkInterval = 1 * time.Minute stateFile = "last_announcements.json" ) var ( telegramBotToken string telegramChatID string discordWebhook string ) type Announcement struct { Title string `json:"title"` URL string `json:"url"` Timestamp string `json:"timestamp"` } func main() { // Load .env file if err := godotenv.Load(); err != nil { fmt.Println("⚠️ No .env file found, using environment variables") } // Load environment variables telegramBotToken = os.Getenv("TELEGRAM_BOT_TOKEN") telegramChatID = os.Getenv("TELEGRAM_CHAT_ID") discordWebhook = os.Getenv("DISCORD_WEBHOOK_URL") fmt.Println("🚀 NTNU CSIE Announcement Monitor Started") fmt.Printf("📍 Monitoring: %s\n", announcementURL) fmt.Printf("⏱️ Check interval: %v\n", checkInterval) // Check notification settings if telegramBotToken != "" && telegramChatID != "" { fmt.Println("✓ Telegram notifications enabled") } else { fmt.Println("✗ Telegram notifications disabled (set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID)") } if discordWebhook != "" { fmt.Println("✓ Discord notifications enabled") } else { fmt.Println("✗ Discord notifications disabled (set DISCORD_WEBHOOK_URL)") } fmt.Println(strings.Repeat("-", 70)) for { checkForNewAnnouncements() time.Sleep(checkInterval) } } func sendTelegramNotification(announcement Announcement) error { if telegramBotToken == "" || telegramChatID == "" { return nil // Skip if not configured } message := fmt.Sprintf("🔔 *NTNU CSIE 新公告*\n\n📢 %s\n\n🔗 %s", announcement.Title, announcement.URL) apiURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", telegramBotToken) payload := map[string]interface{}{ "chat_id": telegramChatID, "text": message, "parse_mode": "Markdown", } jsonData, err := json.Marshal(payload) if err != nil { return fmt.Errorf("failed to marshal telegram payload: %w", err) } resp, err := http.Post(apiURL, "application/json", bytes.NewBuffer(jsonData)) if err != nil { return fmt.Errorf("failed to send telegram message: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) return fmt.Errorf("telegram API error (status %d): %s", resp.StatusCode, string(body)) } return nil } func sendDiscordNotification(announcement Announcement) error { if discordWebhook == "" { return nil // Skip if not configured } payload := map[string]interface{}{ "embeds": []map[string]interface{}{ { "title": "🔔 NTNU CSIE 新公告", "description": announcement.Title, "url": announcement.URL, "color": 3447003, // Blue color "fields": []map[string]interface{}{ { "name": "連結", "value": fmt.Sprintf("[點擊查看](%s)", announcement.URL), }, }, "timestamp": time.Now().Format(time.RFC3339), }, }, } jsonData, err := json.Marshal(payload) if err != nil { return fmt.Errorf("failed to marshal discord payload: %w", err) } resp, err := http.Post(discordWebhook, "application/json", bytes.NewBuffer(jsonData)) if err != nil { return fmt.Errorf("failed to send discord message: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) return fmt.Errorf("discord webhook error (status %d): %s", resp.StatusCode, string(body)) } return nil } func fetchAnnouncements() ([]Announcement, error) { client := &http.Client{ Timeout: 10 * time.Second, } resp, err := client.Get(announcementURL) if err != nil { return nil, fmt.Errorf("failed to fetch page: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read response: %w", err) } doc, err := html.Parse(strings.NewReader(string(body))) if err != nil { return nil, fmt.Errorf("failed to parse HTML: %w", err) } announcements := extractAnnouncements(doc) return announcements, nil } func extractAnnouncements(n *html.Node) []Announcement { var announcements []Announcement var traverse func(*html.Node, bool) traverse = func(node *html.Node, inArticle bool) { // Check if this is an article tag with blog-entry class if node.Type == html.ElementNode && node.Data == "article" { hasClass := false for _, attr := range node.Attr { if attr.Key == "class" && strings.Contains(attr.Val, "blog-entry") { hasClass = true break } } if hasClass { inArticle = true } } // Look for links within article tags if node.Type == html.ElementNode && node.Data == "a" && inArticle { for _, attr := range node.Attr { if attr.Key == "href" { // NTNU uses date-based permalinks: /index.php/YYYY/MM/DD/slug/ // Filter to only include post permalinks, exclude category/page links if strings.Contains(attr.Val, "/index.php/") && !strings.Contains(attr.Val, "/category/") && !strings.Contains(attr.Val, "/page/") { // Get the text content of the link title := getTextContent(node) if title != "" && !strings.Contains(title, "上一頁") && !strings.Contains(title, "下一頁") && !strings.Contains(title, "Next") && !strings.Contains(title, "Previous") { fullURL := attr.Val if !strings.HasPrefix(fullURL, "http") { fullURL = "https://www.csie.ntnu.edu.tw" + fullURL } // Avoid duplicates isDuplicate := false for _, a := range announcements { if a.URL == fullURL { isDuplicate = true break } } if !isDuplicate && len(announcements) < 5 { announcements = append(announcements, Announcement{ Title: strings.TrimSpace(title), URL: fullURL, Timestamp: time.Now().Format(time.RFC3339), }) } } } } } } for child := node.FirstChild; child != nil; child = child.NextSibling { traverse(child, inArticle) } } traverse(n, false) return announcements } func getTextContent(n *html.Node) string { if n.Type == html.TextNode { return n.Data } var text string for c := n.FirstChild; c != nil; c = c.NextSibling { text += getTextContent(c) } return text } func loadPreviousAnnouncements() ([]Announcement, error) { data, err := os.ReadFile(stateFile) if err != nil { if os.IsNotExist(err) { return []Announcement{}, nil } return nil, err } var announcements []Announcement if err := json.Unmarshal(data, &announcements); err != nil { return nil, err } return announcements, nil } func saveAnnouncements(announcements []Announcement) error { data, err := json.MarshalIndent(announcements, "", " ") if err != nil { return err } return os.WriteFile(stateFile, data, 0644) } func checkForNewAnnouncements() { current, err := fetchAnnouncements() if err != nil { fmt.Printf("❌ Error fetching announcements: %v\n", err) return } previous, err := loadPreviousAnnouncements() if err != nil { fmt.Printf("⚠️ Warning: Could not load previous state: %v\n", err) previous = []Announcement{} } // First run if len(previous) == 0 { fmt.Printf("🔍 Initial check at %s\n", time.Now().Format("2006-01-02 15:04:05")) fmt.Printf(" Found %d announcements. Monitoring started...\n", len(current)) if err := saveAnnouncements(current); err != nil { fmt.Printf("⚠️ Warning: Could not save state: %v\n", err) } return } // Create a map of previous URLs for quick lookup previousURLs := make(map[string]bool) for _, a := range previous { previousURLs[a.URL] = true } // Find new announcements var newAnnouncements []Announcement for _, a := range current { if !previousURLs[a.URL] { newAnnouncements = append(newAnnouncements, a) } } if len(newAnnouncements) > 0 { fmt.Printf("\n🔔 NEW ANNOUNCEMENT(S) DETECTED at %s!\n", time.Now().Format("2006-01-02 15:04:05")) fmt.Println(strings.Repeat("=", 70)) for _, a := range newAnnouncements { fmt.Printf("\n📢 %s\n", a.Title) fmt.Printf(" 🔗 %s\n", a.URL) // Send notifications if err := sendTelegramNotification(a); err != nil { fmt.Printf("⚠️ Warning: Failed to send Telegram notification: %v\n", err) } else if telegramBotToken != "" && telegramChatID != "" { fmt.Println(" ✓ Telegram notification sent") } if err := sendDiscordNotification(a); err != nil { fmt.Printf("⚠️ Warning: Failed to send Discord notification: %v\n", err) } else if discordWebhook != "" { fmt.Println(" ✓ Discord notification sent") } } fmt.Println("\n" + strings.Repeat("=", 70)) if err := saveAnnouncements(current); err != nil { fmt.Printf("⚠️ Warning: Could not save state: %v\n", err) } } else { fmt.Printf("✓ Checked at %s - No new announcements\n", time.Now().Format("2006-01-02 15:04:05")) } }
yorukot/csie.ncu
0
Go
yorukot
Yorukot
internal/database/db.go
Go
package database import ( "fmt" "log" "os" "path/filepath" "github.com/yorukot/sharing/internal/models" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) var DB *gorm.DB // Initialize sets up the database connection and runs migrations func Initialize(dbPath string) error { // Ensure the database directory exists dbDir := filepath.Dir(dbPath) if err := os.MkdirAll(dbDir, 0755); err != nil { return fmt.Errorf("failed to create database directory: %w", err) } // Open database connection var err error DB, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) if err != nil { return fmt.Errorf("failed to connect to database: %w", err) } // Run auto-migration if err := DB.AutoMigrate(&models.File{}); err != nil { return fmt.Errorf("failed to run migrations: %w", err) } log.Println("Database initialized successfully") return nil } // Close closes the database connection func Close() error { sqlDB, err := DB.DB() if err != nil { return err } return sqlDB.Close() }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/handlers/api.go
Go
package handlers import ( "encoding/json" "errors" "io" "net/http" "strconv" "time" "github.com/go-chi/chi/v5" "github.com/yorukot/sharing/internal/services" "github.com/yorukot/sharing/internal/storage" ) // APIHandler handles API requests type APIHandler struct { fileService *services.FileService } // NewAPIHandler creates a new API handler func NewAPIHandler(storageBackend storage.Storage) *APIHandler { return &APIHandler{ fileService: services.NewFileService(storageBackend), } } // UploadRequest represents the upload request payload type UploadRequest struct { ExpiresAt *time.Time `json:"expires_at,omitempty"` Password *string `json:"password,omitempty"` } // UpdateRequest represents the update request payload type UpdateRequest struct { ExpiresAt *time.Time `json:"expires_at,omitempty"` Password *string `json:"password,omitempty"` Slug *string `json:"slug,omitempty"` } // ErrorResponse represents an error response type ErrorResponse struct { Error string `json:"error"` } // UploadFile handles file upload func (h *APIHandler) UploadFile(w http.ResponseWriter, r *http.Request) { // Parse multipart form (32 MB max) if err := r.ParseMultipartForm(32 << 20); err != nil { respondError(w, "Failed to parse form", http.StatusBadRequest) return } // Get file from form file, fileHeader, err := r.FormFile("file") if err != nil { respondError(w, "File is required", http.StatusBadRequest) return } defer file.Close() // Parse optional parameters var expiresAt *time.Time if expiresAtStr := r.FormValue("expires_at"); expiresAtStr != "" { t, err := time.Parse(time.RFC3339, expiresAtStr) if err != nil { respondError(w, "Invalid expires_at format (use RFC3339)", http.StatusBadRequest) return } expiresAt = &t } var password *string if pwd := r.FormValue("password"); pwd != "" { password = &pwd } var slug *string if s := r.FormValue("slug"); s != "" { slug = &s } // Parse replace parameter replace := r.FormValue("replace") == "true" // Save file savedFile, err := h.fileService.SaveFile(fileHeader, expiresAt, password, slug, replace) if err != nil { if errors.Is(err, services.ErrSlugTaken) { respondError(w, "Slug already taken", http.StatusConflict) return } if errors.Is(err, services.ErrInvalidSlug) { respondError(w, "Invalid slug format (use lowercase letters, numbers, and hyphens only)", http.StatusBadRequest) return } respondError(w, "Failed to save file: "+err.Error(), http.StatusInternalServerError) return } respondJSON(w, savedFile, http.StatusCreated) } // ListFiles handles listing all files func (h *APIHandler) ListFiles(w http.ResponseWriter, r *http.Request) { files, err := h.fileService.ListFiles() if err != nil { respondError(w, "Failed to list files: "+err.Error(), http.StatusInternalServerError) return } respondJSON(w, files, http.StatusOK) } // GetFile handles getting a single file's metadata func (h *APIHandler) GetFile(w http.ResponseWriter, r *http.Request) { id, err := getIDFromURL(r) if err != nil { respondError(w, err.Error(), http.StatusBadRequest) return } file, err := h.fileService.GetFile(id) if err != nil { if errors.Is(err, services.ErrFileNotFound) { respondError(w, "File not found", http.StatusNotFound) return } if errors.Is(err, services.ErrFileExpired) { respondError(w, "File has expired", http.StatusGone) return } respondError(w, "Failed to get file: "+err.Error(), http.StatusInternalServerError) return } respondJSON(w, file, http.StatusOK) } // UpdateFile handles updating file metadata func (h *APIHandler) UpdateFile(w http.ResponseWriter, r *http.Request) { id, err := getIDFromURL(r) if err != nil { respondError(w, err.Error(), http.StatusBadRequest) return } var req UpdateRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { respondError(w, "Invalid request body", http.StatusBadRequest) return } file, err := h.fileService.UpdateFile(id, req.ExpiresAt, req.Password, req.Slug) if err != nil { if errors.Is(err, services.ErrFileNotFound) { respondError(w, "File not found", http.StatusNotFound) return } if errors.Is(err, services.ErrFileExpired) { respondError(w, "File has expired", http.StatusGone) return } if errors.Is(err, services.ErrSlugTaken) { respondError(w, "Slug already taken", http.StatusConflict) return } if errors.Is(err, services.ErrInvalidSlug) { respondError(w, "Invalid slug format (use lowercase letters, numbers, and hyphens only)", http.StatusBadRequest) return } respondError(w, "Failed to update file: "+err.Error(), http.StatusInternalServerError) return } respondJSON(w, file, http.StatusOK) } // DeleteFile handles file deletion func (h *APIHandler) DeleteFile(w http.ResponseWriter, r *http.Request) { id, err := getIDFromURL(r) if err != nil { respondError(w, err.Error(), http.StatusBadRequest) return } if err := h.fileService.DeleteFile(id); err != nil { if errors.Is(err, services.ErrFileNotFound) { respondError(w, "File not found", http.StatusNotFound) return } respondError(w, "Failed to delete file: "+err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) } // DownloadFile handles file download with password validation func (h *APIHandler) DownloadFile(w http.ResponseWriter, r *http.Request) { id, err := getIDFromURL(r) if err != nil { respondError(w, err.Error(), http.StatusBadRequest) return } file, err := h.fileService.GetFile(id) if err != nil { if errors.Is(err, services.ErrFileNotFound) { respondError(w, "File not found", http.StatusNotFound) return } if errors.Is(err, services.ErrFileExpired) { respondError(w, "File has expired", http.StatusGone) return } respondError(w, "Failed to get file: "+err.Error(), http.StatusInternalServerError) return } // Validate password if required password := r.URL.Query().Get("password") if err := h.fileService.ValidatePassword(file, password); err != nil { if errors.Is(err, services.ErrPasswordRequired) { respondError(w, "Password required", http.StatusUnauthorized) return } if errors.Is(err, services.ErrInvalidPassword) { respondError(w, "Invalid password", http.StatusForbidden) return } respondError(w, "Password validation failed", http.StatusInternalServerError) return } // Set headers for file download w.Header().Set("Content-Disposition", "attachment; filename=\""+file.OriginalName+"\"") w.Header().Set("Content-Type", file.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(file.FileSize, 10)) // Get file reader from storage reader, err := h.fileService.GetFileReader(file) if err != nil { respondError(w, "Failed to read file", http.StatusInternalServerError) return } defer reader.Close() // Copy file content to response if _, err := io.Copy(w, reader); err != nil { // Log error but don't send response as headers already sent return } } // Helper functions func getIDFromURL(r *http.Request) (uint, error) { idStr := chi.URLParam(r, "id") if idStr == "" { return 0, errors.New("ID parameter is required") } id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { return 0, errors.New("invalid ID format") } return uint(id), nil } func respondJSON(w http.ResponseWriter, data interface{}, status int) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(data) } func respondError(w http.ResponseWriter, message string, status int) { respondJSON(w, ErrorResponse{Error: message}, status) }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/handlers/public.go
Go
package handlers import ( "errors" "html/template" "io" "net/http" "net/url" "strconv" "github.com/go-chi/chi/v5" "github.com/yorukot/sharing/internal/services" "github.com/yorukot/sharing/internal/storage" ) // PublicHandler handles public sharing routes (no API key required) type PublicHandler struct { fileService *services.FileService templates *template.Template } // NewPublicHandler creates a new public handler func NewPublicHandler(storageBackend storage.Storage) *PublicHandler { // Parse templates for public pages tmpl, err := template.ParseGlob("templates/*.html") if err != nil { // If templates don't exist yet, create empty template tmpl = template.New("public") } return &PublicHandler{ fileService: services.NewFileService(storageBackend), templates: tmpl, } } // renderPasswordPrompt renders a unified password prompt page func (h *PublicHandler) renderPasswordPrompt(w http.ResponseWriter, originalName, filename string, statusCode int) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(statusCode) w.Write([]byte(`<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Password Required</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; align-items: center; justify-content: center; min-height: 100vh; background: #f5f5f5; } .container { max-width: 450px; width: 90%; text-align: center; } h1 { font-size: 24px; font-weight: 600; color: #000; margin-bottom: 10px; } p { font-size: 14px; color: #666; margin-bottom: 30px; } input[type="password"] { width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; margin-bottom: 15px; background: white; } input[type="password"]:focus { outline: none; border-color: #3498db; } button { width: 100%; padding: 12px; background: #3498db; color: white; border: none; border-radius: 4px; font-size: 14px; font-weight: 500; cursor: pointer; transition: background 0.2s; } button:hover { background: #2980b9; } </style> </head> <body> <div class="container"> <h1>Password Required</h1> <p>This file is password protected.</p> <form onsubmit="download(event)"> <input type="password" id="pwd" placeholder="Enter password" required autofocus> <button type="submit">Download</button> </form> </div> <script> function download(e) { e.preventDefault(); const pwd = document.getElementById('pwd').value; window.location.href = '/d/` + originalName + `?password=' + encodeURIComponent(pwd); } </script> </body> </html>`)) } // SharePage redirects directly to download (with password prompt if needed) func (h *PublicHandler) SharePage(w http.ResponseWriter, r *http.Request) { slug := chi.URLParam(r, "slug") file, err := h.fileService.GetFileBySlug(slug) if err != nil { if errors.Is(err, services.ErrFileNotFound) { http.Error(w, "File not found", http.StatusNotFound) return } if errors.Is(err, services.ErrFileExpired) { http.Error(w, "This file has expired", http.StatusGone) return } http.Error(w, "Failed to load file", http.StatusInternalServerError) return } // If password protected, show simple password prompt if file.HasPassword() { // For password prompt, always use original filename in the /d/ URL h.renderPasswordPrompt(w, file.OriginalName, file.OriginalName, http.StatusOK) return } // No password, redirect directly to download using original filename // URL encode the filename to handle Unicode characters properly http.Redirect(w, r, "/d/"+url.PathEscape(file.OriginalName), http.StatusFound) } // DownloadByOriginalName handles file download via original filename (public, no API key required) func (h *PublicHandler) DownloadByOriginalName(w http.ResponseWriter, r *http.Request) { encodedFilename := chi.URLParam(r, "filename") // URL decode the filename to handle Unicode characters filename, err := url.QueryUnescape(encodedFilename) if err != nil { // If decoding fails, use the original filename = encodedFilename } file, err := h.fileService.GetFileByOriginalName(filename) if err != nil { if errors.Is(err, services.ErrFileNotFound) { http.Error(w, "File not found", http.StatusNotFound) return } if errors.Is(err, services.ErrFileExpired) { http.Error(w, "This file has expired", http.StatusGone) return } http.Error(w, "Failed to get file", http.StatusInternalServerError) return } // Validate password if required password := r.URL.Query().Get("password") if err := h.fileService.ValidatePassword(file, password); err != nil { if errors.Is(err, services.ErrPasswordRequired) { // Show password prompt page h.renderPasswordPrompt(w, file.OriginalName, file.OriginalName, http.StatusUnauthorized) return } if errors.Is(err, services.ErrInvalidPassword) { http.Error(w, "Invalid password", http.StatusForbidden) return } http.Error(w, "Password validation failed", http.StatusInternalServerError) return } // Set headers for inline viewing (browser preview instead of download) w.Header().Set("Content-Disposition", "inline; filename=\""+file.OriginalName+"\"") w.Header().Set("Content-Type", file.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(file.FileSize, 10)) // Get file reader from storage reader, err := h.fileService.GetFileReader(file) if err != nil { http.Error(w, "Failed to read file", http.StatusInternalServerError) return } defer reader.Close() // Copy file content to response if _, err := io.Copy(w, reader); err != nil { // Log error but don't send response as headers already sent return } }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/handlers/web.go
Go
package handlers import ( "errors" "html/template" "io" "net/http" "strconv" "time" "github.com/go-chi/chi/v5" "github.com/yorukot/sharing/internal/services" "github.com/yorukot/sharing/internal/storage" ) // WebHandler handles web UI requests type WebHandler struct { fileService *services.FileService templates *template.Template } // NewWebHandler creates a new web handler func NewWebHandler(storageBackend storage.Storage) *WebHandler { // Parse templates tmpl := template.Must(template.ParseGlob("templates/*.html")) return &WebHandler{ fileService: services.NewFileService(storageBackend), templates: tmpl, } } // Index renders the main page func (h *WebHandler) Index(w http.ResponseWriter, r *http.Request) { files, err := h.fileService.ListFiles() if err != nil { http.Error(w, "Failed to load files", http.StatusInternalServerError) return } data := struct { Files interface{} }{ Files: files, } if err := h.templates.ExecuteTemplate(w, "index.html", data); err != nil { http.Error(w, "Template error", http.StatusInternalServerError) return } } // UploadFileWeb handles file upload from web UI func (h *WebHandler) UploadFileWeb(w http.ResponseWriter, r *http.Request) { // Parse multipart form (32 MB max) if err := r.ParseMultipartForm(32 << 20); err != nil { http.Error(w, "Failed to parse form", http.StatusBadRequest) return } // Get file from form file, fileHeader, err := r.FormFile("file") if err != nil { http.Error(w, "File is required", http.StatusBadRequest) return } defer file.Close() // Parse optional parameters var expiresAt *time.Time if expiresAtStr := r.FormValue("expires_at"); expiresAtStr != "" { t, err := time.Parse("2006-01-02T15:04", expiresAtStr) if err != nil { http.Error(w, "Invalid expiry date format", http.StatusBadRequest) return } expiresAt = &t } var password *string if pwd := r.FormValue("password"); pwd != "" { password = &pwd } var slug *string if s := r.FormValue("slug"); s != "" { slug = &s } // Parse replace parameter replace := r.FormValue("replace") == "true" // Save file _, err = h.fileService.SaveFile(fileHeader, expiresAt, password, slug, replace) if err != nil { if errors.Is(err, services.ErrSlugTaken) { http.Error(w, "Slug already taken", http.StatusConflict) return } if errors.Is(err, services.ErrInvalidSlug) { http.Error(w, "Invalid slug format (use lowercase letters, numbers, and hyphens only)", http.StatusBadRequest) return } http.Error(w, "Failed to save file: "+err.Error(), http.StatusInternalServerError) return } // Return updated file list h.FileList(w, r) } // FileList returns the file list HTML fragment func (h *WebHandler) FileList(w http.ResponseWriter, r *http.Request) { files, err := h.fileService.ListFiles() if err != nil { http.Error(w, "Failed to load files", http.StatusInternalServerError) return } data := struct { Files interface{} }{ Files: files, } if err := h.templates.ExecuteTemplate(w, "file-list", data); err != nil { http.Error(w, "Template error", http.StatusInternalServerError) return } } // DeleteFileWeb handles file deletion from web UI func (h *WebHandler) DeleteFileWeb(w http.ResponseWriter, r *http.Request) { idStr := chi.URLParam(r, "id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { http.Error(w, "Invalid ID", http.StatusBadRequest) return } if err := h.fileService.DeleteFile(uint(id)); err != nil { if errors.Is(err, services.ErrFileNotFound) { http.Error(w, "File not found", http.StatusNotFound) return } http.Error(w, "Failed to delete file", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } // EditForm returns the edit form for a file func (h *WebHandler) EditForm(w http.ResponseWriter, r *http.Request) { idStr := chi.URLParam(r, "id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { http.Error(w, "Invalid ID", http.StatusBadRequest) return } file, err := h.fileService.GetFile(uint(id)) if err != nil { http.Error(w, "File not found", http.StatusNotFound) return } data := struct { File interface{} }{ File: file, } if err := h.templates.ExecuteTemplate(w, "edit-form", data); err != nil { http.Error(w, "Template error", http.StatusInternalServerError) return } } // UpdateFileWeb handles file update from web UI func (h *WebHandler) UpdateFileWeb(w http.ResponseWriter, r *http.Request) { idStr := chi.URLParam(r, "id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { http.Error(w, "Invalid ID", http.StatusBadRequest) return } if err := r.ParseForm(); err != nil { http.Error(w, "Failed to parse form", http.StatusBadRequest) return } var expiresAt *time.Time if expiresAtStr := r.FormValue("expires_at"); expiresAtStr != "" { t, err := time.Parse("2006-01-02T15:04", expiresAtStr) if err != nil { http.Error(w, "Invalid expiry date format", http.StatusBadRequest) return } expiresAt = &t } var password *string if pwd := r.FormValue("password"); pwd != "" { password = &pwd } var slug *string if s := r.FormValue("slug"); s != "" { slug = &s } file, err := h.fileService.UpdateFile(uint(id), expiresAt, password, slug) if err != nil { if errors.Is(err, services.ErrSlugTaken) { http.Error(w, "Slug already taken", http.StatusConflict) return } if errors.Is(err, services.ErrInvalidSlug) { http.Error(w, "Invalid slug format", http.StatusBadRequest) return } http.Error(w, "Failed to update file", http.StatusInternalServerError) return } data := struct { File interface{} }{ File: file, } if err := h.templates.ExecuteTemplate(w, "file-row", data); err != nil { http.Error(w, "Template error", http.StatusInternalServerError) return } } // DownloadFileWeb handles file download from web UI func (h *WebHandler) DownloadFileWeb(w http.ResponseWriter, r *http.Request) { idStr := chi.URLParam(r, "id") id, err := strconv.ParseUint(idStr, 10, 32) if err != nil { http.Error(w, "Invalid ID", http.StatusBadRequest) return } file, err := h.fileService.GetFile(uint(id)) if err != nil { if errors.Is(err, services.ErrFileNotFound) { http.Error(w, "File not found", http.StatusNotFound) return } if errors.Is(err, services.ErrFileExpired) { http.Error(w, "File has expired", http.StatusGone) return } http.Error(w, "Failed to get file", http.StatusInternalServerError) return } // Check if password is required if file.HasPassword() { password := r.URL.Query().Get("password") if password == "" { // Return password prompt data := struct { FileID uint }{ FileID: file.ID, } if err := h.templates.ExecuteTemplate(w, "password-prompt", data); err != nil { http.Error(w, "Template error", http.StatusInternalServerError) } return } // Validate password if err := h.fileService.ValidatePassword(file, password); err != nil { http.Error(w, "Invalid password", http.StatusForbidden) return } } // Set headers for file download w.Header().Set("Content-Disposition", "attachment; filename=\""+file.OriginalName+"\"") w.Header().Set("Content-Type", file.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(file.FileSize, 10)) // Get file reader from storage reader, err := h.fileService.GetFileReader(file) if err != nil { http.Error(w, "Failed to read file", http.StatusInternalServerError) return } defer reader.Close() // Copy file content to response if _, err := io.Copy(w, reader); err != nil { // Log error but don't send response as headers already sent return } }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/middleware/auth.go
Go
package middleware import ( "net/http" "os" ) // APIKeyAuth validates the API key from the request header func APIKeyAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { apiKey := r.Header.Get("X-API-Key") expectedKey := os.Getenv("API_KEY") if expectedKey == "" { http.Error(w, "Server configuration error: API key not set", http.StatusInternalServerError) return } if apiKey == "" { http.Error(w, "API key required", http.StatusUnauthorized) return } if apiKey != expectedKey { http.Error(w, "Invalid API key", http.StatusForbidden) return } next.ServeHTTP(w, r) }) }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/models/file.go
Go
package models import ( "time" "gorm.io/gorm" ) // File represents a shared file in the system type File struct { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt gorm.DeletedAt `gorm:"index;uniqueIndex:idx_slug_deleted;uniqueIndex:idx_filename_deleted" json:"-"` // File metadata Filename string `gorm:"uniqueIndex:idx_filename_deleted;not null" json:"filename"` // Unique stored filename OriginalName string `gorm:"not null" json:"original_name"` // Original uploaded filename FilePath string `gorm:"not null" json:"-"` // Full path on disk FileSize int64 `gorm:"not null" json:"file_size"` // Size in bytes ContentType string `gorm:"not null" json:"content_type"` // MIME type // Short link / slug for public sharing Slug string `gorm:"uniqueIndex:idx_slug_deleted;not null" json:"slug"` // URL-safe short link (e.g., "demo-file") // Security and access control PasswordHash *string `json:"-"` // Bcrypt hash (nullable) ExpiresAt *time.Time `gorm:"index" json:"expires_at,omitempty"` // Expiration time (nullable) } // IsExpired checks if the file has expired func (f *File) IsExpired() bool { if f.ExpiresAt == nil { return false } return time.Now().After(*f.ExpiresAt) } // HasPassword checks if the file is password protected func (f *File) HasPassword() bool { return f.PasswordHash != nil && *f.PasswordHash != "" }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/services/file.go
Go
package services import ( "crypto/rand" "encoding/hex" "errors" "fmt" "io" "mime/multipart" "path/filepath" "regexp" "strings" "time" "github.com/yorukot/sharing/internal/database" "github.com/yorukot/sharing/internal/models" "github.com/yorukot/sharing/internal/storage" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" ) var ( ErrFileNotFound = errors.New("file not found") ErrFileExpired = errors.New("file has expired") ErrInvalidPassword = errors.New("invalid password") ErrPasswordRequired = errors.New("password required") ErrSlugTaken = errors.New("slug already taken") ErrInvalidSlug = errors.New("invalid slug format") ) var slugRegex = regexp.MustCompile(`^[a-zA-Z0-9\p{L}\p{N}._-]+$`) // FileService handles file operations type FileService struct { storage storage.Storage } // NewFileService creates a new file service instance func NewFileService(storageBackend storage.Storage) *FileService { return &FileService{ storage: storageBackend, } } // SaveFile saves an uploaded file to storage and creates a database record // If replace is true and a file with the same original name exists, it will replace that file's content func (s *FileService) SaveFile(fileHeader *multipart.FileHeader, expiresAt *time.Time, password *string, slug *string, replace bool) (*models.File, error) { // Check if we should replace an existing file if replace { existingFile, err := s.GetFileByOriginalName(fileHeader.Filename) if err == nil { // File exists, replace it return s.ReplaceFileByOriginalName(existingFile, fileHeader) } // File doesn't exist or error occurred, continue with normal save // (errors other than ErrFileNotFound will be caught later) } // Generate unique filename uniqueFilename, err := s.generateUniqueFilename(fileHeader.Filename) if err != nil { return nil, fmt.Errorf("failed to generate filename: %w", err) } // Open uploaded file src, err := fileHeader.Open() if err != nil { return nil, fmt.Errorf("failed to open uploaded file: %w", err) } defer src.Close() // Save to storage backend storagePath, err := s.storage.Save(src, uniqueFilename, fileHeader.Size) if err != nil { return nil, fmt.Errorf("failed to save file to storage: %w", err) } // Hash password if provided var passwordHash *string if password != nil && *password != "" { hash, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost) if err != nil { s.storage.Delete(storagePath) // Clean up on error return nil, fmt.Errorf("failed to hash password: %w", err) } hashStr := string(hash) passwordHash = &hashStr } // Generate or validate slug var fileSlug string var uniqueOriginalName string if slug != nil && *slug != "" { // User provided custom slug - validate and check uniqueness if err := s.validateSlug(*slug); err != nil { s.storage.Delete(storagePath) // Clean up on error return nil, err } if err := s.checkSlugUnique(*slug); err != nil { s.storage.Delete(storagePath) // Clean up on error return nil, err } fileSlug = *slug // Make original filename unique if duplicate exists uniqueOriginalName = s.makeOriginalNameUnique(fileHeader.Filename, uniqueFilename) } else { // No custom slug provided - use original filename as slug // Make both slug and original name unique together (same value) uniqueOriginalName, err = s.makeFilenameAndSlugUnique(fileHeader.Filename, uniqueFilename) if err != nil { s.storage.Delete(storagePath) // Clean up on error return nil, fmt.Errorf("failed to generate unique filename: %w", err) } fileSlug = uniqueOriginalName // Slug is the same as the unique original name } // Create database record file := &models.File{ Filename: uniqueFilename, OriginalName: uniqueOriginalName, FilePath: storagePath, FileSize: fileHeader.Size, ContentType: fileHeader.Header.Get("Content-Type"), Slug: fileSlug, PasswordHash: passwordHash, ExpiresAt: expiresAt, } if err := database.DB.Create(file).Error; err != nil { s.storage.Delete(storagePath) // Clean up on error return nil, fmt.Errorf("failed to create database record: %w", err) } return file, nil } // GetFile retrieves a file by ID func (s *FileService) GetFile(id uint) (*models.File, error) { var file models.File if err := database.DB.First(&file, id).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrFileNotFound } return nil, err } if file.IsExpired() { return nil, ErrFileExpired } return &file, nil } // GetFileBySlug retrieves a file by its slug func (s *FileService) GetFileBySlug(slug string) (*models.File, error) { var file models.File if err := database.DB.Where("slug = ?", slug).First(&file).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrFileNotFound } return nil, err } if file.IsExpired() { return nil, ErrFileExpired } return &file, nil } // GetFileByOriginalName retrieves a file by its original filename func (s *FileService) GetFileByOriginalName(originalName string) (*models.File, error) { var file models.File if err := database.DB.Where("original_name = ?", originalName).First(&file).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrFileNotFound } return nil, err } if file.IsExpired() { return nil, ErrFileExpired } return &file, nil } // ListFiles retrieves all non-expired files func (s *FileService) ListFiles() ([]models.File, error) { var files []models.File if err := database.DB.Where("expires_at IS NULL OR expires_at > ?", time.Now()). Order("created_at DESC"). Find(&files).Error; err != nil { return nil, err } return files, nil } // UpdateFile updates a file's expiry date, password, and/or slug func (s *FileService) UpdateFile(id uint, expiresAt *time.Time, password *string, slug *string) (*models.File, error) { file, err := s.GetFile(id) if err != nil { return nil, err } updates := make(map[string]interface{}) // Update expiry date if expiresAt != nil { updates["expires_at"] = expiresAt } // Update password if password != nil { if *password == "" { // Remove password protection updates["password_hash"] = nil } else { // Set new password hash, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost) if err != nil { return nil, fmt.Errorf("failed to hash password: %w", err) } updates["password_hash"] = string(hash) } } // Update slug if slug != nil && *slug != "" && *slug != file.Slug { // Validate new slug if err := s.validateSlug(*slug); err != nil { return nil, err } // Check if slug is unique (excluding current file and soft-deleted files) var count int64 database.DB.Model(&models.File{}).Where("slug = ? AND id != ? AND deleted_at IS NULL", *slug, id).Count(&count) if count > 0 { return nil, ErrSlugTaken } updates["slug"] = *slug } if err := database.DB.Model(file).Updates(updates).Error; err != nil { return nil, fmt.Errorf("failed to update file: %w", err) } // Reload to get updated values return s.GetFile(id) } // DeleteFile deletes a file from storage and database func (s *FileService) DeleteFile(id uint) error { file, err := s.GetFile(id) if err != nil { return err } // Delete file from storage if err := s.storage.Delete(file.FilePath); err != nil { return fmt.Errorf("failed to delete file from storage: %w", err) } // Delete from database (soft delete) if err := database.DB.Delete(file).Error; err != nil { return fmt.Errorf("failed to delete from database: %w", err) } return nil } // GetFileReader returns a reader for the file content from storage func (s *FileService) GetFileReader(file *models.File) (io.ReadCloser, error) { return s.storage.Get(file.FilePath) } // ValidatePassword checks if the provided password matches the file's password hash func (s *FileService) ValidatePassword(file *models.File, password string) error { if !file.HasPassword() { return nil // No password protection } if password == "" { return ErrPasswordRequired } if err := bcrypt.CompareHashAndPassword([]byte(*file.PasswordHash), []byte(password)); err != nil { return ErrInvalidPassword } return nil } // ReplaceFileByOriginalName replaces an existing file's content while preserving metadata func (s *FileService) ReplaceFileByOriginalName(existingFile *models.File, fileHeader *multipart.FileHeader) (*models.File, error) { // Generate new unique filename uniqueFilename, err := s.generateUniqueFilename(fileHeader.Filename) if err != nil { return nil, fmt.Errorf("failed to generate filename: %w", err) } // Open uploaded file src, err := fileHeader.Open() if err != nil { return nil, fmt.Errorf("failed to open uploaded file: %w", err) } defer src.Close() // Save new file to storage backend storagePath, err := s.storage.Save(src, uniqueFilename, fileHeader.Size) if err != nil { return nil, fmt.Errorf("failed to save file to storage: %w", err) } // Delete old file from storage if err := s.storage.Delete(existingFile.FilePath); err != nil { // Try to clean up new file if old deletion fails s.storage.Delete(storagePath) return nil, fmt.Errorf("failed to delete old file from storage: %w", err) } // Update database record with new file details updates := map[string]interface{}{ "filename": uniqueFilename, "file_path": storagePath, "file_size": fileHeader.Size, "content_type": fileHeader.Header.Get("Content-Type"), } if err := database.DB.Model(existingFile).Updates(updates).Error; err != nil { // Old file is already deleted, so we can't fully rollback return nil, fmt.Errorf("failed to update database record: %w", err) } // Reload to get updated values return s.GetFile(existingFile.ID) } // CleanupExpiredFiles removes expired files from storage and database func (s *FileService) CleanupExpiredFiles() error { var expiredFiles []models.File if err := database.DB.Where("expires_at IS NOT NULL AND expires_at <= ?", time.Now()). Find(&expiredFiles).Error; err != nil { return err } for _, file := range expiredFiles { // Delete file from storage if err := s.storage.Delete(file.FilePath); err != nil { // Log error but continue fmt.Printf("Warning: failed to delete expired file %s: %v\n", file.FilePath, err) } // Delete from database if err := database.DB.Delete(&file).Error; err != nil { fmt.Printf("Warning: failed to delete expired file record %d: %v\n", file.ID, err) } } return nil } // generateUniqueFilename creates a unique filename with the original extension func (s *FileService) generateUniqueFilename(originalName string) (string, error) { // Generate random bytes randomBytes := make([]byte, 16) if _, err := rand.Read(randomBytes); err != nil { return "", err } // Convert to hex string uniqueID := hex.EncodeToString(randomBytes) // Preserve original extension ext := filepath.Ext(originalName) return uniqueID + ext, nil } // makeOriginalNameUnique ensures the original filename is unique by appending hex prefix if needed func (s *FileService) makeOriginalNameUnique(originalName, uniqueFilename string) string { // Check if original name already exists (excluding soft-deleted) var count int64 database.DB.Model(&models.File{}).Where("original_name = ? AND deleted_at IS NULL", originalName).Count(&count) if count == 0 { // No duplicate, return as-is return originalName } // Duplicate found - append first 5 chars of unique filename ext := filepath.Ext(originalName) basename := strings.TrimSuffix(originalName, ext) // Extract first 5 chars from the hex filename (excluding extension) hexFilename := strings.TrimSuffix(uniqueFilename, filepath.Ext(uniqueFilename)) prefix := "" if len(hexFilename) >= 5 { prefix = hexFilename[:5] } else { prefix = hexFilename } return fmt.Sprintf("%s-%s%s", basename, prefix, ext) } // makeFilenameAndSlugUnique ensures both the original filename and slug are unique (returns same value for both) func (s *FileService) makeFilenameAndSlugUnique(originalName, uniqueFilename string) (string, error) { // Check if original name already exists in either original_name or slug columns (excluding soft-deleted) var count int64 database.DB.Model(&models.File{}).Where("(original_name = ? OR slug = ?) AND deleted_at IS NULL", originalName, originalName).Count(&count) if count == 0 { // No duplicate, return as-is return originalName, nil } // Duplicate found - append random suffix before extension ext := filepath.Ext(originalName) basename := strings.TrimSuffix(originalName, ext) // Try up to 100 times to find a unique name for i := 0; i < 100; i++ { // Generate random suffix randomBytes := make([]byte, 2) if _, err := rand.Read(randomBytes); err != nil { return "", err } suffix := hex.EncodeToString(randomBytes) uniqueName := fmt.Sprintf("%s-%s%s", basename, suffix, ext) // Check if this is unique (excluding soft-deleted) database.DB.Model(&models.File{}).Where("(original_name = ? OR slug = ?) AND deleted_at IS NULL", uniqueName, uniqueName).Count(&count) if count == 0 { return uniqueName, nil } } return "", fmt.Errorf("failed to generate unique filename after 100 attempts") } // validateSlug checks if a slug is in valid format func (s *FileService) validateSlug(slug string) error { if len(slug) < 1 || len(slug) > 100 { return ErrInvalidSlug } if !slugRegex.MatchString(slug) { return ErrInvalidSlug } return nil } // checkSlugUnique checks if a slug is already taken func (s *FileService) checkSlugUnique(slug string) error { var count int64 database.DB.Model(&models.File{}).Where("slug = ? AND deleted_at IS NULL", slug).Count(&count) if count > 0 { return ErrSlugTaken } return nil } // generateSlugFromFilename creates a URL-safe slug from a filename func (s *FileService) generateSlugFromFilename(filename string) (string, error) { // Keep the full filename including extension as the slug slug := filename // Replace spaces and underscores with hyphens slug = strings.ReplaceAll(slug, " ", "-") slug = strings.ReplaceAll(slug, "_", "-") // Remove consecutive hyphens slug = regexp.MustCompile(`-+`).ReplaceAllString(slug, "-") // Trim hyphens from start and end slug = strings.Trim(slug, "-") // If slug is empty, generate random if slug == "" { randomBytes := make([]byte, 4) rand.Read(randomBytes) slug = "file-" + hex.EncodeToString(randomBytes) } // Make unique by appending random suffix if taken originalSlug := slug for i := 0; i < 100; i++ { if err := s.checkSlugUnique(slug); err == nil { return slug, nil } // Append random suffix (before extension if it exists) ext := filepath.Ext(originalSlug) basename := strings.TrimSuffix(originalSlug, ext) randomBytes := make([]byte, 2) rand.Read(randomBytes) slug = basename + "-" + hex.EncodeToString(randomBytes) + ext } return "", fmt.Errorf("failed to generate unique slug") }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/storage/local.go
Go
package storage import ( "fmt" "io" "os" "path/filepath" ) // LocalStorage implements the Storage interface using the local filesystem type LocalStorage struct { dataDir string } // NewLocalStorage creates a new local filesystem storage backend func NewLocalStorage(dataDir string) (*LocalStorage, error) { // Ensure data directory exists if err := os.MkdirAll(dataDir, 0755); err != nil { return nil, fmt.Errorf("failed to create data directory: %w", err) } return &LocalStorage{ dataDir: dataDir, }, nil } // Save saves a file to the local filesystem func (l *LocalStorage) Save(reader io.Reader, filename string, size int64) (string, error) { filePath := filepath.Join(l.dataDir, filename) // Create destination file dst, err := os.Create(filePath) if err != nil { return "", fmt.Errorf("failed to create file: %w", err) } defer dst.Close() // Copy file contents if _, err := io.Copy(dst, reader); err != nil { os.Remove(filePath) // Clean up on error return "", fmt.Errorf("failed to save file: %w", err) } return filePath, nil } // Get retrieves a file from the local filesystem func (l *LocalStorage) Get(path string) (io.ReadCloser, error) { file, err := os.Open(path) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("file not found: %w", err) } return nil, fmt.Errorf("failed to open file: %w", err) } return file, nil } // Delete removes a file from the local filesystem func (l *LocalStorage) Delete(path string) error { if err := os.Remove(path); err != nil && !os.IsNotExist(err) { return fmt.Errorf("failed to delete file: %w", err) } return nil } // Exists checks if a file exists on the local filesystem func (l *LocalStorage) Exists(path string) (bool, error) { _, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { return false, nil } return false, fmt.Errorf("failed to check file existence: %w", err) } return true, nil }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/storage/s3.go
Go
package storage import ( "context" "fmt" "io" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" ) // S3Storage implements the Storage interface using S3-compatible storage type S3Storage struct { client *s3.Client bucket string } // S3Config holds configuration for S3 storage type S3Config struct { Endpoint string Bucket string Region string AccessKeyID string SecretAccessKey string UsePathStyle bool } // NewS3Storage creates a new S3 storage backend func NewS3Storage(config S3Config) (*S3Storage, error) { // Create custom resolver for endpoint customResolver := aws.EndpointResolverWithOptionsFunc( func(service, region string, options ...interface{}) (aws.Endpoint, error) { if config.Endpoint != "" { return aws.Endpoint{ URL: config.Endpoint, HostnameImmutable: true, Source: aws.EndpointSourceCustom, }, nil } // Return empty endpoint to use default return aws.Endpoint{}, &aws.EndpointNotFoundError{} }, ) // Create AWS config cfg := aws.Config{ Region: config.Region, Credentials: credentials.NewStaticCredentialsProvider( config.AccessKeyID, config.SecretAccessKey, "", ), EndpointResolverWithOptions: customResolver, } // Create S3 client client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.UsePathStyle = config.UsePathStyle }) return &S3Storage{ client: client, bucket: config.Bucket, }, nil } // Save uploads a file to S3 func (s *S3Storage) Save(reader io.Reader, filename string, size int64) (string, error) { ctx := context.Background() // Use filename as the S3 key key := filename _, err := s.client.PutObject(ctx, &s3.PutObjectInput{ Bucket: aws.String(s.bucket), Key: aws.String(key), Body: reader, }) if err != nil { return "", fmt.Errorf("failed to upload to S3: %w", err) } return key, nil } // Get downloads a file from S3 func (s *S3Storage) Get(path string) (io.ReadCloser, error) { ctx := context.Background() result, err := s.client.GetObject(ctx, &s3.GetObjectInput{ Bucket: aws.String(s.bucket), Key: aws.String(path), }) if err != nil { return nil, fmt.Errorf("failed to download from S3: %w", err) } return result.Body, nil } // Delete removes a file from S3 func (s *S3Storage) Delete(path string) error { ctx := context.Background() _, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{ Bucket: aws.String(s.bucket), Key: aws.String(path), }) if err != nil { return fmt.Errorf("failed to delete from S3: %w", err) } return nil } // Exists checks if a file exists in S3 func (s *S3Storage) Exists(path string) (bool, error) { ctx := context.Background() _, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{ Bucket: aws.String(s.bucket), Key: aws.String(path), }) if err != nil { // Check if error is "not found" return false, nil } return true, nil }
yorukot/sharing
2
Go
yorukot
Yorukot
internal/storage/storage.go
Go
package storage import ( "io" ) // Storage defines the interface for file storage backends type Storage interface { // Save saves a file with the given filename and returns the storage path/key Save(reader io.Reader, filename string, size int64) (string, error) // Get retrieves a file by its storage path/key and returns a reader Get(path string) (io.ReadCloser, error) // Delete removes a file from storage Delete(path string) error // Exists checks if a file exists in storage Exists(path string) (bool, error) }
yorukot/sharing
2
Go
yorukot
Yorukot
main.go
Go
package main import ( "fmt" "log" "net/http" "os" "strconv" "strings" "time" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/joho/godotenv" "github.com/yorukot/sharing/internal/database" "github.com/yorukot/sharing/internal/handlers" mw "github.com/yorukot/sharing/internal/middleware" "github.com/yorukot/sharing/internal/services" "github.com/yorukot/sharing/internal/storage" ) func main() { // Load environment variables if err := godotenv.Load(); err != nil { log.Println("Warning: .env file not found, using system environment variables") } // Get configuration from environment port := os.Getenv("PORT") if port == "" { port = "8080" } dbPath := os.Getenv("DB_PATH") if dbPath == "" { dbPath = "./data/sharing.db" } // Initialize storage backend storageBackend, err := initializeStorage() if err != nil { log.Fatalf("Failed to initialize storage: %v", err) } // Initialize database if err := database.Initialize(dbPath); err != nil { log.Fatalf("Failed to initialize database: %v", err) } defer database.Close() // Initialize file service with storage backend fileService := services.NewFileService(storageBackend) // Start background cleanup job startCleanupJob(fileService) // Initialize handlers apiHandler := handlers.NewAPIHandler(storageBackend) webHandler := handlers.NewWebHandler(storageBackend) publicHandler := handlers.NewPublicHandler(storageBackend) // Setup router r := chi.NewRouter() // Global middleware r.Use(middleware.Logger) r.Use(middleware.Recoverer) r.Use(middleware.RealIP) r.Use(middleware.Compress(5)) // API routes (protected with API key) r.Route("/api", func(r chi.Router) { r.Use(mw.APIKeyAuth) r.Post("/upload", apiHandler.UploadFile) r.Get("/files", apiHandler.ListFiles) r.Get("/files/{id}", apiHandler.GetFile) r.Patch("/files/{id}", apiHandler.UpdateFile) r.Delete("/files/{id}", apiHandler.DeleteFile) r.Get("/download/{id}", apiHandler.DownloadFile) }) // Web routes (protected with API key for management) r.Route("/web", func(r chi.Router) { // Public index page (shows login if not authenticated) r.Get("/", webHandler.Index) // Protected management routes r.Group(func(r chi.Router) { r.Use(mw.APIKeyAuth) r.Post("/upload", webHandler.UploadFileWeb) r.Get("/files", webHandler.FileList) r.Get("/edit/{id}", webHandler.EditForm) r.Post("/update/{id}", webHandler.UpdateFileWeb) r.Delete("/files/{id}", webHandler.DeleteFileWeb) r.Get("/download/{id}", webHandler.DownloadFileWeb) }) }) // Health check endpoint (before catch-all routes) r.Get("/health", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) }) // Redirect root to web UI r.Get("/", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/web/", http.StatusMovedPermanently) }) // Public sharing routes (no API key required) // Direct download route by original filename r.Get("/d/{filename}", publicHandler.DownloadByOriginalName) // Share page route by slug (catch-all, must be last) r.Get("/{slug}", publicHandler.SharePage) // Start server log.Printf("Starting server on port %s", port) log.Printf("Web UI: http://localhost:%s/web/", port) log.Printf("API: http://localhost:%s/api/", port) if err := http.ListenAndServe(":"+port, r); err != nil { log.Fatalf("Server failed to start: %v", err) } } // initializeStorage creates and configures the storage backend based on environment variables func initializeStorage() (storage.Storage, error) { storageType := strings.ToLower(os.Getenv("STORAGE_TYPE")) if storageType == "" { storageType = "local" // Default to local storage } switch storageType { case "local": dataDir := os.Getenv("DATA_DIR") if dataDir == "" { dataDir = "./data" } log.Printf("Using local storage: %s", dataDir) return storage.NewLocalStorage(dataDir) case "s3": endpoint := os.Getenv("S3_ENDPOINT") bucket := os.Getenv("S3_BUCKET") region := os.Getenv("S3_REGION") accessKeyID := os.Getenv("S3_ACCESS_KEY_ID") secretAccessKey := os.Getenv("S3_SECRET_ACCESS_KEY") usePathStyleStr := os.Getenv("S3_USE_PATH_STYLE") // Validate required S3 configuration if bucket == "" { return nil, fmt.Errorf("S3_BUCKET is required when using S3 storage") } if region == "" { region = "us-east-1" // Default region } if accessKeyID == "" || secretAccessKey == "" { return nil, fmt.Errorf("S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are required when using S3 storage") } usePathStyle := false if usePathStyleStr != "" { var err error usePathStyle, err = strconv.ParseBool(usePathStyleStr) if err != nil { log.Printf("Warning: invalid S3_USE_PATH_STYLE value, using default (false)") } } config := storage.S3Config{ Endpoint: endpoint, Bucket: bucket, Region: region, AccessKeyID: accessKeyID, SecretAccessKey: secretAccessKey, UsePathStyle: usePathStyle, } log.Printf("Using S3 storage: bucket=%s, region=%s, endpoint=%s", bucket, region, endpoint) return storage.NewS3Storage(config) default: return nil, fmt.Errorf("unsupported storage type: %s (supported: local, s3)", storageType) } } // startCleanupJob runs a background job to clean up expired files func startCleanupJob(fileService *services.FileService) { // Run cleanup every hour ticker := time.NewTicker(1 * time.Hour) go func() { // Run immediately on startup if err := fileService.CleanupExpiredFiles(); err != nil { log.Printf("Cleanup error: %v", err) } else { log.Println("Initial cleanup completed") } // Then run periodically for range ticker.C { if err := fileService.CleanupExpiredFiles(); err != nil { log.Printf("Cleanup error: %v", err) } else { log.Println("Cleanup completed") } } }() }
yorukot/sharing
2
Go
yorukot
Yorukot
templates/index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Sharing Service</title> <script src="https://unpkg.com/htmx.org@1.9.10"></script> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; color: #333; line-height: 1.6; padding: 20px; } .login-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 9999; } .login-box { background: white; padding: 40px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); max-width: 400px; width: 90%; } .login-box h2 { margin-bottom: 20px; color: #2c3e50; } .container { max-width: 1400px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); padding: 30px; } h1 { color: #2c3e50; margin-bottom: 10px; } .subtitle { color: #7f8c8d; margin-bottom: 20px; } .header-actions { float: right; } .header-actions button { background: #e74c3c; font-size: 12px; padding: 5px 15px; } .upload-section { background: #ecf0f1; padding: 25px; border-radius: 8px; margin-bottom: 30px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: 500; color: #2c3e50; } input[type="file"], input[type="datetime-local"], input[type="password"], input[type="text"] { width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; font-size: 14px; } button { background: #3498db; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: 500; transition: background 0.3s; } button:hover { background: #2980b9; } button.delete { background: #e74c3c; padding: 5px 10px; font-size: 12px; } button.delete:hover { background: #c0392b; } button.edit { background: #f39c12; padding: 5px 10px; font-size: 12px; margin-right: 5px; } button.edit:hover { background: #e67e22; } button.copy { background: #27ae60; padding: 5px 10px; font-size: 12px; margin-right: 5px; } button.copy:hover { background: #229954; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ecf0f1; } th { background: #34495e; color: white; font-weight: 500; } tr:hover { background: #f8f9fa; } .actions { white-space: nowrap; } .badge { display: inline-block; padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: 500; margin-right: 3px; } .badge.protected { background: #e74c3c; color: white; } .badge.expires { background: #f39c12; color: white; } .share-link { font-family: monospace; font-size: 12px; color: #3498db; } .empty-state { text-align: center; padding: 40px; color: #7f8c8d; } .hidden { display: none; } .help-text { font-size: 12px; color: #7f8c8d; margin-top: 5px; } /* Upload Progress Styles */ .progress-container { margin-top: 15px; padding: 15px; background: white; border-radius: 4px; border: 1px solid #bdc3c7; } .progress-bar-wrapper { width: 100%; height: 24px; background: #ecf0f1; border-radius: 12px; overflow: hidden; position: relative; margin-bottom: 8px; } .progress-bar { height: 100%; background: linear-gradient(90deg, #3498db, #2980b9); width: 0%; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: white; font-size: 11px; font-weight: 600; } .progress-bar.complete { background: linear-gradient(90deg, #27ae60, #229954); } .progress-bar.error { background: linear-gradient(90deg, #e74c3c, #c0392b); } .progress-info { display: flex; justify-content: space-between; font-size: 12px; color: #7f8c8d; } button:disabled { background: #95a5a6; cursor: not-allowed; } button:disabled:hover { background: #95a5a6; } </style> </head> <body> <div id="login-screen" class="login-overlay"> <div class="login-box"> <h2>Authentication Required</h2> <p style="margin-bottom: 20px;">Enter your API key to manage files:</p> <div class="form-group"> <label for="api-key-input">API Key</label> <input type="password" id="api-key-input" placeholder="Enter API key" autofocus> </div> <button onclick="login()">Login</button> <p id="login-error" style="color: #e74c3c; margin-top: 10px; display: none;"></p> </div> </div> <div id="main-content" class="hidden"> <div class="container"> <div style="overflow: hidden; margin-bottom: 20px;"> <div style="float: left;"> <h1>File Sharing Service</h1> <p class="subtitle">Securely share files with short links, expiration dates, and password protection</p> </div> <div class="header-actions"> <button onclick="logout()">Logout</button> </div> </div> <div class="upload-section"> <h2>Upload File</h2> <form id="upload-form" hx-post="/web/upload" hx-target="#file-list" hx-swap="innerHTML" hx-encoding="multipart/form-data" hx-headers='{"X-API-Key": ""}'> <div class="form-group"> <label for="file">Select File *</label> <input type="file" id="file" name="file" required> </div> <div class="form-group"> <label for="slug">Short Link (Optional)</label> <input type="text" id="slug" name="slug" placeholder="e.g., my-document (auto-generated if empty)"> <p class="help-text">Lowercase letters, numbers, and hyphens only. Leave blank to auto-generate from filename.</p> </div> <div class="form-group"> <label for="expires_at">Expiry Date (Optional)</label> <input type="datetime-local" id="expires_at" name="expires_at"> </div> <div class="form-group"> <label for="password">Password Protection (Optional)</label> <input type="password" id="password" name="password" placeholder="Leave blank for no password"> </div> <div class="form-group"> <label style="display: flex; align-items: center; cursor: pointer; user-select: none;"> <input type="checkbox" id="replace" name="replace" value="true" style="width: auto; margin-right: 8px;"> <span>Replace if filename exists</span> </label> <p class="help-text">If checked and a file with the same name exists, it will be replaced (keeps slug, password, and expiry).</p> </div> <button type="submit" id="upload-button">Upload File</button> </form> <!-- Upload Progress Bar --> <div id="progress-container" class="progress-container hidden"> <div class="progress-bar-wrapper"> <div id="progress-bar" class="progress-bar"> <span id="progress-percentage">0%</span> </div> </div> <div class="progress-info"> <span id="progress-status">Uploading...</span> <span id="progress-size"></span> </div> </div> </div> <div class="files-section"> <h2>Shared Files</h2> <div id="file-list"> {{template "file-list" .}} </div> </div> </div> </div> <script> const API_KEY_STORAGE = 'file_sharing_api_key'; function getApiKey() { return localStorage.getItem(API_KEY_STORAGE); } function setApiKey(key) { localStorage.setItem(API_KEY_STORAGE, key); } function clearApiKey() { localStorage.removeItem(API_KEY_STORAGE); } function login() { const key = document.getElementById('api-key-input').value; if (!key) { showLoginError('Please enter an API key'); return; } // Test API key by fetching file list fetch('/web/files', { headers: { 'X-API-Key': key } }).then(response => { if (response.ok) { setApiKey(key); showMainContent(); } else { showLoginError('Invalid API key'); } }).catch(() => { showLoginError('Connection error'); }); } function logout() { clearApiKey(); location.reload(); } function showLoginError(msg) { const errEl = document.getElementById('login-error'); errEl.textContent = msg; errEl.style.display = 'block'; } function showMainContent() { document.getElementById('login-screen').classList.add('hidden'); document.getElementById('main-content').classList.remove('hidden'); updateHeaders(); } function updateHeaders() { const apiKey = getApiKey(); document.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-API-Key'] = apiKey; }); } function copyShareLink(slug) { const url = window.location.origin + '/' + slug; navigator.clipboard.writeText(url).then(() => { alert('Share link copied: ' + url); }); } // Upload progress tracking function formatBytes(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i]; } function formatAllFileSizes() { // Format all file size elements on the page document.querySelectorAll('.file-size').forEach(el => { const bytes = parseInt(el.getAttribute('data-bytes')); if (!isNaN(bytes)) { el.textContent = formatBytes(bytes); } }); } // Format file sizes when HTMX loads content document.addEventListener('htmx:afterSwap', formatAllFileSizes); // Format file sizes on initial page load document.addEventListener('DOMContentLoaded', formatAllFileSizes); function showProgress() { const progressContainer = document.getElementById('progress-container'); const progressBar = document.getElementById('progress-bar'); const uploadButton = document.getElementById('upload-button'); progressContainer.classList.remove('hidden'); progressBar.style.width = '0%'; progressBar.className = 'progress-bar'; uploadButton.disabled = true; document.getElementById('progress-percentage').textContent = '0%'; document.getElementById('progress-status').textContent = 'Uploading...'; document.getElementById('progress-size').textContent = ''; } function hideProgress() { const progressContainer = document.getElementById('progress-container'); const uploadButton = document.getElementById('upload-button'); const uploadForm = document.getElementById('upload-form'); setTimeout(() => { progressContainer.classList.add('hidden'); uploadButton.disabled = false; uploadForm.reset(); }, 2000); } function updateProgress(loaded, total) { const percentage = Math.round((loaded / total) * 100); const progressBar = document.getElementById('progress-bar'); const progressPercentage = document.getElementById('progress-percentage'); const progressSize = document.getElementById('progress-size'); progressBar.style.width = percentage + '%'; progressPercentage.textContent = percentage + '%'; progressSize.textContent = formatBytes(loaded) + ' / ' + formatBytes(total); } function setProgressComplete() { const progressBar = document.getElementById('progress-bar'); const progressStatus = document.getElementById('progress-status'); progressBar.style.width = '100%'; progressBar.classList.add('complete'); progressStatus.textContent = 'Upload complete!'; document.getElementById('progress-percentage').textContent = '100%'; } function setProgressError(message) { const progressBar = document.getElementById('progress-bar'); const progressStatus = document.getElementById('progress-status'); progressBar.classList.add('error'); progressStatus.textContent = 'Upload failed: ' + (message || 'Unknown error'); } // HTMX event listeners for upload progress document.addEventListener('htmx:xhr:loadstart', function(event) { const form = event.detail.elt; if (form && form.id === 'upload-form') { showProgress(); } }); document.addEventListener('htmx:xhr:progress', function(event) { const form = event.detail.elt; if (form && form.id === 'upload-form') { const loaded = event.detail.loaded; const total = event.detail.total; if (total > 0) { updateProgress(loaded, total); } } }); document.addEventListener('htmx:afterRequest', function(event) { const form = event.detail.elt; if (form && form.id === 'upload-form') { if (event.detail.successful) { setProgressComplete(); } else { setProgressError(event.detail.xhr?.statusText || 'Unknown error'); } hideProgress(); } }); // Check if already logged in if (getApiKey()) { showMainContent(); } // Handle Enter key on login document.getElementById('api-key-input')?.addEventListener('keypress', (e) => { if (e.key === 'Enter') login(); }); </script> </body> </html> {{define "file-list"}} {{if .Files}} <table> <thead> <tr> <th>Filename</th> <th>Short Link</th> <th>Size</th> <th>Uploaded</th> <th>Expires</th> <th>Status</th> <th>Actions</th> </tr> </thead> <tbody> {{range .Files}} {{template "file-row" .}} {{end}} </tbody> </table> {{else}} <div class="empty-state"> <p>No files uploaded yet. Upload your first file above!</p> </div> {{end}} {{end}} {{define "file-row"}} <tr id="file-{{.ID}}"> <td>{{.OriginalName}}</td> <td><span class="share-link">/{{.Slug}}</span></td> <td><span class="file-size" data-bytes="{{.FileSize}}">{{.FileSize}} bytes</span></td> <td>{{.CreatedAt.Format "2006-01-02 15:04"}}</td> <td> {{if .ExpiresAt}} {{.ExpiresAt.Format "2006-01-02 15:04"}} {{else}} Never {{end}} </td> <td> {{if .HasPassword}} <span class="badge protected">Protected</span> {{end}} {{if .ExpiresAt}} <span class="badge expires">Expires</span> {{end}} </td> <td class="actions"> <button class="copy" onclick="copyShareLink('{{.Slug}}')">Copy Link</button> <button class="edit" hx-get="/web/edit/{{.ID}}" hx-target="#file-{{.ID}}" hx-swap="outerHTML"> Edit </button> <button class="delete" hx-delete="/web/files/{{.ID}}" hx-target="#file-{{.ID}}" hx-swap="outerHTML swap:1s" hx-confirm="Are you sure you want to delete this file?"> Delete </button> </td> </tr> {{end}} {{define "edit-form"}} <tr id="file-{{.File.ID}}"> <td colspan="7"> <form hx-post="/web/update/{{.File.ID}}" hx-target="#file-{{.File.ID}}" hx-swap="outerHTML" style="padding: 15px;"> <div style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr auto; gap: 15px; align-items: end;"> <div class="form-group"> <label>Filename</label> <input type="text" value="{{.File.OriginalName}}" disabled> </div> <div class="form-group"> <label>Short Link</label> <input type="text" name="slug" value="{{.File.Slug}}" placeholder="my-custom-link"> </div> <div class="form-group"> <label>Expiry Date</label> <input type="datetime-local" name="expires_at" value="{{if .File.ExpiresAt}}{{.File.ExpiresAt.Format "2006-01-02T15:04"}}{{end}}"> </div> <div class="form-group"> <label>New Password</label> <input type="password" name="password" placeholder="Leave blank to keep current"> </div> <div> <button type="submit">Save</button> <button type="button" hx-get="/web/files" hx-target="#file-list" hx-swap="innerHTML" style="background: #95a5a6;"> Cancel </button> </div> </div> </form> </td> </tr> {{end}}
yorukot/sharing
2
Go
yorukot
Yorukot
cmd/main.go
Go
package main import ( "net/http" "github.com/go-chi/chi/v5" chiMiddleware "github.com/go-chi/chi/v5/middleware" httpSwagger "github.com/swaggo/http-swagger" "go.uber.org/zap" "github.com/yorukot/stargo/internal/config" "github.com/yorukot/stargo/internal/database" "github.com/yorukot/stargo/internal/handler" "github.com/yorukot/stargo/internal/middleware" "github.com/yorukot/stargo/internal/router" "github.com/yorukot/stargo/pkg/logger" "github.com/yorukot/stargo/pkg/response" _ "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" _ "github.com/joho/godotenv/autoload" _ "github.com/yorukot/stargo/docs" ) // @title Stargo Go API Template // @version 1.0 // @description Stargo Go API Template // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email support@swagger.io // @license.name MIT // @license.url https://opensource.org/licenses/MIT // @host localhost:8000 // @BasePath /api // @schemes http https // Run starts the server func main() { logger.InitLogger() _, err := config.InitConfig() if err != nil { zap.L().Fatal("Error initializing config", zap.Error(err)) return } r := chi.NewRouter() db, err := database.InitDatabase() if err != nil { zap.L().Fatal("Failed to initialize database", zap.Error(err)) } defer db.Close() r.Use(middleware.ZapLoggerMiddleware(zap.L())) r.Use(chiMiddleware.StripSlashes) setupRouter(r, &handler.App{DB: db}) zap.L().Info("Starting server on http://localhost:" + config.Env().Port) zap.L().Info("Environment: " + string(config.Env().AppEnv)) err = http.ListenAndServe(":"+config.Env().Port, r) if err != nil { zap.L().Fatal("Failed to start server", zap.Error(err)) } } // setupRouter sets up the router func setupRouter(r chi.Router, app *handler.App) { r.Route("/api", func(r chi.Router) { router.AuthRouter(r, app) }) if config.Env().AppEnv == config.AppEnvDev { r.Get("/swagger/*", httpSwagger.WrapHandler) } r.Get("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) }) // Not found handler r.NotFound(func(w http.ResponseWriter, r *http.Request) { response.RespondWithError(w, http.StatusNotFound, "Not Found", "NOT_FOUND") }) r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) { response.RespondWithError(w, http.StatusMethodNotAllowed, "Method Not Allowed", "METHOD_NOT_ALLOWED") }) zap.L().Info("Router setup complete") }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
docs/docs.go
Go
// Package docs Code generated by swaggo/swag. DO NOT EDIT package docs import "github.com/swaggo/swag" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "API Support", "url": "http://www.swagger.io/support", "email": "support@swagger.io" }, "license": { "name": "MIT", "url": "https://opensource.org/licenses/MIT" }, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/auth/login": { "post": { "description": "Authenticates a user with email and password, returns a refresh token cookie", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "auth" ], "summary": "User login", "parameters": [ { "description": "Login request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/authsvc.LoginRequest" } } ], "responses": { "200": { "description": "Login successful", "schema": { "type": "string" } }, "400": { "description": "Invalid request body, user not found, or invalid password", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/auth/oauth/{provider}": { "get": { "description": "Redirects user to OAuth provider for authentication", "tags": [ "oauth" ], "summary": "Initiate OAuth flow", "parameters": [ { "type": "string", "description": "OAuth provider (e.g., google, github)", "name": "provider", "in": "path", "required": true }, { "type": "string", "description": "Redirect URL after successful OAuth linking", "name": "next", "in": "query" } ], "responses": { "307": { "description": "Redirect to OAuth provider", "schema": { "type": "string" } }, "400": { "description": "Invalid provider or bad request", "schema": { "type": "object", "additionalProperties": true } }, "500": { "description": "Internal server error", "schema": { "type": "object", "additionalProperties": true } } } } }, "/auth/oauth/{provider}/callback": { "get": { "description": "Handles OAuth provider callback, processes authorization code, creates/links user accounts, and issues authentication tokens", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "oauth" ], "summary": "OAuth callback handler", "parameters": [ { "type": "string", "description": "OAuth provider (e.g., google, github)", "name": "provider", "in": "path", "required": true }, { "type": "string", "description": "Authorization code from OAuth provider", "name": "code", "in": "query", "required": true }, { "type": "string", "description": "OAuth state parameter for CSRF protection", "name": "state", "in": "query", "required": true } ], "responses": { "307": { "description": "Redirect to success URL with authentication cookies set", "schema": { "type": "string" } }, "400": { "description": "Invalid provider, oauth state, or verification failed", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error during user creation or token generation", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/auth/refresh": { "post": { "description": "Refreshes the access token and returns a new refresh token cookie", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "auth" ], "summary": "Refresh token", "responses": { "200": { "description": "Access token generated successfully", "schema": { "type": "string" } }, "400": { "description": "Invalid request body, refresh token not found, or refresh token already used", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } }, "/auth/register": { "post": { "description": "Creates a new user account with email and password", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "auth" ], "summary": "Register a new user", "parameters": [ { "description": "Registration request", "name": "request", "in": "body", "required": true, "schema": { "$ref": "#/definitions/authsvc.RegisterRequest" } } ], "responses": { "200": { "description": "User registered successfully", "schema": { "type": "string" } }, "400": { "description": "Invalid request body or email already in use", "schema": { "$ref": "#/definitions/response.ErrorResponse" } }, "500": { "description": "Internal server error", "schema": { "$ref": "#/definitions/response.ErrorResponse" } } } } } }, "definitions": { "authsvc.LoginRequest": { "type": "object", "required": [ "email", "password" ], "properties": { "email": { "type": "string", "maxLength": 255 }, "password": { "type": "string", "maxLength": 255, "minLength": 8 } } }, "authsvc.RegisterRequest": { "type": "object", "required": [ "email", "password" ], "properties": { "email": { "type": "string", "maxLength": 255 }, "password": { "type": "string", "maxLength": 255, "minLength": 8 } } }, "response.ErrorResponse": { "type": "object", "properties": { "err_code": { "type": "string" }, "message": { "type": "string" } } } } }` // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = &swag.Spec{ Version: "1.0", Host: "localhost:8000", BasePath: "/api", Schemes: []string{"http", "https"}, Title: "Stargo Go API Template", Description: "Stargo Go API Template", InfoInstanceName: "swagger", SwaggerTemplate: docTemplate, LeftDelim: "{{", RightDelim: "}}", } func init() { swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/config/env.go
Go
package config import ( "sync" "github.com/caarlos0/env/v10" "go.uber.org/zap" ) type AppEnv string const ( AppEnvDev AppEnv = "dev" AppEnvProd AppEnv = "prod" ) // EnvConfig holds all environment variables for the application type EnvConfig struct { JWTSecretKey string `env:"JWT_SECRET_KEY,required"` GoogleClientID string `env:"GOOGLE_CLIENT_ID,required"` GoogleClientSecret string `env:"GOOGLE_CLIENT_SECRET,required"` GoogleRedirectURL string `env:"GOOGLE_REDIRECT_URL,required"` DBHost string `env:"DB_HOST,required"` DBPort string `env:"DB_PORT,required"` DBUser string `env:"DB_USER,required"` DBPassword string `env:"DB_PASSWORD,required"` DBName string `env:"DB_NAME,required"` DBSSLMode string `env:"DB_SSL_MODE,required"` // Optional Settings OAuthStateExpiresAt int `env:"OAUTH_STATE_EXPIRES_AT" envDefault:"600"` // 10 minutes AccessTokenExpiresAt int `env:"ACCESS_TOKEN_EXPIRES_AT" envDefault:"900"` // 15 minutes RefreshTokenExpiresAt int `env:"REFRESH_TOKEN_EXPIRES_AT" envDefault:"31536000"` // 365 days Port string `env:"PORT" envDefault:"8080"` Debug bool `env:"DEBUG" envDefault:"false"` AppEnv AppEnv `env:"APP_ENV" envDefault:"prod"` AppName string `env:"APP_NAME" envDefault:"stargo"` } var ( appConfig *EnvConfig once sync.Once ) // loadConfig loads and validates all environment variables func loadConfig() (*EnvConfig, error) { cfg := &EnvConfig{} if err := env.Parse(cfg); err != nil { return nil, err } return cfg, nil } // InitConfig initializes the config only once func InitConfig() (*EnvConfig, error) { var err error once.Do(func() { appConfig, err = loadConfig() zap.L().Info("Config loaded") }) return appConfig, err } // Env returns the config. Panics if not initialized. func Env() *EnvConfig { if appConfig == nil { zap.L().Panic("config not initialized — call InitConfig() first") } return appConfig }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/config/oauth.go
Go
package config import ( "context" "github.com/coreos/go-oidc/v3/oidc" "go.uber.org/zap" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "github.com/yorukot/stargo/internal/models" ) // OAuthConfig is the configuration for the OAuth providers type OAuthConfig struct { Providers map[models.Provider]*oauth2.Config OIDCProviders map[models.Provider]*oidc.Provider } // GetOAuthConfig returns the OAuth2 configuration for Google func GetOAuthConfig() (*OAuthConfig, error) { googleOauthConfig := &oauth2.Config{ RedirectURL: Env().GoogleRedirectURL, ClientID: Env().GoogleClientID, ClientSecret: Env().GoogleClientSecret, Scopes: []string{"openid", "email", "profile"}, Endpoint: google.Endpoint, } // Create OIDC provider for Google ctx := context.Background() googleOIDCProvider, err := oidc.NewProvider(ctx, "https://accounts.google.com") if err != nil { zap.L().Error("failed to create google oidc provider", zap.Error(err)) return nil, err } return &OAuthConfig{ Providers: map[models.Provider]*oauth2.Config{ models.ProviderGoogle: googleOauthConfig, }, OIDCProviders: map[models.Provider]*oidc.Provider{ models.ProviderGoogle: googleOIDCProvider, }, }, nil }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/database/postgresql.go
Go
package database import ( "context" "errors" "fmt" "os" "github.com/golang-migrate/migrate/v4" "github.com/jackc/pgx/v5/pgxpool" "go.uber.org/zap" "github.com/yorukot/stargo/internal/config" ) // InitDatabase initialize the database connection pool and return the pool and also migrate the database func InitDatabase() (*pgxpool.Pool, error) { ctx := context.Background() pool, err := pgxpool.New(ctx, getDatabaseURL()) if err != nil { return nil, err } if err := pool.Ping(ctx); err != nil { pool.Close() return nil, err } zap.L().Info("Database initialized") Migrator() return pool, nil } // getDatabaseURL return a pgsql connection uri by the environment variables func getDatabaseURL() string { dbHost := config.Env().DBHost dbPort := config.Env().DBPort dbUser := config.Env().DBUser dbPassword := config.Env().DBPassword dbName := config.Env().DBName dbSSLMode := config.Env().DBSSLMode if dbSSLMode == "" { dbSSLMode = "disable" } return fmt.Sprintf( "postgres://%s:%s@%s:%s/%s?sslmode=%s", dbUser, dbPassword, dbHost, dbPort, dbName, dbSSLMode, ) } // Migrator the database func Migrator() { zap.L().Info("Migrating database") wd, _ := os.Getwd() databaseURL := getDatabaseURL() migrationsPath := "file://" + wd + "/migrations" m, err := migrate.New(migrationsPath, databaseURL) if err != nil { zap.L().Fatal("failed to create migrator", zap.Error(err)) } if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { zap.L().Fatal("failed to migrate database", zap.Error(err)) } zap.L().Info("Database migrated") }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/handler/auth/auth.go
Go
// Package auth provides the auth handler. package auth import ( "encoding/json" "net/http" "time" "github.com/jackc/pgx/v5/pgxpool" "go.uber.org/zap" "github.com/yorukot/stargo/internal/config" "github.com/yorukot/stargo/internal/repository" "github.com/yorukot/stargo/internal/service/authsvc" "github.com/yorukot/stargo/pkg/encrypt" "github.com/yorukot/stargo/pkg/response" ) // AuthHandler is the handler for the auth routes type AuthHandler struct { DB *pgxpool.Pool } // +----------------------------------------------+ // | Register | // +----------------------------------------------+ // Register godoc // @Summary Register a new user // @Description Creates a new user account with email and password // @Tags auth // @Accept json // @Produce json // @Param request body authsvc.RegisterRequest true "Registration request" // @Success 200 {object} string "User registered successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body or email already in use" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /auth/register [post] func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) { // Decode the request body var registerRequest authsvc.RegisterRequest if err := json.NewDecoder(r.Body).Decode(&registerRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := authsvc.RegisterValidate(registerRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Begin the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the account by email checkedAccount, err := repository.GetAccountByEmail(r.Context(), tx, registerRequest.Email) if err != nil { zap.L().Error("Failed to check if user already exists", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to check if user already exists", "FAILED_TO_CHECK_IF_USER_EXISTS") return } // If the account is found, return an error if checkedAccount != nil { response.RespondWithError(w, http.StatusBadRequest, "This email is already in use", "EMAIL_ALREADY_IN_USE") return } // Generate the user and account user, account, err := authsvc.GenerateUser(registerRequest) if err != nil { zap.L().Error("Failed to generate user", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate user", "FAILED_TO_GENERATE_USER") return } // Create the user and account in the database if err = repository.CreateUserAndAccount(r.Context(), tx, user, account); err != nil { zap.L().Error("Failed to create user", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create user", "FAILED_TO_CREATE_USER") return } // Generate the refresh token refreshToken, err := GenerateTokenAndSaveRefreshToken(r.Context(), tx, user.ID, r.UserAgent(), r.RemoteAddr) if err != nil { zap.L().Error("Failed to generate refresh token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate refresh token", "FAILED_TO_GENERATE_REFRESH_TOKEN") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Generate the refresh token cookie refreshTokenCookie := authsvc.GenerateRefreshTokenCookie(refreshToken) http.SetCookie(w, &refreshTokenCookie) // Respond with the success message response.RespondWithJSON(w, http.StatusOK, "User registered successfully", nil) } // +----------------------------------------------+ // | Login | // +----------------------------------------------+ // Login godoc // @Summary User login // @Description Authenticates a user with email and password, returns a refresh token cookie // @Tags auth // @Accept json // @Produce json // @Param request body authsvc.LoginRequest true "Login request" // @Success 200 {object} string "Login successful" // @Failure 400 {object} response.ErrorResponse "Invalid request body, user not found, or invalid password" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /auth/login [post] func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { // Decode the request body var loginRequest authsvc.LoginRequest if err := json.NewDecoder(r.Body).Decode(&loginRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Validate the request body if err := authsvc.LoginValidate(loginRequest); err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid request body", "INVALID_REQUEST_BODY") return } // Begin the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the user by email user, err := repository.GetUserByEmail(r.Context(), tx, loginRequest.Email) if err != nil { zap.L().Error("Failed to get user by email", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get user by email", "FAILED_TO_GET_USER_BY_EMAIL") return } // TODO: Need to change this // If the user is not found, return an error if user == nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid credentials", "INVALID_CREDENTIALS") return } // Compare the password and hash match, err := encrypt.ComparePasswordAndHash(loginRequest.Password, *user.PasswordHash) if err != nil { zap.L().Error("Failed to compare password and hash", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to compare password and hash", "FAILED_TO_COMPARE_PASSWORD_AND_HASH") return } // If the password is not correct, return an error if !match { response.RespondWithError(w, http.StatusBadRequest, "Invalid credentials", "INVALID_CREDENTIALS") return } // Generate the refresh token refreshToken, err := GenerateTokenAndSaveRefreshToken(r.Context(), tx, user.ID, r.UserAgent(), r.RemoteAddr) if err != nil { zap.L().Error("Failed to generate refresh token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate refresh token", "FAILED_TO_GENERATE_REFRESH_TOKEN") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Generate the refresh token cookie refreshTokenCookie := authsvc.GenerateRefreshTokenCookie(refreshToken) http.SetCookie(w, &refreshTokenCookie) response.RespondWithJSON(w, http.StatusOK, "Login successful", nil) } // +----------------------------------------------+ // | Refresh Token | // +----------------------------------------------+ // RefreshToken godoc // @Summary Refresh token // @Description Refreshes the access token and returns a new refresh token cookie // @Tags auth // @Accept json // @Produce json // @Success 200 {object} string "Access token generated successfully" // @Failure 400 {object} response.ErrorResponse "Invalid request body, refresh token not found, or refresh token already used" // @Failure 500 {object} response.ErrorResponse "Internal server error" // @Router /auth/refresh [post] func (h *AuthHandler) RefreshToken(w http.ResponseWriter, r *http.Request) { userRefreshToken, err := r.Cookie("refresh_token") if err != nil { response.RespondWithError(w, http.StatusUnauthorized, "Refresh token not found", "REFRESH_TOKEN_NOT_FOUND") return } // Begin the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the refresh token by token checkedRefreshToken, err := repository.GetRefreshTokenByToken(r.Context(), tx, userRefreshToken.Value) if err != nil { zap.L().Error("Failed to get refresh token by token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get refresh token by token", "FAILED_TO_GET_REFRESH_TOKEN_BY_TOKEN") return } // If the refresh token is not found, return an error if checkedRefreshToken == nil { response.RespondWithError(w, http.StatusUnauthorized, "Refresh token not found", "REFRESH_TOKEN_NOT_FOUND") return } // TODO: Need to tell the user might just been hacked if checkedRefreshToken.UsedAt != nil { zap.L().Warn("Refresh token already used", zap.String("refresh_token_id", checkedRefreshToken.ID), zap.String("ip", r.RemoteAddr), zap.String("user_agent", r.UserAgent()), ) response.RespondWithError(w, http.StatusUnauthorized, "Refresh token already used", "REFRESH_TOKEN_ALREADY_USED") return } // Update the refresh token used_at now := time.Now() checkedRefreshToken.UsedAt = &now if err = repository.UpdateRefreshTokenUsedAt(r.Context(), tx, *checkedRefreshToken); err != nil { zap.L().Error("Failed to update refresh token used_at", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to update refresh token used_at", "FAILED_TO_UPDATE_REFRESH_TOKEN_USED_AT") return } // Generate new refresh token newRefreshToken, err := GenerateTokenAndSaveRefreshToken(r.Context(), tx, checkedRefreshToken.UserID, r.UserAgent(), r.RemoteAddr) if err != nil { zap.L().Error("Failed to generate refresh token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate refresh token", "FAILED_TO_GENERATE_REFRESH_TOKEN") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Generate the refresh token cookie refreshTokenCookie := authsvc.GenerateRefreshTokenCookie(newRefreshToken) http.SetCookie(w, &refreshTokenCookie) // Generate AccessTokenClaims accessTokenClaims := encrypt.JWTSecret{ Secret: config.Env().JWTSecretKey, } // Generate the access token accessToken, err := accessTokenClaims.GenerateAccessToken(config.Env().AppName, checkedRefreshToken.UserID, time.Now().Add(time.Duration(config.Env().AccessTokenExpiresAt)*time.Second)) if err != nil { zap.L().Error("Failed to generate access token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Internal server error", "INTERNAL_SERVER_ERROR") return } response.RespondWithJSON(w, 200, "Access token generated successfully", map[string]string{ "access_token": accessToken, }) }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/handler/auth/auth_utils.go
Go
package auth import ( "context" "github.com/jackc/pgx/v5" "github.com/yorukot/stargo/internal/models" "github.com/yorukot/stargo/internal/repository" "github.com/yorukot/stargo/internal/service/authsvc" ) // GenerateTokenAndSaveRefreshToken generate a refresh token and save it to the database func GenerateTokenAndSaveRefreshToken(ctx context.Context, db pgx.Tx, userID string, userAgent string, ip string) (models.RefreshToken, error) { refreshToken, err := authsvc.GenerateRefreshToken(userID, userAgent, ip) if err != nil { return models.RefreshToken{}, err } err = repository.CreateRefreshToken(ctx, db, refreshToken) if err != nil { return models.RefreshToken{}, err } return refreshToken, nil }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/handler/auth/oauth.go
Go
package auth import ( "context" "net/http" "time" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgxpool" "go.uber.org/zap" "golang.org/x/oauth2" "github.com/yorukot/stargo/internal/config" "github.com/yorukot/stargo/internal/middleware" "github.com/yorukot/stargo/internal/models" "github.com/yorukot/stargo/internal/repository" "github.com/yorukot/stargo/internal/service/authsvc" "github.com/yorukot/stargo/pkg/response" ) // OAuthHandler is the handler for the oauth routes type OAuthHandler struct { DB *pgxpool.Pool OAuthConfig *config.OAuthConfig } // +----------------------------------------------+ // | OAuth Entry | // +----------------------------------------------+ // OAuthEntry godoc // @Summary Initiate OAuth flow // @Description Redirects user to OAuth provider for authentication // @Tags oauth // @Param provider path string true "OAuth provider (e.g., google, github)" // @Param next query string false "Redirect URL after successful OAuth linking" // @Success 307 {string} string "Redirect to OAuth provider" // @Failure 400 {object} map[string]interface{} "Invalid provider or bad request" // @Failure 500 {object} map[string]interface{} "Internal server error" // @Router /auth/oauth/{provider} [get] func (h *OAuthHandler) OAuthEntry(w http.ResponseWriter, r *http.Request) { // Parse the provider provider, err := authsvc.ParseProvider(chi.URLParam(r, "provider")) if err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid provider", "INVALID_PROVIDER") return } var userID string if userIDValue := r.Context().Value(middleware.UserIDKey); userIDValue != nil { userID = userIDValue.(string) } expiresAt := time.Now().Add(time.Duration(config.Env().OAuthStateExpiresAt) * time.Second) next := r.URL.Query().Get("next") if next == "" { next = "/" } oauthStateJwt, oauthState, err := authsvc.OAuthGenerateStateWithPayload(next, expiresAt, userID) if err != nil { zap.L().Error("Failed to generate oauth state", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate oauth state", "FAILED_TO_GENERATE_OAUTH_STATE") return } // Get the oauth config oauthConfig := h.OAuthConfig.Providers[provider] // Generate the auth URL authURL := oauthConfig.AuthCodeURL(oauthState, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent")) oauthSessionCookie := authsvc.GenerateOAuthSessionCookie(oauthStateJwt) http.SetCookie(w, &oauthSessionCookie) http.Redirect(w, r, authURL, http.StatusTemporaryRedirect) } // +----------------------------------------------+ // | OAuth Callback | // +----------------------------------------------+ // OAuthCallback godoc // @Summary OAuth callback handler // @Description Handles OAuth provider callback, processes authorization code, creates/links user accounts, and issues authentication tokens // @Tags oauth // @Accept json // @Produce json // @Param provider path string true "OAuth provider (e.g., google, github)" // @Param code query string true "Authorization code from OAuth provider" // @Param state query string true "OAuth state parameter for CSRF protection" // @Success 307 {string} string "Redirect to success URL with authentication cookies set" // @Failure 400 {object} response.ErrorResponse "Invalid provider, oauth state, or verification failed" // @Failure 500 {object} response.ErrorResponse "Internal server error during user creation or token generation" // @Router /auth/oauth/{provider}/callback [get] func (h *OAuthHandler) OAuthCallback(w http.ResponseWriter, r *http.Request) { // Get the oauth state from the query params oauthState := r.URL.Query().Get("state") code := r.URL.Query().Get("code") // Get the oauth session cookie oauthSessionCookie, err := r.Cookie(models.CookieNameOAuthSession) if err != nil { zap.L().Debug("OAuth session cookie not found", zap.Error(err)) response.RespondWithError(w, http.StatusBadRequest, "OAuth session not found", "OAUTH_SESSION_NOT_FOUND") return } // Parse the provider provider, err := authsvc.ParseProvider(chi.URLParam(r, "provider")) if err != nil { response.RespondWithError(w, http.StatusBadRequest, "Invalid provider", "INVALID_PROVIDER") return } // No need to check if the provider is valid because it's checked in the ParseProvider function oauthConfig := h.OAuthConfig.Providers[provider] // Get the oidc provider oidcProvider := h.OAuthConfig.OIDCProviders[provider] // Validate the oauth state valid, payload, err := authsvc.OAuthValidateStateWithPayload(oauthSessionCookie.Value) if err != nil || !valid || oauthState != payload.State { zap.L().Warn("OAuth state validation failed", zap.String("ip", r.RemoteAddr), zap.String("user_agent", r.UserAgent()), zap.String("provider", string(provider)), zap.String("oauth_state", oauthState), zap.String("payload_state", payload.State)) response.RespondWithError(w, http.StatusBadRequest, "Invalid oauth state", "INVALID_OAUTH_STATE") return } // Get the user ID from the session cookie var userID string var accountID string if payload.Subject != "" { userID = payload.Subject } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() // Exchange the code for a token token, err := oauthConfig.Exchange(ctx, code) if err != nil { response.RespondWithError(w, http.StatusBadRequest, "Failed to exchange code", "FAILED_TO_EXCHANGE_CODE") return } // Get the raw ID token rawIDToken, ok := token.Extra("id_token").(string) if !ok { zap.L().Error("Failed to get id token") response.RespondWithError(w, http.StatusInternalServerError, "Failed to get id token", "FAILED_TO_GET_ID_TOKEN") return } // Verify the token userInfo, err := authsvc.OAuthVerifyTokenAndGetUserInfo(r.Context(), rawIDToken, token, oidcProvider, oauthConfig) if err != nil { response.RespondWithError(w, http.StatusBadRequest, "Failed to verify token", "FAILED_TO_VERIFY_TOKEN") return } // Begin the transaction tx, err := repository.StartTransaction(h.DB, r.Context()) if err != nil { zap.L().Error("Failed to begin transaction", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to begin transaction", "FAILED_TO_BEGIN_TRANSACTION") return } defer repository.DeferRollback(tx, r.Context()) // Get the account and user by the provider and user ID for checking if the user is already linked/registered account, user, err := repository.GetAccountWithUserByProviderUserID(r.Context(), tx, provider, userInfo.Subject) if err != nil { zap.L().Error("Failed to get account", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to get account", "FAILED_TO_GET_ACCOUNT") return } // If the account is not found and the userID is not nil, it means the user is already registered // so we need to link the account to the user if user == nil && userID != "" { // Link the account to the user account, err := authsvc.GenerateUserAccountFromOAuthUserInfo(userInfo, provider, userID) if err != nil { zap.L().Error("Failed to link account", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate user and account", "FAILED_TO_GENERATE_USER_AND_ACCOUNT") return } accountID = account.ID // Create the account if err = repository.CreateAccount(r.Context(), tx, account); err != nil { zap.L().Error("Failed to create account", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create user and account", "FAILED_TO_CREATE_USER_AND_ACCOUNT") return } zap.L().Info("OAuth new user registered", zap.String("provider", string(provider)), zap.String("user_id", userID), zap.String("ip", r.RemoteAddr)) } else if account == nil && userID == "" { // Generate the full user object user, account, err := authsvc.GenerateUserFromOAuthUserInfo(userInfo, provider) if err != nil { zap.L().Error("Failed to generate user", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to generate user and account", "FAILED_TO_GENERATE_USER_AND_ACCOUNT") return } // Create the user and account if err = repository.CreateUserAndAccount(r.Context(), tx, user, account); err != nil { zap.L().Error("Failed to create user", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create user and account", "FAILED_TO_CREATE_USER_AND_ACCOUNT") return } accountID = account.ID // Set the user ID to the user ID userID = user.ID zap.L().Info("OAuth link account successful", zap.String("provider", string(provider)), zap.String("user_id", userID), zap.String("ip", r.RemoteAddr)) } else { accountID = account.ID userID = user.ID zap.L().Info("OAuth login successful", zap.String("provider", string(provider)), zap.String("user_id", userID), zap.String("ip", r.RemoteAddr)) } // If the user ID is empty, it means something went wrong (it should not happen) if userID == "" { zap.L().Error("User ID is nil", zap.Any("user", user)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create user and account", "FAILED_TO_CREATE_USER_AND_ACCOUNT") return } // Create the oauth token err = repository.CreateOAuthToken(r.Context(), tx, models.OAuthToken{ AccountID: accountID, AccessToken: token.AccessToken, RefreshToken: token.RefreshToken, Expiry: token.Expiry, TokenType: token.TokenType, Provider: provider, CreatedAt: time.Now(), UpdatedAt: time.Now(), }) if err != nil { zap.L().Error("Failed to create oauth token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create oauth token", "FAILED_TO_CREATE_OAUTH_TOKEN") return } // Generate the refresh token refreshToken, err := GenerateTokenAndSaveRefreshToken(r.Context(), tx, userID, r.UserAgent(), r.RemoteAddr) if err != nil { zap.L().Error("Failed to create refresh token and access token", zap.Error(err)) response.RespondWithError(w, http.StatusInternalServerError, "Failed to create refresh token and access token", "FAILED_TO_CREATE_REFRESH_TOKEN_AND_ACCESS_TOKEN") return } // Commit the transaction repository.CommitTransaction(tx, r.Context()) // Generate the refresh token cookie refreshTokenCookie := authsvc.GenerateRefreshTokenCookie(refreshToken) http.SetCookie(w, &refreshTokenCookie) // Redirect to the redirect URI http.Redirect(w, r, payload.RedirectURI, http.StatusTemporaryRedirect) }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/handler/type.go
Go
package handler import "github.com/jackc/pgx/v5/pgxpool" // App is the application context type App struct { DB *pgxpool.Pool }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/middleware/auth.go
Go
package middleware import ( "context" "net/http" "strings" "github.com/yorukot/stargo/internal/config" "github.com/yorukot/stargo/pkg/encrypt" "github.com/yorukot/stargo/pkg/response" ) // authMiddlewareLogic is the logic for the auth middleware func authMiddlewareLogic(w http.ResponseWriter, token string) (bool, *encrypt.AccessTokenClaims, error) { token = strings.TrimPrefix(token, "Bearer ") JWTSecret := encrypt.JWTSecret{ Secret: config.Env().JWTSecretKey, } valid, claims, err := JWTSecret.ValidateAccessTokenAndGetClaims(token) if err != nil { response.RespondWithError(w, http.StatusInternalServerError, "Internal server error", "INTERNAL_SERVER_ERROR") return false, nil, err } if !valid { response.RespondWithError(w, http.StatusUnauthorized, "Invalid token", "INVALID_TOKEN") return false, nil, nil } return true, &claims, nil } // AuthRequiredMiddleware is the middleware for the auth required func AuthRequiredMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := r.Header.Get("Authorization") if token == "" { response.RespondWithError(w, http.StatusUnauthorized, "Unauthorized", "UNAUTHORIZED") return } valid, claims, err := authMiddlewareLogic(w, token) if err != nil || !valid { return } ctx := context.WithValue(r.Context(), UserIDKey, claims.Subject) next.ServeHTTP(w, r.WithContext(ctx)) }) } // AuthOptionalMiddleware is the middleware for the auth optional func AuthOptionalMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := r.Header.Get("Authorization") if token == "" { next.ServeHTTP(w, r) return } valid, claims, err := authMiddlewareLogic(w, token) if err != nil || !valid { next.ServeHTTP(w, r) return } ctx := context.WithValue(r.Context(), UserIDKey, claims.Subject) next.ServeHTTP(w, r.WithContext(ctx)) }) }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/middleware/logger.go
Go
package middleware import ( "net/http" "time" "github.com/fatih/color" "github.com/google/uuid" "go.uber.org/zap" "github.com/yorukot/stargo/internal/config" ) // ZapLoggerMiddleware is a middleware that logs the incoming request and the response time func ZapLoggerMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestID := uuid.New().String() start := time.Now() next.ServeHTTP(w, r) logger.Info(GenerateDiffrentColorForMethod(r.Method)+" request completed", zap.String("request_id", requestID), zap.String("path", r.URL.Path), zap.String("user_agent", r.UserAgent()), zap.String("remote_addr", r.RemoteAddr), zap.Duration("duration", time.Since(start)), ) }) } } // GenerateDiffrentColorForMethod generate a different color for the method func GenerateDiffrentColorForMethod(method string) string { if config.Env().AppEnv == config.AppEnvDev { switch method { case "GET": return color.GreenString(method) case "POST": return color.BlueString(method) case "PUT": return color.YellowString(method) case "PATCH": return color.MagentaString(method) case "DELETE": return color.RedString(method) case "OPTIONS": return color.CyanString(method) case "HEAD": return color.WhiteString(method) default: return method } } return method }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/middleware/type.go
Go
package middleware // ContextKey is a type for the context key type ContextKey string // ContextKey constants const ( UserIDKey ContextKey = "userID" )
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/models/auth.go
Go
package models import "time" // CookieName constants const ( CookieNameOAuthSession = "oauth_session" CookieNameRefreshToken = "refresh_token" ) // RefreshToken represents a refresh token for user authentication type RefreshToken struct { ID string `json:"id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Unique identifier for the refresh token UserID string `json:"user_id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // User ID associated with this token Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."` // The actual refresh token UserAgent string `json:"user_agent" example:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"` // User agent string from the client IP string `json:"ip" example:"192.168.1.100"` // IP address of the client UsedAt *time.Time `json:"used_at,omitempty" example:"2023-01-01T12:00:00Z"` // Timestamp when the token was last used CreatedAt time.Time `json:"created_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the token was created } // Provider represents the authentication provider type type Provider string // Provider constants const ( ProviderEmail Provider = "email" // Email/password authentication ProviderGoogle Provider = "google" // Google OAuth authentication // You can add more providers here )
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/models/user.go
Go
package models import "time" // User represents a user in the system type User struct { ID string `json:"id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Unique identifier for the user PasswordHash *string `json:"password_hash,omitempty" example:"hashed_password"` // Hashed password (omitted in responses) Avatar *string `json:"avatar,omitempty" example:"https://example.com/avatar.jpg"` // URL to user's avatar image CreatedAt time.Time `json:"created_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the user was created UpdatedAt time.Time `json:"updated_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the user was last updated } // Account represents how a user can login to the system type Account struct { ID string `json:"id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Unique identifier for the account Provider Provider `json:"provider" example:"email"` // Authentication provider type ProviderUserID string `json:"provider_user_id" example:"user123"` // User ID from the provider UserID string `json:"user_id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Associated user ID Email string `json:"email" example:"user@example.com"` // User's email address CreatedAt time.Time `json:"created_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the account was created UpdatedAt time.Time `json:"updated_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the account was last updated } // OAuthToken represents OAuth tokens for external providers type OAuthToken struct { AccountID string `json:"account_id" example:"01ARZ3NDEKTSV4RRFFQ69G5FAV"` // Associated account ID AccessToken string `json:"access_token" example:"ya29.a0AfH6SMC..."` // OAuth access token RefreshToken string `json:"refresh_token" example:"1//0GWthXqhYjIsKCgYIARAA..."` // OAuth refresh token Expiry time.Time `json:"expiry" example:"2023-01-01T13:00:00Z"` // Token expiration time TokenType string `json:"token_type" example:"Bearer"` // Token type (usually Bearer) Provider Provider `json:"provider" example:"google"` // OAuth provider CreatedAt time.Time `json:"created_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the token was created UpdatedAt time.Time `json:"updated_at" example:"2023-01-01T12:00:00Z"` // Timestamp when the token was last updated }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/repository/auth.go
Go
package repository import ( "context" "errors" "github.com/georgysavva/scany/v2/pgxscan" "github.com/jackc/pgx/v5" "github.com/yorukot/stargo/internal/models" ) // GetRefreshTokenByToken gets a refresh token by token func GetRefreshTokenByToken(ctx context.Context, db pgx.Tx, token string) (*models.RefreshToken, error) { query := ` SELECT id, user_id, token, user_agent, ip::text, used_at, created_at FROM refresh_tokens WHERE token = $1 ` var refreshToken models.RefreshToken err := pgxscan.Get(ctx, db, &refreshToken, query, token) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } else if err != nil { return nil, err } return &refreshToken, nil } // CreateRefreshToken creates a new refresh token func CreateRefreshToken(ctx context.Context, db pgx.Tx, refreshToken models.RefreshToken) error { query := ` INSERT INTO refresh_tokens (id, user_id, token, user_agent, ip, used_at, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7) ` _, err := db.Exec(ctx, query, refreshToken.ID, refreshToken.UserID, refreshToken.Token, refreshToken.UserAgent, refreshToken.IP, refreshToken.UsedAt, refreshToken.CreatedAt, ) return err } // CreateOAuthToken creates a new OAuth token func CreateOAuthToken(ctx context.Context, db pgx.Tx, oauthToken models.OAuthToken) error { query := ` INSERT INTO oauth_tokens ( account_id, access_token, refresh_token, expiry, token_type, provider, created_at, updated_at ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (account_id) DO UPDATE SET access_token = EXCLUDED.access_token, refresh_token = EXCLUDED.refresh_token, expiry = EXCLUDED.expiry, token_type = EXCLUDED.token_type, updated_at = EXCLUDED.updated_at ` _, err := db.Exec(ctx, query, oauthToken.AccountID, oauthToken.AccessToken, oauthToken.RefreshToken, oauthToken.Expiry, oauthToken.TokenType, oauthToken.Provider, oauthToken.CreatedAt, oauthToken.UpdatedAt, ) return err } // UpdateRefreshTokenUsedAt updates the used_at of a refresh token func UpdateRefreshTokenUsedAt(ctx context.Context, db pgx.Tx, refreshToken models.RefreshToken) error { query := ` UPDATE refresh_tokens SET used_at = $1 WHERE id = $2 ` _, err := db.Exec(ctx, query, refreshToken.UsedAt, refreshToken.ID) return err }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/repository/transaction.go
Go
package repository import ( "context" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "go.uber.org/zap" ) // StartTransaction return a tx func StartTransaction(db *pgxpool.Pool, ctx context.Context) (pgx.Tx, error) { tx, err := db.Begin(ctx) if err != nil { return nil, err } return tx, nil } // DeferRollback rollback the transaction func DeferRollback(tx pgx.Tx, ctx context.Context) { if err := tx.Rollback(ctx); err != nil { zap.L().Error("Failed to rollback transaction", zap.Error(err)) } } // CommitTransaction commit the transaction func CommitTransaction(tx pgx.Tx, ctx context.Context) { if err := tx.Commit(ctx); err != nil { zap.L().Error("Failed to commit transaction", zap.Error(err)) } }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/repository/user.go
Go
package repository import ( "context" "errors" "github.com/georgysavva/scany/v2/pgxscan" "github.com/jackc/pgx/v5" "github.com/yorukot/stargo/internal/models" ) // GetAccountByEmail checks if the user already exists func GetAccountByEmail(ctx context.Context, db pgx.Tx, email string) (*models.Account, error) { query := ` SELECT * FROM accounts WHERE email = $1 AND provider = $2 ` var account models.Account err := pgxscan.Get(ctx, db, &account, query, email, models.ProviderEmail) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } else if err != nil { return nil, err } return &account, nil } // GetUserByEmail checks if the user already exists func GetUserByEmail(ctx context.Context, db pgx.Tx, email string) (*models.User, error) { // This need to get the account first and then join the user query := ` SELECT u.* FROM users u JOIN accounts a ON u.id = a.user_id WHERE a.email = $1 AND a.provider = $2 ` var user models.User err := pgxscan.Get(ctx, db, &user, query, email, models.ProviderEmail) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } else if err != nil { return nil, err } return &user, nil } // GetAccountByProviderAndProviderUserID check if the account already exists func GetAccountByProviderAndProviderUserID(ctx context.Context, db pgx.Tx, provider models.Provider, providerUserID string) (*models.Account, error) { query := ` SELECT * FROM accounts WHERE provider = $1 AND provider_user_id = $2 ` var account models.Account err := pgxscan.Get(ctx, db, &account, query, provider, providerUserID) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } else if err != nil { return nil, err } return &account, nil } // GetAccountWithUserByProviderUserID retrieves the account and its associated user func GetAccountWithUserByProviderUserID(ctx context.Context, db pgx.Tx, provider models.Provider, providerUserID string) (*models.Account, *models.User, error) { query := ` SELECT a.id AS "a.id", a.provider AS "a.provider", a.provider_user_id AS "a.provider_user_id", a.user_id AS "a.user_id", u.id AS "u.id", u.created_at AS "u.created_at", u.updated_at AS "u.updated_at" FROM accounts a JOIN users u ON a.user_id = u.id WHERE a.provider = $1 AND a.provider_user_id = $2 ` // Using aliases to scan into both Account and User var result struct { A models.Account `db:"a"` U models.User `db:"u"` } err := pgxscan.Get(ctx, db, &result, query, provider, providerUserID) if errors.Is(err, pgx.ErrNoRows) { return nil, nil, nil } else if err != nil { return nil, nil, err } return &result.A, &result.U, nil } // CreateUser creates a new user func CreateUser(ctx context.Context, db pgx.Tx, user models.User) error { query := ` INSERT INTO users (id, password_hash, avatar, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) ` _, err := db.Exec(ctx, query, user.ID, user.PasswordHash, user.Avatar, user.CreatedAt, user.UpdatedAt, ) return err } // CreateAccount creates a new account func CreateAccount(ctx context.Context, db pgx.Tx, account models.Account) error { query := ` INSERT INTO accounts (id, provider, provider_user_id, user_id, email, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7) ` _, err := db.Exec(ctx, query, account.ID, account.Provider, account.ProviderUserID, account.UserID, account.Email, account.CreatedAt, account.UpdatedAt, ) return err } // CreateUserAndAccount creates a user and account func CreateUserAndAccount(ctx context.Context, db pgx.Tx, user models.User, account models.Account) error { if err := CreateUser(ctx, db, user); err != nil { return err } if err := CreateAccount(ctx, db, account); err != nil { return err } return nil }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/router/auth.go
Go
package router import ( "github.com/go-chi/chi/v5" "go.uber.org/zap" "github.com/yorukot/stargo/internal/config" "github.com/yorukot/stargo/internal/handler" "github.com/yorukot/stargo/internal/handler/auth" "github.com/yorukot/stargo/internal/middleware" ) // AuthRouter sets up the authentication routes func AuthRouter(r chi.Router, app *handler.App) { authHandler := auth.AuthHandler{ DB: app.DB, } oauthConfig, err := config.GetOAuthConfig() if err != nil { zap.L().Panic("failed to get oauth config", zap.Error(err)) return } oauthHandler := auth.OAuthHandler{ DB: app.DB, OAuthConfig: oauthConfig, } r.Route("/auth", func(r chi.Router) { r.Route("/oauth", func(r chi.Router) { // We use AuthOptionalMiddleware because we want to allow users to access the OAuth session without being authenticated (first time login/register) r.With(middleware.AuthOptionalMiddleware).Get("/{provider}", oauthHandler.OAuthEntry) r.Get("/{provider}/callback", oauthHandler.OAuthCallback) }) r.Post("/register", authHandler.Register) r.Post("/login", authHandler.Login) r.Post("/refresh", authHandler.RefreshToken) }) }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/service/authsvc/auth.go
Go
package authsvc import ( "fmt" "net" "net/http" "time" "github.com/go-playground/validator/v10" "github.com/segmentio/ksuid" "github.com/yorukot/stargo/internal/config" "github.com/yorukot/stargo/internal/models" "github.com/yorukot/stargo/pkg/encrypt" ) // RegisterRequest is the request body for the register endpoint type RegisterRequest struct { Email string `json:"email" validate:"required,email,max=255"` Password string `json:"password" validate:"required,min=8,max=255"` } // RegisterValidate validate the register request func RegisterValidate(registerRequest RegisterRequest) error { return validator.New().Struct(registerRequest) } // GenerateUser generate a user and account for the register request func GenerateUser(registerRequest RegisterRequest) (models.User, models.Account, error) { userID := ksuid.New().String() // hash the password passwordHash, err := encrypt.CreateArgon2idHash(registerRequest.Password) if err != nil { return models.User{}, models.Account{}, fmt.Errorf("failed to hash password: %w", err) } // create the user user := models.User{ ID: userID, PasswordHash: &passwordHash, CreatedAt: time.Now(), UpdatedAt: time.Now(), } // Create the account account := models.Account{ ID: ksuid.New().String(), Provider: models.ProviderEmail, ProviderUserID: userID, UserID: userID, Email: registerRequest.Email, CreatedAt: time.Now(), UpdatedAt: time.Now(), } return user, account, nil } // LoginRequest is the request body for the login endpoint type LoginRequest struct { Email string `json:"email" validate:"required,email,max=255"` Password string `json:"password" validate:"required,min=8,max=255"` } // LoginValidate validate the login request func LoginValidate(loginRequest LoginRequest) error { return validator.New().Struct(loginRequest) } // GenerateRefreshToken generates a refresh token for the user func GenerateRefreshToken(userID string, userAgent string, ip string) (models.RefreshToken, error) { ipStr, _, err := net.SplitHostPort(ip) if err != nil { return models.RefreshToken{}, fmt.Errorf("failed to split host port: %w", err) } refreshToken, err := encrypt.GenerateSecureRefreshToken() if err != nil { return models.RefreshToken{}, fmt.Errorf("failed to generate refresh token: %w", err) } return models.RefreshToken{ ID: ksuid.New().String(), UserID: userID, Token: refreshToken, UserAgent: userAgent, IP: ipStr, UsedAt: nil, CreatedAt: time.Now(), }, nil } // GenerateRefreshTokenCookie generates a refresh token cookie func GenerateRefreshTokenCookie(refreshToken models.RefreshToken) http.Cookie { return http.Cookie{ Name: models.CookieNameRefreshToken, Path: "/api/auth/refresh", // TODO: Add config for frontend domain // Domain: "localhost", Value: refreshToken.Token, HttpOnly: true, Secure: config.Env().AppEnv == config.AppEnvProd, Expires: refreshToken.CreatedAt.Add(time.Duration(config.Env().RefreshTokenExpiresAt) * time.Second), SameSite: http.SameSiteLaxMode, } }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
internal/service/authsvc/oauth.go
Go
package authsvc import ( "context" "fmt" "net/http" "time" "github.com/coreos/go-oidc/v3/oidc" "github.com/segmentio/ksuid" "golang.org/x/oauth2" "github.com/yorukot/stargo/internal/config" "github.com/yorukot/stargo/internal/models" "github.com/yorukot/stargo/pkg/encrypt" ) // ParseProvider parse the provider from the request func ParseProvider(provider string) (models.Provider, error) { switch provider { case string(models.ProviderGoogle): return models.ProviderGoogle, nil default: return "", fmt.Errorf("invalid provider: %s", provider) } } // OAuthGenerateStateWithPayload generate the oauth state with the payload func OAuthGenerateStateWithPayload(redirectURI string, expiresAt time.Time, userID string) (string, string, error) { OAuthState, err := encrypt.GenerateRandomString(32) if err != nil { return "", "", fmt.Errorf("failed to generate random string: %w", err) } secret := encrypt.JWTSecret{ Secret: config.Env().JWTSecretKey, } tokenString, err := secret.GenerateOAuthState(OAuthState, redirectURI, expiresAt, userID) if err != nil { return "", "", fmt.Errorf("failed to generate oauth state: %w", err) } return tokenString, OAuthState, nil } // OAuthValidateStateWithPayload validate the oauth state with the payload func OAuthValidateStateWithPayload(oauthState string) (bool, encrypt.OAuthStateClaims, error) { secret := encrypt.JWTSecret{ Secret: config.Env().JWTSecretKey, } valid, payload, err := secret.ValidateOAuthStateAndGetClaims(oauthState) if err != nil { return false, encrypt.OAuthStateClaims{}, fmt.Errorf("failed to validate oauth state: %w", err) } if payload.ExpiresAt < time.Now().Unix() { return false, encrypt.OAuthStateClaims{}, fmt.Errorf("oauth state expired") } return valid, payload, nil } // OAuthVerifyTokenAndGetUserInfo verifies the token for the OAuth flow func OAuthVerifyTokenAndGetUserInfo(ctx context.Context, rawIDToken string, token *oauth2.Token, oidcProvider *oidc.Provider, oauthConfig *oauth2.Config) (*oidc.UserInfo, error) { // Create verifier with client ID for audience validation verifier := oidcProvider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID}) // Verify the ID token verifiedToken, err := verifier.Verify(ctx, rawIDToken) if err != nil { return nil, fmt.Errorf("failed to verify ID token: %w", err) } // Extract claims from verified token var tokenClaims map[string]interface{} if err := verifiedToken.Claims(&tokenClaims); err != nil { return nil, fmt.Errorf("failed to extract claims: %w", err) } userInfo, err := oidcProvider.UserInfo(ctx, oauth2.StaticTokenSource(token)) if err != nil { return nil, fmt.Errorf("failed to get user info: %w", err) } return userInfo, nil } // GenerateUserFromOAuthUserInfo generate the user and account from the oauth user info func GenerateUserFromOAuthUserInfo(userInfo *oidc.UserInfo, provider models.Provider) (models.User, models.Account, error) { userID := ksuid.New().String() // Get the picture from the user info var picture *string var claims struct { Picture string `json:"picture"` } if err := userInfo.Claims(&claims); err == nil && claims.Picture != "" { picture = &claims.Picture } // create the user user := models.User{ ID: userID, PasswordHash: nil, Avatar: picture, CreatedAt: time.Now(), UpdatedAt: time.Now(), } // create the account account := models.Account{ ID: ksuid.New().String(), UserID: userID, Provider: provider, ProviderUserID: userInfo.Subject, Email: userInfo.Email, CreatedAt: time.Now(), UpdatedAt: time.Now(), } return user, account, nil } // GenerateUserAccountFromOAuthUserInfo generate the user and account from the oauth user info func GenerateUserAccountFromOAuthUserInfo(userInfo *oidc.UserInfo, provider models.Provider, userID string) (models.Account, error) { // create the account account := models.Account{ ID: ksuid.New().String(), UserID: userID, Provider: provider, ProviderUserID: userInfo.Subject, Email: userInfo.Email, CreatedAt: time.Now(), UpdatedAt: time.Now(), } return account, nil } // GenerateSessionCookie generates a session cookie func GenerateOAuthSessionCookie(session string) http.Cookie { oauthSessionCookie := http.Cookie{ Name: models.CookieNameOAuthSession, Value: session, HttpOnly: true, Path: "/api/auth/oauth", Secure: config.Env().AppEnv == config.AppEnvProd, Expires: time.Now().Add(time.Duration(config.Env().OAuthStateExpiresAt) * time.Second), SameSite: http.SameSiteLaxMode, } return oauthSessionCookie }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
migrations/1_initialize_schema.up.sql
SQL
-- Create users table CREATE TABLE users ( id VARCHAR(27) PRIMARY KEY, password_hash TEXT, avatar TEXT, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() ); -- Create accounts table CREATE TABLE accounts ( id VARCHAR(27) PRIMARY KEY, provider VARCHAR(50) NOT NULL, provider_user_id VARCHAR(255) NOT NULL, user_id VARCHAR(27) NOT NULL REFERENCES users(id) ON DELETE CASCADE, email VARCHAR(255) NOT NULL, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), UNIQUE(provider, provider_user_id), UNIQUE(provider, email) ); -- Create oauth_tokens table CREATE TABLE oauth_tokens ( account_id VARCHAR(27) PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE, access_token TEXT NOT NULL, refresh_token TEXT, expiry TIMESTAMP WITH TIME ZONE NOT NULL, token_type VARCHAR(50) NOT NULL DEFAULT 'Bearer', provider VARCHAR(50) NOT NULL, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() ); -- Create refresh_tokens table CREATE TABLE refresh_tokens ( id VARCHAR(27) PRIMARY KEY, user_id VARCHAR(27) NOT NULL REFERENCES users(id) ON DELETE CASCADE, token TEXT NOT NULL UNIQUE, user_agent TEXT, ip INET, used_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() ); -- Create indexes for better performance CREATE INDEX idx_accounts_user_id ON accounts(user_id); CREATE INDEX idx_accounts_email ON accounts(email); CREATE INDEX idx_accounts_provider ON accounts(provider); CREATE INDEX idx_oauth_tokens_provider ON oauth_tokens(provider); CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens(user_id); CREATE INDEX idx_refresh_tokens_token ON refresh_tokens(token); CREATE INDEX idx_refresh_tokens_created_at ON refresh_tokens(created_at);
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
pkg/encrypt/argon.go
Go
package encrypt import ( "crypto/rand" "crypto/subtle" "encoding/base64" "fmt" "strings" "golang.org/x/crypto/argon2" ) // params is the parameters for the Argon2id hash type params struct { memory uint32 iterations uint32 parallelism uint8 saltLength uint32 keyLength uint32 } // CreateArgon2idHash generate a Argon2id hash for the password func CreateArgon2idHash(password string) (string, error) { p := &params{ memory: 128 * 1024, iterations: 15, parallelism: 4, saltLength: 16, keyLength: 32, } salt := make([]byte, p.saltLength) if _, err := rand.Read(salt); err != nil { return "", fmt.Errorf("failed to generate salt: %w", err) } hash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength) b64Salt := base64.RawStdEncoding.EncodeToString(salt) b64Hash := base64.RawStdEncoding.EncodeToString(hash) encodedHash := fmt.Sprintf("$argon2id$v=19$t=%d$m=%d$p=%d$%s$%s", p.iterations, p.memory, p.parallelism, b64Salt, b64Hash) return encodedHash, nil } // ComparePasswordAndHash compare the password and the hash func ComparePasswordAndHash(password, encodedHash string) (match bool, err error) { p, salt, hash, err := decodeHash(encodedHash) if err != nil { return false, err } otherHash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength) // Use subtle.ConstantTimeCompare to avoid timing attacks if subtle.ConstantTimeCompare(hash, otherHash) == 1 { return true, nil } return false, nil } // decodeHash decode the hash func decodeHash(encodedHash string) (p *params, salt, hash []byte, err error) { vals := strings.Split(encodedHash, "$") if len(vals) != 8 { return nil, nil, nil, fmt.Errorf("invalid hash") } var version int _, err = fmt.Sscanf(vals[2], "v=%d", &version) if err != nil { return nil, nil, nil, err } if version != argon2.Version { return nil, nil, nil, fmt.Errorf("incompatible version") } p = &params{} _, err = fmt.Sscanf(vals[3], "t=%d", &p.iterations) if err != nil { return nil, nil, nil, err } _, err = fmt.Sscanf(vals[4], "m=%d", &p.memory) if err != nil { return nil, nil, nil, err } _, err = fmt.Sscanf(vals[5], "p=%d", &p.parallelism) if err != nil { return nil, nil, nil, err } salt, err = base64.RawStdEncoding.Strict().DecodeString(vals[6]) if err != nil { return nil, nil, nil, err } p.saltLength = uint32(len(salt)) hash, err = base64.RawStdEncoding.Strict().DecodeString(vals[7]) if err != nil { return nil, nil, nil, err } p.keyLength = uint32(len(hash)) return p, salt, hash, nil }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
pkg/encrypt/jwt_token.go
Go
package encrypt import ( "errors" "time" "github.com/golang-jwt/jwt/v5" ) // JWTSecret is the secret for the JWT // We doing this because this make the function more testable type JWTSecret struct { Secret string } // AccessTokenClaims is the claims for the access token type AccessTokenClaims struct { Issuer string `json:"iss"` Subject string `json:"sub"` ExpiresAt int64 `json:"exp"` IssuedAt int64 `json:"iat"` } // GenerateAccessToken generate an access token func (j *JWTSecret) GenerateAccessToken(issuer string, subject string, expiresAt time.Time) (string, error) { claims := AccessTokenClaims{ Issuer: issuer, Subject: subject, ExpiresAt: expiresAt.Unix(), IssuedAt: time.Now().Unix(), } // TODO: Maybe need a way to covert the struct to map token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "iss": claims.Issuer, "sub": claims.Subject, "exp": claims.ExpiresAt, "iat": claims.IssuedAt, }) return token.SignedString([]byte(j.Secret)) } // ValidateAccessTokenAndGetClaims validate the access token and get the claims func (j *JWTSecret) ValidateAccessTokenAndGetClaims(token string) (bool, AccessTokenClaims, error) { claims := jwt.MapClaims{} _, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) { return []byte(j.Secret), nil }) if err != nil { if err == jwt.ErrTokenInvalidClaims { return false, AccessTokenClaims{}, nil } return false, AccessTokenClaims{}, err } // TODO: Maybe need a more clean way to covert the map to struct issuer, ok := claims["iss"].(string) if !ok { return false, AccessTokenClaims{}, nil } subject, ok := claims["sub"].(string) if !ok { return false, AccessTokenClaims{}, nil } expiresAt, ok := claims["exp"].(float64) if !ok { return false, AccessTokenClaims{}, nil } issuedAt, ok := claims["iat"].(float64) if !ok { return false, AccessTokenClaims{}, nil } accessTokenClaims := AccessTokenClaims{ Issuer: issuer, Subject: subject, ExpiresAt: int64(expiresAt), IssuedAt: int64(issuedAt), } return true, accessTokenClaims, nil } // OAuthStateClaims is the claims for the oauth state type OAuthStateClaims struct { State string `json:"state"` RedirectURI string `json:"redirect_uri"` ExpiresAt int64 `json:"exp"` Subject string `json:"sub"` } // GenerateOAuthState generate an oauth state func (j *JWTSecret) GenerateOAuthState(state string, redirectURI string, expiresAt time.Time, userID string) (string, error) { claims := OAuthStateClaims{ State: state, RedirectURI: redirectURI, ExpiresAt: expiresAt.Unix(), Subject: userID, } // TODO: Maybe need a way to covert the struct to map token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "sub": claims.Subject, "state": claims.State, "redirect_uri": claims.RedirectURI, "exp": claims.ExpiresAt, }) return token.SignedString([]byte(j.Secret)) } // ValidateOAuthStateAndGetClaims validate the oauth state and get the claims func (j *JWTSecret) ValidateOAuthStateAndGetClaims(token string) (bool, OAuthStateClaims, error) { claims := jwt.MapClaims{} _, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) { return []byte(j.Secret), nil }) if err != nil { if errors.Is(err, jwt.ErrTokenInvalidClaims) { return false, OAuthStateClaims{}, nil } return false, OAuthStateClaims{}, err } // TODO: Maybe need a more clean way to covert the map to struct state, ok := claims["state"].(string) if !ok { return false, OAuthStateClaims{}, nil } redirectURI, ok := claims["redirect_uri"].(string) if !ok { return false, OAuthStateClaims{}, nil } expiresAt, ok := claims["exp"].(float64) if !ok { return false, OAuthStateClaims{}, nil } oauthStateClaims := OAuthStateClaims{ State: state, RedirectURI: redirectURI, ExpiresAt: int64(expiresAt), } return true, oauthStateClaims, nil }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
pkg/encrypt/random.go
Go
package encrypt import ( "crypto/rand" "math/big" ) // GenerateRandomString generate a random string func GenerateRandomString(length int) (string, error) { const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" result := make([]byte, length) for i := 0; i < length; i++ { num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset)))) if err != nil { return "", err } result[i] = charset[num.Int64()] } return string(result), nil }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot
pkg/encrypt/refresh_token_generate.go
Go
package encrypt import ( "crypto/rand" "encoding/base64" "fmt" "github.com/segmentio/ksuid" ) // GenerateSecureRefreshToken generate a secure refresh token func GenerateSecureRefreshToken() (string, error) { bytes := make([]byte, 256) // 256-bit _, err := rand.Read(bytes) if err != nil { return "", fmt.Errorf("failed to generate token: %w", err) } return ksuid.New().String() + "_" + base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(bytes), nil }
yorukot/stargo
3
Simple and modern Go web API template built with chi router
Go
yorukot
Yorukot