Skip to content

Commit

Permalink
feat: All token system moved to JWT instead of random DB generated st…
Browse files Browse the repository at this point in the history
…ring
  • Loading branch information
dogukanoksuz committed Jul 19, 2024
1 parent b87da9d commit 53baf4d
Show file tree
Hide file tree
Showing 11 changed files with 53 additions and 133 deletions.
7 changes: 1 addition & 6 deletions app/handlers/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,6 @@ func ExtensionRunner(c *fiber.Ctx) error {

formValues := helpers.GetFormData(c)

token := c.FormValue("token")
if len(c.FormValue("liman-token")) > 0 {
token = c.FormValue("liman-token")
}

command, err := sandbox.GenerateCommand(
extension,
credentials,
Expand All @@ -63,7 +58,7 @@ func ExtensionRunner(c *fiber.Ctx) error {
Extension: c.FormValue("extension_id"),
Server: c.FormValue("server_id"),
RequestData: formValues,
Token: token,
Token: c.Locals("token").(string),
BaseURL: c.FormValue("lmnbaseurl", c.Get("origin")),
Locale: c.FormValue("locale", helpers.Env("APP_LANG", "tr")),
LogID: c.Locals("log_id").(string),
Expand Down
7 changes: 1 addition & 6 deletions app/handlers/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,6 @@ func ExternalAPI(c *fiber.Ctx) error {

formValues := helpers.GetFormData(c)

token := c.FormValue("token")
if len(c.FormValue("liman-token")) > 0 {
token = c.FormValue("liman-token")
}

command, err := sandbox.GenerateCommand(
extension,
credentials,
Expand All @@ -68,7 +63,7 @@ func ExternalAPI(c *fiber.Ctx) error {
Extension: c.FormValue("extension_id"),
Server: c.FormValue("server_id"),
RequestData: formValues,
Token: token,
Token: c.Locals("token").(string),
BaseURL: c.FormValue("lmnbaseurl", c.Get("origin")),
Locale: c.FormValue("locale", helpers.Env("APP_LANG", "tr")),
LogID: c.Locals("log_id").(string),
Expand Down
7 changes: 1 addition & 6 deletions app/handlers/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,6 @@ func DownloadFile(c *fiber.Ctx) error {

formValues := helpers.GetFormData(c)

token := c.FormValue("token")
if len(c.FormValue("liman-token")) > 0 {
token = c.FormValue("liman-token")
}

_, err = sandbox.GenerateCommand(
extension,
credentials,
Expand All @@ -148,7 +143,7 @@ func DownloadFile(c *fiber.Ctx) error {
Extension: c.FormValue("extension_id"),
Server: c.FormValue("server_id"),
RequestData: formValues,
Token: token,
Token: c.Locals("token").(string),
BaseURL: c.FormValue("lmnbaseurl", c.Get("origin")),
Locale: c.FormValue("locale", helpers.Env("APP_LANG", "tr")),
LogID: c.Locals("log_id").(string),
Expand Down
7 changes: 1 addition & 6 deletions app/handlers/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,6 @@ func BackgroundJob(c *fiber.Ctx) error {

formValues := helpers.GetFormData(c)

token := c.FormValue("token")
if len(c.FormValue("liman-token")) > 0 {
token = c.FormValue("liman-token")
}

command, err := sandbox.GenerateCommand(
extension,
credentials,
Expand All @@ -59,7 +54,7 @@ func BackgroundJob(c *fiber.Ctx) error {
Extension: c.FormValue("extension_id"),
Server: c.FormValue("server_id"),
RequestData: formValues,
Token: token,
Token: c.Locals("token").(string),
BaseURL: c.FormValue("lmnbaseurl", c.Get("origin")),
Locale: c.FormValue("locale", helpers.Env("APP_LANG", "tr")),
},
Expand Down
61 changes: 27 additions & 34 deletions app/middleware/auth/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,64 +22,56 @@ type Cookie struct {

// authorization Middleware auths users before requests
func authorization(c *fiber.Ctx) error {
cookie := new(Cookie)
c.CookieParser(cookie)
if len(c.FormValue("liman-token")) > 0 {
user, err := liman.AuthWithAccessToken(
strings.Trim(c.FormValue("liman-token"), ""),
)

if len(cookie.Token) > 0 {
decoded, err := url.QueryUnescape(cookie.Token)
if err != nil {
logger.FiberError(fiber.StatusUnauthorized, "invalid authorization token (cookie), "+err.Error())
return logger.FiberError(fiber.StatusUnauthorized, err.Error())
}

if len(decoded) < 1 {
return logger.FiberError(fiber.StatusUnauthorized, "authorization token is missing")
}
c.Locals("user_id", user)
return c.Next()
}

code, err := helpers.LaravelAesDecrypt("token", decoded)
if len(string(c.Request().Header.Peek("Authorization"))) > 0 {
code, err := helpers.LaravelAesDecrypt("token", c.FormValue("token"))
if err != nil {
return logger.FiberError(fiber.StatusUnauthorized, "invalid authorization token (cookie), "+err.Error())
return jwtValidation(c, c.FormValue("token"))
}

return jwtValidation(c, code)
}

if len(c.FormValue("token")) > 0 {
user, err := liman.AuthWithToken(
strings.Trim(c.FormValue("token"), ""),
)
cookie := new(Cookie)
c.CookieParser(cookie)

if len(cookie.Token) > 0 {
decoded, err := url.QueryUnescape(cookie.Token)
if err != nil {
return logger.FiberError(fiber.StatusUnauthorized, err.Error())
logger.FiberError(fiber.StatusUnauthorized, "invalid authorization token (cookie), "+err.Error())
}

c.Locals("user_id", user)
return c.Next()
}

if len(c.FormValue("liman-token")) > 0 {
user, err := liman.AuthWithAccessToken(
strings.Trim(c.FormValue("liman-token"), ""),
)
if len(decoded) < 1 {
return logger.FiberError(fiber.StatusUnauthorized, "authorization token is missing")
}

code, err := helpers.LaravelAesDecrypt("token", decoded)
if err != nil {
return logger.FiberError(fiber.StatusUnauthorized, err.Error())
return jwtValidation(c, decoded)
}

c.Locals("user_id", user)
return c.Next()
return jwtValidation(c, code)
}

if len(string(c.Request().Header.Peek("Authorization"))) > 0 {
user, err := liman.AuthWithToken(
strings.Trim(string(c.Request().Header.Peek("Authorization")), ""),
)

if len(c.FormValue("token")) > 0 {
code, err := helpers.LaravelAesDecrypt("token", c.FormValue("token"))
if err != nil {
return logger.FiberError(fiber.StatusUnauthorized, err.Error())
return jwtValidation(c, c.FormValue("token"))
}

c.Locals("user_id", user)
return c.Next()
return jwtValidation(c, code)
}

return logger.FiberError(fiber.StatusUnauthorized, "authorization token is missing")
Expand All @@ -99,6 +91,7 @@ func jwtValidation(c *fiber.Ctx, code string) error {

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
c.Locals("user_id", claims["sub"])
c.Locals("token", code)
return c.Next()
} else {
return logger.FiberError(fiber.StatusUnauthorized, "invalid authorization token")
Expand Down
14 changes: 0 additions & 14 deletions app/models/token.go

This file was deleted.

1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ require (
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/avast/retry-go v3.0.0+incompatible
github.com/dariubs/gorm-jsonb v0.1.5
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/hirochachacha/go-smb2 v1.1.0
github.com/jackc/pgpassfile v1.0.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ github.com/dariubs/gorm-jsonb v0.1.5/go.mod h1:e6GXwMviS3e9QxADNOWWZq0WBTdxpK2So
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/geoffgarside/ber v1.1.0 h1:qTmFG4jJbwiSzSXoNJeHcOprVzZ8Ulde2Rrrifu5U9w=
github.com/geoffgarside/ber v1.1.0/go.mod h1:jVPKeCbj6MvQZhwLYsGwaGI52oUorHoHKNecGT85ZCc=
github.com/go-co-op/gocron v1.35.3 h1:it2WjWnabS8eJZ+P68WroBe+ZWyJ3kVjRD6KXdpr5yI=
Expand Down
13 changes: 0 additions & 13 deletions internal/liman/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,6 @@ import (
"github.com/limanmys/render-engine/pkg/logger"
)

// AuthWithToken Auth user with proprietary Liman token
func AuthWithToken(token string) (string, error) {
tokenObj := &models.Token{}

err := database.Connection().First(&tokenObj, "token = ?", token).Error

if err != nil || len(tokenObj.UserID) < 1 {
return "", logger.FiberError(fiber.StatusUnauthorized, "authorization token is not valid")
}

return tokenObj.UserID, nil
}

// AuthWithAccessToken Auth user with generated access token
func AuthWithAccessToken(token string) (string, error) {
tokenObj := &models.AccessToken{}
Expand Down
62 changes: 14 additions & 48 deletions internal/user_token/user_token.go
Original file line number Diff line number Diff line change
@@ -1,63 +1,29 @@
package user_token

import (
"os"
"time"

"github.com/google/uuid"
"github.com/limanmys/render-engine/app/models"
"github.com/limanmys/render-engine/internal/database"
gorandom "github.com/zekiahmetbayar/go-random"
"github.com/dgrijalva/jwt-go"
)

// Create a new token or retrieve old one
// Create a new token for user purpose of internal use
func Create(user_id string) (string, error) {
// Search token on database
var token models.Token
database.Connection().Model(&models.Token{}).Where("user_id = ?", user_id).First(&token)

// If token does not exists, create token
if token.ID == "" {
// Create new id for token
uid := uuid.New()
// Generate token
token := generate()
// Create token on database
if err := database.Connection().Model(&models.Token{}).Create(models.Token{
ID: uid.String(),
CreatedAt: time.Now().Format(time.RFC3339),
UpdatedAt: time.Now().Format(time.RFC3339),
UserID: user_id,
Token: token,
}).Error; err != nil {
return "", err
}

return token, nil
}
// Get token update date
updateDate, err := time.Parse(time.RFC3339, token.UpdatedAt)
if err != nil {
return "", err
}
// If token updated after 6 hours
if time.Since(updateDate).Hours() > 6 {
// TODO: Update token
token_str := generate()
if err := database.Connection().Model(&token).Update("token", token_str).Error; err != nil {
return "", err
}
return token_str, nil
// Define the JWT claims
claims := jwt.MapClaims{
"sub": user_id,
"exp": time.Now().Add(time.Minute * 15).Unix(), // Token expiration time
}

return token.Token, nil
}
// Create the JWT token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

// Generate a new token
func generate() string {
token, err := gorandom.String(false, true, false, 32)
// Sign the token with a secret key
// Replace "your-secret-key" with your actual secret key
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
if err != nil {
return ""
return "", err
}

return token
return tokenString, nil
}
5 changes: 5 additions & 0 deletions pkg/utils/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/helmet/v2"
"github.com/limanmys/render-engine/app/middleware/app_logger"
Expand Down Expand Up @@ -42,6 +43,10 @@ func CreateServer() {
app.Use(auth.New())
app.Use(permission.New())
app.Use(app_logger.New())
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowCredentials: true,
}))

// Mount routes
routes.Install(app)
Expand Down

0 comments on commit 53baf4d

Please sign in to comment.