-
Notifications
You must be signed in to change notification settings - Fork 284
/
main.go
247 lines (209 loc) · 7.24 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
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
package main
import (
"flag"
"github.com/cihub/seelog"
"github.com/claudiu/gocron"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/wangsongyan/wblog/controllers"
"github.com/wangsongyan/wblog/helpers"
"github.com/wangsongyan/wblog/models"
"github.com/wangsongyan/wblog/system"
"html/template"
"net/http"
"os"
"path/filepath"
)
func main() {
configFilePath := flag.String("C", "conf/conf.toml", "config file path")
logConfigPath := flag.String("L", "conf/seelog.xml", "log config file path")
generate := flag.Bool("g", false, "generate sample config file")
flag.Parse()
if *generate {
system.Generate()
os.Exit(0)
}
logger, err := seelog.LoggerFromConfigAsFile(*logConfigPath)
if err != nil {
seelog.Critical("err parsing seelog config file", err)
return
}
seelog.ReplaceLogger(logger)
defer seelog.Flush()
if err := system.LoadConfiguration(*configFilePath); err != nil {
seelog.Critical("err parsing config log file", err)
return
}
db, err := models.InitDB()
if err != nil {
seelog.Critical("err open databases", err)
return
}
defer func() {
dbInstance, _ := db.DB()
_ = dbInstance.Close()
}()
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
setTemplate(router)
setSessions(router)
router.Use(SharedData())
//Periodic tasks
gocron.Every(1).Day().Do(controllers.CreateXMLSitemap)
gocron.Every(7).Days().Do(controllers.Backup)
gocron.Start()
router.Static("/static", filepath.Join(helpers.GetCurrentDirectory(), system.GetConfiguration().PublicDir))
router.NoRoute(controllers.Handle404)
router.GET("/", controllers.IndexGet)
router.GET("/index", controllers.IndexGet)
router.GET("/rss", controllers.RssGet)
if system.GetConfiguration().SignupEnabled {
router.GET("/signup", controllers.SignupGet)
router.POST("/signup", controllers.SignupPost)
}
// user signin and logout
router.GET("/signin", controllers.SigninGet)
router.POST("/signin", controllers.SigninPost)
router.GET("/logout", controllers.LogoutGet)
router.GET("/oauth2callback", controllers.Oauth2Callback)
router.GET("/auth/:authType", controllers.AuthGet)
// captcha
router.GET("/captcha", controllers.CaptchaGet)
visitor := router.Group("/visitor")
visitor.Use(AuthRequired(false))
{
visitor.POST("/new_comment", controllers.CommentPost)
visitor.POST("/comment/:id/delete", controllers.CommentDelete)
}
// subscriber
router.GET("/subscribe", controllers.SubscribeGet)
router.POST("/subscribe", controllers.Subscribe)
router.GET("/active", controllers.ActiveSubscriber)
router.GET("/unsubscribe", controllers.UnSubscribe)
router.GET("/page/:id", controllers.PageGet)
router.GET("/post/:id", controllers.PostGet)
router.GET("/tag/:tag", controllers.TagGet)
router.GET("/archives/:year/:month", controllers.ArchiveGet)
router.GET("/link/:id", controllers.LinkGet)
authorized := router.Group("/admin")
authorized.Use(AuthRequired(true))
{
// index
authorized.GET("/index", controllers.AdminIndex)
// image upload
authorized.POST("/upload", controllers.Upload)
// page
authorized.GET("/page", controllers.PageIndex)
authorized.GET("/new_page", controllers.PageNew)
authorized.POST("/new_page", controllers.PageCreate)
authorized.GET("/page/:id/edit", controllers.PageEdit)
authorized.POST("/page/:id/edit", controllers.PageUpdate)
authorized.POST("/page/:id/publish", controllers.PagePublish)
authorized.POST("/page/:id/delete", controllers.PageDelete)
// post
authorized.GET("/post", controllers.PostIndex)
authorized.GET("/new_post", controllers.PostNew)
authorized.POST("/new_post", controllers.PostCreate)
authorized.GET("/post/:id/edit", controllers.PostEdit)
authorized.POST("/post/:id/edit", controllers.PostUpdate)
authorized.POST("/post/:id/publish", controllers.PostPublish)
authorized.POST("/post/:id/delete", controllers.PostDelete)
// tag
authorized.POST("/new_tag", controllers.TagCreate)
//
authorized.GET("/user", controllers.UserIndex)
authorized.POST("/user/:id/lock", controllers.UserLock)
// profile
authorized.GET("/profile", controllers.ProfileGet)
authorized.POST("/profile", controllers.ProfileUpdate)
authorized.POST("/profile/email/bind", controllers.BindEmail)
authorized.POST("/profile/email/unbind", controllers.UnbindEmail)
authorized.POST("/profile/github/unbind", controllers.UnbindGithub)
// subscriber
authorized.GET("/subscriber", controllers.SubscriberIndex)
authorized.POST("/subscriber", controllers.SubscriberPost)
// link
authorized.GET("/link", controllers.LinkIndex)
authorized.POST("/new_link", controllers.LinkCreate)
authorized.POST("/link/:id/edit", controllers.LinkUpdate)
authorized.POST("/link/:id/delete", controllers.LinkDelete)
// comment
authorized.POST("/comment/:id", controllers.CommentRead)
authorized.POST("/read_all", controllers.CommentReadAll)
// backup
authorized.POST("/backup", controllers.BackupPost)
authorized.POST("/restore", controllers.RestorePost)
// mail
authorized.POST("/new_mail", controllers.SendMail)
authorized.POST("/new_batchmail", controllers.SendBatchMail)
}
err = router.Run(system.GetConfiguration().Addr)
if err != nil {
seelog.Critical(err)
}
}
func setTemplate(engine *gin.Engine) {
funcMap := template.FuncMap{
"dateFormat": helpers.DateFormat,
"substring": helpers.Substring,
"isOdd": helpers.IsOdd,
"isEven": helpers.IsEven,
"truncate": helpers.Truncate,
"length": helpers.Len,
"add": helpers.Add,
"minus": helpers.Minus,
"listtag": helpers.ListTag,
}
engine.SetFuncMap(funcMap)
engine.LoadHTMLGlob(filepath.Join(helpers.GetCurrentDirectory(), system.GetConfiguration().ViewDir))
}
// setSessions initializes sessions & csrf middlewares
func setSessions(router *gin.Engine) {
config := system.GetConfiguration()
//https://github.com/gin-gonic/contrib/tree/master/sessions
store := cookie.NewStore([]byte(config.SessionSecret))
store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"}) //Also set Secure: true if using SSL, you should though
router.Use(sessions.Sessions("gin-session", store))
//https://github.com/utrack/gin-csrf
/*router.Use(csrf.Middleware(csrf.Options{
Secret: config.SessionSecret,
ErrorFunc: func(c *gin.Context) {
c.String(400, "CSRF token mismatch")
c.Abort()
},
}))*/
}
//+++++++++++++ middlewares +++++++++++++++++++++++
// SharedData fills in common data, such as user info, etc...
func SharedData() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
if uID := session.Get(controllers.SessionKey); uID != nil {
user, err := models.GetUser(uID)
if err == nil {
c.Set(controllers.ContextUserKey, user)
}
}
if system.GetConfiguration().SignupEnabled {
c.Set("SignupEnabled", true)
}
c.Next()
}
}
// AuthRequired grants access to authenticated users
func AuthRequired(adminScope bool) gin.HandlerFunc {
return func(c *gin.Context) {
if user, _ := c.Get(controllers.ContextUserKey); user != nil {
if u, ok := user.(*models.User); ok && (!adminScope || u.IsAdmin) {
c.Next()
return
}
}
seelog.Warnf("User not authorized to visit %s", c.Request.RequestURI)
c.HTML(http.StatusForbidden, "errors/error.html", gin.H{
"message": "Forbidden!",
})
c.Abort()
}
}