-
Notifications
You must be signed in to change notification settings - Fork 125
/
main.go
147 lines (127 loc) · 4.69 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
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
package main
import (
"context"
"encoding/base64"
"fmt"
"log"
"net/http"
"net/url"
"regexp"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
gkc "github.com/anselm94/googlekeepclone"
gkcserver "github.com/anselm94/googlekeepclone/server"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/rs/cors"
"github.com/volatiletech/authboss/v3"
_ "github.com/volatiletech/authboss/v3/auth" // Adds Login support
"github.com/volatiletech/authboss/v3/defaults"
_ "github.com/volatiletech/authboss/v3/logout" // Adds Logout support
_ "github.com/volatiletech/authboss/v3/register" // Adds Register support
)
var (
config *gkc.AppConfig
db *gorm.DB
)
func main() {
config = gkc.DefaultAppConfig()
db = setupDB()
defer db.Close()
ab := setupAuthboss()
handlerUserContext := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userID, _ := ab.CurrentUserID(r)
userID = url.QueryEscape(userID) // Encode the email, so it's available as userID
ctx = context.WithValue(ctx, gkcserver.CtxUserIDKey, userID)
h.ServeHTTP(w, r.WithContext(ctx))
})
}
handlerCors := cors.New(cors.Options{
AllowedOrigins: []string{
config.AppHost.String(),
},
AllowCredentials: true,
}).Handler
handlerGraphQL := handler.NewDefaultServer(
gkcserver.NewExecutableSchema(gkcserver.Config{
Resolvers: &gkcserver.Resolver{
DB: db,
},
}),
)
log.Println("Setting up routes ...")
router := mux.NewRouter()
router.Use(handlerCors, ab.LoadClientStateMiddleware, handlerUserContext)
router.Path("/playground").Handler(playground.Handler("Playground", "/query"))
router.PathPrefix("/query").Handler(handlerGraphQL)
router.PathPrefix("/auth").Handler(http.StripPrefix("/auth", ab.Config.Core.Router))
router.PathPrefix("/login").Handler(http.RedirectHandler("/", http.StatusMovedPermanently)) // handled by SPA client router
router.PathPrefix("/register").Handler(http.RedirectHandler("/", http.StatusMovedPermanently)) // handled by SPA client router
router.PathPrefix("/").Handler(http.FileServer(http.Dir(config.StaticDir)))
log.Println("Route setup complete")
log.Printf("Starting and listening server at %s", config.AppHost)
log.Fatalf("Error running server -> %s", http.ListenAndServe(fmt.Sprintf(":%s", config.AppHost.Port()), router))
}
func setupDB() *gorm.DB {
log.Println("Setting up SQLite 3 database ...")
db, err := gorm.Open("sqlite3", config.DBFile)
if err != nil {
log.Fatalf("Error while setting up DB -> %s", err)
}
db.Exec("PRAGMA foreign_keys = ON;")
log.Println("Database initialised")
db.AutoMigrate(&gkcserver.Todo{}, &gkcserver.Note{}, &gkcserver.Label{}, &gkcserver.User{})
log.Println("Database migration complete")
return db
}
func setupAuthboss() *authboss.Authboss {
log.Println("Setting up authentication ...")
ab := authboss.New()
ab.Config.Paths.Mount = "/auth"
ab.Config.Paths.RootURL = config.AppHost.String()
cookieStoreKey, _ := base64.StdEncoding.DecodeString(config.CookieStoreKey)
sessionStoreKey, _ := base64.StdEncoding.DecodeString(config.SessionStoreKey)
ab.Config.Storage.Server = gkcserver.NewSQLiteStorer(db)
ab.Config.Storage.SessionState = gkcserver.NewSessionStorer(config.SessionCookieName, sessionStoreKey)
ab.Config.Storage.CookieState = gkcserver.NewCookieStorer(cookieStoreKey, config.IsProd)
ab.Config.Core.ViewRenderer = defaults.JSONRenderer{}
defaults.SetCore(&ab.Config, true, false)
ab.Config.Modules.LogoutMethod = "POST"
redirector := defaults.NewRedirector(ab.Config.Core.ViewRenderer, authboss.FormValueRedirect)
redirector.CorceRedirectTo200 = true // Since using in API mode, map redirects to API
ab.Config.Core.Redirector = redirector
// Overriding the default bodyreader and making lenient
emailRule := defaults.Rules{
FieldName: "email", Required: false,
MatchError: "Must be a valid e-mail address",
MustMatch: regexp.MustCompile(`.*@.*\.[a-z]+`),
}
passwordRule := defaults.Rules{
FieldName: "password", Required: true,
MinLength: 4,
}
nameRule := defaults.Rules{
FieldName: "name", Required: false,
AllowWhitespace: true,
MinLength: 2,
}
ab.Config.Core.BodyReader = defaults.HTTPBodyReader{
ReadJSON: true,
UseUsername: false,
Rulesets: map[string][]defaults.Rules{
"login": {emailRule},
"register": {emailRule, passwordRule, nameRule},
},
Whitelist: map[string][]string{ // for arbitrary values to not get filtered
"register": {"email", "name"},
},
}
if err := ab.Init(); err != nil {
log.Fatalf("Error while initialising Authboss -> %s", err)
}
log.Println("Authentication setup complete")
return ab
}