feat: add simple jwt middleware and update oauth handlers
All checks were successful
Backend ci / build (push) Successful in 3m44s
All checks were successful
Backend ci / build (push) Successful in 3m44s
This commit is contained in:
60
backend/internal/auth/jwt.go
Normal file
60
backend/internal/auth/jwt.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gitea.d3m0k1d.ru/d3m0k1d/d3m0k1d.ru/backend/internal/storage"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var jwtSecret = []byte(os.Getenv("JWT_SECRET"))
|
||||
|
||||
func GenerateJWT(user storage.User) (string, error) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
|
||||
"id": user.ID,
|
||||
"email": user.Email,
|
||||
"login": user.GithubLogin,
|
||||
})
|
||||
tokenString, err := token.SignedString(jwtSecret)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return tokenString, nil
|
||||
}
|
||||
|
||||
func JWTMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
auth := c.GetHeader("Authorization")
|
||||
if !strings.HasPrefix(auth, "Bearer ") {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "Bearer required"})
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := strings.TrimPrefix(auth, "Bearer ")
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return jwtSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "invalid token"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "invalid claims"})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", int(claims["id"].(float64)))
|
||||
c.Set("login", claims["login"].(string))
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -13,36 +13,75 @@ import (
|
||||
type AuthHandlers struct {
|
||||
repo repositories.AuthRepository
|
||||
logger *logger.Logger
|
||||
}
|
||||
|
||||
var configGithub = &oauth2.Config{
|
||||
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
|
||||
RedirectURL: "https://d3m0k1d.ru/",
|
||||
Scopes: []string{"user"},
|
||||
Endpoint: endpoints.GitHub,
|
||||
config *oauth2.Config
|
||||
}
|
||||
|
||||
func NewAuthHandlers(repo repositories.AuthRepository) *AuthHandlers {
|
||||
return &AuthHandlers{repo: repo, logger: logger.New(false)}
|
||||
clientID := os.Getenv("GITHUB_CLIENT_ID")
|
||||
clientSecret := os.Getenv("GITHUB_CLIENT_SECRET")
|
||||
redirectURL := os.Getenv("REDIRECT_URL")
|
||||
|
||||
if clientID == "" || clientSecret == "" {
|
||||
panic("GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET must be set")
|
||||
}
|
||||
if redirectURL == "" {
|
||||
redirectURL = "http://localhost:8080/api/v1/callback/github"
|
||||
}
|
||||
|
||||
return &AuthHandlers{
|
||||
repo: repo,
|
||||
logger: logger.New(false),
|
||||
config: &oauth2.Config{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
RedirectURL: redirectURL,
|
||||
Scopes: []string{"user:email"},
|
||||
Endpoint: endpoints.GitHub,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Callback godoc
|
||||
// @Summary Callback for oauth2 providers
|
||||
// @Description Callback for oauth2 providers
|
||||
// LoginGithub godoc
|
||||
// @Summary Start GitHub OAuth login
|
||||
// @Description Redirects to GitHub authorization
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Success 302
|
||||
// @Router /api/v1/auth/github [get]
|
||||
func (h *AuthHandlers) LoginGithub(c *gin.Context) {
|
||||
url := h.config.AuthCodeURL("state", oauth2.AccessTypeOnline)
|
||||
h.logger.Info("Redirect to GitHub: " + url)
|
||||
c.Redirect(302, url)
|
||||
}
|
||||
|
||||
// CallbackGithub godoc
|
||||
// @Summary GitHub OAuth callback
|
||||
// @Description Exchanges authorization code for access token
|
||||
// @Tags auth
|
||||
// @Param code query string true "Authorization code"
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "Access token"
|
||||
// @Failure 400 {object} map[string]string "Missing code"
|
||||
// @Failure 500 {object} map[string]string "Exchange failed"
|
||||
// @Router /callback/github [get]
|
||||
func (h *AuthHandlers) CallbackGithub(c *gin.Context) {
|
||||
h.logger.Info("CallbackGithub called")
|
||||
|
||||
token, err := configGithub.Exchange(c.Request.Context(), c.Query("code"))
|
||||
if err != nil {
|
||||
h.logger.Error("error request: " + err.Error())
|
||||
c.Status(500)
|
||||
code := c.Query("code")
|
||||
if code == "" {
|
||||
h.logger.Error("missing code")
|
||||
c.JSON(400, gin.H{"error": "missing code"})
|
||||
return
|
||||
}
|
||||
h.logger.Info("200 OK GET /callback/github")
|
||||
|
||||
h.logger.Info("Processing code: " + code[:10] + "...")
|
||||
|
||||
token, err := h.config.Exchange(c.Request.Context(), code)
|
||||
if err != nil {
|
||||
h.logger.Error("Exchange failed: " + err.Error())
|
||||
c.JSON(500, gin.H{"error": "exchange failed", "details": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
h.logger.Info("200 OK - token received")
|
||||
c.JSON(200, gin.H{"token": token})
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ func Register(router *gin.Engine, db *sql.DB) {
|
||||
handler_posts := NewPostHandlers(repositories.NewPostRepository(db))
|
||||
handler_auth := NewAuthHandlers(repositories.NewAuthRepository(db))
|
||||
v1 := router.Group("api/v1")
|
||||
v1.GET("/callback", handler_auth.CallbackGithub)
|
||||
v1.GET("/callback/github", handler_auth.CallbackGithub)
|
||||
v1.GET("/auth/github", handler_auth.LoginGithub)
|
||||
posts := v1.Group("posts")
|
||||
{
|
||||
posts.GET("/", handler_posts.GetPosts)
|
||||
|
||||
@@ -6,5 +6,13 @@ CREATE TABLE IF NOT EXISTS posts(
|
||||
title TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
CREATED_AT DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT,
|
||||
github_id TEXT,
|
||||
github_login TEXT,
|
||||
avatar_url TEXT
|
||||
);
|
||||
`
|
||||
|
||||
@@ -17,3 +17,11 @@ type PostCreate struct {
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int `db:"id"`
|
||||
Email string `db:"email"`
|
||||
GithubID string `db:"github_id"`
|
||||
GithubLogin string `db:"github_login"`
|
||||
AvatarURL string `db:"avatar_url"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user