You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

359 lines
7.3 KiB

  1. package Webserver
  2. import (
  3. "fmt"
  4. "log"
  5. "mime/multipart"
  6. "net/http"
  7. "strconv"
  8. "time"
  9. "PersonalWebsite/Database"
  10. "PersonalWebsite/Helper"
  11. "PersonalWebsite/Variables"
  12. "github.com/gorilla/mux"
  13. "github.com/gorilla/sessions"
  14. )
  15. func CheckAuth(w http.ResponseWriter, r *http.Request) bool {
  16. var (
  17. session *sessions.Session
  18. lastActiveUnix int64
  19. lastActive time.Time
  20. auth bool
  21. exists bool
  22. e error
  23. )
  24. session, e = Variables.CookieStore.Get(r, Variables.CookieName)
  25. if e != nil {
  26. return false
  27. }
  28. auth, exists = session.Values["authenticated"].(bool)
  29. if !(auth && exists) {
  30. return false
  31. }
  32. lastActiveUnix, exists = session.Values["lastActive"].(int64)
  33. if !exists {
  34. return false
  35. }
  36. lastActive = time.Unix(lastActiveUnix, 0)
  37. lastActive.Add(12 * time.Hour)
  38. if time.Now().Before(lastActive) {
  39. session.Values = make(map[interface{}]interface{})
  40. session.Values["authenticated"] = false
  41. session.AddFlash("Login Expired")
  42. e = session.Save(r, w)
  43. if e != nil {
  44. log.Println(e.Error())
  45. }
  46. return false
  47. }
  48. session.Values["lastLogin"] = time.Now().Unix()
  49. e = session.Save(r, w)
  50. if e != nil {
  51. log.Println(e.Error())
  52. return false
  53. }
  54. return true
  55. }
  56. func AdminView(w http.ResponseWriter, r *http.Request) {
  57. var (
  58. v = make(map[string]interface{})
  59. urlParams map[string]string
  60. page string
  61. pageInt int
  62. pageOffset int
  63. posts []Database.Post
  64. exists bool
  65. e error
  66. )
  67. if !CheckAuth(w, r) {
  68. http.Redirect(w, r, "/admin/login", 302)
  69. return
  70. }
  71. switch r.Method {
  72. case http.MethodGet:
  73. urlParams = mux.Vars(r)
  74. page, exists = urlParams["page"]
  75. if exists {
  76. pageInt, e = strconv.Atoi(page)
  77. if e != nil {
  78. log.Fatal("Url Parameter page cannot be converted to an int")
  79. }
  80. } else {
  81. pageInt = 0
  82. }
  83. pageOffset = pageInt * 10
  84. posts, e = Database.GetPostsList(10, pageOffset)
  85. v["Posts"] = posts
  86. ServeTemplate(w, r, "html/admin/admin-index.gohtml", v)
  87. return
  88. }
  89. }
  90. func AdminLogin(w http.ResponseWriter, r *http.Request) {
  91. var (
  92. session *sessions.Session
  93. v = make(map[string]interface{})
  94. flashes []interface{}
  95. username string
  96. password string
  97. e error
  98. )
  99. if CheckAuth(w, r) {
  100. http.Redirect(w, r, "/admin", 302)
  101. return
  102. }
  103. session, e = Variables.CookieStore.Get(r, Variables.CookieName)
  104. if e != nil {
  105. log.Println("Could not get session cookie")
  106. http.Error(w, "Error", http.StatusInternalServerError)
  107. return
  108. }
  109. switch r.Method {
  110. case http.MethodGet:
  111. flashes = session.Flashes()
  112. e = session.Save(r, w)
  113. if e != nil {
  114. log.Println(e.Error())
  115. return
  116. }
  117. if len(flashes) > 0 {
  118. v["FlashMsg"] = flashes[0].(string)
  119. }
  120. ServeTemplate(w, r, "html/admin/admin-login.gohtml", v)
  121. return
  122. case http.MethodPost:
  123. e = r.ParseForm()
  124. if e != nil {
  125. log.Println(e.Error())
  126. http.Redirect(w, r, "/login", 302)
  127. }
  128. username = r.FormValue("username")
  129. password = r.FormValue("password")
  130. if username != Variables.AdminPassword && password != Variables.AdminPassword {
  131. session.AddFlash("Invalid Username or Password")
  132. e = session.Save(r, w)
  133. if e != nil {
  134. log.Println(e.Error())
  135. }
  136. http.Redirect(w, r, "/admin/login", 302)
  137. return
  138. }
  139. session.Values["authenticated"] = true
  140. session.Values["lastActive"] = time.Now().Unix()
  141. session.Save(r, w)
  142. http.Redirect(w, r, "/admin", 302)
  143. return
  144. }
  145. }
  146. func AdminNewPost(w http.ResponseWriter, r *http.Request) {
  147. var (
  148. session *sessions.Session
  149. v = make(map[string]interface{})
  150. flashes []interface{}
  151. title, subject, intro, body string
  152. bodyPath string
  153. mainFilePath string = ""
  154. fileUpload []*multipart.FileHeader
  155. //otherImgs string
  156. e error
  157. )
  158. if !CheckAuth(w, r) {
  159. http.Redirect(w, r, "/admin/login", 302)
  160. return
  161. }
  162. session, e = Variables.CookieStore.Get(r, Variables.CookieName)
  163. if e != nil {
  164. log.Println("Could not get session cookie")
  165. http.Error(w, "Error", http.StatusInternalServerError)
  166. return
  167. }
  168. switch r.Method {
  169. case http.MethodGet:
  170. flashes = session.Flashes()
  171. e = session.Save(r, w)
  172. if e != nil {
  173. log.Println(e.Error())
  174. return
  175. }
  176. if len(flashes) > 0 {
  177. v["FlashMsg"] = flashes[0].(string)
  178. }
  179. ServeTemplate(w, r, "html/admin/admin-new-post.gohtml", v)
  180. return
  181. case http.MethodPost:
  182. title = r.FormValue("title")
  183. subject = r.FormValue("subject")
  184. intro = r.FormValue("intro")
  185. body = r.FormValue("body")
  186. bodyPath, e = Helper.WriteBody(title, body)
  187. if e != nil {
  188. log.Fatal(e)
  189. }
  190. r.ParseMultipartForm(32 << 20) // 32MB is the default used by FormFile
  191. fileUpload = r.MultipartForm.File["img"]
  192. Helper.UploadFiles(fileUpload)
  193. if len(fileUpload) == 1 {
  194. mainFilePath = fileUpload[0].Filename
  195. }
  196. fileUpload = r.MultipartForm.File["files"]
  197. Helper.UploadFiles(fileUpload)
  198. Database.CreatePost(
  199. Database.Post{
  200. Title: title,
  201. Subject: subject,
  202. Intro: intro,
  203. HtmlPath: bodyPath,
  204. MainImage: mainFilePath,
  205. },
  206. )
  207. http.Redirect(w, r, "/admin", 302)
  208. return
  209. }
  210. }
  211. func AdminEditPost(w http.ResponseWriter, r *http.Request) {
  212. var (
  213. session *sessions.Session
  214. v = make(map[string]interface{})
  215. urlParams map[string]string
  216. flashes []interface{}
  217. title, subject, intro, body string
  218. bodyPath string
  219. post Database.Post
  220. fileUpload []*multipart.FileHeader
  221. e error
  222. )
  223. if !CheckAuth(w, r) {
  224. http.Redirect(w, r, "/admin/login", 302)
  225. return
  226. }
  227. session, e = Variables.CookieStore.Get(r, Variables.CookieName)
  228. if e != nil {
  229. log.Println("Could not get session cookie")
  230. http.Error(w, "Error", http.StatusInternalServerError)
  231. return
  232. }
  233. switch r.Method {
  234. case http.MethodGet:
  235. flashes = session.Flashes()
  236. e = session.Save(r, w)
  237. if e != nil {
  238. log.Println(e.Error())
  239. return
  240. }
  241. if len(flashes) > 0 {
  242. v["FlashMsg"] = flashes[0].(string)
  243. }
  244. urlParams = mux.Vars(r)
  245. post, e = Database.GetPostById(urlParams["id"])
  246. if e != nil {
  247. log.Fatal("Cannot get Post by id")
  248. }
  249. post.Body, e = Helper.GetFileContents(post.HtmlPath)
  250. if e != nil {
  251. log.Fatal("Cannot read body file")
  252. }
  253. v["Post"] = post
  254. ServeTemplate(w, r, "html/admin/admin-update-post.gohtml", v)
  255. return
  256. case http.MethodPost:
  257. urlParams = mux.Vars(r)
  258. post, e = Database.GetPostById(urlParams["id"])
  259. if e != nil {
  260. log.Fatal("Cannot get Post by id")
  261. }
  262. title = r.FormValue("title")
  263. subject = r.FormValue("subject")
  264. intro = r.FormValue("intro")
  265. body = r.FormValue("body")
  266. if title != post.Title {
  267. defer Helper.DeleteOldPostFile(post.Title)
  268. }
  269. bodyPath, e = Helper.WriteBody(title, body)
  270. if e != nil {
  271. log.Fatal(e)
  272. }
  273. r.ParseMultipartForm(32 << 20) // 32MB is the default used by FormFile
  274. fileUpload = r.MultipartForm.File["img"]
  275. Helper.UploadFiles(fileUpload)
  276. if len(fileUpload) == 1 {
  277. post.MainImage = fileUpload[0].Filename
  278. }
  279. fileUpload = r.MultipartForm.File["files"]
  280. Helper.UploadFiles(fileUpload)
  281. post.Title = title
  282. post.Subject = subject
  283. post.Intro = intro
  284. post.HtmlPath = bodyPath
  285. Database.UpdatePost(
  286. post,
  287. )
  288. http.Redirect(w, r, fmt.Sprintf("/admin/post/%s/edit", post.ID), 302)
  289. return
  290. }
  291. }