forked from pilinux/gorest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.go
More file actions
352 lines (310 loc) · 11 KB
/
router.go
File metadata and controls
352 lines (310 loc) · 11 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Package router contains all routes of the example2 application.
package router
import (
"github.com/gin-gonic/gin"
gconfig "github.com/pilinux/gorest/config"
gcontroller "github.com/pilinux/gorest/controller"
gdb "github.com/pilinux/gorest/database"
glib "github.com/pilinux/gorest/lib"
gmiddleware "github.com/pilinux/gorest/lib/middleware"
gservice "github.com/pilinux/gorest/service"
"github.com/pilinux/gorest/example2/internal/handler"
"github.com/pilinux/gorest/example2/internal/repo"
"github.com/pilinux/gorest/example2/internal/service"
)
// SetupRouter sets up all the routes.
func SetupRouter(configure *gconfig.Configuration) (*gin.Engine, error) {
// Set Gin mode
if gconfig.IsProd() {
gin.SetMode(gin.ReleaseMode)
}
// gin.Default() = gin.New() + gin.Logger() + gin.Recovery()
r := gin.Default()
// Which proxy to trust:
err := r.SetTrustedProxies(nil)
if err != nil {
return r, err
}
// when using Cloudflare's CDN:
// router.TrustedPlatform = gin.PlatformCloudflare
//
// when running on Google App Engine:
// router.TrustedPlatform = gin.PlatformGoogleAppEngine
//
/*
when using apache or nginx reverse proxy
without Cloudflare's CDN or Google App Engine
config for nginx:
=================
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
*/
// router.TrustedPlatform = "X-Real-Ip"
//
// set TrustedPlatform to get the real client IP
trustedPlatform := configure.Security.TrustedPlatform
if trustedPlatform == "cf" {
trustedPlatform = gin.PlatformCloudflare
}
if trustedPlatform == "google" {
trustedPlatform = gin.PlatformGoogleAppEngine
}
r.TrustedPlatform = trustedPlatform
// CORS
if gconfig.IsCORS() {
r.Use(gmiddleware.CORS(configure.Security.CORS))
}
// Origin
if gconfig.IsOriginCheck() {
r.Use(gmiddleware.CheckOrigin(gmiddleware.GetCORS().AllowedOrigins))
}
// Sentry.io
if gconfig.IsSentry() {
_, err := gmiddleware.InitSentry(
configure.Logger.SentryDsn,
configure.Server.ServerEnv,
configure.Version,
configure.Logger.PerformanceTracing,
configure.Logger.TracesSampleRate,
)
if err != nil {
return r, err
}
r.Use(gmiddleware.SentryCapture())
}
// WAF
if gconfig.IsWAF() {
r.Use(gmiddleware.Firewall(
configure.Security.Firewall.ListType,
configure.Security.Firewall.IP,
))
}
// Rate Limiter
if gconfig.IsRateLimit() {
// create a rate limiter instance
limiterInstance, err := glib.InitRateLimiter(
configure.Security.RateLimit,
trustedPlatform,
)
if err != nil {
return r, err
}
r.Use(gmiddleware.RateLimit(limiterInstance))
}
// Render HTML
if gconfig.IsTemplatingEngine() {
r.Use(gmiddleware.Pongo2(configure.ViewConfig.Directory))
}
// API Status
r.GET("", handler.APIStatus)
// Health check
r.GET("health", handler.APIStatus)
// API:v1.0
v1 := r.Group("/api/v1/")
{
// RDBMS
if gconfig.IsRDBMS() {
// Register - no JWT required
v1.POST("register", gcontroller.CreateUserAuth)
// Verify email
if gconfig.IsEmailVerificationService() {
if gconfig.IsRedis() {
v1.POST("verify", gcontroller.VerifyEmail)
v1.POST("resend-verification-email", gcontroller.CreateVerificationEmail)
v1.POST("verify-updated-email", gcontroller.VerifyUpdatedEmail)
}
}
// Login - app issues JWT
// - if cookie management is enabled, save tokens on client browser
v1.POST("login", gcontroller.Login)
// Logout
// - if cookie management is enabled, delete tokens from cookies
// - if Redis is enabled, save tokens in a blacklist until TTL
rLogout := v1.Group("logout")
rLogout.Use(gmiddleware.JWT()).Use(gmiddleware.RefreshJWT()).Use(gservice.JWTBlacklistChecker())
rLogout.POST("", gcontroller.Logout)
// Refresh - app issues new JWT
// - if cookie management is enabled, save tokens on client browser
rJWT := v1.Group("refresh")
rJWT.Use(gmiddleware.RefreshJWT()).Use(gservice.JWTBlacklistChecker())
rJWT.POST("", gcontroller.Refresh)
// Double authentication
if gconfig.Is2FA() {
r2FA := v1.Group("2fa")
r2FA.Use(gmiddleware.JWT()).Use(gservice.JWTBlacklistChecker())
r2FA.POST("setup", gcontroller.Setup2FA)
r2FA.POST("activate", gcontroller.Activate2FA)
r2FA.POST("validate", gcontroller.Validate2FA)
r2FA.POST("validate-backup-code", gcontroller.ValidateBackup2FA)
r2FA.Use(gmiddleware.TwoFA(
configure.Security.TwoFA.Status.On,
configure.Security.TwoFA.Status.Off,
configure.Security.TwoFA.Status.Verified,
))
// get 2FA backup codes
r2FA.POST("create-backup-codes", gcontroller.CreateBackup2FA)
// disable 2FA
r2FA.POST("deactivate", gcontroller.Deactivate2FA)
}
// Update/reset password
rPass := v1.Group("password")
// Reset forgotten password
if gconfig.IsEmailService() {
// send password recovery email
rPass.POST("forgot", gcontroller.PasswordForgot)
// recover account and set new password
rPass.POST("reset", gcontroller.PasswordRecover)
}
rPass.Use(gmiddleware.JWT()).Use(gservice.JWTBlacklistChecker())
if gconfig.Is2FA() {
rPass.Use(gmiddleware.TwoFA(
configure.Security.TwoFA.Status.On,
configure.Security.TwoFA.Status.Off,
configure.Security.TwoFA.Status.Verified,
))
}
// change password while logged in
rPass.POST("edit", gcontroller.PasswordUpdate)
// Change existing email
rEmail := v1.Group("email")
rEmail.Use(gmiddleware.JWT()).Use(gservice.JWTBlacklistChecker())
if gconfig.Is2FA() {
rPass.Use(gmiddleware.TwoFA(
configure.Security.TwoFA.Status.On,
configure.Security.TwoFA.Status.Off,
configure.Security.TwoFA.Status.Verified,
))
}
// add new email to replace the existing one
rEmail.POST("update", gcontroller.UpdateEmail)
// retrieve the email which needs to be verified
rEmail.GET("unverified", gcontroller.GetUnverifiedEmail)
// resend verification code to verify the modified email address
rEmail.POST("resend-verification-email", gcontroller.ResendVerificationCodeToModifyActiveEmail)
// db client
db := gdb.GetDB()
userRepo := repo.NewUserRepo(db)
postRepo := repo.NewPostRepo(db)
hobbyRepo := repo.NewHobbyRepo(db)
// User
userSrv := service.NewUserService(userRepo, postRepo, hobbyRepo)
userAPI := handler.NewUserAPI(userSrv)
rUsers := v1.Group("users")
rUsers.GET("", userAPI.GetUsers) // Not protected
rUsers.GET("/:id", userAPI.GetUser) // Not protected
rUsers.Use(gmiddleware.JWT())
rUsers.Use(gservice.JWTBlacklistChecker())
if gconfig.Is2FA() {
rUsers.Use(gmiddleware.TwoFA(
configure.Security.TwoFA.Status.On,
configure.Security.TwoFA.Status.Off,
configure.Security.TwoFA.Status.Verified,
))
}
rUsers.POST("", userAPI.CreateUser) // Protected
rUsers.PUT("", userAPI.UpdateUser) // Protected
rUsers.DELETE("", userAPI.DeleteUser) // Protected, irreversible
// Post
postSrv := service.NewPostService(postRepo, userRepo)
postAPI := handler.NewPostAPI(postSrv)
rPosts := v1.Group("posts")
rPosts.GET("", postAPI.GetPosts) // Not protected
rPosts.GET("/:id", postAPI.GetPost) // Not protected
rPosts.Use(gmiddleware.JWT())
rPosts.Use(gservice.JWTBlacklistChecker())
if gconfig.Is2FA() {
rPosts.Use(gmiddleware.TwoFA(
configure.Security.TwoFA.Status.On,
configure.Security.TwoFA.Status.Off,
configure.Security.TwoFA.Status.Verified,
))
}
rPosts.POST("", postAPI.CreatePost) // Protected
rPosts.PUT("/:id", postAPI.UpdatePost) // Protected
rPosts.DELETE("/:id", postAPI.DeletePost) // Protected
rPosts.DELETE("all", postAPI.DeleteAllPostsOfUser) // Protected
// Hobby
hobbySrv := service.NewHobbyService(hobbyRepo, userRepo)
hobbyAPI := handler.NewHobbyAPI(hobbySrv)
rHobbies := v1.Group("hobbies")
rHobbies.GET("", hobbyAPI.GetHobbies) // Not protected
rHobbies.GET("/:id", hobbyAPI.GetHobby) // Not protected
rHobbies.Use(gmiddleware.JWT())
rHobbies.Use(gservice.JWTBlacklistChecker())
if gconfig.Is2FA() {
rHobbies.Use(gmiddleware.TwoFA(
configure.Security.TwoFA.Status.On,
configure.Security.TwoFA.Status.Off,
configure.Security.TwoFA.Status.Verified,
))
}
rHobbies.GET("me", hobbyAPI.GetHobbiesMe) // Protected
rHobbies.POST("", hobbyAPI.AddHobbyToUser) // Protected
rHobbies.DELETE("/:id", hobbyAPI.DeleteHobbyFromUser) // Protected
}
// REDIS Playground - kv
if gconfig.IsRedis() {
// Redis connection from the pool
conn := gdb.GetRedis()
kvRepo := repo.NewKeyValueRepo(conn)
kvSrv := service.NewKeyValueService(kvRepo)
kvAPI := handler.NewKeyValueAPI(kvSrv)
rKV := v1.Group("kv")
rKV.POST("", kvAPI.SetKeyValue) // Not protected
rKV.GET("/:key", kvAPI.GetKeyValue) // Not protected
rKV.DELETE("/:key", kvAPI.DeleteKeyValue) // Not protected
rKV.POST("hash", kvAPI.SetHashKeyValue) // Not protected
rKV.GET("hash/:key", kvAPI.GetHashKeyValue) // Not protected
rKV.DELETE("hash/:key", kvAPI.DeleteHashKeyValue) // Not protected
}
// Mongo Playground - addresses
if gconfig.IsMongo() {
// MongoDB connection from the pool
conn := gdb.GetMongo()
addressRepo := repo.NewAddressRepo(conn)
addressSrv := service.NewAddressService(addressRepo)
addressAPI := handler.NewAddressAPI(addressSrv)
rAddress := v1.Group("addresses")
rAddress.POST("", addressAPI.AddAddress) // Not protected
rAddress.GET("", addressAPI.GetAddresses) // Not protected
rAddress.GET("/:id", addressAPI.GetAddress) // Not protected
rAddress.POST("filter", addressAPI.GetAddressByFilter) // Not protected
rAddress.PUT("", addressAPI.UpdateAddress) // Not protected
rAddress.DELETE("/:id", addressAPI.DeleteAddress) // Not protected
}
// Playground - JWT
if gconfig.IsJWT() {
rTestJWT := v1.Group("test-jwt")
rTestJWT.Use(gmiddleware.JWT())
rTestJWT.Use(gservice.JWTBlacklistChecker())
if gconfig.Is2FA() {
rTestJWT.Use(gmiddleware.TwoFA(
configure.Security.TwoFA.Status.On,
configure.Security.TwoFA.Status.Off,
configure.Security.TwoFA.Status.Verified,
))
}
rTestJWT.GET("", handler.APIStatus) // Protected
}
// Playground - Basic Auth
if gconfig.IsBasicAuth() {
user := configure.Security.BasicAuth.Username
pass := configure.Security.BasicAuth.Password
rBasicAuth := v1.Group("basic-auth")
rBasicAuth.Use(gin.BasicAuth(gin.Accounts{
user: pass,
}))
rBasicAuth.GET("", handler.APIStatus) // Protected
}
// if you want to use clerk.com auth provider:
// __session contains the JWT
// clerk uses RS256 algorithm for JWT token generation
// use the `sub` claim: c.GetString("sub") to get the user ID from JWT token
// and build relation in the database
rClerk := v1.Group("clerk")
rClerk.Use(gmiddleware.JWT("__session"))
rClerk.Use(gservice.JWTBlacklistChecker())
rClerk.GET("", handler.APIStatus) // Protected
}
return r, nil
}