Phase 2 completed: Stream Server Auth, Database and Business API
This commit is contained in:
55
internal/utils/utils.go
Normal file
55
internal/utils/utils.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// In production, load this from environment variables
|
||||
var jwtKey = []byte("hightube_super_secret_key_MVP_only")
|
||||
|
||||
// GenerateToken generates a JWT token for a given user ID
|
||||
func GenerateToken(userID uint) (string, error) {
|
||||
claims := &jwt.RegisteredClaims{
|
||||
Subject: fmt.Sprintf("%d", userID),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtKey)
|
||||
}
|
||||
|
||||
// ParseToken parses the JWT string and returns the user ID (Subject)
|
||||
func ParseToken(tokenStr string) (string, error) {
|
||||
claims := &jwt.RegisteredClaims{}
|
||||
token, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (interface{}, error) {
|
||||
return jwtKey, nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
return "", err
|
||||
}
|
||||
return claims.Subject, nil
|
||||
}
|
||||
|
||||
// HashPassword creates a bcrypt hash of the password
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
// CheckPasswordHash compares a bcrypt hashed password with its possible plaintext equivalent
|
||||
func CheckPasswordHash(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// GenerateStreamKey generates a random string to be used as a stream key
|
||||
func GenerateStreamKey() string {
|
||||
bytes := make([]byte, 16)
|
||||
rand.Read(bytes)
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
Reference in New Issue
Block a user