This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
/
tEditUser.go
122 lines (112 loc) · 2.23 KB
/
tEditUser.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package dgraph
import (
"context"
"encoding/json"
"github.com/dgraph-io/dgo/protos/api"
"github.com/romshark/dgraph_graphql_go/store"
strerr "github.com/romshark/dgraph_graphql_go/store/errors"
)
// EditUser edits an existing user profile
func (str *impl) EditUser(
ctx context.Context,
user store.ID,
editor store.ID,
newEmail *string,
newPassword *string,
) (
result store.User,
changes struct {
Email bool
Password bool
},
err error,
) {
result.ID = user
// Begin transaction
txn, close := str.txn(&err)
if err != nil {
return
}
defer close()
// Ensure user and editor exist
var qr struct {
User []User `json:"user"`
Editor []User `json:"editor"`
}
err = txn.QueryVars(
ctx,
`query User(
$id: string,
$editorId: string
) {
user(func: eq(User.id, $id)) {
uid
User.creation
User.displayName
User.email
User.password
}
editor(func: eq(User.id, $editorId)) { uid }
}`,
map[string]string{
"$id": string(user),
"$editorId": string(editor),
},
&qr,
)
if err != nil {
return
}
if len(qr.User) < 1 {
err = strerr.New(strerr.ErrInvalidInput, "user profile not found")
return
}
if len(qr.Editor) < 1 {
err = strerr.Newf(strerr.ErrInvalidInput, "editor not found")
return
}
if newEmail != nil {
result.Email = *newEmail
if qr.User[0].Email == *newEmail {
newEmail = nil
} else {
changes.Email = true
}
} else {
result.Email = qr.User[0].Email
}
if newPassword != nil {
result.Password = *newPassword
if qr.User[0].Password == *newPassword {
newPassword = nil
} else {
changes.Password = true
}
} else {
result.Password = qr.User[0].Password
}
result.UID = qr.User[0].UID
result.Creation = qr.User[0].Creation
result.DisplayName = qr.User[0].DisplayName
// Edit the user profile
var mutatedUserJSON []byte
mutatedUserJSON, err = json.Marshal(struct {
UID string `json:"uid"`
NewEmail *string `json:"User.email,omitempty"`
NewPassword *string `json:"User.password,omitempty"`
}{
UID: result.UID,
NewEmail: newEmail,
NewPassword: newPassword,
})
if err != nil {
return
}
_, err = txn.Mutation(ctx, &api.Mutation{
SetJson: mutatedUserJSON,
})
if err != nil {
return
}
return
}