Chore: project init

This commit is contained in:
2026-02-24 13:18:43 +09:00
commit 3345549051
23 changed files with 788 additions and 0 deletions

41
internal/auth/handler.go Normal file
View File

@@ -0,0 +1,41 @@
package auth
import "github.com/gofiber/fiber/v2"
type Handler struct {
svc *Service
}
func NewHandler(svc *Service) *Handler {
return &Handler{svc: svc}
}
func (h *Handler) Login(c *fiber.Ctx) error {
var req struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "잘못된 요청입니다"})
}
if req.Username == "" || req.Password == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "아이디와 비밀번호를 입력해주세요"})
}
tokenStr, user, err := h.svc.Login(req.Username, req.Password)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": err.Error()})
}
return c.JSON(fiber.Map{
"token": tokenStr,
"username": user.Username,
"role": user.Role,
})
}
func (h *Handler) Logout(c *fiber.Ctx) error {
userID := c.Locals("userID").(uint)
h.svc.Logout(userID)
return c.JSON(fiber.Map{"message": "로그아웃 되었습니다"})
}

17
internal/auth/model.go Normal file
View File

@@ -0,0 +1,17 @@
package auth
import "gorm.io/gorm"
type Role string
const (
RoleAdmin Role = "admin"
RoleUser Role = "user"
)
type User struct {
gorm.Model
Username string `gorm:"uniqueIndex;not null"`
PasswordHash string `gorm:"not null"`
Role Role `gorm:"default:'user'"`
}

View File

@@ -0,0 +1,21 @@
package auth
import "gorm.io/gorm"
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
func (r *Repository) FindByUsername(username string) (*User, error) {
var user User
err := r.db.Where("username = ?", username).First(&user).Error
return &user, err
}
func (r *Repository) Create(user *User) error {
return r.db.Create(user).Error
}

66
internal/auth/service.go Normal file
View File

@@ -0,0 +1,66 @@
package auth
import (
"context"
"fmt"
"time"
"a301_server/pkg/config"
"github.com/golang-jwt/jwt/v5"
"github.com/redis/go-redis/v9"
"golang.org/x/crypto/bcrypt"
)
type Claims struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
jwt.RegisteredClaims
}
type Service struct {
repo *Repository
rdb *redis.Client
}
func NewService(repo *Repository, rdb *redis.Client) *Service {
return &Service{repo: repo, rdb: rdb}
}
func (s *Service) Login(username, password string) (string, *User, error) {
user, err := s.repo.FindByUsername(username)
if err != nil {
return "", nil, fmt.Errorf("아이디 또는 비밀번호가 올바르지 않습니다")
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
return "", nil, fmt.Errorf("아이디 또는 비밀번호가 올바르지 않습니다")
}
expiry := time.Duration(config.C.JWTExpiryHours) * time.Hour
claims := &Claims{
UserID: user.ID,
Username: user.Username,
Role: string(user.Role),
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiry)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenStr, err := token.SignedString([]byte(config.C.JWTSecret))
if err != nil {
return "", nil, fmt.Errorf("토큰 생성에 실패했습니다")
}
// Redis에 세션 저장 (1계정 1세션)
key := fmt.Sprintf("session:%d", user.ID)
s.rdb.Set(context.Background(), key, tokenStr, expiry)
return tokenStr, user, nil
}
func (s *Service) Logout(userID uint) {
key := fmt.Sprintf("session:%d", userID)
s.rdb.Del(context.Background(), key)
}