Skip to content

Commit

Permalink
implemented api key funtionality
Browse files Browse the repository at this point in the history
  • Loading branch information
Kirari04 committed Jan 20, 2024
1 parent f96aa85 commit 18b189d
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
8 changes: 5 additions & 3 deletions auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
39 changes: 39 additions & 0 deletions controllers/AuthApikeyController.go
Original file line number Diff line number Diff line change
@@ -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,
})
}
4 changes: 4 additions & 0 deletions routes/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 18b189d

Please sign in to comment.