Example #1
0
func islogin(c *gin.Context) bool {
	// cookie.Name = "user"
	// cookie.Value = "uid"
	// ck type --- > string
	ck, err := util.GetSecureCookie(c.Request, "user")
	log.Print(ck)

	if err != nil || ck == "" {
		log.Print(" no ck current...........")
		return false
	}

	uid, e := strconv.Atoi(ck)
	if e != nil {
		return false
	}

	// select id from users where id = ?
	var user models.User
	models.DB.Where("uid = ?", uid).Find(&user)
	if user.Uid != uint(uid) {
		return false
	}
	return true
}
Example #2
0
func NewPostAndEditHandler(c *gin.Context) {
	//  post: --> /post/   or  -->/post/*slug

	Title := c.PostForm("title")
	Content := c.PostForm("content")
	Published := time.Now()
	now := time.Now()

	slug := c.PostForm("slug")
	//  /post/*slug  ---> slug start with "/"
	var Slug string
	if slug == "/" {
		Slug = now.Format("2006/1/02/") + strconv.Itoa(now.Nanosecond())
	} else {
		Slug = string([]byte(slug)[1:])
	}

	uid, err := util.GetSecureCookie(c.Request, "user")
	if err != nil {
		c.Redirect(http.StatusNonAuthoritativeInfo, "/login")
		return
	}

	Useridstr, _ := strconv.Atoi(uid)
	Userid := uint(Useridstr)

	tag := c.PostForm("tag")
	var (
		tags  Tag
		Tagid uint = 0
	)
	if tag != "" {
		DB.Where("type=?", tag).Find(&tags)
		Tagid = tags.Tid
	}

	post := Post{
		Title:     Title,
		Content:   Content,
		Published: Published,
		Slug:      Slug,
		Userid:    Userid,
		Tagid:     Tagid,
	}
	if slug == "/" {
		DB.Create(&post)
	} else {
		DB.Model(&post).Update("title", "content", "slug", "tagid")
	}

	c.Redirect(http.StatusMovedPermanently, "/posts/"+Slug)
}
Example #3
0
func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		// cookie.Name = "user"
		// cookie.Value = "uid"
		// ck type --- > string
		ck, err := util.GetSecureCookie(c.Request, "user")
		log.Print(ck)

		if err != nil || ck == "" {
			log.Print(" no ck ...........")
			c.Redirect(http.StatusMovedPermanently, "/login")
			c.AbortWithStatus(401)
			return
		}

		uid, e := strconv.Atoi(ck)
		if e != nil {
			c.Abort()
			log.Print(" no uid ...........")
			c.Redirect(http.StatusMovedPermanently, "/login")
			return
		}

		// select id from users where id = ?
		var user models.User
		models.DB.Where("uid = ?", uid).Find(&user)
		if user.Uid != uint(uid) {
			c.Abort()
			log.Print(" no correct ck ...........")
			c.Redirect(http.StatusMovedPermanently, "/login")
			return
		}

		c.Next()
	}
}