Passport/pkg/services/accounts.go

113 lines
2.6 KiB
Go
Raw Normal View History

2024-01-06 17:56:32 +00:00
package services
import (
"code.smartsheep.studio/hydrogen/passport/pkg/database"
"code.smartsheep.studio/hydrogen/passport/pkg/models"
2024-01-28 08:17:38 +00:00
"code.smartsheep.studio/hydrogen/passport/pkg/security"
"fmt"
2024-01-28 16:32:39 +00:00
"github.com/samber/lo"
2024-01-28 08:17:38 +00:00
"gorm.io/datatypes"
2024-01-28 16:32:39 +00:00
"gorm.io/gorm"
"time"
2024-01-06 17:56:32 +00:00
)
2024-01-07 07:52:23 +00:00
func GetAccount(id uint) (models.Account, error) {
var account models.Account
if err := database.C.Where(models.Account{
BaseModel: models.BaseModel{ID: id},
}).First(&account).Error; err != nil {
return account, err
}
return account, nil
}
2024-01-06 17:56:32 +00:00
func LookupAccount(id string) (models.Account, error) {
var account models.Account
if err := database.C.Where(models.Account{Name: id}).First(&account).Error; err == nil {
return account, nil
}
var contact models.AccountContact
if err := database.C.Where(models.AccountContact{Content: id}).First(&contact).Error; err == nil {
if err := database.C.
Where(models.Account{
BaseModel: models.BaseModel{ID: contact.AccountID},
2024-01-27 16:05:19 +00:00
}).First(&account).Error; err == nil {
2024-01-06 17:56:32 +00:00
return account, err
}
}
return account, fmt.Errorf("account was not found")
}
2024-01-28 08:17:38 +00:00
func CreateAccount(name, nick, email, password string) (models.Account, error) {
user := models.Account{
Name: name,
Nick: nick,
State: models.PendingAccountState,
Profile: models.AccountProfile{
Experience: 100,
},
Factors: []models.AuthFactor{
{
Type: models.PasswordAuthFactor,
Secret: security.HashPassword(password),
},
},
Contacts: []models.AccountContact{
{
Type: models.EmailAccountContact,
Content: email,
VerifiedAt: nil,
},
},
Permissions: datatypes.NewJSONType(make([]string, 0)),
ConfirmedAt: nil,
}
if err := database.C.Create(&user).Error; err != nil {
return user, err
}
2024-01-28 16:32:39 +00:00
if tk, err := NewMagicToken(models.ConfirmMagicToken, &user, nil); err != nil {
return user, err
} else if err := NotifyMagicToken(tk); err != nil {
return user, err
}
return user, nil
}
func ConfirmAccount(code string) error {
var token models.MagicToken
if err := database.C.Where(&models.MagicToken{
Code: code,
Type: models.ConfirmMagicToken,
}).First(&token).Error; err != nil {
return err
} else if token.AssignTo == nil {
return fmt.Errorf("account was not found")
}
var user models.Account
if err := database.C.Where(&models.Account{
BaseModel: models.BaseModel{ID: *token.AssignTo},
}).First(&user).Error; err != nil {
return err
}
return database.C.Transaction(func(tx *gorm.DB) error {
user.ConfirmedAt = lo.ToPtr(time.Now())
if err := database.C.Delete(&token).Error; err != nil {
return err
}
if err := database.C.Save(&user).Error; err != nil {
return err
}
return nil
})
2024-01-28 08:17:38 +00:00
}