/
serve.go
189 lines (157 loc) · 4.54 KB
/
serve.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
package cmd
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/openshift/osin"
"github.com/rs/cors"
"github.com/spf13/cobra"
"github.com/bartmika/osin-example/internal/controllers"
repo "github.com/bartmika/osin-example/internal/repositories"
"github.com/bartmika/osin-example/internal/session"
"github.com/bartmika/osin-example/internal/utils"
)
func init() {
rootCmd.AddCommand(serveCmd)
}
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Serve the JSON API over HTTP",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
runServeCmd()
},
}
func doRunServe() {
fmt.Println("Server started")
}
func runServeCmd() {
var env = make(map[string]string)
env["ClientID"] = applicationFrontendClientID
env["ClientSecret"] = applicationFrontendClientSecret
env["ClientReturnURL"] = applicationFrontendReturnURL
env["ClientAuthURL"] = fmt.Sprintf("%s/authorize", applicationAddress)
env["ClientTokenURL"] = fmt.Sprintf("%s/token", applicationAddress)
env["ApplicationAddress"] = applicationAddress
// For debugging purposes only.
// log.Println(applicationFrontendClientID)
// log.Println(applicationFrontendClientSecret)
// log.Println(applicationFrontendReturnURL)
// // Load up the S3.
// key := os.Getenv("OSIN_AWS_S3_ACCESS_KEY")
// secret := os.Getenv("OSIN_AWS_S3_SECRET_KEY")
// endpoint := os.Getenv("OSIN_AWS_S3_ENDPOINT")
// region := os.Getenv("OSIN_AWS_S3_REGION")
// bucketName := os.Getenv("OSIN_AWS_S3_BUCKET_NAME")
// Load up our database.
db, err := utils.ConnectDB(
databaseHost,
databasePort,
databaseUser,
databasePassword,
databaseName,
"public",
)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Load up our repositories.
tr := repo.NewTenantRepo(db)
ur := repo.NewUserRepo(db)
ar := repo.NewApplicationRepo(db)
alr := repo.NewApplicationLiteRepo(db)
aar := repo.NewAuthorizedApplicationRepo(db)
aalr := repo.NewAuthorizedApplicationLiteRepo(db)
// Open up our session handler, powered by redis and let's save the user
// account with our ID
sm := session.New()
//
// oAuth 2.0 Storage
//
oastore := controllers.NewOSINRedisStorage()
oastore.CreateClient(&osin.DefaultClient{
Id: applicationFrontendClientID,
Secret: applicationFrontendClientSecret,
RedirectUri: applicationFrontendReturnURL,
})
//
// oAuth 2.0
//
sconfig := osin.NewServerConfig()
sconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{
osin.CODE,
osin.TOKEN,
}
sconfig.AllowedAccessTypes = osin.AllowedAccessType{
osin.AUTHORIZATION_CODE,
osin.REFRESH_TOKEN,
osin.PASSWORD,
osin.CLIENT_CREDENTIALS,
osin.ASSERTION,
}
sconfig.AllowGetAccessRequest = true
sconfig.AllowClientSecretInParams = true
oas := osin.NewServer(sconfig, oastore)
//
// Background worker.
//
//TODO: Impl.
//
// Controller server.
//
c := &controllers.Controller{
Config: env,
OAuthServer: oas,
OAuthStorage: oastore,
TenantRepo: tr,
UserRepo: ur,
ApplicationRepo: ar,
ApplicationLiteRepo: alr,
AuthorizedApplicationRepo: aar,
AuthorizedApplicationLiteRepo: aalr,
SessionManager: sm,
}
mux := http.NewServeMux()
mux.HandleFunc("/", c.AttachMiddleware(c.HandleRequests))
// cors.Default() setup the middleware with default options being
// all origins accepted with simple methods (GET, POST). See
// documentation via `https://github.com/rs/cors` for more options.
handler := cors.AllowAll().Handler(mux)
srv := &http.Server{
Addr: fmt.Sprintf("%s:%s", "localhost", "8000"),
Handler: handler,
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go runMainRuntimeLoop(srv)
log.Print("Server Started")
// Run the main loop blocking code.
<-done
stopMainRuntimeLoop(srv)
}
func runMainRuntimeLoop(srv *http.Server) {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}
func stopMainRuntimeLoop(srv *http.Server) {
log.Printf("Starting graceful shutdown now...")
// Execute the graceful shutdown sub-routine which will terminate any
// active connections and reject any new connections.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
// extra handling here
cancel()
}()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server Shutdown Failed:%+v", err)
}
log.Printf("Graceful shutdown finished.")
log.Print("Server Exited")
}