67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type Handler struct {
|
|
service *Service
|
|
}
|
|
|
|
func NewHandler(s *Service) *Handler {
|
|
return &Handler{service: s}
|
|
}
|
|
|
|
func (h *Handler) Me(c *gin.Context) {
|
|
userID, _ := c.Get("user_id")
|
|
role, _ := c.Get("role")
|
|
|
|
c.JSON(200, gin.H{
|
|
"user_id": userID,
|
|
"role": role,
|
|
})
|
|
}
|
|
|
|
func (h *Handler) AdminCheck(c *gin.Context) {
|
|
c.JSON(200, gin.H{
|
|
"message": "you are an admin",
|
|
})
|
|
}
|
|
|
|
func (h *Handler) Login(c *gin.Context) {
|
|
var req struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(400, gin.H{"error": "Invalid request body"})
|
|
return
|
|
}
|
|
|
|
token, err := h.service.Login(req.Username, req.Password)
|
|
if err != nil {
|
|
c.JSON(401, gin.H{"error": "Invalid credentials"})
|
|
return
|
|
}
|
|
|
|
isSecure := os.Getenv("USE_HTTPS") == "true"
|
|
|
|
// Use http.SetCookie so we can set SameSite.
|
|
http.SetCookie(c.Writer, &http.Cookie{
|
|
Name: "auth_token",
|
|
Value: token,
|
|
Path: "/",
|
|
Domain: os.Getenv("DOMAIN"),
|
|
MaxAge: 3600 * 24,
|
|
Secure: isSecure,
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteStrictMode,
|
|
})
|
|
|
|
c.JSON(200, gin.H{"token": token})
|
|
}
|