Protected routes

This commit is contained in:
Nedim
2023-11-10 17:32:17 +01:00
parent 367b5d51f2
commit 99b9df5066
14 changed files with 172 additions and 100 deletions

View File

@@ -3,10 +3,12 @@ package user
import (
"errors"
"fmt"
"strconv"
"time"
"github.com/golang-jwt/jwt"
"github.com/jinzhu/gorm"
"gitlab.com/pactual1/backend/config"
"gitlab.com/pactual1/backend/models"
"gitlab.com/pactual1/backend/shared"
"golang.org/x/crypto/bcrypt"
@@ -50,7 +52,7 @@ func CheckPassword(hashedPassword, password string) bool {
return err == nil
}
func CreateSessionToken(userID uint) (string, error) {
func CreateSessionToken(userID, companyID uint) (string, error) {
// Generate JWT token
tokenString, err := CreateJWTToken(userID)
if err != nil {
@@ -59,9 +61,10 @@ func CreateSessionToken(userID uint) (string, error) {
// Create and save the session token in the database
sessionToken := models.SessionToken{
UserID: userID,
Token: tokenString,
IsActive: true,
UserID: userID,
Token: tokenString,
CompanyID: companyID,
IsActive: true,
}
if result := shared.GetDb().Create(&sessionToken); result.Error != nil {
return "", result.Error
@@ -84,10 +87,15 @@ func IncrementLoginAttempts(user models.User) {
shared.GetDb().Save(&user)
}
var jwtKey = []byte("MDQsCiJwYWNrZXRWZXJzaW9uIjogMSwKImhhcm")
func CreateJWTToken(userID uint) (string, error) {
expirationTime := time.Now().Add(24 * time.Hour)
var jwtKey = []byte(config.AppConfig.Service.JwtSecretKey)
expiryHours, err := strconv.Atoi(config.AppConfig.Service.JwtSecretKeyExpiryHours)
if err != nil {
return "", err
}
expirationTime := time.Now().Add(time.Duration(expiryHours) * time.Hour)
claims := &jwt.StandardClaims{
Subject: fmt.Sprint(userID),
ExpiresAt: expirationTime.Unix(),