This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
/
tCloseAllSessions.go
98 lines (87 loc) · 1.84 KB
/
tCloseAllSessions.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
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"
)
// CloseAllSessions closes all sessions of the given user
func (str *impl) CloseAllSessions(
ctx context.Context,
user store.ID,
) (
result []string,
err error,
) {
// Begin transaction
txn, close := str.txn(&err)
if err != nil {
return
}
defer close()
// Find the user and all associated sessions
var qr struct {
User []User `json:"user"`
}
err = txn.QueryVars(
ctx,
`query Sessions(
$userID: string
) {
user(func: eq(User.id, $userID)) {
uid
User.sessions {
uid
Session.key
~sessions {
uid
}
}
}
}`,
map[string]string{
"$userID": string(user),
},
&qr,
)
if err != nil {
return
}
if len(qr.User) < 1 {
err = strerr.Newf(
strerr.ErrInvalidInput,
"user not found",
)
return
}
usr := qr.User[0]
deletions := make([]interface{}, 0, len(usr.Sessions)*2+1)
result = make([]string, len(usr.Sessions))
for i, sess := range usr.Sessions {
result[i] = sess.Key
// Delete the global "sessions" references
deletions = append(deletions, sess.RSessions[0])
// Delete the actual Session nodes
deletions = append(deletions, UID{NodeID: sess.UID})
}
// Delete the "User.sessions" references
userSessions := make([]UID, len(usr.Sessions))
for i, sess := range usr.Sessions {
userSessions[i] = UID{NodeID: sess.UID}
}
deletions = append(deletions, struct {
UID string `json:"uid"`
UserSessions []UID `json:"User.sessions"`
}{
UID: usr.UID,
UserSessions: userSessions,
})
var deleteJSON []byte
deleteJSON, err = json.Marshal(deletions)
if err != nil {
return
}
_, err = txn.Mutation(ctx, &api.Mutation{DeleteJson: deleteJSON})
return
}