示例#1
0
// stubosEdit is shared between the create and update handler, since they share most of the logic.
func (h *DBHandler) stubosEdit(rw http.ResponseWriter, req *http.Request, id uint) {
	stuboForm := new(StuboForm)

	log.WithFields(log.Fields{
		"id":       id,
		"url_path": req.URL.Path,
	}).Info("Entering stubosEdti")

	// validate form
	if err := binding.Bind(req, stuboForm); err.Handle(rw) {
		fmt.Println(err.Error())
		return
	}
	// assing form variables to stubo struct
	stubo := Stubo{Name: stuboForm.Name, Version: stuboForm.Version, Hostname: stuboForm.Hostname,
		Port: stuboForm.Port, Protocol: stuboForm.Protocol}

	h.db.Create(&stubo)
	log.WithFields(log.Fields{
		"id":       id,
		"url_path": req.URL.Path,
	}).Info("Stubo added")

	// TODO: should add some messages to user about successful creation
	h.stuboShowHandler(rw, req)
}
示例#2
0
//RegisterUser ...
func (client *ClientController) RegisterUser(res http.ResponseWriter, req *http.Request) {
	//Extract the models from the request
	render := render.New(render.Options{})
	registeredType := new(services.RegisteredUser)
	errs := binding.Bind(req, registeredType)
	userlogic.ServiceList = client.ServiceList
	userlogic.Logger = client.Logger
	if errs.Handle(res) {
		client.Logger.Crit(errs.Error())
		render.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := registeredType.Validate(req, errs)
	if bindingErr != nil {
		client.Logger.Crit(bindingErr.Error())
		render.JSON(res, 422, bindingErr.Error())
		return
	}

	person, user, err := userlogic.RegisterUser(registeredType.Person, registeredType.User)
	if err != nil {
		client.Logger.Error(err.Error())
		panic(err)
	}
	render.JSON(res, 200, map[string]interface{}{"Person": person, "User": user})
}
示例#3
0
// UpdateUser updates selected fields of a user provided by an id mux parameter.
func UpdateUser(server *app.App) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		id := vars["id"]
		user := &models.User{ID: id}
		if ok, err := server.DB.Exists(user); err != nil || !ok {
			server.Render.JSON(w, http.StatusNotFound, nil)
			return
		}
		updateReq := &models.UserUpdateRequest{}
		if err := binding.Bind(req, updateReq); err.Handle(w) {
			return
		}
		hash, err := bcrypt.GenerateFromPassword([]byte(updateReq.Password), 12)
		if err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error updating the user"})
			log.Println(err)
			return
		}
		if err := server.DB.Update(user, map[string]interface{}{"Hash": string(hash)}); err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error updating the user"})
			log.Println(err)
			return
		}
		user.Hash = ""
		server.Render.JSON(w, http.StatusOK, user)
	}
}
示例#4
0
//AddNewAddressToUser ... Add address to a user profile
func (client *ClientController) AddNewAddressToUser(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {

	render := render.New(render.Options{})
	address := models.Addresses{}
	errs := binding.Bind(req, &address)
	userlogic.ServiceList = client.ServiceList
	userlogic.Logger = client.Logger
	userlogic.AuthorizationToken = req.Header.Get("Authorization")
	if errs.Handle(res) {
		client.Logger.Crit(errs.Error())
		render.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := address.Validate(req, errs)
	if bindingErr != nil {
		client.Logger.Crit(bindingErr.Error())
		render.JSON(res, 422, bindingErr.Error())
		return
	}

	savedEntity, bSave, err := userlogic.AddNewAddressToUser(address)
	if !bSave && err != nil {
		client.Logger.Error(err.Error())
		panic(err)
	}
	render.JSON(res, 200, savedEntity)
}
示例#5
0
// CreateUser is a http handler function to creation a new user.
func CreateUser(server *app.App) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		userReq := &models.UserRequest{}
		if err := binding.Bind(req, userReq); err.Handle(w) {
			return
		}
		existing, err := models.FindUserByEmail(server.DB, userReq.Email)
		if err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"})
			log.Println(err)
			return
		}
		if existing.ID != "" {
			server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "user email must be unique across the application"})
			return
		}
		user, err := models.NewUser(userReq.Email, []byte(userReq.Password))
		if err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"})
			log.Println(err)
			return
		}
		if err := server.DB.Save(user); err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the user to the database"})
			log.Println(err)
			return
		}
		user.Hash = ""
		server.Render.JSON(w, http.StatusCreated, user)
	}
}
示例#6
0
文件: room.go 项目: RorNHJ/GoLanguage
func createRoom(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	// binding 패키지를 사용하여 room 생성 요청 정보를 Room 타입의 값으로 변환
	r := new(Room)
	errs := binding.Bind(req, r)
	if errs.Handle(w) {
		return
	}

	// 몽고DB 세션 생성
	session := mongoSession.Copy()
	// 몽고DB 세션을 닫는 코드를 defer로 등록
	defer session.Close()

	// 몽고DB 아이디 생성
	r.ID = bson.NewObjectId()
	// room 정보 저장을 위한 몽고DB 컬렉션 객체 생성
	c := session.DB("test").C("rooms")

	// rooms 컬렉션에 room 정보 저장
	if err := c.Insert(r); err != nil {
		// 오류 발생시 500 에러 리턴
		renderer.JSON(w, http.StatusInternalServerError, err)
		return
	}
	// 처리 결과 리턴
	renderer.JSON(w, http.StatusCreated, r)
}
示例#7
0
// CreateGood ... create new merchant
func (mer MerchantController) CreateGood(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	good := new(models.Goods)
	errs := binding.Bind(req, good)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}

	bindingErr := good.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	// save to database
	p := models.Goods{mer.BaseModel, good.MerchantID, good.PercentDiscount, good.AvailFrom, good.AvailTo, good.Promo, good.UnitPrice, good.GoodServices, good.GoodserviceID,
		good.GoodCategoryID, good.GoodHist}

	err := mer.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}

	// render response
	r.JSON(res, 200, p)
}
示例#8
0
// CreateCountry ... create new country
func (c CommonController) CreateCountry(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	country := new(models.Country)
	errs := binding.Bind(req, country)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}

	bindingErr := country.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	// save to database
	p := models.Country{c.BaseModel, country.ISOCode, country.Name, country.RegionStates, country.Language, country.LanguageID}

	err := c.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		fmt.Println(err.Error())
		panic(err)
	} else {
		r.JSON(res, 200, p)
	}

	// render response

}
示例#9
0
func (h *H) Generate(w http.ResponseWriter, req *http.Request) {
	opts := &generateReq{}
	if errs := binding.Bind(req, opts); errs.Handle(w) {
		return
	}
	vopts := []string{}
	for _, o := range opts.Options {
		vopts = append(vopts, fmt.Sprintf("%s=%s", o.Key, o.Value))
	}
	var paths string
	err := h.C.Call("generate", vopts, &paths)
	if err != nil {
		h.JSON400(w, errors.New("could not parse the response from veil, likely no options or an invalid payload"))
		return
	}
	if paths == "" {
		h.JSON400(w, errors.New("no payload was generated"))
		return
	}
	fullDir := path.Dir(paths)
	rootDir := path.Base(fullDir)
	f := path.Base(paths)
	httpath := path.Join(rootDir, f)
	h.JSON(w, map[string]string{"result": httpath})
}
示例#10
0
// CreateCustomer ... Add new customer
func (acct AccountController) CreateCustomer(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	customer := new(models.Customer)
	errs := binding.Bind(req, customer)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := customer.Validate(req, errs)
	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	p := models.Customer{acct.BaseModel, customer.Person, customer.PersonID, customer.CompanyEntites, customer.CompanyEntitesID, customer.CustomerType, customer.CustomerTypeID}
	//p := models.User{acct.BaseModel, user.Realm, user.Username, user.Password, user.Credential, user.Challenges, user.Email, user.Emailverified, user.Verificationtoken,
	//	user.LogInCummulative, user.FailedAttemptedLogin, uuid.New(), user.PersonID, user.PhoneNum, user.VerifiedPhoneNum}

	err := acct.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}
	// render response
	r.JSON(res, 200, p)
}
示例#11
0
// CreateLanguage ... create new language
func (c CommonController) CreateLanguage(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	language := new(models.Language)
	errs := binding.Bind(req, language)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := language.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	// save to database
	p := models.Language{c.BaseModel, language.ISOCode, language.Name}

	err := c.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}

	// render response
	r.JSON(res, 200, p)
}
示例#12
0
// CreateContact ... add new contact to a person
func (c PersonController) CreateContact(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	contact := new(models.Contacts)
	errs := binding.Bind(req, contact)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := contact.Validate(req, errs)
	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	p := models.Contacts{
		BaseModel:         c.BaseModel,
		PhoneNo:           contact.PhoneNo,
		PhoneNo2:          contact.PhoneNo2,
		PhoneNo3:          contact.PhoneNo3,
		Email:             contact.Email,
		Website:           contact.Website,
		FacebookID:        contact.FacebookID,
		PersonID:          contact.PersonID,
		CompanyEntitiesID: contact.CompanyEntitiesID}

	err := c.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}
	// render response
	r.JSON(res, 200, p)
}
示例#13
0
// CreateAddress ... add new address to a person
func (c PersonController) CreateAddress(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	address := new(models.Addresses)
	errs := binding.Bind(req, address)
	bs, _ := ioutil.ReadAll(req.Body)
	if errs.Handle(res) {
		c.Logger.Error(fmt.Sprintf("%s, %s", errs.Error(), string(bs)))
		r.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := address.Validate(req, errs)
	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	p := &models.Addresses{
		BaseModel:         c.BaseModel,
		AddressType:       address.AddressType,
		HouseNo:           address.HouseNo,
		Street:            address.Street,
		Area:              address.Area,
		TownsID:           address.TownsID,
		RegionStateID:     address.RegionStateID,
		CountryID:         address.CountryID,
		PersonID:          address.PersonID,
		CompanyEntitiesID: address.CompanyEntitiesID}

	err := c.DataStore.SaveDatabaseObject(p)
	if err != nil {
		panic(err)
	}
	c.Logger.Info(fmt.Sprintf("%v", &p))
	r.JSON(res, 200, p)
}
示例#14
0
文件: handlers.go 项目: duanqy/retask
//  pushHandler 推送一个任务到队列中
func pushHandler(w http.ResponseWriter, r *http.Request) {
	httpTask := new(HttpTask)
	errs := binding.Bind(r, httpTask)
	if errs.Len() > 0 {
		Response{W: w}.JSON("1704", "参数错误", errs)
		return
	}
	job := Job{Job: "re_task@v1", Data: httpTask}
	jobStr, err := json.Marshal(job)
	if err != nil {
		Response{W: w}.JSON("1705", err.Error(), nil)
		return
	}
	id, err := tube.Put(jobStr, 0, 0, 0)
	if err != nil {
		Response{W: w}.JSON("1706", err.Error(), nil)
		return
	}

	Response{W: w}.JSON("0", "success", map[string]interface{}{
		"id":  id,
		"job": job,
	})
	return
}
示例#15
0
// CreatePersonIDType ... add new contact to a person
func (c PersonController) CreatePersonIDType(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	personIDType := new(models.PersonIDType)
	errs := binding.Bind(req, personIDType)
	idTypes := models.IDType{}
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := personIDType.Validate(req, errs)
	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	p := models.PersonIDType{
		BaseModel:      c.BaseModel,
		PersonID:       personIDType.PersonID,
		IDType:         personIDType.IDType,
		IDNumber:       personIDType.IDNumber,
		DateIssued:     personIDType.DateIssued,
		ExpiryDate:     personIDType.ExpiryDate,
		ScannedPicture: personIDType.ScannedPicture,
		IDTypes:        idTypes}
	err := c.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}
	r.JSON(res, 200, p)
}
示例#16
0
// CreateCustomerType ... Add new customer
func (cust CustomerController) CreateCustomerType(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	custType := new(models.CustomerType)
	errs := binding.Bind(req, custType)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := custType.Validate(req, errs)
	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	p := models.CustomerType{cust.BaseModel, custType.Name, custType.Code, custType.Description}
	//p := models.User{acct.BaseModel, user.Realm, user.Username, user.Password, user.Credential, user.Challenges, user.Email, user.Emailverified, user.Verificationtoken,
	//	user.LogInCummulative, user.FailedAttemptedLogin, uuid.New(), user.PersonID, user.PhoneNum, user.VerifiedPhoneNum}

	tx := cust.Db.Begin()

	if err := tx.Create(&p).Error; err != nil {
		tx.Rollback()
		panic(err)
	}
	tx.Commit()
	// render response
	r.JSON(res, 200, p)
}
示例#17
0
func (rcv *controller) post() []error {

	var errs []error

	// Map html input value to fields
	if formErrs := binding.Bind(rcv.Request, rcv.formUser); formErrs != nil {

		for _, e := range formErrs {
			errs = append(errs, errors.New(e.Message))
		}
		return errs
	}

	// Validate captcha
	if err := captcha.Validate(rcv.Request, rcv.formUser.Certification, rcv.formUser.Human); err != nil {
		return []error{errors.New(rcv.Translate("text09"))}
	}

	if errs := maccount.Create(rcv.formUser.Name, rcv.formUser.Email, rcv.formUser.Password, rcv.Local, rcv.formUser.TermOf); errs != nil {
		return errs
	}

	if err := rcv.sendActivationLink(rcv.formUser.Email); err != nil {
		return []error{err}
	}

	return nil

}
示例#18
0
// CreateRegion ... create new region
func (c CommonController) CreateRegion(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	region := new(models.RegionState)
	errs := binding.Bind(req, region)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}

	bindingErr := region.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	// save to database
	p := models.RegionState{c.BaseModel, region.Name, region.CountryID, region.Towns}

	err := c.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}

	// render response
	r.JSON(res, 200, p)
}
// UpdateSensor updates a sensor record in the database
func (m *SensorHandler) UpdateSensor(resp http.ResponseWriter, req *http.Request) {
	// bind the request to a sensor model
	sensorUpdates := new(db.Sensor)
	errs := binding.Bind(req, sensorUpdates)
	if errs.Handle(resp) {
		log.Printf("Error while binding request to model: %s", errs.Error())
		http.Error(resp,
			"Invalid request",
			http.StatusBadRequest)
		return
	}

	sensorID := mux.Vars(req)["sensor_id"]
	if _, err := m.database.GetSensor(sensorID); err != nil {
		log.Printf("Error getting sensor for update: %s", err.Error())
		http.Error(resp,
			"Error getting sensor for update",
			http.StatusBadRequest)
		return
	}
	if sensor, err := m.database.UpdateSensor(sensorID, sensorUpdates); err == nil {
		resp.Header().Set("Content-Type", "application/json")
		resp.WriteHeader(http.StatusOK)
		responseEncoder := json.NewEncoder(resp)
		responseEncoder.Encode(sensor)
	} else {
		log.Printf("Error getting sensor: %s", err.Error())
		http.Error(resp,
			"Error getting sensor",
			http.StatusInternalServerError)
	}
}
示例#20
0
// CreateMerchant ... create new merchant
func (mer MerchantController) CreateMerchant(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	merchant := new(models.Merchant)
	errs := binding.Bind(req, merchant)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}

	bindingErr := merchant.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	// save to database

	p := models.Merchant{mer.BaseModel, merchant.Account, merchant.AccountID, merchant.Customer, merchant.CustomerID, merchant.AlternativeID, merchant.Goods}

	err := mer.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}

	// render response
	r.JSON(res, 200, p)
}
示例#21
0
// UserToken returns an HTTP handler to generate a token for a user.
func UserToken(server *app.App) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		userTokenReq := &models.UserTokenRequest{}
		if err := binding.Bind(req, userTokenReq); err.Handle(w) {
			return
		}
		user, err := models.FindUserByEmail(server.DB, userTokenReq.Email)
		if err != nil {
			log.Println(err)
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "error getting user from database"})
			return
		}
		if user.ID == "" {
			server.Render.JSON(w, http.StatusNotFound, map[string]string{"error": "invalid username or password"})
			return
		}
		if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(userTokenReq.Password)); err != nil {
			server.Render.JSON(w, http.StatusNotFound, map[string]string{"error": "invalid username or password"})
			return
		}
		token := jwt.New(jwt.GetSigningMethod("HS256"))
		token.Claims["id"] = user.ID
		tokenString, err := token.SignedString(server.JWTSecret)
		if err != nil {
			log.Println(err)
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "error signing token"})
			return
		}
		server.Render.JSON(w, http.StatusCreated, map[string]string{"token": tokenString})
	}
}
示例#22
0
// CreateAccount ... add new contact to a person
func (acct AccountController) CreateAccount(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	account := new(models.Account)
	errs := binding.Bind(req, account)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	bindingErr := account.Validate(req, errs)
	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	p := models.Account{acct.BaseModel, account.AccountType, account.AccountNo, account.AccountCategoryID, account.AccountFundSource, account.AccountFundSourceID,
		account.AccountLimit, account.AccountLimitID, account.MaxBalance, account.MinBalance, account.CurrentBalance, account.CustomerID, account.Customer}
	//p := models.User{acct.BaseModel, user.Realm, user.Username, user.Password, user.Credential, user.Challenges, user.Email, user.Emailverified, user.Verificationtoken,
	//	user.LogInCummulative, user.FailedAttemptedLogin, uuid.New(), user.PersonID, user.PhoneNum, user.VerifiedPhoneNum}

	err := acct.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}
	// render response
	r.JSON(res, 200, p)
}
示例#23
0
func (rcv *controller) put() []error {
	var errs []error

	// Map html input value to fields
	if fieldsErrs := binding.Bind(rcv.Request, rcv.formUser); fieldsErrs != nil {

		for _, e := range fieldsErrs {
			errs = append(errs, errors.New(e.Message))
		}
		return errs
	}

	// Validate captcha
	if err := captcha.Validate(rcv.Request, rcv.formUser.Certification, rcv.formUser.Human); err != nil {
		return []error{err}
	}

	if err := rcv.updateEmail(); err != nil {
		errs = append(errs, err)
	}

	if err := rcv.updateName(); err != nil {
		errs = append(errs, err)
	}

	return errs
}
func decodeSensorReadingsHTTPRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	message := new(endpoint.MeasurementMessage)
	errs := binding.Bind(r, message)
	if errs != nil {
		return nil, fmt.Errorf("Error while binding request to model: %s", errs.Error())
	}
	message.APIToken = r.Header.Get("X-API-KEY")
	return message, nil
}
示例#25
0
文件: search.go 项目: hobeone/gonab
func searchHandler(rw http.ResponseWriter, r *http.Request) {
	rend := render.New()
	searchrequest := new(searchReq)
	errs := binding.Bind(r, searchrequest)
	if errs.Len() > 0 {
		handleBindingErrors(rw, errs)
		return
	}
	if searchrequest.Limit == 0 {
		searchrequest.Limit = defaultLimit
	}

	dbh := getDB(r)
	var cats []types.Category
	for _, c := range searchrequest.Categories {
		cats = append(cats, types.CategoryFromInt(c))
	}

	releases, err := dbh.SearchReleases(searchrequest.Query, searchrequest.Offset, searchrequest.Limit, cats)
	if err != nil {
		rend.Text(rw, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
		return
	}

	sr := &searchResponse{
		Header:       template.HTML(`<?xml version="1.0" encoding="UTF-8"?>`),
		URL:          r.RequestURI,
		ContactEmail: "*****@*****.**",
		Offset:       searchrequest.Offset,
		Total:        len(releases),
		Image: &rssImage{
			URL:         "http://localhost/foo.jpg",
			Title:       "gonab",
			Link:        "myurl",
			Description: "visit gonab",
		},
	}
	sr.NZBs = make([]NZB, len(releases))
	for i, rel := range releases {
		sr.NZBs[i] = NZB{
			Title:       rel.Name,
			Link:        makeNZBUrl(rel, r),
			Size:        rel.Size,
			Category:    rel.Category.Name,
			Description: rel.Name,
			GUID:        rel.Hash,
			PermaLink:   true,
			Comments:    fmt.Sprintf("https://%s/nzb/details/%s#comments", r.Host, rel.Hash),
			Date:        rel.Posted,
			Group:       rel.Group.Name,
		}
	}

	searchResponseTemplate.Execute(rw, sr)
}
示例#26
0
// UpdateRecord handles a request to update a single record provided the mux parameter id.
func UpdateRecord(server *app.App) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		id := vars["id"]
		record := &models.Record{ID: id}
		if ok, err := server.DB.Exists(record); err != nil || !ok {
			server.Render.JSON(w, http.StatusNotFound, nil)
			return
		}

		updateReq := &models.UpdateRecordRequest{}
		if err := binding.Bind(req, updateReq); err.Handle(w) {
			return
		}

		if err := server.DB.Get(record); err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error getting record from the database"})
			log.Println(err)
			return
		}

		if updateReq.FQDN != record.FQDN {
			existing, err := models.FindRecordByFQDN(server.DB, updateReq.FQDN)
			if err != nil {
				server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the record to the database"})
				log.Println(err)
				return
			}
			if existing.ID != "" {
				server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "fqdn must be unique across the application"})
				return
			}
		}

		if updateReq.Owner.ID != record.ID {
			if ok, err := server.DB.Exists(&models.User{ID: updateReq.Owner.ID}); err != nil || !ok {
				server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "owner does not exist"})
				return
			}
		}

		if err := copier.Copy(record, updateReq); err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error updating the record"})
			return
		}
		record.UpdatedAt = time.Now().Unix()
		if err := server.DB.Save(record); err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error updating the record"})
			log.Println(err)
			return
		}
		server.Render.JSON(w, http.StatusOK, record)
	}
}
示例#27
0
文件: job_valid.go 项目: zbzzbd/beego
func NewJobValidForm(req *http.Request) (*JobValidForm, error) {
	jv := new(JobValidForm)

	//binding
	errs := binding.Bind(req, jv)
	if errs.Len() > 0 {
		return nil, fmt.Errorf("%s", errs.Error())
	}

	//validator
	if err := jv.Valid(); err != nil {
		return nil, err
	}

	return jv, nil
}
示例#28
0
// UpdateRegion ... Update a Region by ID
func (c CommonController) UpdateRegion(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	vars := mux.Vars(req)
	id := vars["id"]

	region := new(models.RegionState)
	errs := binding.Bind(req, region)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	queryDict, _ := c.HTTPUtilDunc.DecodeHTTPBody(req)

	bindingErr := region.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	regionExist := &models.RegionState{}
	//query := tx.Where("id = ?", id).First(regionExist)

	qryparam := map[string]interface{}{"id": id}
	err := c.DataStore.FetchFirstGenericObject(qryparam, regionExist)

	regionExist.UpdatedAt = time.Now()

	if err != nil && err.ErrNo == 1001 {
		r.JSON(res, 404, err.Error())
	} else if err == nil {
		regionExist.Name = region.Name
		regionExist.UpdatedAt = time.Now()
		regionExist.CountryID = region.CountryID
		//UpdateDatabaseObject
		err := c.DataStore.UpdateDatabaseObject(regionExist, queryDict)
		if err != nil {
			panic(err)
		} else {
			r.JSON(res, 200, regionExist)
		}

	} else {
		fmt.Println(err.Error())
		panic(err)
	}
}
示例#29
0
// LoginUser is a route which compares plaintext password sent with POST request with
// hash stored in database. On successful request returns session cookie named "user", which contains
// user's ID encrypted, which is the primary key used in database table.
// When called by API it responds with user struct.
// On frontend call it redirects the client to "/user" page.
func LoginUser(w http.ResponseWriter, r *http.Request) {

	newuser := new(User)
	errs := binding.Bind(r, newuser)
	if errs != nil {
		log.Println(errs)
	}

	switch root(r) {
	case "api":
		user, err := newuser.Login(r)
		if err != nil {
			if err.Error() == "wrong username or password" {
				rend.JSON(w, http.StatusUnauthorized, map[string]interface{}{"error": "Wrong username or password."})
				return
			}
			if err.Error() == "not found" {
				rend.JSON(w, http.StatusUnauthorized, map[string]interface{}{"error": "User with that email does not exist."})
				return
			}
			rend.JSON(w, http.StatusInternalServerError, map[string]interface{}{"error": "Internal server error"})
			return
		}
		SessionSetValue(w, r, "id", user.ID)
		user.Password = ""
		rend.JSON(w, http.StatusOK, user)
		return
	case "user":
		user, err := newuser.Login(r)
		if err != nil {
			if err.Error() == "wrong username or password" {
				rend.HTML(w, http.StatusUnauthorized, "user/login", "Wrong username or password.")
				return
			}
			if err.Error() == "not found" {
				rend.HTML(w, http.StatusUnauthorized, "user/login", "User with that email does not exist.")
				return
			}
			rend.HTML(w, http.StatusInternalServerError, "user/login", "Internal server error. Please try again.")
			return
		}
		SessionSetValue(w, r, "id", user.ID)
		http.Redirect(w, r, "/user", http.StatusFound)
		return
	}
}
示例#30
0
// CreateRecord handles a request to create a new record.
func CreateRecord(server *app.App) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		user := &models.User{}
		user = context.Get(req, "user").(*models.User)
		recordReq := &models.RecordRequest{}
		if err := binding.Bind(req, recordReq); err.Handle(w) {
			return
		}
		if isSameAsListener(server.Config.Proxy.HTTP.Listener, recordReq) {
			server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "Handler Host and Handler Port must not be the same as HTTP Listener"})
			return
		}
		if isSameAsListener(server.Config.Proxy.SSL.Listener, recordReq) {
			server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "Handler Host and Handler Port must not be the same as SSL Listener"})
			return
		}
		existing, err := models.FindRecordByFQDN(server.DB, recordReq.FQDN)
		if err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the record to the database"})
			log.Println(err)
			return
		}
		if existing.ID != "" {
			server.Render.JSON(w, http.StatusBadRequest, map[string]string{"error": "fqdn must be unique across the application"})
			return
		}
		now := time.Now().Unix()
		record := &models.Record{
			CreatedAt: now,
			UpdatedAt: now,
		}
		record.Owner.Email = user.Email
		record.Owner.ID = user.ID
		if err := copier.Copy(record, recordReq); err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the record to the database"})
			return
		}

		if err := server.DB.Save(record); err != nil {
			server.Render.JSON(w, http.StatusInternalServerError, map[string]string{"error": "there was an error saving the record to the database"})
			return
		}

		server.Render.JSON(w, http.StatusCreated, record)
	}
}