Пример #1
0
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")
}
Пример #2
0
//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,
	})
}
Пример #3
0
func CurrentUserUuid(c *gin.Context) string {
	sess := sessions.Default(c)
	if sess.Get("uuid") == nil {
		return ""
	}
	return sess.Get("uuid").(string)
}
Пример #4
0
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)
	}
}
Пример #5
0
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, "/")
	}
}
Пример #6
0
// UserMiddleware gets the current user object from the database that
// matches userID from the session, it then sets it on the gin context.
// This allows the user to be used throughout the application without
// needing to query it again each time it is needed.
func UserMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var userID uint
		session := sessions.Default(c)

		// grab userID from session
		v := session.Get("userID")
		if v == nil {
			userID = 0
		} else {
			userID = v.(uint)
		}

		// a valid userID starts at 1, 0 is an unauthenticated user
		if userID > 0 {
			var user User
			db.DB.Where("id = ?", userID).First(&user)
			c.Set("user", &user)
		} else {
			c.Set("user", nil)
		}

		c.Next()
	}
}
Пример #7
0
// Login is a page with a login form and an alternative to the login API,
// this route handles both GET and POST requests.
func Login(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	// returnURL can come from GET or POST or use default.
	returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))

	if c.Request.Method == "POST" {
		var schema LoginSchema
		if c.Bind(&schema) == nil {
			// Fetch the user matching this username.
			user := GetUserByUsername(schema.Username)

			// If the user exists, the ID is > 0, check the password.
			if user.ID > 0 && user.CheckPassword(schema.Password) {
				session.Set("userID", user.ID)
				c.Redirect(http.StatusFound, returnURL)
				return
			}
			session.AddFlash("Invalid username or password")
		}
	}

	c.HTML(200, "login.html", pongo2.Context{
		"title":      "Login",
		"messages":   session.Flashes(),
		"csrf_token": nosurf.Token(c.Request),
		"return_url": returnURL,
	})
}
Пример #8
0
func LoginPostHandler(c *gin.Context) {
	redirect := c.DefaultQuery(auth.RedirectParam, "/")
	a := auth.Default(c)
	if a.User.IsAuthenticated() {
		c.Redirect(http.StatusMovedPermanently, redirect)
		return
	}

	loginURL := fmt.Sprintf("/login?%s=%s", auth.RedirectParam, redirect)

	var form LoginForm
	if c.Bind(&form) == nil {
		model := models.Default(c)
		u := model.GetUserByNicknamePwd(form.Nickname, form.Password)
		if u != nil {
			session := sessions.Default(c)
			err := auth.AuthenticateSession(session, u)
			if err != nil {
				c.JSON(http.StatusBadRequest, err)
			}
			c.Redirect(http.StatusMovedPermanently, redirect)
			return
		} else {
			c.Redirect(http.StatusMovedPermanently, loginURL)
			return
		}
	} else {
		c.Redirect(http.StatusMovedPermanently, loginURL)
		return
	}
}
func (h *FrontendHandlers) PostLogin(c *gin.Context) {
	data := &LoginData{
		Username: c.PostForm("username"),
		Password: c.PostForm("password"),
	}

	if v := validateLogin(data); v.HasError() {
		data.Validate = v.Messages()
		h.render.HTML(c.Writer, 200, "login", data)
		return
	}

	info, err := h.loginService.Login(data.Username, data.Password)
	if err != nil {
		data.Error = err.Error()
		h.render.HTML(c.Writer, 200, "login", data)
		return
	}

	session := sessions.Default(c)
	session.Set("user_id", info.Id)
	session.Save()

	c.Redirect(302, "/")
}
Пример #10
0
//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, "/")
	}
}
Пример #11
0
func (self *SessionController) SignOut(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("token")
	session.Save()

	c.Redirect(http.StatusSeeOther, "/")
}
func (h *FrontendHandlers) Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	session.Save()

	c.Redirect(302, "/login")
}
Пример #13
0
func saveRememberMe(c *gin.Context) error {
	session := sessions.Default(c)
	loginUser := session.Get(authConf.Session.SessionKey)

	RMSession := setRMSessionValue(c, authConf.Session.SessionKey, loginUser)
	return saveRMSession(c, RMSession)
}
Пример #14
0
//SignInPost handles POST /signin route, authenticates user
func SignInPost(c *gin.Context) {
	session := sessions.Default(c)
	user := &models.User{}
	if err := c.Bind(user); err != nil {
		session.AddFlash("Please, fill out form correctly.")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	userDB, _ := models.GetUserByEmail(user.Email)
	if userDB.ID == 0 {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}
	if err := bcrypt.CompareHashAndPassword([]byte(userDB.Password), []byte(user.Password)); err != nil {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	session.Set("UserID", userDB.ID)
	session.Save()
	c.Redirect(http.StatusFound, "/")
}
Пример #15
0
func RegisterPostHandler(c *gin.Context) {
	redirect := c.DefaultQuery(auth.RedirectParam, "/")
	a := auth.Default(c)
	if a.User.IsAuthenticated() {
		c.Redirect(http.StatusMovedPermanently, redirect)
		return
	}

	registerURL := fmt.Sprintf("/register?%s=%s", auth.RedirectParam, redirect)

	var form LoginForm
	if c.Bind(&form) == nil {
		model := models.Default(c)
		u := model.AddUserWithNicknamePwd(form.Nickname, form.Password)
		if u != nil {
			session := sessions.Default(c)
			err := auth.AuthenticateSession(session, u)
			if err != nil {
				c.JSON(http.StatusBadRequest, err)
			}
			c.Redirect(http.StatusMovedPermanently, redirect)
			return
		} else {
			log.Print("Register user add error")
			c.Redirect(http.StatusMovedPermanently, registerURL)
			return
		}
	} else {
		log.Print("Register form bind error")
		c.Redirect(http.StatusMovedPermanently, registerURL)
		return
	}
}
Пример #16
0
func LogoutHandler(c *gin.Context) {
	session := sessions.Default(c)
	a := auth.Default(c)
	auth.Logout(session, a.User)

	c.Redirect(http.StatusMovedPermanently, "/")
}
Пример #17
0
//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),
	})
}
Пример #18
0
func (fc *FrontController) HomeCtr(c *gin.Context) {
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil {
		log.Fatal(err)
	}
	page -= 1
	if page < 0 {
		page = 0
	}

	prev_page := page
	if prev_page < 1 {
		prev_page = 1
	}
	next_page := page + 2

	rpp := 20
	offset := page * rpp
	CKey := fmt.Sprintf("home-page-%d-rpp-%d", page, rpp)
	var blogList string
	val, ok := Cache.Get(CKey)
	if val != nil && ok == true {
		fmt.Println("Ok, we found cache, Cache Len: ", Cache.Len())
		blogList = val.(string)
	} else {
		rows, err := DB.Query("Select aid, title from top_article where publish_status = 1 order by aid desc limit ? offset ? ", &rpp, &offset)
		if err != nil {
			log.Fatal(err)
		}
		defer rows.Close()
		var (
			aid   int
			title sql.NullString
		)
		for rows.Next() {
			err := rows.Scan(&aid, &title)
			if err != nil {
				log.Fatal(err)
			}
			blogList += fmt.Sprintf(
				"<li><a href=\"/view/%d\">%s</a></li>",
				aid,
				title.String,
			)
		}
		err = rows.Err()
		if err != nil {
			log.Fatal(err)
		}
		Cache.Add(CKey, blogList)
	}
	session := sessions.Default(c)
	username := session.Get("username")
	c.HTML(http.StatusOK, "index.html", gin.H{
		"bloglist":  template.HTML(blogList),
		"username":  username,
		"prev_page": prev_page,
		"next_page": next_page,
	})
}
Пример #19
0
func LoginHandler(ctx *gin.Context) {
	state = randToken()
	session := sessions.Default(ctx)
	session.Set("state", state)
	session.Save()
	ctx.Writer.Write([]byte("<html><title>Golang Google</title> <body> <a href='" + GetLoginURL(state) + "'><button>Login with Google!</button> </a> </body></html>"))
}
Пример #20
0
func (ac *AdminController) SaveBlogEditCtr(c *gin.Context) {
	session := sessions.Default(c)
	username := session.Get("username")
	if username == nil {
		(&umsg{"You have no permission", "/"}).ShowMessage(c)
		return
	}
	var BI EditBlogItem
	c.BindWith(&BI, binding.Form)
	if BI.Aid == "" {
		(&umsg{"Can not find the blog been edit", "/"}).ShowMessage(c)
		return
	}
	if BI.Title == "" {
		(&umsg{"Title can not empty", "/"}).ShowMessage(c)
		return
	}
	if BI.Content == "" {
		(&umsg{"Content can not empty", "/"}).ShowMessage(c)
		return
	}
	_, err := DB.Exec("update top_article set title=?, content=? where aid = ?", BI.Title, BI.Content, BI.Aid)
	if err == nil {
		Cache = lru.New(8192)
		(&umsg{"Success", "/"}).ShowMessage(c)
	} else {
		(&umsg{"Failed to save blog", "/"}).ShowMessage(c)
	}

}
Пример #21
0
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, "/")
	}
}
Пример #22
0
func (ac *AdminController) SaveBlogAddCtr(c *gin.Context) {
	session := sessions.Default(c)
	username := session.Get("username")
	if username == nil {
		(&umsg{"You have no permission", "/"}).ShowMessage(c)
		return
	}
	var BI BlogItem
	c.BindWith(&BI, binding.Form)
	if BI.Title == "" {
		(&umsg{"Title can not empty", "/"}).ShowMessage(c)
		return
	}
	if BI.Content == "" {
		(&umsg{"Content can not empty", "/"}).ShowMessage(c)
		return
	}
	_, err := DB.Exec(
		"insert into top_article (title, content, publish_time, publish_status) values (?, ?, ?, 1)",
		BI.Title, BI.Content, time.Now().Format("2006-01-02 15:04:05"))
	if err == nil {
		Cache = lru.New(8192)
		(&umsg{"Success", "/"}).ShowMessage(c)
	} else {
		(&umsg{"Failed to save blog", "/"}).ShowMessage(c)
	}

}
Пример #23
0
func GetUser(c *gin.Context) User {
	session := sessions.Default(c)
	if obj := session.Get("user"); obj != nil {
		return obj.(User)
	}

	return User{}
}
Пример #24
0
func LogoutHandler(c *gin.Context) {
	sess := sessions.Default(c)
	next := extractNextPath(c.Request.URL.Query().Get("next"))
	sess.Delete("user_id")
	sess.Delete("uuid")
	sess.Save()
	http.Redirect(c.Writer, c.Request, next, http.StatusFound)
}
Пример #25
0
// LogoutAPI is an API endoint using DELETE to end the current session.
func LogoutAPI(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	var userID uint // userID must be a uint, sets userID to 0
	session.Set("userID", userID)

	c.JSON(http.StatusOK, gin.H{"status": "OK"})
}
Пример #26
0
func (ac *AdminController) ListBlogCtr(c *gin.Context) {

	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil {
		log.Fatal(err)
	}
	page -= 1
	if page < 0 {
		page = 0
	}

	prev_page := page
	if prev_page < 1 {
		prev_page = 1
	}
	next_page := page + 2

	var blogList string
	rpp := 20
	offset := page * rpp
	log.Println(rpp)
	log.Println(offset)
	rows, err := DB.Query("Select aid, title from top_article where publish_status = 1 order by aid desc limit ? offset ? ", &rpp, &offset)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	var (
		aid   int
		title sql.NullString
	)
	for rows.Next() {
		err := rows.Scan(&aid, &title)
		if err != nil {
			log.Fatal(err)
		}
		blogList += fmt.Sprintf(
			"<li><a href=\"/view/%d\">%s</a>    [<a href=\"/admin/editblog/%d\">Edit</a>] [<a href=\"/admin/deleteblog/%d\">Delete</a>]</li>",
			aid,
			title.String,
			aid,
			aid,
		)
	}
	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}
	session := sessions.Default(c)
	username := session.Get("username")
	c.HTML(http.StatusOK, "admin.list.blog.html", gin.H{
		"bloglist":  template.HTML(blogList),
		"username":  username,
		"prev_page": prev_page,
		"next_page": next_page,
	})
}
Пример #27
0
func (fc *FrontController) HomeCtr(c *gin.Context) {
	config := GetConfig()
	db := GetDB(config)
	defer db.Close()
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil {
		log.Fatal(err)
	}
	page -= 1
	if page < 0 {
		page = 0
	}

	prev_page := page
	if prev_page < 1 {
		prev_page = 1
	}
	next_page := page + 2

	var blogList string
	rpp := 20
	offset := page * rpp
	log.Println(rpp)
	log.Println(offset)
	rows, err := db.Query("Select aid, title from top_article where publish_status = 1 order by aid desc limit ? offset ? ", &rpp, &offset)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	var (
		aid   int
		title sql.NullString
	)
	for rows.Next() {
		err := rows.Scan(&aid, &title)
		if err != nil {
			log.Fatal(err)
		}
		blogList += fmt.Sprintf(
			"<li><a href=\"/view/%d\">%s</a></li>",
			aid,
			title.String,
		)
	}
	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}
	session := sessions.Default(c)
	username := session.Get("username")
	c.HTML(http.StatusOK, "index.html", gin.H{
		"bloglist":  template.HTML(blogList),
		"username":  username,
		"prev_page": prev_page,
		"next_page": next_page,
	})
}
Пример #28
0
//UserNew handles GET /admin/new_user route
func UserNew(c *gin.Context) {
	h := helpers.DefaultH(c)
	h["Title"] = "New user"
	h["Active"] = "users"
	session := sessions.Default(c)
	h["Flash"] = session.Flashes()
	session.Save()
	c.HTML(http.StatusOK, "users/form", h)
}
Пример #29
0
func (ac *AdminController) AddBlogCtr(c *gin.Context) {
	session := sessions.Default(c)
	username := session.Get("username")
	if username == nil {
		(&umsg{"You have no permission", "/"}).ShowMessage(c)
		return
	}
	c.HTML(http.StatusOK, "add-blog.html", gin.H{})
}
Пример #30
0
//SignUpGet handles GET /signup route
func SignUpGet(c *gin.Context) {
	h := helpers.DefaultH(c)
	h["Title"] = "Basic GIN web-site signup form"
	h["Active"] = "signup"
	session := sessions.Default(c)
	h["Flash"] = session.Flashes()
	session.Save()
	c.HTML(http.StatusOK, "auth/signup", h)
}