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

hotfix(security): add token check #122

Merged
merged 1 commit into from
Dec 4, 2024
Merged
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
28 changes: 3 additions & 25 deletions client_web/src/Components/Security.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React, { useState, useEffect } from "react";
import { useAuth } from "@/Context/ContextHooks";
import { useNavigate } from "react-router-dom";
// import { instance, auth } from "@/Config/backend.routes";
import { Spin } from 'antd';
import {instance, root} from "@Config/backend.routes";
import { instance, instanceWithAuth, root, auth } from "@Config/backend.routes";
import {toast} from "react-toastify";

type SecurityProps = {
Expand All @@ -21,8 +20,7 @@ const Security = ({ children }: SecurityProps) => {
const checkAuth = () => {
if (!isAuthenticated || !jsonWebToken) {
if (localStorage.getItem("jsonWebToken")) {
// instance.post(auth.health, {jwt: localStorage.getItem("jsonWebToken")}) //TODO: Create /health endpoint
Promise.resolve()
instanceWithAuth.get(auth.health)
.then(() => {
setIsAuthenticated(true);
setJsonWebToken(localStorage.getItem("jsonWebToken") as string);
Expand Down Expand Up @@ -50,27 +48,7 @@ const Security = ({ children }: SecurityProps) => {
};

checkAuth();
}, [isAuthenticated, jsonWebToken, navigate, setIsAuthenticated, setJsonWebToken]);

const ping = () => {
const response = instance.get(root.ping)
.then((response) => {
setPingResponse(true);
})
.catch((error) => {
setPingResponse(false);
console.error(error);
navigate("/error/connection");
toast.error('Failed to ping the server');
});
};

React.useEffect(() => {
if (!hasPinged.current) {
ping();
hasPinged.current = true;
}
}, []);
}, [isAuthenticated, jsonWebToken]);

if (loading) {
return <Spin size="large" />;
Expand Down
5 changes: 0 additions & 5 deletions server/internal/controllers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,6 @@ func Register(c *gin.Context) {
// @Failure 401 {object} map[string]string
// @Router /auth/health [get]
func Health(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: No token provided"})
return
}
_, err := utils.VerifyToken(c)

if err != nil {
Expand Down
16 changes: 6 additions & 10 deletions server/internal/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,8 @@ func AuthMiddleware() gin.HandlerFunc {
}

func isAuthenticated(c *gin.Context) bool {
token := c.GetHeader("Authorization")
if token == "" {
return false
}

user := models.User{}
db.DB.Where("token = ?", token).First(&user)
if user.ID == 0 {
return false
}
_, err := utils.VerifyToken(c)
email, err := utils.VerifyToken(c)
if err != nil {
if err.Error() == "Token is expired" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is expired"})
Expand All @@ -38,5 +29,10 @@ func isAuthenticated(c *gin.Context) bool {
}
return false
}
db.DB.Where("email = ?", email).First(&user)
if user.ID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return false
}
return true
}
3 changes: 2 additions & 1 deletion server/internal/middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
func EnableCors() gin.HandlerFunc {
corsConfig := cors.DefaultConfig()
corsConfig.AllowOrigins = config.AppConfig.CorsOrigins
corsConfig.AllowMethods = []string{"GET", "POST", "PUT", "DELETE"}
corsConfig.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
corsConfig.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Authorization"}
return cors.New(corsConfig)
}
10 changes: 9 additions & 1 deletion server/internal/utils/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/gin-gonic/gin"
"net/http"
"time"
"strings"
)

func NewToken(c *gin.Context, email string) string {
Expand All @@ -21,7 +22,14 @@ func NewToken(c *gin.Context, email string) string {
}

func VerifyToken(c *gin.Context) (string, error) {
tokenString := c.GetHeader("Authorization")
authHeader := c.GetHeader("Authorization")

if !strings.HasPrefix(authHeader, "Bearer ") {
return "", errors.New("Bearer token is missing")
}

tokenString := strings.TrimPrefix(authHeader, "Bearer ")

if tokenString == "" {
return "", errors.New("Authorization token is missing")
}
Expand Down
Loading