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

#6 Added auth middleware #50

Merged
merged 3 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
40 changes: 40 additions & 0 deletions App/Backend/cmd/auth/AuthHandlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package auth

import (
"github.com/gin-gonic/gin"
"net/http"
)

var envUsername = "test" //os.Getenv("USERNAME")
var envPassword = "test" //os.Getenv("PASSWORD")

func HandleLogin(ctx *gin.Context) {
var credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}

if err := ctx.BindJSON(&credentials); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}

if credentials.Username != envUsername || credentials.Password != envPassword {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
return
}

token, err := GenerateToken(credentials.Username)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
return
}

ctx.SetCookie("jwt", token, 3600*24, "/", "", false, true)
ctx.JSON(http.StatusOK, gin.H{"message": "Login successful"})
}

func HandleLogout(ctx *gin.Context) {
ctx.SetCookie("jwt", "", -1, "/", "", false, true)
ctx.JSON(http.StatusOK, gin.H{"message": "Logout successful"})
}
50 changes: 50 additions & 0 deletions App/Backend/cmd/auth/AuthMiddleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package auth

import (
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"net/http"
"time"
)

var jwtSecret = []byte("L7Naq/2kj9tAYs2Aap47w5Pzo7q/HhtsVFB/zgGnLHg=") //[]byte(os.Getenv("JWT_SECRET"))

type JwtClaims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}

func AuthMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
jwtTokenString, err := ctx.Cookie("jwt")
if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}

token, err := jwt.Parse(jwtTokenString, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})

if err != nil || !token.Valid {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}

ctx.Next()
}
}

func GenerateToken(username string) (string, error) {
claims := JwtClaims{
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
},
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(jwtSecret)
}
20 changes: 18 additions & 2 deletions App/Backend/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,25 @@
package main

import (
"fmt"
"github.com/eliasdehondt/K10s/App/Backend/cmd/auth"
"github.com/gin-gonic/gin"
)

func main() {
fmt.Println("K10s")

r := gin.Default()

r.POST("/login", auth.HandleLogin)
r.GET("/logout", auth.HandleLogout)

secured := r.Group("/secured")
secured.Use(auth.AuthMiddleware())
secured.GET("/", func(c *gin.Context) {
println("Test print")
})

err := r.Run(":8080")
if err != nil {
panic(err)
}
}
Loading