-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
209 lines (183 loc) · 5.93 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"encoding/gob"
"fmt"
"net/http"
"os"
"path"
"text/template"
"time"
"github.com/Masterminds/sprig/v3"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httprate"
"github.com/gorilla/csrf"
"github.com/gorilla/sessions"
"github.com/microcosm-cc/bluemonday"
"github.com/oodzchen/dproject/config"
i18nc "github.com/oodzchen/dproject/i18n"
mdw "github.com/oodzchen/dproject/middleware"
"github.com/oodzchen/dproject/model"
"github.com/oodzchen/dproject/service"
"github.com/oodzchen/dproject/store"
"github.com/oodzchen/dproject/utils"
"github.com/oodzchen/dproject/web"
"github.com/oschwald/geoip2-golang"
"github.com/redis/go-redis/v9"
"github.com/sergi/go-diff/diffmatchpatch"
)
type ServiceConfig struct {
sessSecret string
csrfSecret string
store *store.Store
permisisonSrv *service.Permission
sanitizePolicy *bluemonday.Policy
i18nCustom *i18nc.I18nCustom
rdb *redis.Client
mail *service.Mail
geoDB *geoip2.Reader
}
// func FileServer(r chi.Router, path string, root http.FileSystem) {
// if strings.ContainsAny(path, "{}*") {
// panic("FileServer does not permit any URL parameters.")
// }
// if path != "/" && path[len(path)-1] != '/' {
// r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
// path += "/"
// }
// path += "*"
// r.Get(path, func(w http.ResponseWriter, r *http.Request) {
// rctx := chi.RouteContext(r.Context())
// pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
// fs := http.StripPrefix(pathPrefix, http.FileServer(root))
// fs.ServeHTTP(w, r)
// })
// }
func Service(c *ServiceConfig) http.Handler {
wd, _ := os.Getwd()
// fmt.Println("work directory: ", wd)
// fmt.Println("templates directory: ", path.Join(wd, "./views/*.tmpl"))
tmplPath := path.Join(wd, "./views/*.tmpl")
tmplFuncs := template.FuncMap{
"permit": func(module, action string) bool {
return c.permisisonSrv.Permit(nil, module, action)
},
"local": c.i18nCustom.LocalTpl,
"timeAgo": c.i18nCustom.TimeAgo.Format,
}
baseTmpl := template.New("base").Funcs(TmplFuncs).Funcs(tmplFuncs).Funcs(sprig.FuncMap())
baseTmpl = template.Must(baseTmpl.ParseGlob(tmplPath))
r := chi.NewRouter()
r.Use(mdw.RequestDuration)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.AllowContentEncoding("default", "gzip"))
r.Use(middleware.AllowContentType("application/x-www-form-urlencoded"))
r.Use(middleware.Compress(5, "text/html", "text/css", "text/plain", "text/javascript"))
r.Use(middleware.GetHead)
// r.Use(middleware.RedirectSlashes)
r.Use(mdw.CreateGeoDetect(c.geoDB))
gob.Register(model.Lang(""))
sessStore := sessions.NewCookieStore([]byte(c.sessSecret))
sessStore.Options.HttpOnly = true
sessStore.Options.Secure = !utils.IsDebug()
sessStore.Options.SameSite = http.SameSiteLaxMode
userLogger := &service.UserLogger{
Store: c.store,
}
settingsManager := &service.SettingsManager{
Rdb: c.rdb,
LifeTime: service.DefaultSettingsLifeTime,
}
srv := &service.Service{
Article: &service.Article{
Store: c.store,
SantizePolicy: c.sanitizePolicy,
},
User: &service.User{
Store: c.store,
SantizePolicy: c.sanitizePolicy,
},
Permission: c.permisisonSrv,
UserLogger: userLogger,
Verifier: &service.Verifier{
CodeLifeTime: service.DefaultCodeLifeTime,
Rdb: c.rdb,
},
Mail: c.mail,
SettingsManager: settingsManager,
}
dmp := diffmatchpatch.New()
renderer := web.NewRenderer(
baseTmpl,
sessStore,
r,
c.store,
c.sanitizePolicy,
c.i18nCustom,
srv,
c.rdb,
dmp,
)
r.Use(mdw.FetchUserData(c.store, sessStore, c.permisisonSrv, renderer))
r.Use(mdw.CreateUISettingsMiddleware(sessStore, settingsManager, c.i18nCustom))
articleResource := web.NewArticleResource(renderer)
userResource := web.NewUserResource(renderer)
mainResource := web.NewMainResource(renderer, articleResource)
manageResource := web.NewManageResource(renderer, userResource)
rssResource := web.NewRSSResource(renderer, articleResource)
rateLimit := 100
if utils.IsDebug() {
rateLimit = 10000
}
r.Use(httprate.Limit(
rateLimit,
1*time.Minute,
httprate.WithKeyByIP(),
httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
mainResource.Error("", nil, w, r, http.StatusTooManyRequests)
}),
))
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
mainResource.Error("", nil, w, r, http.StatusNotFound)
})
r.HandleFunc("/403", func(w http.ResponseWriter, r *http.Request) {
mainResource.Error("", nil, w, r, http.StatusForbidden)
})
r.HandleFunc("/500", func(w http.ResponseWriter, r *http.Request) {
mainResource.Error("", nil, w, r, http.StatusInternalServerError)
})
r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
mainResource.Error("", nil, w, r, http.StatusMethodNotAllowed)
})
if config.Config.Debug {
r.Mount("/debug", middleware.Profiler())
}
// FileServer(r, "/static", http.Dir("./static"))
// r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
// http.Redirect(w, r, "/static/favicon.ico", http.StatusFound)
// })
r.Mount("/", mainResource.Routes())
r.Mount("/articles", articleResource.Routes())
r.Mount("/u/{username}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username := chi.URLParam(r, "username")
http.Redirect(w, r, fmt.Sprintf("/users/%s", username), http.StatusFound)
}))
r.Mount("/users", userResource.Routes())
r.Mount("/manage", manageResource.Routes())
r.Mount("/feed", rssResource.Routes())
// chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
// ////
// fmt.Println("walk:", method, route)
// return nil
// })
CSRF := csrf.Protect([]byte(c.csrfSecret),
csrf.FieldName("tk"),
csrf.CookieName("sc"),
csrf.HttpOnly(true),
csrf.Secure(!utils.IsDebug()),
csrf.Path("/"),
// csrf.ErrorHandler(r),
)
return CSRF(r)
}