-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathusers.go
134 lines (108 loc) · 2.31 KB
/
users.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
package main
import (
"errors"
"log"
"net/http"
graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
)
var Schema = `
schema {
query: Query
mutation: Mutation
}
interface Node {
id: ID!
}
type User implements Node {
id: ID!
}
type Query {
node(id: ID!): Node
}
type loginUserOutput {
token: String!
}
type Mutation {
loginUser(username: String!, password: String!): loginUserOutput!
}
`
var users = []*User{
{
ID: "1",
Username: "username1",
Password: "password1",
},
{
ID: "2",
Username: "username2",
Password: "password2",
},
{
ID: "3",
Username: "username3",
Password: "password3",
},
}
// LoginUser is the primary userResolver for the mutation to log a user in.
// It's resposibility it to check that the credentials are correct
// and return a string that will be used to identity the user later.
func (r *userResolver) LoginUser(args struct {
Username string
Password string
}) (*LoginUserOutput, error) {
// look for the user with the corresponding username and password
for _, user := range users {
if user.Username == args.Username && user.Password == args.Password {
// return the token that the client will send back to us to claim the identity
return &LoginUserOutput{
Tkn: string(user.ID),
}, nil
}
}
// we didn't find a matching username and password
return nil, errors.New("Provided information was invalid")
}
//
//
// boilerplate for rest of API
//
//
type userResolver struct{}
func (r *userResolver) Node(args struct{ ID string }) *NodeResolver {
return &NodeResolver{&UserResolver{users[0]}}
}
type User struct {
ID graphql.ID
Username string
Password string
}
type LoginUserOutput struct {
Tkn string
}
func (o *LoginUserOutput) Token() string {
return o.Tkn
}
type Resolver struct{}
type node interface {
ID() graphql.ID
}
type NodeResolver struct {
node
}
func (node *NodeResolver) ToUser() (*UserResolver, bool) {
user, ok := node.node.(*UserResolver)
return user, ok
}
type UserResolver struct {
user *User
}
func (u *UserResolver) ID() graphql.ID {
return u.user.ID
}
// start the service
func main() {
schema := graphql.MustParseSchema(Schema, &userResolver{})
http.Handle("/", &relay.Handler{Schema: schema})
log.Fatal(http.ListenAndServe(":8080", nil))
}