2024-08-24 12:28:10 +00:00
|
|
|
package services
|
|
|
|
|
|
|
|
import (
|
2024-10-30 16:15:25 +00:00
|
|
|
"git.solsynth.dev/hydrogen/passport/pkg/authkit/models"
|
2024-09-15 18:37:02 +00:00
|
|
|
"time"
|
|
|
|
|
2024-08-24 12:28:10 +00:00
|
|
|
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/samber/lo"
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewApiKey(user models.Account, key models.ApiKey, ip, ua string, claims []string) (models.ApiKey, error) {
|
2024-08-25 15:15:29 +00:00
|
|
|
key.Account = user
|
|
|
|
key.AccountID = user.ID
|
|
|
|
|
2024-08-24 12:28:10 +00:00
|
|
|
var expiredAt *time.Time
|
|
|
|
if key.Lifecycle != nil {
|
|
|
|
expiredAt = lo.ToPtr(time.Now().Add(time.Duration(*key.Lifecycle) * time.Second))
|
|
|
|
}
|
|
|
|
|
|
|
|
key.Ticket = models.AuthTicket{
|
2024-09-15 18:37:02 +00:00
|
|
|
IpAddress: ip,
|
|
|
|
UserAgent: ua,
|
|
|
|
StepRemain: 0,
|
|
|
|
Claims: claims,
|
|
|
|
Audiences: []string{InternalTokenAudience},
|
|
|
|
GrantToken: lo.ToPtr(uuid.NewString()),
|
|
|
|
AccessToken: lo.ToPtr(uuid.NewString()),
|
|
|
|
RefreshToken: lo.ToPtr(uuid.NewString()),
|
|
|
|
AvailableAt: lo.ToPtr(time.Now()),
|
|
|
|
ExpiredAt: expiredAt,
|
|
|
|
Account: user,
|
|
|
|
AccountID: user.ID,
|
2024-08-24 12:28:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := database.C.Save(&key).Error; err != nil {
|
|
|
|
return key, err
|
|
|
|
}
|
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func RollApiKey(key models.ApiKey) (models.ApiKey, error) {
|
|
|
|
var ticket models.AuthTicket
|
2024-08-25 16:53:13 +00:00
|
|
|
if err := database.C.Where("id = ?", key.TicketID).First(&ticket).Error; err != nil {
|
2024-08-24 12:28:10 +00:00
|
|
|
return key, err
|
|
|
|
}
|
|
|
|
|
2024-08-24 15:49:19 +00:00
|
|
|
ticket, err := RotateTicket(ticket, true)
|
2024-08-24 12:28:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return key, err
|
|
|
|
} else {
|
|
|
|
key.Ticket = ticket
|
|
|
|
}
|
|
|
|
|
|
|
|
return key, nil
|
|
|
|
}
|