Skip to content

Commit

Permalink
added comments
Browse files Browse the repository at this point in the history
  • Loading branch information
kwa0x2 committed May 27, 2024
1 parent 5a7f862 commit 6da9bbd
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 21 deletions.
51 changes: 51 additions & 0 deletions .air.toml
Original file line number Diff line number Diff line change
@@ -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
10 changes: 2 additions & 8 deletions .env
Original file line number Diff line number Diff line change
@@ -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
25 changes: 20 additions & 5 deletions controller/session_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,39 +8,54 @@ 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"),
"user_email":session.Get("user_email"),
})
}

// 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.",
})
}
}
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 8 additions & 3 deletions middleware/auth_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
1 change: 1 addition & 0 deletions tmp/build-errors.log
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exit status 1exit status 1exit status 1exit status 1exit status 1
16 changes: 12 additions & 4 deletions utils/redis_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 6da9bbd

Please sign in to comment.