I am batman
This commit is contained in:
32
api-gateway/Dockerfile
Normal file
32
api-gateway/Dockerfile
Normal file
@@ -0,0 +1,32 @@
|
||||
FROM golang:1.24-alpine AS build
|
||||
RUN apk add --no-cache git ca-certificates protobuf-dev
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# install Go protoc plugins
|
||||
RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@latest && \
|
||||
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
|
||||
|
||||
COPY api-gateway ./api-gateway
|
||||
COPY services/auth-service ./services/auth-service
|
||||
COPY proto ./proto
|
||||
|
||||
# generate proto files
|
||||
RUN mkdir -p proto/auth proto/user proto/post && \
|
||||
export PATH=/go/bin:$PATH && \
|
||||
protoc --go_out=proto --go_opt=paths=source_relative \
|
||||
--go-grpc_out=proto --go-grpc_opt=paths=source_relative \
|
||||
--proto_path=proto \
|
||||
proto/auth.proto proto/user.proto proto/post.proto && \
|
||||
ls -la proto/auth/ proto/user/ proto/post/
|
||||
|
||||
RUN go build -o /app/main ./api-gateway/cmd
|
||||
|
||||
FROM alpine:3.20
|
||||
RUN apk add --no-cache ca-certificates
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/main /app/main
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/app/main"]
|
||||
42
api-gateway/cmd/main.go
Normal file
42
api-gateway/cmd/main.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"go-microservices/api-gateway/internal/handlers"
|
||||
"go-microservices/api-gateway/internal/routes"
|
||||
|
||||
"go-microservices/api-gateway/internal/clients"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("Starting API Gateway...")
|
||||
app := fiber.New()
|
||||
|
||||
// Connect to AuthService gRPC
|
||||
authServiceAddr := os.Getenv("AUTH_SERVICE_GRPC")
|
||||
|
||||
conn, err := grpc.Dial(authServiceAddr, grpc.WithInsecure())
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to AuthService: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
authClient := clients.NewAuthClient(conn)
|
||||
authHandler := handlers.NewAuthHandler(authClient)
|
||||
|
||||
routes.RegisterAuthRoutes(app, authHandler, authClient)
|
||||
|
||||
port := os.Getenv("PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
log.Printf("API Gateway listening on :%s", port)
|
||||
|
||||
log.Fatal(app.Listen(":" + port))
|
||||
}
|
||||
0
api-gateway/config/config.yml
Normal file
0
api-gateway/config/config.yml
Normal file
36
api-gateway/config/env.go
Normal file
36
api-gateway/config/env.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package config
|
||||
|
||||
// import (
|
||||
// "os"
|
||||
// "strconv"
|
||||
// )
|
||||
|
||||
// type Env struct {
|
||||
// Port string
|
||||
// AuthServiceURL string
|
||||
// UserServiceURL string
|
||||
// PostServiceURL string
|
||||
// CommentServiceURL string
|
||||
// LikeServiceURL string
|
||||
// FollowServiceURL string
|
||||
// NotificationURL string
|
||||
// RateLimitPerMinute int
|
||||
// }
|
||||
|
||||
// func LoadEnv() *Env {
|
||||
// rateLimit, err := strconv.Atoi(os.Getenv("RATE_LIMIT_PER_MINUTE"))
|
||||
// if err != nil {
|
||||
// rateLimit = 60 // default value
|
||||
// }
|
||||
// return &Env{
|
||||
// Port: getEnv("PORT", "8080"),
|
||||
// AuthServiceURL: getEnv("AUTH_SERVICE_URL", "http://localhost:8001"),
|
||||
// UserServiceURL: getEnv("USER_SERVICE_URL", "http://localhost:8002"),
|
||||
// PostServiceURL: getEnv("POST_SERVICE_URL", "http://localhost:8003"),
|
||||
// CommentServiceURL: getEnv("COMMENT_SERVICE_URL", "http://localhost:8004"),
|
||||
// LikeServiceURL: getEnv("LIKE_SERVICE_URL", "http://localhost:8005"),
|
||||
// FollowServiceURL: getEnv("FOLLOW_SERVICE_URL", "http://localhost:8006"),
|
||||
// NotificationURL: getEnv("NOTIFICATION_SERVICE_URL", "http://localhost:8007"),
|
||||
// RateLimitPerMinute: rateLimit,
|
||||
// }
|
||||
// }
|
||||
118
api-gateway/internal/clients/clients.go
Normal file
118
api-gateway/internal/clients/clients.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package clients
|
||||
|
||||
import (
|
||||
"context"
|
||||
pb "go-microservices/proto/auth"
|
||||
pbPost "go-microservices/proto/post"
|
||||
pbUser "go-microservices/proto/user"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type AuthClient struct {
|
||||
client pb.AuthServiceClient
|
||||
}
|
||||
|
||||
func NewAuthClient(conn *grpc.ClientConn) *AuthClient {
|
||||
return &AuthClient{
|
||||
client: pb.NewAuthServiceClient(conn),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *AuthClient) SignUp(ctx context.Context, req *pb.SignUpRequest) (*pb.SignUpResponse, error) {
|
||||
return a.client.SignUp(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) SignIn(ctx context.Context, req *pb.SignInRequest) (*pb.SignInResponse, error) {
|
||||
return a.client.SignIn(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) ValidateToken(ctx context.Context, req *pb.ValidateTokenRequest) (*pb.ValidateTokenResponse, error) {
|
||||
return a.client.ValidateToken(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) GetUserInfo(ctx context.Context, req *pb.GetUserInfoRequest) (*pb.GetUserInfoResponse, error) {
|
||||
return a.client.GetUserInfo(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) CreateTest(ctx context.Context, req *pb.CreateTestRequest) (*pb.CreateTestResponse, error) {
|
||||
return a.client.CreateTest(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) ListTests(ctx context.Context, req *pb.ListTestsRequest) (*pb.ListTestsResponse, error) {
|
||||
return a.client.ListTests(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) GetTest(ctx context.Context, req *pb.GetTestRequest) (*pb.GetTestResponse, error) {
|
||||
return a.client.GetTest(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) UpdateTest(ctx context.Context, req *pb.UpdateTestRequest) (*pb.UpdateTestResponse, error) {
|
||||
return a.client.UpdateTest(ctx, req)
|
||||
}
|
||||
|
||||
func (a *AuthClient) DeleteTest(ctx context.Context, req *pb.DeleteTestRequest) (*pb.DeleteTestResponse, error) {
|
||||
return a.client.DeleteTest(ctx, req)
|
||||
}
|
||||
|
||||
type UserClient struct {
|
||||
client pbUser.UserServiceClient
|
||||
}
|
||||
|
||||
func NewUserClient(conn *grpc.ClientConn) *UserClient {
|
||||
return &UserClient{
|
||||
client: pbUser.NewUserServiceClient(conn),
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UserClient) CreateUser(ctx context.Context, req *pbUser.CreateUserRequest) (*pbUser.CreateUserResponse, error) {
|
||||
return u.client.CreateUser(ctx, req)
|
||||
}
|
||||
|
||||
func (u *UserClient) GetUser(ctx context.Context, req *pbUser.GetUserRequest) (*pbUser.GetUserResponse, error) {
|
||||
return u.client.GetUser(ctx, req)
|
||||
}
|
||||
|
||||
func (u *UserClient) UpdateUser(ctx context.Context, req *pbUser.UpdateUserRequest) (*pbUser.UpdateUserResponse, error) {
|
||||
return u.client.UpdateUser(ctx, req)
|
||||
}
|
||||
|
||||
func (u *UserClient) DeleteUser(ctx context.Context, req *pbUser.DeleteUserRequest) error {
|
||||
_, err := u.client.DeleteUser(ctx, req)
|
||||
return err
|
||||
}
|
||||
|
||||
func (u *UserClient) ListUsers(ctx context.Context, req *pbUser.ListUsersRequest) (*pbUser.ListUsersResponse, error) {
|
||||
return u.client.ListUsers(ctx, req)
|
||||
}
|
||||
|
||||
type PostClient struct {
|
||||
client pbPost.PostServiceClient
|
||||
}
|
||||
|
||||
func NewPostClient(conn *grpc.ClientConn) *PostClient {
|
||||
return &PostClient{
|
||||
client: pbPost.NewPostServiceClient(conn),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PostClient) CreatePost(ctx context.Context, req *pbPost.CreatePostRequest) (*pbPost.CreatePostResponse, error) {
|
||||
return p.client.CreatePost(ctx, req)
|
||||
}
|
||||
|
||||
func (p *PostClient) GetPost(ctx context.Context, req *pbPost.GetPostRequest) (*pbPost.GetPostResponse, error) {
|
||||
return p.client.GetPost(ctx, req)
|
||||
}
|
||||
|
||||
func (p *PostClient) UpdatePost(ctx context.Context, req *pbPost.UpdatePostRequest) (*pbPost.UpdatePostResponse, error) {
|
||||
return p.client.UpdatePost(ctx, req)
|
||||
}
|
||||
|
||||
func (p *PostClient) DeletePost(ctx context.Context, req *pbPost.DeletePostRequest) error {
|
||||
_, err := p.client.DeletePost(ctx, req)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *PostClient) ListPosts(ctx context.Context, req *pbPost.ListPostsRequest) (*pbPost.ListPostsResponse, error) {
|
||||
return p.client.ListPosts(ctx, req)
|
||||
}
|
||||
167
api-gateway/internal/handlers/handlers.go
Normal file
167
api-gateway/internal/handlers/handlers.go
Normal file
@@ -0,0 +1,167 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"go-microservices/api-gateway/internal/clients"
|
||||
pb "go-microservices/proto/auth"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
AuthClient *clients.AuthClient
|
||||
}
|
||||
|
||||
func NewAuthHandler(authClient *clients.AuthClient) *AuthHandler {
|
||||
return &AuthHandler{AuthClient: authClient}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) SignUp(c *fiber.Ctx) error {
|
||||
var req pb.SignUpRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
|
||||
}
|
||||
resp, err := h.AuthClient.SignUp(context.Background(), &req)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) SignIn(c *fiber.Ctx) error {
|
||||
var req pb.SignInRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
|
||||
}
|
||||
resp, err := h.AuthClient.SignIn(context.Background(), &req)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusUnauthorized).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) ValidateToken(c *fiber.Ctx) error {
|
||||
var req pb.ValidateTokenRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
|
||||
}
|
||||
resp, err := h.AuthClient.ValidateToken(context.Background(), &req)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusUnauthorized).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) GetUserInfo(c *fiber.Ctx) error {
|
||||
var req pb.GetUserInfoRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
|
||||
}
|
||||
resp, err := h.AuthClient.GetUserInfo(context.Background(), &req)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
// CreateTest forwards a test creation request to the auth service
|
||||
func (h *AuthHandler) CreateTest(c *fiber.Ctx) error {
|
||||
var body struct {
|
||||
Test string `json:"test"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
|
||||
}
|
||||
req := pb.CreateTestRequest{Content: body.Test}
|
||||
resp, err := h.AuthClient.CreateTest(context.Background(), &req)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
// ListTests retrieves tests from the auth service
|
||||
func (h *AuthHandler) ListTests(c *fiber.Ctx) error {
|
||||
resp, err := h.AuthClient.ListTests(context.Background(), &pb.ListTestsRequest{})
|
||||
if err != nil {
|
||||
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
// GetTest retrieves a single test by ID
|
||||
func (h *AuthHandler) GetTest(c *fiber.Ctx) error {
|
||||
id := c.Params("id")
|
||||
if id == "" {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "test id required"})
|
||||
}
|
||||
|
||||
var testID uint64
|
||||
_, err := fmt.Sscanf(id, "%d", &testID)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid test id"})
|
||||
}
|
||||
|
||||
resp, err := h.AuthClient.GetTest(context.Background(), &pb.GetTestRequest{Id: testID})
|
||||
if err != nil {
|
||||
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
// UpdateTest updates a test by ID
|
||||
func (h *AuthHandler) UpdateTest(c *fiber.Ctx) error {
|
||||
id := c.Params("id")
|
||||
if id == "" {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "test id required"})
|
||||
}
|
||||
|
||||
var testID uint64
|
||||
_, err := fmt.Sscanf(id, "%d", &testID)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid test id"})
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
|
||||
}
|
||||
|
||||
if body.Content == "" {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "content required"})
|
||||
}
|
||||
|
||||
resp, err := h.AuthClient.UpdateTest(context.Background(), &pb.UpdateTestRequest{
|
||||
Id: testID,
|
||||
Content: body.Content,
|
||||
})
|
||||
if err != nil {
|
||||
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
|
||||
// DeleteTest deletes a test by ID
|
||||
func (h *AuthHandler) DeleteTest(c *fiber.Ctx) error {
|
||||
id := c.Params("id")
|
||||
if id == "" {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "test id required"})
|
||||
}
|
||||
|
||||
var testID uint64
|
||||
_, err := fmt.Sscanf(id, "%d", &testID)
|
||||
if err != nil {
|
||||
return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid test id"})
|
||||
}
|
||||
|
||||
resp, err := h.AuthClient.DeleteTest(context.Background(), &pb.DeleteTestRequest{Id: testID})
|
||||
if err != nil {
|
||||
return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
return c.JSON(resp)
|
||||
}
|
||||
50
api-gateway/internal/middlewares/jwt.go
Normal file
50
api-gateway/internal/middlewares/jwt.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"go-microservices/api-gateway/internal/clients"
|
||||
pb "go-microservices/proto/auth"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// JWTMiddleware returns a Fiber middleware that validates JWT via the auth service gRPC.
|
||||
func JWTMiddleware(authClient *clients.AuthClient) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
// Try to get Authorization header (Fiber handles case-insensitivity)
|
||||
authHeader := c.Get("Authorization")
|
||||
var token string
|
||||
|
||||
if authHeader != "" {
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) == 2 && parts[0] == "Bearer" {
|
||||
token = parts[1]
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to cookie if no Bearer token found
|
||||
if token == "" {
|
||||
token = c.Cookies("access_token")
|
||||
}
|
||||
|
||||
if token == "" {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "missing token"})
|
||||
}
|
||||
|
||||
// Validate token via gRPC
|
||||
resp, err := authClient.ValidateToken(context.Background(), &pb.ValidateTokenRequest{Token: token})
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "token validation failed"})
|
||||
}
|
||||
|
||||
if !resp.Valid {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid token"})
|
||||
}
|
||||
|
||||
c.Locals("userID", resp.UserId)
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
36
api-gateway/internal/middlewares/roles.go
Normal file
36
api-gateway/internal/middlewares/roles.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func OnlyAdmin(db *gorm.DB, fn fiber.Handler) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
role, ok := c.Locals("userRole").(string)
|
||||
if !ok || role != "Admin" {
|
||||
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "Access denied"})
|
||||
}
|
||||
return fn(c)
|
||||
}
|
||||
}
|
||||
|
||||
func OnlyModerator(db *gorm.DB, fn fiber.Handler) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
role, ok := c.Locals("userRole").(string)
|
||||
if !ok || (role != "Moderator" && role != "Admin") {
|
||||
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "Access denied"})
|
||||
}
|
||||
return fn(c)
|
||||
}
|
||||
}
|
||||
|
||||
func OnlyUser(db *gorm.DB, fn fiber.Handler) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
role, ok := c.Locals("userRole").(string)
|
||||
if !ok || role != "User" {
|
||||
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "Access denied"})
|
||||
}
|
||||
return fn(c)
|
||||
}
|
||||
}
|
||||
30
api-gateway/internal/routes/routes.go
Normal file
30
api-gateway/internal/routes/routes.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"go-microservices/api-gateway/internal/clients"
|
||||
"go-microservices/api-gateway/internal/handlers"
|
||||
"go-microservices/api-gateway/internal/middlewares"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func RegisterAuthRoutes(app *fiber.App, authHandler *handlers.AuthHandler, authClient *clients.AuthClient) {
|
||||
api := app.Group("/api/v1")
|
||||
|
||||
// Health route
|
||||
api.Get("/", func(c *fiber.Ctx) error {
|
||||
return c.SendString("API Gateway is running!")
|
||||
})
|
||||
|
||||
api.Post("/signup", authHandler.SignUp)
|
||||
api.Post("/signin", authHandler.SignIn)
|
||||
api.Post("/validate", authHandler.ValidateToken)
|
||||
api.Post("/userinfo", middlewares.JWTMiddleware(authClient), authHandler.GetUserInfo)
|
||||
|
||||
// Test endpoints
|
||||
api.Post("/test", authHandler.CreateTest)
|
||||
api.Get("/tests", authHandler.ListTests)
|
||||
api.Get("/tests/:id", authHandler.GetTest)
|
||||
api.Put("/tests/:id", authHandler.UpdateTest)
|
||||
api.Delete("/tests/:id", authHandler.DeleteTest)
|
||||
}
|
||||
Reference in New Issue
Block a user