This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
/
tCreateSession.go
136 lines (123 loc) · 2.54 KB
/
tCreateSession.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package dgraph
import (
"context"
"encoding/json"
"time"
"github.com/dgraph-io/dgo/protos/api"
"github.com/romshark/dgraph_graphql_go/store"
strerr "github.com/romshark/dgraph_graphql_go/store/errors"
)
// CreateSession creates a new session and updates the indexes
func (str *impl) CreateSession(
ctx context.Context,
key string,
creation time.Time,
email string,
password string,
) (
result store.Session,
err error,
) {
// Begin transaction
txn, close := str.txn(&err)
if err != nil {
return
}
defer close()
// Ensure user exists
var qr struct {
ByEmail []struct {
UID string `json:"uid"`
ID string `json:"User.id"`
Password string `json:"User.password"`
} `json:"byEmail"`
}
err = txn.QueryVars(
ctx,
`query User(
$email: string
) {
byEmail(func: eq(User.email, $email)) {
uid
User.id
User.password
}
}`,
map[string]string{
"$email": email,
},
&qr,
)
if err != nil {
return
}
// Ensure the user exists and the password is correct
if len(qr.ByEmail) < 1 || !str.comparePassword(
password,
qr.ByEmail[0].Password,
) {
err = strerr.New(strerr.ErrWrongCreds, "wrong credentials")
return
}
result.User = &store.User{
GraphNode: store.GraphNode{
UID: qr.ByEmail[0].UID,
},
ID: store.ID(qr.ByEmail[0].ID),
}
// Create new session
var newSessionJSON []byte
newSessionJSON, err = json.Marshal(struct {
Key string `json:"Session.key"`
Creation time.Time `json:"Session.creation"`
User UID `json:"Session.user"`
}{
Key: key,
Creation: creation,
User: UID{NodeID: result.User.UID},
})
if err != nil {
return
}
var sessCreationMut map[string]string
sessCreationMut, err = txn.Mutation(ctx, &api.Mutation{
SetJson: newSessionJSON,
})
if err != nil {
return
}
result.UID = sessCreationMut["blank-0"]
// Update owner (User.sessions -> new session)
var updateOwnerJSON []byte
updateOwnerJSON, err = json.Marshal(struct {
UID string `json:"uid"`
Sessions UID `json:"User.sessions"`
}{
UID: result.User.UID,
Sessions: UID{NodeID: result.UID},
})
if err != nil {
return
}
_, err = txn.Mutation(ctx, &api.Mutation{
SetJson: updateOwnerJSON,
})
if err != nil {
return
}
// Add the new session to the global Index
var newSessionIndexJSON []byte
newSessionIndexJSON, err = json.Marshal(struct {
UID UID `json:"sessions"`
}{
UID: UID{NodeID: result.UID},
})
if err != nil {
return
}
_, err = txn.Mutation(ctx, &api.Mutation{
SetJson: newSessionIndexJSON,
Set: nil,
})
return
}