示例#1
0
// EchoLogger 用于 echo 框架的日志中间件
func HTTPError() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(ctx echo.Context) error {
			if err := next(ctx); err != nil {

				if !ctx.Response().Committed() {
					if he, ok := err.(*echo.HTTPError); ok {
						switch he.Code {
						case http.StatusNotFound:
							if util.IsAjax(ctx) {
								return ctx.String(http.StatusOK, `{"ok":0,"error":"接口不存在"}`)
							}
							return Render(ctx, "404.html", nil)
						case http.StatusForbidden:
							if util.IsAjax(ctx) {
								return ctx.String(http.StatusOK, `{"ok":0,"error":"没有权限访问"}`)
							}
							return Render(ctx, "403.html", map[string]interface{}{"msg": he.Message})
						case http.StatusInternalServerError:
							if util.IsAjax(ctx) {
								return ctx.String(http.StatusOK, `{"ok":0,"error":"接口服务器错误"}`)
							}
							return Render(ctx, "500.html", nil)
						}
					}
				}
			}
			return nil
		}
	}
}
示例#2
0
// Login 登录
func (AccountController) Login(ctx echo.Context) error {
	if _, ok := ctx.Get("user").(*model.Me); ok {
		return ctx.Redirect(http.StatusSeeOther, "/")
	}

	// 支持跳转到源页面
	uri := ctx.FormValue("redirect_uri")
	if uri == "" {
		uri = "/"
	}

	contentTpl := "login.html"
	data := make(map[string]interface{})

	username := ctx.FormValue("username")
	if username == "" || ctx.Request().Method() != "POST" {
		data["redirect_uri"] = uri
		return render(ctx, contentTpl, data)
	}

	// 处理用户登录
	passwd := ctx.FormValue("passwd")
	userLogin, err := logic.DefaultUser.Login(ctx, username, passwd)
	if err != nil {
		data["username"] = username
		data["error"] = err.Error()

		if util.IsAjax(ctx) {
			return fail(ctx, 1, err.Error())
		}

		return render(ctx, contentTpl, data)
	}

	// 登录成功,种cookie
	SetCookie(ctx, userLogin.Username)

	if util.IsAjax(ctx) {
		return success(ctx, nil)
	}

	return ctx.Redirect(http.StatusSeeOther, uri)
}
示例#3
0
// NeedLogin 用于 echo 框架的验证必须登录的请求
func NeedLogin() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(ctx echo.Context) error {
			user, ok := ctx.Get("user").(*model.Me)
			if !ok || user.Status != model.UserStatusAudit {
				method := ctx.Request().Method()
				if util.IsAjax(ctx) {
					return ctx.JSON(http.StatusForbidden, `{"ok":0,"error":"403 Forbidden"}`)
				} else {
					if method == "POST" {
						return ctx.HTML(http.StatusForbidden, `403 Forbidden`)
					}

					if !ok {
						reqURL := ctx.Request().URL()
						uri := reqURL.Path()
						if reqURL.QueryString() != "" {
							uri += "?" + reqURL.QueryString()
						}
						return ctx.Redirect(http.StatusSeeOther, "/account/login?redirect_uri="+url.QueryEscape(uri))
					} else {
						// 未激活可以查看账号信息
						if !strings.HasPrefix(ctx.Path(), "/account") {
							return echo.NewHTTPError(http.StatusForbidden, `您的邮箱未激活,<a href="/account/edit">去激活</a>`)
						}
					}
				}
			}

			if err := next(ctx); err != nil {
				return err
			}

			return nil
		}
	}
}