From 6da9bbd786d144c33ef3c89c344f11ab7ca98500 Mon Sep 17 00:00:00 2001 From: kwa0x2 Date: Tue, 28 May 2024 01:30:14 +0300 Subject: [PATCH] added comments --- .air.toml | 51 ++++++++++++++++++++++++++++++++ .env | 10 ++----- controller/session_controller.go | 25 ++++++++++++---- main.go | 2 +- middleware/auth_middleware.go | 11 +++++-- tmp/build-errors.log | 1 + utils/redis_session.go | 16 +++++++--- 7 files changed, 95 insertions(+), 21 deletions(-) create mode 100644 .air.toml create mode 100644 tmp/build-errors.log diff --git a/.air.toml b/.air.toml new file mode 100644 index 0000000..52fa757 --- /dev/null +++ b/.air.toml @@ -0,0 +1,51 @@ +root = "." +testdata_dir = "testdata" +tmp_dir = "tmp" + +[build] + args_bin = [] + bin = "tmp\\main.exe" + cmd = "go build -o ./tmp/main.exe ." + delay = 1000 + exclude_dir = ["assets", "tmp", "vendor", "testdata"] + exclude_file = [] + exclude_regex = ["_test.go"] + exclude_unchanged = false + follow_symlink = false + full_bin = "" + include_dir = [] + include_ext = ["go", "tpl", "tmpl", "html"] + include_file = [] + kill_delay = "0s" + log = "build-errors.log" + poll = false + poll_interval = 0 + post_cmd = [] + pre_cmd = [] + rerun = false + rerun_delay = 500 + send_interrupt = false + stop_on_error = false + +[color] + app = "" + build = "yellow" + main = "magenta" + runner = "green" + watcher = "cyan" + +[log] + main_only = false + time = false + +[misc] + clean_on_exit = false + +[proxy] + app_port = 0 + enabled = false + proxy_port = 0 + +[screen] + clear_on_rebuild = false + keep_scroll = true diff --git a/.env b/.env index cdd35e3..a530a69 100644 --- a/.env +++ b/.env @@ -1,9 +1,3 @@ SESSION_SECRET_KEY=6XM2Xa/gnN0aMGHt44JMOcl/kfA0axF7SvnImGCUwVpv5X/Gp86FOKPE5hKOjJmDqY4q+DIWhTayw0C9gSKykm2mdDKOG6FZBkT/KLbZtr8= - -POSTGRE_USER=nettasec -POSTGRE_PASSWORD=nettaseclocal -POSTGRE_HOST=localhost:5437 -POSTGRE_DB=nettasec_global_db - -REDIS_HOST=localhost:6379 -REDIS_PASSWORD=nettaseclocal +REDIS_HOST=localhost:6380 +REDIS_PASSWORD=redispassword diff --git a/controller/session_controller.go b/controller/session_controller.go index 0b9cf1e..d9e32a9 100644 --- a/controller/session_controller.go +++ b/controller/session_controller.go @@ -8,19 +8,23 @@ import ( "github.com/google/uuid" ) +// SetSessionExample sets a user ID and email in the session and saves it. func SetSessionExample(ctx *gin.Context) { session := sessions.Default(ctx) - session.Set("user_id", uuid.New()) + // Generate a new UUID for the user and set it in the session + session.Set("user_id", uuid.New().String()) session.Set("user_email", "example@nettasec.com") err := session.Save() if err != nil { + // Return an internal server error if the session could not be saved ctx.JSON(http.StatusInternalServerError, gin.H{ - "error":"Failed to save session", + "error":err.Error(), }) return } + // Return a success message with the user ID and email from the session ctx.JSON(http.StatusOK, gin.H{ "message":"Successfully logged in", "user_id":session.Get("user_id"), @@ -28,19 +32,30 @@ func SetSessionExample(ctx *gin.Context) { }) } +// ClearSessionExample clears the session and deletes the session cookie. func ClearSessionExample(ctx *gin.Context) { session := sessions.Default(ctx) + // Clear all session data and set the session's max age to -1 (delete it) session.Clear() session.Options(sessions.Options{MaxAge: -1}) session.Save() + // Delete the session cookie ctx.SetCookie("connect.sid","",-1,"/","localhost",true,true) - ctx.Redirect(http.StatusTemporaryRedirect, "/api/session/auth") + + // Return a success message indicating the session has been cleared + ctx.JSON(http.StatusOK, gin.H{ + "message":"Successfully cleared. Please go to the authentication endpoint for testing.", + }) } +// AuthSessionExample returns a message indicating the user is authenticated. func AuthSessionExample(ctx *gin.Context) { + // If the request reaches this handler, it means the user has passed through the authentication middleware. + + // Return a success message indicating the user is authenticated. ctx.JSON(http.StatusOK, gin.H{ - "message":"If you are seeing this message, you are authenticated.", + "message": "If you are seeing this message, you are authenticated.", }) -} \ No newline at end of file +} diff --git a/main.go b/main.go index 11a9198..20424b0 100644 --- a/main.go +++ b/main.go @@ -15,7 +15,7 @@ func main() { // The name of your cookie is "connect.sid" router.Use(sessions.Sessions("connect.sid", store)) - sessionRoutes:=router.Group("/api/sessions") + sessionRoutes:=router.Group("/api/session") sessionRoutes.GET("set", controller.SetSessionExample) sessionRoutes.GET("clear", controller.ClearSessionExample) sessionRoutes.GET("auth",middleware.SessionAuthMiddleware(), controller.AuthSessionExample) diff --git a/middleware/auth_middleware.go b/middleware/auth_middleware.go index fe2ce21..cbd5d0a 100644 --- a/middleware/auth_middleware.go +++ b/middleware/auth_middleware.go @@ -10,16 +10,21 @@ import ( func SessionAuthMiddleware() gin.HandlerFunc { return func(ctx *gin.Context) { + // Get the default session for the current context session := sessions.Default(ctx) + // Get the user ID from the session sessionUserID := session.Get("user_id") + // If the user ID is nil (meaning no user is logged in), return an unauthorized status and message if sessionUserID == nil { ctx.JSON(http.StatusUnauthorized, gin.H{ - "message": "Autharization failed", + "message": "Authorization failed", }) + // Abort the request processing since the user is not authorized ctx.Abort() - } + // Set the expiration time for the session to 24 hours from now session.Set("Expires", time.Now().Add(24*time.Hour)) - session.Save() + // Save the session + session.Save() } } diff --git a/tmp/build-errors.log b/tmp/build-errors.log new file mode 100644 index 0000000..1cada71 --- /dev/null +++ b/tmp/build-errors.log @@ -0,0 +1 @@ +exit status 1exit status 1exit status 1exit status 1exit status 1 \ No newline at end of file diff --git a/utils/redis_session.go b/utils/redis_session.go index fce057f..873dfb6 100644 --- a/utils/redis_session.go +++ b/utils/redis_session.go @@ -9,17 +9,25 @@ import ( ) func RedisSession() redis.Store { - store, err := redis.NewStore(10,"tcp", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PASSWORD"), []byte(os.Getenv("SESSION_SECRET_KEY"))) + // Create a new Redis session store + store, err := redis.NewStore(10, "tcp", os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PASSWORD"), []byte(os.Getenv("SESSION_SECRET_KEY"))) if err != nil { + // Panic if there is an error creating the store panic(err) } + // Configure the session options store.Options(sessions.Options{ - MaxAge: int((24 *time.Hour).Seconds()), - Path: "/", + // Set the maximum age of the session to 24 hours + MaxAge: int((24 * time.Hour).Seconds()), + // Set the path for the session cookie to "/" + Path: "/", + // Set the HttpOnly flag to true to prevent client-side JavaScript access to the cookie HttpOnly: true, - Secure: true, + // Set the Secure flag to true to ensure the cookie is only sent over HTTPS + Secure: true, }) + // Return the configured store return store } \ No newline at end of file