Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Middleware and Google OAuth Authentication #24

Open
wants to merge 2 commits into
base: go-backend
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions backend-go/internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ import (
"context"
"fmt"
"log"
"net/http"
"os"
"regexp"

"strings"

"google.golang.org/api/idtoken"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)


var clientID string = os.Getenv("GOOGLE_CLIENT_ID") // get from env to validate tokenid

// User data structure
Expand Down Expand Up @@ -152,3 +154,38 @@ func IsUserExists(email string) (bool, int, error) {

return true, userID, nil
}

func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is missing"})
c.Abort()
return
}

tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader { // No "Bearer" prefix
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
c.Abort()
return
}

isValid, claims := VerifyToken(tokenString)
if !isValid {
c.JSON(http.StatusUnauthorized, gin.H{"error": claims.(string)}) // Claims will be the error message
c.Abort()
return
}

// Extract user ID from the claims (assuming it's stored under the "sub" key)
claimsMap := claims.(jwt.MapClaims)
userID := claimsMap["sub"].(string)

// Store the userID in the context so that handlers can access it
c.Set("user_id", userID)

// Proceed to the next handler
c.Next()
}
}
2 changes: 2 additions & 0 deletions backend-go/internal/auth/controller.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package auth

import (
"fmt"
"net/http"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -49,4 +50,5 @@ func LoginHandler(c *gin.Context) {
} else {
c.JSON(http.StatusUnauthorized, gin.H{"error": msg})
}
fmt.Println(loginRequest.IDToken)
}
10 changes: 4 additions & 6 deletions backend-go/internal/server/routes/lost_found.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@ package routes

import (
"net/http"

"github.com/gin-gonic/gin"
)


func SetupLostRouter(r *gin.Engine){
lost_handler := r.Group("/some_route")
{
lost_handler.GET("/lost", HelloWorldHandler);
}
func SetupLostRouter(rg *gin.RouterGroup) {
rg.GET("/lost", HelloWorldHandler)
rg.POST("/lost", HelloWorldHandler)
}

func HelloWorldHandler(c *gin.Context) {
Expand Down
25 changes: 15 additions & 10 deletions backend-go/internal/server/server.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package server

import (
"Dashboard/internal/auth"
"Dashboard/internal/database"
"Dashboard/internal/server/routes" // Import the routes
"fmt"
"net/http"
"os"
"strconv"
"time"

"github.com/gin-gonic/gin"
"Dashboard/internal/server/routes" // Import the routes
"Dashboard/internal/database"
)

type Server struct {
Expand All @@ -17,22 +17,28 @@ type Server struct {
db database.Service
}


func (s *Server) RegisterRoutes() http.Handler {
r := gin.Default()

// Register routes from different files
routes.SetupLostRouter(r)
r.GET("/health", routes.HealthHandler)

auth.SetupAuthRoutes(r)

protected := r.Group("/protected")

protected.Use(auth.AuthMiddleware())

routes.SetupLostRouter(protected)

return r
}


func NewServer() *http.Server {
port, _ := strconv.Atoi(os.Getenv("PORT"))
// port, _ := strconv.Atoi(os.Getenv("PORT"))
// port, _ := strconv.Atoi(os.Getenv("8000"))
NewServer := &Server{
port: port,
port: 8000,

db: database.New(),
}
Expand All @@ -46,6 +52,5 @@ func NewServer() *http.Server {
WriteTimeout: 30 * time.Second,
}


return server
}