bigest part of the api done

This commit is contained in:
2022-01-30 05:39:57 +01:00
commit 7585a53baa
38 changed files with 11551 additions and 0 deletions

56
auth/auth.go Normal file
View File

@@ -0,0 +1,56 @@
package auth
import (
"os"
"time"
"github.com/golang-jwt/jwt"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
var secretKey []byte
func Setup() {
secretKeyString, isSet := os.LookupEnv("SECRET_KEY")
if !isSet {
log.Warn("SECRET_KEY not set in environment, using default key")
secretKeyString = "DebugKey"
}
secretKey = []byte(secretKeyString)
}
func makePasswordSalty(password string, salt []byte) []byte {
passwordBytes := []byte(password)
passwordBytes = append(passwordBytes, salt...)
return passwordBytes
}
func HashPassword(password string, salt []byte) (hashedPassword []byte, err error) {
saltyPassword := makePasswordSalty(password, salt)
hashedPassword, err = bcrypt.GenerateFromPassword(saltyPassword, bcrypt.MaxCost)
return
}
func CheckPassword(password string, salt []byte, hashedPassword []byte) (err error) {
saltyPassword := makePasswordSalty(password, salt)
err = bcrypt.CompareHashAndPassword(hashedPassword, saltyPassword)
return
}
func GenerateJWT(id uint, username string, email string) (jwttoken string, err error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["user_id"] = id
claims["username"] = username
claims["email"] = email
claims["exp"] = time.Now().Add(time.Hour * 2).Unix()
if jwttoken, err = token.SignedString(secretKey); err != nil {
log.Errorf("Something Went Wrong: %s", err.Error())
}
return
}

32
auth/middleware.go Normal file
View File

@@ -0,0 +1,32 @@
package auth
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
func GetUser() gin.HandlerFunc {
return func(c *gin.Context) {
tokenCookie, err := c.Cookie("token")
if err != nil || tokenCookie == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
token, err := jwt.ParseWithClaims(tokenCookie, &jwt.MapClaims{}, func(t *jwt.Token) (interface{}, error) {
return secretKey, nil
})
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
claims := token.Claims.(jwt.MapClaims)
c.Set("user_id", claims["user_id"])
c.Set("username", claims["username"])
c.Set("user_email", claims["email"])
c.Next()
}
}

13
auth/userscope.go Normal file
View File

@@ -0,0 +1,13 @@
package auth
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func UserScope(c *gin.Context) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
userId := c.GetUint("user_id")
return db.Where("user_id", userId)
}
}