28 lines
858 B
Go
28 lines
858 B
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
domain "github.com/haydenhargreaves/Potion/internal/domain/user"
|
|
)
|
|
|
|
// AuthenticatedFunc is a function that handles authenticated requests
|
|
type AuthenticatedFunc func(ctx *gin.Context, user *domain.User)
|
|
|
|
// withAuthenticatedUser is a helper to run a handler only if user is authenticated. Otherwise
|
|
// the function will return an error with a 401 status.
|
|
func (s *Server) withAuthenticatedUser(ctx *gin.Context, handler AuthenticatedFunc) {
|
|
user := s.deps.UserService.GetAuthenicatedUser(ctx)
|
|
if user == nil {
|
|
ctx.JSON(http.StatusUnauthorized, gin.H{
|
|
"status": http.StatusUnauthorized,
|
|
"message": "[UNAUTHORIZED] Could not fetch authenticated user.",
|
|
})
|
|
return
|
|
}
|
|
handler(ctx, user)
|
|
}
|
|
|
|
// TODO: Create a function to use for methods that CAN use a user, but sometimes don't.
|