Interactive/pkg/services/auth.go

67 lines
1.8 KiB
Go
Raw Normal View History

2024-02-01 15:26:17 +00:00
package services
import (
"code.smartsheep.studio/hydrogen/identity/pkg/grpc/proto"
2024-02-01 15:26:17 +00:00
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
"code.smartsheep.studio/hydrogen/interactive/pkg/grpc"
2024-02-01 15:26:17 +00:00
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
"context"
2024-02-01 15:26:17 +00:00
"errors"
"fmt"
2024-02-01 15:26:17 +00:00
"gorm.io/gorm"
"time"
)
func LinkAccount(userinfo *proto.Userinfo) (models.Account, error) {
2024-02-01 15:26:17 +00:00
var account models.Account
if userinfo == nil {
return account, fmt.Errorf("remote userinfo was not found")
}
2024-02-01 15:26:17 +00:00
if err := database.C.Where(&models.Account{
ExternalID: uint(userinfo.Id),
2024-02-01 15:26:17 +00:00
}).First(&account).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
account = models.Account{
2024-02-05 07:51:31 +00:00
Name: userinfo.Name,
Nick: userinfo.Nick,
Avatar: userinfo.Avatar,
2024-02-01 15:26:17 +00:00
EmailAddress: userinfo.Email,
PowerLevel: 0,
ExternalID: uint(userinfo.Id),
2024-02-01 15:26:17 +00:00
}
return account, database.C.Save(&account).Error
}
return account, err
}
2024-02-05 07:51:31 +00:00
account.Name = userinfo.Name
account.Nick = userinfo.Nick
account.Avatar = userinfo.Avatar
2024-02-05 07:51:31 +00:00
account.EmailAddress = userinfo.Email
err := database.C.Save(&account).Error
return account, err
2024-02-01 15:26:17 +00:00
}
func Authenticate(atk, rtk string) (models.Account, string, string, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
2024-02-01 15:26:17 +00:00
var err error
var user models.Account
reply, err := grpc.Auth.Authenticate(ctx, &proto.AuthRequest{
AccessToken: atk,
RefreshToken: &rtk,
})
2024-02-01 15:26:17 +00:00
if err != nil {
return user, reply.GetAccessToken(), reply.GetRefreshToken(), err
} else if !reply.IsValid {
return user, reply.GetAccessToken(), reply.GetRefreshToken(), fmt.Errorf("invalid authorization context")
2024-02-01 15:26:17 +00:00
}
user, err = LinkAccount(reply.Userinfo)
2024-02-01 15:26:17 +00:00
return user, reply.GetAccessToken(), reply.GetRefreshToken(), err
2024-02-01 15:26:17 +00:00
}