示例#1
0
func ResetPasswordHandler() httperr.Handler {
	return func(w http.ResponseWriter, r *http.Request) error {

		type resetPasswordReq struct {
			Email string
		}

		req := &resetPasswordReq{}
		if err := json.NewDecoder(r.Body).Decode(req); err != nil {
			return httperr.New(http.StatusBadRequest, err.Error(), err)
		}

		dbmap, err := getDB()
		defer dbmap.Db.Close()
		if err != nil {
			return err
		}

		member, err := model.FindMember(dbmap, req.Email)
		// if member not found return 200 anyway
		if err != nil {
			return nil
		}
		if err := member.ResetPassword(); err != nil {
			return err
		}
		if _, err := dbmap.Update(member); err != nil {
			return err
		}
		return nil
	}
}
示例#2
0
func ChangePasswordHandler() httperr.Handler {
	return func(w http.ResponseWriter, r *http.Request) error {

		type changePasswordReq struct {
			OldPassword string
			NewPassword string
		}

		req := &changePasswordReq{}
		if err := json.NewDecoder(r.Body).Decode(req); err != nil {
			return httperr.New(http.StatusBadRequest, err.Error(), err)
		}

		dbmap, err := getDB()
		defer dbmap.Db.Close()
		if err != nil {
			return err
		}

		email := r.URL.Query().Get(authEmailKey)
		member, err := model.FindMember(dbmap, email)
		if err != nil {
			return err
		}

		if !member.HasPassword(req.OldPassword) {
			err := errors.New("password invalid")
			return httperr.New(http.StatusBadRequest, err.Error(), err)
		}

		pword, err := model.NewPassword(req.NewPassword)
		if err != nil {
			return httperr.New(http.StatusBadRequest, "password must be between 7 and 32 characters", err)
		}
		member.SetPassword(pword)
		if _, err := dbmap.Update(member); err != nil {
			return err
		}
		return nil
	}
}
示例#3
0
func Auth(h httperr.Handler) httperr.Handler {
	return func(w http.ResponseWriter, r *http.Request) error {
		dbmap, err := getDB()
		defer dbmap.Db.Close()
		if err != nil {
			return err
		}

		v := r.URL.Query()
		email := v.Get(authEmailKey)
		token := v.Get(authTokenKey)

		errResp := httperr.New(http.StatusUnauthorized, "not authorized", errors.New("not authorized"))
		member, err := model.FindMember(dbmap, email)
		if err != nil {
			return errResp
		} else if err := model.ValidateToken(dbmap, member.ID, token); err != nil {
			return errResp
		}
		return h(w, r)
	}
}