-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
executable file
·191 lines (145 loc) · 4.2 KB
/
server.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"CareXR_WebService/graph"
"context"
"crypto/md5"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"CareXR_WebService/config"
"CareXR_WebService/ioutils"
"CareXR_WebService/pkg/jwt"
"CareXR_WebService/pkg/randStr"
"github.com/gin-contrib/cors"
)
const defaultPort = "8000"
// Defining the Graphql handler
func graphqlHandler() gin.HandlerFunc {
// NewExecutableSchema and Config are in the generated.go file
// Resolver is in the resolver.go file
h := handler.NewDefaultServer(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{}}))
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}
// Defining the Playground handler
func playgroundHandler() gin.HandlerFunc {
h := playground.Handler("GraphQL", "/query")
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}
/*
func GinContextToContextMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}*/
func GinContextFromContext(ctx context.Context) (*gin.Context, error) {
ginContext := ctx.Value("GinContextKey")
if ginContext == nil {
err := fmt.Errorf("could not retrieve gin.Context")
return nil, err
}
gc, ok := ginContext.(*gin.Context)
if !ok {
err := fmt.Errorf("gin.Context has wrong type")
return nil, err
}
return gc, nil
}
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}
/*
func executeQuery(c *gin.Context) {
jsonData, _ := ioutil.ReadAll(c.Request.Body)
request, err := http.NewRequest("POST", "http://localhost:8000/graphql", bytes.NewBuffer(jsonData))
if err != nil {
panic(err)
}
request.Header.Add("Content-Type", "application/json")
client := &http.Client{}
res, err := client.Do(request)
if err != nil {
panic(err)
}
defer res.Body.Close()
responseRaw, err := io.ReadAll(res.Body)
c.JSON(200, string(responseRaw))
}*/
func generateAuthChannel(ctx *gin.Context) {
msec := time.Now().UnixNano() / 1000000
msecString := strconv.FormatInt(msec, 16)
randString, _ := randStr.GenerateRandomString(32)
channel := msecString + randString
hasher := md5.New()
hasher.Write([]byte(channel))
tokenContent := map[string]any{
"iss": "CareXR",
"sub": "",
"aud": []string{"member"},
"exp": time.Now().Add(time.Minute * 1).Unix(),
"nbf": time.Now().Unix(),
"iat": time.Now().Unix(),
"jti": uuid.New(),
"context": map[string]any{
"channel": &channel,
},
}
token, _ := jwt.GenerateToken(tokenContent)
ctx.JSON(http.StatusOK, gin.H{
"token": token, // cast it to string before showing
"channel": channel,
})
}
func main() {
settings, err := config.ReadConfig("config.json")
ioutils.PanicOnError(err)
println("Username ", settings.Username, "password", settings.Password)
driver, err := config.NewDriver(settings)
defer driver.Close()
if driver == nil {
os.Exit(1)
}
config.Neo4jDriver = driver
// Test
////
defer func() {
ioutils.PanicOnError(driver.Close())
}()
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
router := gin.Default()
/*
router.Use(cors.New(cors.Config{
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
AllowHeaders: []string{"Authorization", "Origin", "Content-Length", "Content-Type"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
AllowAllOrigins: true,
}))*/
router.Use(cors.Default())
router.POST("/api", graphqlHandler())
router.GET("/view", playgroundHandler())
router.GET("/authChannel", generateAuthChannel)
router.Run(":8000")
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
}