/
create.go
104 lines (83 loc) · 2.58 KB
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package service
import (
"time"
"github.com/artem-malko/auth-and-go/infrastructure/database"
"github.com/artem-malko/auth-and-go/models"
identityRepository "github.com/artem-malko/auth-and-go/repositories/identity"
"github.com/artem-malko/auth-and-go/services/identity"
"github.com/google/uuid"
"github.com/pkg/errors"
)
func (s *identityService) CreateEmailIdentity(
executor database.QueryExecutor,
accountID uuid.UUID,
email, password string,
identityStatus models.IdentityStatus,
) (*models.Identity, error) {
newIdentity := models.Identity{
ID: uuid.New(),
AccountID: accountID,
IdentityType: models.IdentityTypeEmail,
IdentityStatus: identityStatus,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
err := newIdentity.SetEmail(email)
if err != nil {
return nil, models.ErrIdentityIncorrectEmail
}
passwordHash, err := createHash(password)
if err != nil {
return nil, errors.Wrap(identity.ErrIdentityPasswordGeneration, err.Error())
}
newIdentity.PasswordHash = passwordHash
createdIdentity, err := s.identityRepository.CreateEmailIdentity(executor, newIdentity)
if err != nil {
switch errors.Cause(err) {
case identityRepository.ErrRepositoryEmailConstraint:
return nil, identity.ErrIdentityExists
default:
return nil, err
}
}
return createdIdentity, nil
}
func (s *identityService) CreateOAuthIdentity(
executor database.QueryExecutor,
accountID uuid.UUID,
socialID string,
socialNetworkType models.SocialNetworkType,
email string,
) (*models.Identity, error) {
newIdentity := models.Identity{
ID: uuid.New(),
AccountID: accountID,
IdentityStatus: models.IdentityStatusConfirmed,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if socialNetworkType == models.SocialNetworkTypeGoogle {
newIdentity.GoogleSocialID = socialID
newIdentity.IdentityType = models.IdentityTypeGoogle
}
if socialNetworkType == models.SocialNetworkTypeFacebook {
newIdentity.FacebookSocialID = socialID
newIdentity.IdentityType = models.IdentityTypeFacebook
}
err := newIdentity.SetEmail(email)
if err != nil {
return nil, models.ErrIdentityIncorrectEmail
}
createdIdentity, err := s.identityRepository.CreateSocialIdentity(executor, newIdentity)
if err != nil {
switch errors.Cause(err) {
case identityRepository.ErrRepositorySocialFacebookConstraint:
fallthrough
case identityRepository.ErrRepositorySocialGoogleConstraint:
return nil, identity.ErrIdentityExists
default:
return nil, errors.Wrap(err, "identity service: CreateOAuthIdentity")
}
}
return createdIdentity, nil
}