//MainMenu returns the list of main menu items func MainMenu() []MenuItem { db := models.GetDB() about := &models.Page{} db.First(about, 4) contacts := &models.Page{} db.First(contacts, 7) menu := []MenuItem{ MenuItem{ URL: "/reviews", Title: "Отзывы", }, MenuItem{ URL: "/articles", Title: "Статьи", }, MenuItem{ URL: about.URL(), Title: "О враче", CssClass: "small", }, MenuItem{ URL: contacts.URL(), Title: "Контакты", CssClass: "small", }, } return menu }
//PageShow handles /pages/:id route func PageShow(c *gin.Context) { db := models.GetDB() session := sessions.Default(c) idslug := c.Param("idslug") id := helpers.Atouint(strings.Split(idslug, "-")[0]) page := &models.Page{} db.First(page, id) if page.ID == 0 || !page.Published { c.HTML(404, "errors/404", nil) return } //redirect to canonical url if c.Request.URL.Path != page.URL() { c.Redirect(303, page.URL()) return } c.HTML(200, "pages/show", gin.H{ "Page": page, "Title": page.Name, "Active": page.URL(), "MetaDescription": page.MetaDescription, "MetaKeywords": page.MetaKeywords, "Authenticated": (session.Get("user_id") != nil), }) }
func ReviewUpdatePost(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() c.Request.ParseMultipartForm(32 << 20) review := &models.Review{} if err := c.Bind(review); err == nil { if mpartFile, mpartHeader, err := c.Request.FormFile("image"); err == nil { defer mpartFile.Close() review.Image, err = saveFile(mpartHeader, mpartFile) if err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } } if err := db.Model(&models.Review{}).Updates(review).Error; err != nil { session.AddFlash(err.Error()) session.Save() c.Redirect(303, c.Request.RequestURI) return } session.AddFlash("Отзыв был успешно сохранен") } else { log.Println(err) session.AddFlash("Ошибка! Внимательно проверьте заполнение всех полей") } session.Save() c.Redirect(303, "/reviews") }
//CommentCreatePost handles /new_comment route func CommentCreatePost(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() comment := &models.Comment{} if c.Bind(comment) == nil { //simple captcha check captcha, err := base64.StdEncoding.DecodeString(comment.Captcha) if err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } if string(captcha) != "100.00" { c.HTML(400, "errors/400", nil) return } comment.Published = false //leave unpublished if err := db.Create(comment).Error; err != nil { c.HTML(400, "errors/400", helpers.ErrorData(err)) return } notifyAdminOfComment(comment) session.AddFlash("Спасибо! Ваш вопрос будет опубликован после проверки.") session.Save() c.Redirect(303, fmt.Sprintf("/articles/%d#comments", comment.ArticleID)) } else { session.AddFlash("Ошибка! Внимательно проверьте заполнение всех полей!") session.Save() c.Redirect(303, "/") } }
func SignInPost(c *gin.Context) { db := models.GetDB() session := sessions.Default(c) login := &models.Login{} if c.Bind(login) == nil { user := &models.User{} db.Where("lower(email) = lower(?)", login.Email).First(user) if user.ID == 0 { log.Printf("ERROR: Login failed, IP: %s, Email: %s\n", c.ClientIP(), login.Email) session.AddFlash("Эл. адрес или пароль указаны неверно") session.Save() c.Redirect(303, "/signin") return } //create user if err := user.ComparePassword(login.Password); err != nil { log.Printf("ERROR: Login failed, IP: %s, Email: %s\n", c.ClientIP(), login.Email) session.AddFlash("Эл. адрес или пароль указаны неверно") session.Save() c.Redirect(303, "/signin") return } session.Set("user_id", user.ID) session.Save() c.Redirect(303, "/") } }
func SignUpPost(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() register := &models.Register{} if c.Bind(register) == nil { user := &models.User{} db.Where("lower(email) = lower(?)", register.Email).First(user) if user.ID != 0 { session.AddFlash("Пользователь с таким эл. адресом уже существует") session.Save() c.Redirect(303, "/signup") return } //create user user.Email = register.Email user.Password = register.Password if err := db.Create(user).Error; err != nil { session.AddFlash("Ошибка регистрации пользователя") session.Save() log.Printf("ERROR: ошибка регистрации пользователя: %v", err) c.Redirect(303, "/signup") return } session.Set("user_id", user.ID) session.Save() c.Redirect(303, "/") } }
//ReviewUpdate handles /edit_review?token=:secure_token route func ReviewUpdateGet(c *gin.Context) { session := sessions.Default(c) flashes := session.Flashes() session.Save() db := models.GetDB() id := getIDFromToken(c.Request.FormValue("token")) review := &models.Review{} db.First(review, id) if review.ID == 0 || review.Published { err := fmt.Errorf("Отзыв не найден или уже был опубликован и не подлежит редактированию") c.HTML(404, "errors/404", helpers.ErrorData(err)) return } var articles []models.Article db.Where("published = ?", true).Find(&articles) review.Published = true //set default to true c.HTML(200, "reviews/form", gin.H{ "Title": "Редактировать отзыв", "Articles": articles, "Active": "reviews", "Review": review, "SecureEdit": true, "Flash": flashes, }) }
func ReviewAdminUpdatePost(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() c.Request.ParseMultipartForm(32 << 20) review := &models.Review{} if c.Bind(review) == nil { review.ArticleID = helpers.Atouintr(c.Request.FormValue("article_id")) if mpartFile, mpartHeader, err := c.Request.FormFile("image"); err == nil { defer mpartFile.Close() review.Image, err = saveFile(mpartHeader, mpartFile) if err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } } if err := db.Model(&models.Review{}).Updates(review).Error; err != nil { session.AddFlash(err.Error()) session.Save() c.Redirect(303, c.Request.RequestURI) return } c.Redirect(303, "/admin/reviews") } else { session.AddFlash("Ошибка! Проверьте внимательно заполнение всех полей!") session.Save() c.Redirect(303, c.Request.RequestURI) } }
//UsersAdminIndex handles GET /admin/users route func UsersAdminIndex(c *gin.Context) { db := models.GetDB() var list []models.User db.Find(&list) c.HTML(200, "users/admin/index", gin.H{ "Title": "Пользователи", "Active": "users", "List": list, }) }
//PagesAdminIndex handles GET /admin/pages route func PagesAdminIndex(c *gin.Context) { db := models.GetDB() var list []models.Page db.Order("published desc, id desc").Find(&list) c.HTML(200, "pages/admin/index", gin.H{ "Title": "Страницы", "Active": "pages", "List": list, }) }
//CommentsAdminIndex handles GET /admin/comments route func CommentsAdminIndex(c *gin.Context) { db := models.GetDB() var list []models.Comment db.Order("id desc").Find(&list) c.HTML(200, "comments/admin/index", gin.H{ "Title": "Вопросы посетителей", "Active": "comments", "List": list, }) }
//ReviewsAdminIndex handles GET /admin/reviews route func ReviewsAdminIndex(c *gin.Context) { db := models.GetDB() var list []models.Review db.Order("id desc").Find(&list) c.HTML(200, "reviews/admin/index", gin.H{ "Title": "Отзывы", "Active": "reviews", "List": list, }) }
//ArticlesAdminIndex handles GET /admin/articles route func ArticlesAdminIndex(c *gin.Context) { db := models.GetDB() var list []models.Article if err := db.Order("published desc, id desc").Find(&list).Error; err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } c.HTML(200, "articles/admin/index", gin.H{ "Title": "Статьи", "Active": "articles", "List": list, }) }
//PageAdminDelete handles /admin/delete_page route func PageAdminDelete(c *gin.Context) { db := models.GetDB() page := &models.Page{} db.First(page, c.Request.PostFormValue("id")) if page.ID == 0 { c.HTML(404, "errors/404", nil) } if err := db.Delete(page).Error; err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } c.Redirect(303, "/admin/pages") }
//ReviewAdminDelete handles /admin/delete_review route func ReviewAdminDelete(c *gin.Context) { db := models.GetDB() review := &models.Review{} db.First(review, c.Request.PostFormValue("id")) if review.ID == 0 { c.HTML(404, "errors/404", nil) } if err := db.Delete(review).Error; err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } c.Redirect(303, "/admin/reviews") }
//UserAdminDelete handles /admin/delete_user route func UserAdminDelete(c *gin.Context) { db := models.GetDB() user := &models.User{} db.First(user, c.Request.PostFormValue("id")) if user.ID == 0 { c.HTML(404, "errors/404", nil) } if err := db.Delete(user).Error; err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } c.Redirect(303, "/admin/users") }
//ReviewAdminCreate handles /admin/new_review route func ReviewAdminCreateGet(c *gin.Context) { session := sessions.Default(c) flashes := session.Flashes() session.Save() db := models.GetDB() var articles []models.Article db.Where("published = ?", true).Find(&articles) c.HTML(200, "reviews/admin/form", gin.H{ "Title": "Новый отзыв", "Active": "reviews", "Articles": articles, "Flash": flashes, }) }
//ArticlesIndex handles GET /articles route func ArticlesIndex(c *gin.Context) { db := models.GetDB() var list []models.Article if err := db.Where("published = ?", true).Order("id desc").Find(&list).Error; err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } c.HTML(200, "articles/index", gin.H{ "Title": "Кинезиология во врачебной практике", "Active": c.Request.RequestURI, "List": list, "MetaDescription": "Статьи о кинезиологической практике лечения заболеваний опорно-двигательного аппарата...", "MetaKeywords": "кинезиология, статьи, лечение болей, прикладная кинезиология", }) }
//CommentAdminDelete handles /admin/delete_comment route func CommentAdminDelete(c *gin.Context) { db := models.GetDB() comment := &models.Comment{} db.First(comment, c.Request.PostFormValue("id")) if comment.ID == 0 { c.HTML(404, "errors/404", nil) } if err := db.Delete(comment).Error; err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } c.Redirect(303, "/admin/comments") }
//ArticleAdminDelete handles /admin/delete_article route func ArticleAdminDelete(c *gin.Context) { db := models.GetDB() article := &models.Article{} db.First(article, c.Request.PostFormValue("id")) if article.ID == 0 { c.HTML(404, "errors/404", nil) return } if err := db.Delete(article).Error; err != nil { c.HTML(500, "errors/500", helpers.ErrorData(err)) return } c.Redirect(303, "/admin/articles") }
//ArticleShow handles GET /articles/:id-slug route func ArticleShow(c *gin.Context) { db := models.GetDB() session := sessions.Default(c) idslug := c.Param("idslug") id := helpers.Atouint(strings.Split(idslug, "-")[0]) article := &models.Article{} db.First(article, id) if article.ID == 0 || !article.Published { c.HTML(404, "errors/404", nil) return } //redirect to canonical url if c.Request.URL.Path != article.URL() { c.Redirect(303, article.URL()) return } var testimonials []models.Review db.Where("published = ? and article_id = ?", true, article.ID).Order("created_at desc").Find(&testimonials) topComments := models.GetTopComments(article.ID) comments := models.GetComments(article.ID) article.Comments = append(topComments, comments...) imageurl := "" if img := article.GetImage(); len(img) > 0 { imageurl = fmt.Sprintf("http://%s%s", c.Request.Host, img) } flashes := session.Flashes() session.Save() c.HTML(200, "articles/show", gin.H{ "Article": article, "Testimonials": testimonials, "Title": article.Name, "Active": "/articles", "MetaDescription": article.MetaDescription, "MetaKeywords": article.MetaKeywords, "Ogheadprefix": "og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#", "Ogtitle": article.Name, "Ogurl": fmt.Sprintf("http://%s/articles/%d", c.Request.Host, article.ID), "Ogtype": "article", "Ogdescription": article.Excerpt, "Ogimage": imageurl, "Flash": flashes, "Authenticated": (session.Get("user_id") != nil), }) }
//ReviewsIndex handles GET /reviews route func ReviewsIndex(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() flashes := session.Flashes() session.Save() var list []models.Review db.Where("published = ?", true).Order("id desc").Find(&list) c.HTML(200, "reviews/index", gin.H{ "Title": "Кинезиология - отзывы пациентов", "Active": c.Request.RequestURI, "List": list, "Flash": flashes, "MetaDescription": "Отзывы пациентов о работе врача кинезиолога Ростовцева Е.В...", "MetaKeywords": "кинезиология отзывы, прикладная кинезиология отзывы, отзывы пациентов", "Authenticated": (session.Get("user_id") != nil), }) }
func PageAdminCreatePost(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() page := &models.Page{} if c.Bind(page) == nil { if err := db.Create(page).Error; err != nil { session.AddFlash(err.Error()) session.Save() c.Redirect(303, "/admin/new_page") return } c.Redirect(303, "/admin/pages") } else { session.AddFlash("Ошибка! Проверьте заполнение всех полей!") session.Save() c.Redirect(303, "/admin/new_page") } }
func ArticleAdminUpdatePost(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() article := &models.Article{} if c.Bind(article) == nil { if err := db.Save(article).Error; err != nil { session.AddFlash(err.Error()) session.Save() c.Redirect(303, c.Request.RequestURI) return } c.Redirect(303, "/admin/articles") } else { session.AddFlash("Ошибка! Проверьте внимательно заполнение всех полей!") session.Save() c.Redirect(303, c.Request.RequestURI) } }
//Home handles GET / route func Home(c *gin.Context) { db := models.GetDB() page := &models.Page{} db.First(page, 1) session := sessions.Default(c) flashes := session.Flashes() session.Save() c.HTML(200, "home/show", gin.H{ "Title": "Кинезиология Миобаланс", "Page": page, "Active": "/", "Flash": flashes, "TitleSuffix": "| Доктор Ростовцев Е.В.", "MetaDescription": "Прикладная кинезиология МиоБаланс - восстановление баланса обмена веществ, опорно-двигательного аппарата и нервной системы...", "Authenticated": (session.Get("user_id") != nil), }) }
func CommentAdminUpdatePost(c *gin.Context) { session := sessions.Default(c) db := models.GetDB() comment := &models.Comment{} if c.Bind(comment) == nil { if err := db.Save(comment).Error; err != nil { session.AddFlash(err.Error()) session.Save() c.Redirect(303, c.Request.RequestURI) return } c.Redirect(303, "/admin/comments") } else { session.AddFlash("Ошибка! Внимательно проверьте заполнение полей!") session.Save() c.Redirect(303, c.Request.RequestURI) } }
//ScrollMenu returns the list of scroll menu items func ScrollMenu() []MenuItem { db := models.GetDB() about := &models.Page{} db.First(about, 4) menu := []MenuItem{ MenuItem{ URL: about.URL(), Title: "О враче", }, MenuItem{ URL: "#withoutpain", Title: "Этапы лечения", }, MenuItem{ URL: "/reviews", Title: "Отзывы", }, } return menu }
//ReviewShow handles /reviews/:id route func ReviewShow(c *gin.Context) { db := models.GetDB() session := sessions.Default(c) id := c.Param("id") review := &models.Review{} db.First(review, id) if review.ID == 0 || !review.Published { c.HTML(404, "errors/404", nil) return } c.HTML(200, "reviews/show", gin.H{ "Review": review, "Title": "Отзыв о работе кинезиолога: " + review.AuthorName, "Active": "/reviews", "MetaDescription": review.MetaDescription, "MetaKeywords": review.MetaKeywords, "Authenticated": (session.Get("user_id") != nil), }) }
//ArticleAdminUpdate handles /admin/edit_article/:id route func ArticleAdminUpdateGet(c *gin.Context) { session := sessions.Default(c) flashes := session.Flashes() session.Save() db := models.GetDB() id := c.Param("id") article := &models.Article{} db.First(article, id) if article.ID == 0 { c.HTML(404, "errors/404", nil) return } c.HTML(200, "articles/admin/form", gin.H{ "Title": "Редактировать статью", "Active": "articles", "Article": article, "Flash": flashes, }) }
//UserAdminUpdate handles /admin/edit_user/:id route func UserAdminUpdateGet(c *gin.Context) { db := models.GetDB() session := sessions.Default(c) flashes := session.Flashes() session.Save() id := c.Param("id") user := &models.User{} db.First(user, id) if user.ID == 0 { c.HTML(404, "errors/404", nil) return } c.HTML(200, "users/admin/form", gin.H{ "Title": "Редактировать пользователя", "Active": "users", "User": user, "Flash": flashes, }) }