Example #1
0
// @api put /admin/api/password 理发密码
// @apiGroup admin
// @apiRequest json
// @apiHeader Authorization xxx
// @apiParam old string 旧密码
// @apiParam new string 新密码
// @apiExample json
// {
//     "old": "123",
//     "new": "456"
// }
//
// @apiSuccess 204 no content
func adminChangePassword(w http.ResponseWriter, r *http.Request) {
	l := &struct {
		Old string `json:"old"`
		New string `json:"new"`
	}{}

	if !util.ReadJSON(w, r, l) {
		return
	}

	errs := &util.ErrorResult{Message: "提交数据错误", Detail: map[string]string{}}
	if len(l.New) == 0 {
		errs.Add("new", "新密码不能为空")
	}
	if opt.Password != app.Password(l.Old) {
		errs.Add("old", "旧密码错误")
	}
	if len(errs.Detail) > 0 {
		util.RenderJSON(w, http.StatusBadRequest, errs, nil)
		return
	}

	o := &models.Option{Key: "password", Value: app.Password(l.New)}
	if _, err := db.Update(o); err != nil {
		logs.Error("adminChangePassword:", err)
		util.RenderJSON(w, http.StatusInternalServerError, nil, nil)
		return
	}
	opt.Password = o.Value
	util.RenderJSON(w, http.StatusNoContent, nil, nil)
}
Example #2
0
// @api post /admin/api/login 登录
// @apiGroup admin
//
// @apiRequest json
// @apiParam password string 登录密码
// @apiExample json
// { "password": "******" }
//
// @apiSuccess 201
// @apiHeader Cache-Control:no-cache
// @apiHeader Pragma:no-cache
// @apiParam token string 登录凭证;
// @apiExample json
// { "token":  "adfwerqeqaeqe313aa" }
func adminPostLogin(w http.ResponseWriter, r *http.Request) {
	inst := &struct {
		Password string `json:"password"`
	}{}
	if !util.ReadJSON(w, r, inst) {
		return
	}

	if app.Password(inst.Password) != opt.Password {
		util.RenderJSON(w, http.StatusUnauthorized, nil, nil)
		return
	}

	ret := make([]byte, 64)
	n, err := io.ReadFull(rand.Reader, ret)
	if err != nil {
		logs.Error("login:无法产生一个随机的token", err)
		util.RenderJSON(w, http.StatusInternalServerError, nil, nil)
		return
	}
	if n == 0 {
		logs.Error("login:无法产生一个随机的token")
		util.RenderJSON(w, http.StatusInternalServerError, nil, nil)
		return
	}

	token = utils.MD5(string(ret))
	if len(token) == 0 {
		logs.Error("login:无法正确生成登录的token")
		util.RenderJSON(w, http.StatusInternalServerError, nil, nil)
		return
	}

	// 记录日志出错,仅输出错误内容,但不返回500错误。
	if err = writeLastLogs(r); err != nil {
		logs.Error("login:"******"token": token}, nil)
}