46 lines
1.0 KiB
Go
46 lines
1.0 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gitlab.celogeek.com/photos/api/internal/photos/models"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func (s *Service) RequireAuthToken(c *gin.Context) {
|
|
token := c.GetHeader("Authorization")
|
|
if !strings.HasPrefix(token, "Private ") {
|
|
s.Error(c, http.StatusForbidden, ErrTokenMissing)
|
|
return
|
|
}
|
|
token = token[8:]
|
|
c.Set("token", token)
|
|
}
|
|
|
|
func (s *Service) RequireSession(c *gin.Context) {
|
|
s.RequireAuthToken(c)
|
|
if c.IsAborted() {
|
|
return
|
|
}
|
|
|
|
sess := &models.Session{}
|
|
if err := s.DB.Preload("Account").Where("token = ?", c.GetString("token")).First(sess).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
s.Error(c, http.StatusForbidden, ErrSessionNotFound)
|
|
} else {
|
|
s.Error(c, http.StatusForbidden, err)
|
|
}
|
|
return
|
|
}
|
|
if sess.Account == nil {
|
|
s.Error(c, http.StatusInternalServerError, ErrSessionInvalid)
|
|
return
|
|
}
|
|
s.DB.Select("updated_at").Save(sess)
|
|
s.Logger.Printf("User: %s", sess.Account.Login)
|
|
c.Set("session", sess)
|
|
}
|