init code

This commit is contained in:
Dmitry Chumak
2025-05-27 19:22:55 +05:00
parent 2b39909fd1
commit b47e0d3445
11 changed files with 529 additions and 0 deletions

102
internal/handlers/auth.go Normal file
View File

@@ -0,0 +1,102 @@
package handlers
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"github.com/yourusername/go-sqlc-jwt/db"
)
type AuthHandler struct {
Queries *db.Queries
JWTSecret string
}
func NewAuthHandler(q *db.Queries, secret string) *AuthHandler {
return &AuthHandler{
Queries: q,
JWTSecret: secret,
}
}
type loginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
func (h *AuthHandler) Login(c *gin.Context) {
var req loginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, err := h.Queries.GetUserByUsername(c.Request.Context(), req.Username)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": user.ID,
"username": user.Username,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
tokenString, err := token.SignedString([]byte(h.JWTSecret))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
return
}
// Create session in database
_, err = h.Queries.CreateSession(c.Request.Context(), db.CreateSessionParams{
UserID: user.ID,
ExpiresAt: time.Now().Add(time.Hour * 24),
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create session"})
return
}
c.JSON(http.StatusOK, gin.H{
"token": tokenString,
"expires_in": 3600 * 24,
})
}
func (h *AuthHandler) Register(c *gin.Context) {
var req loginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to hash password"})
return
}
user, err := h.Queries.CreateUser(c.Request.Context(), db.CreateUserParams{
Username: req.Username,
Password: string(hashedPassword),
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create user"})
return
}
c.JSON(http.StatusCreated, gin.H{
"id": user.ID,
"username": user.Username,
})
}

View File

@@ -0,0 +1,37 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func AuthMiddleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
return []byte(secret), nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
// Add user ID to context
c.Set("userID", claims["sub"])
c.Set("username", claims["username"])
}
c.Next()
}
}