-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (79 loc) · 2.75 KB
/
main.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
package main
import (
"log"
"net/http"
"os"
"path"
"path/filepath"
"github.com/auth0-community/go-auth0"
"github.com/gin-gonic/gin"
jose "gopkg.in/square/go-jose.v2"
"github.com/isaacomondi/todo-backend/handlers"
)
var (
audience string
domain string
)
func main() {
setAuth0Variables()
r := gin.Default()
r.Use(CORSMiddleware())
// This will ensure that the angular files are served correctly
r.NoRoute(func(c *gin.Context) {
dir, file := path.Split(c.Request.RequestURI)
ext := filepath.Ext(file)
if file == "" || ext == "" {
c.File("./ui/dist/ui/index.html")
} else {
c.File("./ui/dist/ui/" + path.Join(dir, file))
}
})
authorized := r.Group("/")
authorized.Use(authRequired())
authorized.GET("/todo", handlers.GetTodoListHandler)
authorized.POST("/todo", handlers.AddTodoHandler)
authorized.DELETE("/todo/:id", handlers.DeleteTodoHandler)
authorized.PUT("/todo", handlers.CompleteTodoHandler)
err := r.Run(":3000")
if err != nil {
panic(err)
}
}
func setAuth0Variables() {
audience = os.Getenv("AUTH0_API_IDENTIFIER")
domain = os.Getenv("AUTH0_DOMAIN")
}
// ValidateRequest will verify that a token received from an http request
// is valid and signyed by Auth0
func authRequired() gin.HandlerFunc {
return func(c *gin.Context) {
var auth0Domain = "https://" + domain + "/"
client := auth0.NewJWKClient(auth0.JWKClientOptions{URI: auth0Domain + ".well-known/jwks.json"}, nil)
configuration := auth0.NewConfiguration(client, []string{audience}, auth0Domain, jose.RS256)
validator := auth0.NewValidator(configuration, nil)
_, err := validator.ValidateRequest(c.Request)
if err != nil {
log.Println(err)
terminateWithError(http.StatusUnauthorized, "token is not valid", c)
return
}
c.Next()
}
}
func terminateWithError(statusCode int, message string, c *gin.Context) {
c.JSON(statusCode, gin.H{"error": message})
c.Abort()
}
// CORSMiddleware enables Cross-Origin Resource Sharing (CORS) because it runs on a different domain than the Front End
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
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", "DELETE, GET, OPTIONS, POST, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}