From 18b189d0e905102e88c7b287a15eee9afdae9a5c Mon Sep 17 00:00:00 2001 From: kirari04 Date: Sat, 20 Jan 2024 12:28:37 +0100 Subject: [PATCH] implemented api key funtionality --- auth/jwt.go | 8 +++--- controllers/AuthApikeyController.go | 39 +++++++++++++++++++++++++++++ routes/api.go | 4 +++ 3 files changed, 48 insertions(+), 3 deletions(-) create mode 100755 controllers/AuthApikeyController.go diff --git a/auth/jwt.go b/auth/jwt.go index d1c3826..69fe30c 100755 --- a/auth/jwt.go +++ b/auth/jwt.go @@ -21,10 +21,12 @@ var jwtKey []byte var sessionDuration = 15 * time.Minute func GenerateJWT(user models.User) (string, time.Time, error) { - jwtKey = []byte(config.ENV.JwtSecretKey) - // Declare the expiration time of the token - // here, we have kept it as 5 minutes expirationTime := time.Now().Add(sessionDuration) + return GenerateTimeJWT(user, expirationTime) +} + +func GenerateTimeJWT(user models.User, expirationTime time.Time) (string, time.Time, error) { + jwtKey = []byte(config.ENV.JwtSecretKey) // Create the JWT claims, which includes the username and expiry time claims := &Claims{ UserID: user.ID, diff --git a/controllers/AuthApikeyController.go b/controllers/AuthApikeyController.go new file mode 100755 index 0000000..a6eb787 --- /dev/null +++ b/controllers/AuthApikeyController.go @@ -0,0 +1,39 @@ +package controllers + +import ( + "ch/kirari04/videocms/auth" + "ch/kirari04/videocms/inits" + "ch/kirari04/videocms/models" + "log" + "net/http" + "time" + + "github.com/labstack/echo/v4" +) + +func AuthApikey(c echo.Context) error { + userId, ok := c.Get("UserID").(uint) + if !ok { + c.Logger().Error("Failed to catch user") + return c.NoContent(http.StatusInternalServerError) + } + + var user models.User + res := inits.DB. + Model(&models.User{}). + First(&user, userId) + if res.Error != nil { + return c.String(http.StatusBadRequest, "User not found") + } + expirationTime := time.Now().Add(time.Hour * 24 * 365) + tokenString, _, err := auth.GenerateTimeJWT(user, expirationTime) + if err != nil { + log.Printf("Failed to generate jwt for user %s: %v\n", user.Username, err) + return c.NoContent(http.StatusInternalServerError) + } + + return c.JSON(http.StatusOK, echo.Map{ + "exp": expirationTime, + "token": tokenString, + }) +} diff --git a/routes/api.go b/routes/api.go index 0975484..2260e54 100755 --- a/routes/api.go +++ b/routes/api.go @@ -23,6 +23,10 @@ func Api() { auth.GET("/refresh", controllers.AuthRefresh, middleware.RateLimiterWithConfig(*helpers.LimiterConfig(1, 2, time.Minute*5))) + auth.POST("/apikey", + controllers.AuthApikey, + middleware.RateLimiterWithConfig(*helpers.LimiterConfig(1, 2, time.Minute*5)), + middlewares.Auth()) // Routes that dont require authentication inits.Api.GET("/config", controllers.GetConfig)