Esempio n. 1
0
// Auth is a gin middleware that checks for session cookie
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {

		// get the jwt cookie from the request
		cookie, err := c.Request.Cookie(u.CookieName)
		if err != nil {
			c.Error(err).SetMeta("middleware.Auth.Cookie")
			c.Redirect(http.StatusFound, "/admin/login")
			c.Abort()
			return
		}

		token, err := jwt.ParseWithClaims(cookie.Value, &u.TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
			return u.ValidateToken(token)
		})
		// the client side should delete any saved JWT tokens on unauth error
		if err != nil || !token.Valid {
			// delete the cookie
			http.SetCookie(c.Writer, u.DeleteCookie())
			c.Error(err).SetMeta("middleware.Auth.ParseWithClaims")
			c.Redirect(http.StatusFound, "/admin/login")
			c.Abort()
			return
		}

		// set user data for controllers
		c.Set("authenticated", true)

		c.Next()

	}
}
Esempio n. 2
0
// PasswordController updates the password
func PasswordController(c *gin.Context) {
	var err error
	var pf passwordForm

	err = c.Bind(&pf)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.Bind")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	err = u.CheckPassword(pf.Old)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.Check")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	if pf.New != pf.Check {
		c.Error(err).SetMeta("admin.PasswordController.Compare")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	var hash []byte

	hash, err = u.HashPassword(pf.Check)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.HashPassword")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	var user u.User

	err = u.Storm.Get("auth", "user", &user)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.HashPassword")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	// set user password
	user.Password = hash

	err = u.Storm.Set("auth", "user", &user)
	if err != nil {
		c.Error(err).SetMeta("admin.PasswordController.Set")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	// unset the jwt cookie
	http.SetCookie(c.Writer, u.DeleteCookie())

	c.Redirect(http.StatusFound, "/admin/panel")

	return

}