Optimized userinfo endpoint

This commit is contained in:
2024-02-01 15:08:40 +08:00
parent cfc1115b2f
commit e2b609cf43
8 changed files with 170 additions and 30 deletions

View File

@ -21,8 +21,7 @@ func getUserinfo(c *fiber.Ctx) error {
Preload("Profile").
Preload("Contacts").
Preload("Factors").
Preload("Sessions").
Preload("Challenges").
Preload("Notifications", "read_at IS NULL").
First(&data).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}

View File

@ -0,0 +1,63 @@
package server
import (
"code.smartsheep.studio/hydrogen/passport/pkg/database"
"code.smartsheep.studio/hydrogen/passport/pkg/models"
"github.com/gofiber/fiber/v2"
)
func getChallenges(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0)
var count int64
var challenges []models.AuthChallenge
if err := database.C.
Where(&models.AuthChallenge{AccountID: user.ID}).
Model(&models.AuthChallenge{}).
Count(&count).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
if err := database.C.
Where(&models.AuthChallenge{AccountID: user.ID}).
Limit(take).
Offset(offset).
Find(&challenges).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(fiber.Map{
"count": count,
"data": challenges,
})
}
func getSessions(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0)
var count int64
var sessions []models.AuthSession
if err := database.C.
Where(&models.AuthSession{AccountID: user.ID}).
Model(&models.AuthSession{}).
Count(&count).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
if err := database.C.
Where(&models.AuthSession{AccountID: user.ID}).
Limit(take).
Offset(offset).
Find(&sessions).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(fiber.Map{
"count": count,
"data": sessions,
})
}

View File

@ -63,6 +63,8 @@ func NewServer() {
api.Get("/users/me", auth, getUserinfo)
api.Put("/users/me", auth, editUserinfo)
api.Get("/users/me/events", auth, getEvents)
api.Get("/users/me/challenges", auth, getChallenges)
api.Get("/users/me/sessions", auth, getSessions)
api.Delete("/users/me/sessions/:sessionId", auth, killSession)
api.Post("/users", doRegister)