generated from tsivinsky/go-template
allow to upload images
but also files, hmmmm
This commit is contained in:
45
auth/cookies.go
Normal file
45
auth/cookies.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func SetUserCookie(w http.ResponseWriter, token string, expiryTime time.Time) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "token",
|
||||
Value: token,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
Path: "/",
|
||||
Expires: expiryTime,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveUserCookie(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "token",
|
||||
Value: "",
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
Path: "/",
|
||||
Expires: time.Now().Add(-time.Hour),
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
||||
|
||||
func GetUserIdFromRequest(r *http.Request) (int64, error) {
|
||||
c, err := r.Cookie("token")
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("no token cookie: %v", err)
|
||||
}
|
||||
|
||||
userId, err := ValidateUserToken(c.Value)
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("invalid token: %v", err)
|
||||
}
|
||||
|
||||
return userId, nil
|
||||
}
|
||||
48
auth/jwt.go
Normal file
48
auth/jwt.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var secretKey = os.Getenv("JWT_SECRET_KEY")
|
||||
|
||||
type UserClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
UserID int64
|
||||
}
|
||||
|
||||
func GenerateUserToken(userId int64, expiryTime time.Time) (string, error) {
|
||||
now := time.Now()
|
||||
claims := UserClaims{
|
||||
UserID: userId,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(expiryTime),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
return token.SignedString([]byte(secretKey))
|
||||
}
|
||||
|
||||
func ValidateUserToken(token string) (int64, error) {
|
||||
claims := &UserClaims{}
|
||||
|
||||
parsed, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {
|
||||
return []byte(secretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("failed to parse token: %v", err)
|
||||
}
|
||||
|
||||
if !parsed.Valid {
|
||||
return -1, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
return claims.UserID, nil
|
||||
}
|
||||
Reference in New Issue
Block a user