Exemplo n.º 1
0
func getTicket(db *mgo.Database, boardIDHex, ticketIDHex string) (
	*models.Ticket, *APIError,
) {
	if !bson.IsObjectIdHex(boardIDHex) || !bson.IsObjectIdHex(ticketIDHex) {
		return nil, &APIError{
			"Both 'board_id' and 'ticket_id' must be a valid 'ObjectIDs'",
			http.StatusBadRequest}
	}

	var (
		ticket      = models.Ticket{}
		ticketQuery = db.C("tickets").Find(bson.M{
			"_id":      bson.ObjectIdHex(ticketIDHex),
			"board_id": bson.ObjectIdHex(boardIDHex),
		})
	)

	if err := ticketQuery.One(&ticket); err != nil {
		if err == mgo.ErrNotFound {
			return nil, &APIError{"Ticket not found", http.StatusNotFound}
		}
		return nil, &APIError{err.Error(), http.StatusInternalServerError}
	}

	return &ticket, nil
}
Exemplo n.º 2
0
// DeleteSubmission deletes a submission as well as updating a form's stats.
func DeleteSubmission(context interface{}, db *db.DB, id, formID string) error {
	log.Dev(context, "DeleteSubmission", "Started : Submission[%s]", id)

	if !bson.IsObjectIdHex(id) {
		log.Error(context, "DeleteSubmission", ErrInvalidID, "Completed")
		return ErrInvalidID
	}

	if !bson.IsObjectIdHex(formID) {
		log.Error(context, "Delete", ErrInvalidID, "Completed")
		return ErrInvalidID
	}

	if err := submission.Delete(context, db, id); err != nil {
		log.Error(context, "DeleteSubmission", err, "Completed")
		return err
	}

	if _, err := form.UpdateStats(context, db, formID); err != nil {
		log.Error(context, "DeleteSubmission", err, "Completed")
		return err
	}

	log.Dev(context, "DeleteSubmission", "Started")
	return nil
}
Exemplo n.º 3
0
func SavePerson(p *Person) {
	c := getCollection()

	log.Printf("Saving person: %s", p.Id.Hex())

	log.Printf("Person has valid objectid: %s", bson.IsObjectIdHex(p.Id.Hex()))

	// Does the object exist?
	if !bson.IsObjectIdHex(p.Id.Hex()) {
		p.Id = bson.NewObjectId()
		err := c.Insert(p)

		log.Printf("Inserted person: %v", p.Id)
		if err != nil {
			log.Panic("Error whilst inserting person: %v", err)
		}
	} else {
		err := c.UpdateId(p.Id, p)

		log.Printf("Saved person: %v", p.Id)
		if err != nil {
			log.Panic("Error whilst updating person: %v", err)
		}
	}
}
Exemplo n.º 4
0
// 是否是我的文件
func (this *FileService) IsMyFile(userId, fileId string) bool {
	// 如果有问题会panic
	if !bson.IsObjectIdHex(fileId) || !bson.IsObjectIdHex(userId) {
		return false
	}
	return db.Has(db.Files, bson.M{"UserId": bson.ObjectIdHex(userId), "_id": bson.ObjectIdHex(fileId)})
}
Exemplo n.º 5
0
// DelAdmin removes a member from an existing group
func DelAdmin(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Get group id and convert from string to objectId
	rawMID := c.Param("mid")
	if !bson.IsObjectIdHex(rawMID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	memberID := bson.ObjectIdHex(rawMID)

	// Get group id and convert from string to objectId
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	groupID := bson.ObjectIdHex(rawGID)
	err := mangos.Update(constants.CGroups, bson.M{
		"$and": []bson.M{
			bson.M{"_id": groupID},
			bson.M{"admins": digitsID},
		},
	}, bson.M{"$pull": bson.M{"admins": memberID}})
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok("deleted admin")
}
Exemplo n.º 6
0
func (loccontroller Controller) Plan(writer http.ResponseWriter, request *http.Request, param httprouter.Params) {
	
	var detail RoutePlan

	arr := make([]Cordnts, 0)
	var map1 map[string]Cordnts
	map1 = make(map[string]Cordnts)

	json.NewDecoder(request.Body).Decode(&detail)
	if !bson.IsObjectIdHex(detail.Strt_locid) {
		writer.WriteHeader(400)
		return
	}
	strtpt = detail.Strt_locid
	strtid := bson.ObjectIdHex(detail.Strt_locid)
	if err := loccontroller.session.DB("jaspalgill").C("locations").FindId(strtid).One(&intLoc); err != nil {
		writer.WriteHeader(400)
		return
	}
	var bstroute BestRoute
	iniCordnts.Latitude = intLoc.Coordinate.Latitude
	iniCordnts.Longitude = intLoc.Coordinate.Longitude
	for l := 0; l < len(detail.Loc_id); l++ {
		id := detail.Loc_id[l]
		if !bson.IsObjectIdHex(id) {
			writer.WriteHeader(400)
			return
		} else {
			nid := bson.ObjectIdHex(id)
			var locatn Loc
			if err := loccontroller.session.DB("jaspalgill").C("locations").FindId(nid).One(&locatn); err != nil {
				writer.WriteHeader(400)
				return
			} else {
				var cordnt Cordnts
				cordnt.Latitude = locatn.Coordinate.Latitude
				cordnt.Longitude = locatn.Coordinate.Longitude
				map1[detail.Loc_id[l]] = cordnt
				arr = append(arr, cordnt)
			}
		}
	}
	Loop(iniCordnts, arr, map1)

	bstroute.id = bson.NewObjectId()
	bstroute.stats = "planning"
	bstroute.totldst = totldst
	bstroute.total_cost = totlcost
	bstroute.total_dur = totldur
	bstroute.Strt_locid = strtpt
	bstroute.bstroute_locid = bstRout
	loccontroller.session.DB("jaspalgill").C("cmpe273").Insert(bstroute)
	
	jsn, _ := json.Marshal(bstroute)

	writer.Header().Set("Content-Type", "application/json")
	writer.WriteHeader(200)
	fmt.Fprintf(writer, "%sess", jsn)
}
/*
 * Handle all inbound websocket messages. This is where all payments and purchases
 * are given to the back-end, to be processed appropriately. There is no need for
 * this handle function to return a value to the webserver, because the webserver
 * rebroadcasts incoming feed items on its own, automatically. Just return an error
 * if the webserver should not be rebroadcasting: e.g. if an invalid purchase is made.
 *
 * This function is passed in a userId, which it uses to fill in the FeedItem, if
 * necessary. It then returns a new, filled-in feeditem.
 */
func HandleFeedItem(fi *FeedItem, userId string) (*FeedItem, error) {
	if !bson.IsObjectIdHex(fi.GroupID) || !bson.IsObjectIdHex(userId) {
		return nil, errors.New(invalidBsonIdHexErrorMessage)
	}
	switch fi.Type {
	case FeedItemTypeComment:
		comment := &Comment{}
		err := json.Unmarshal(fi.Content, comment)
		if err != nil {
			return nil, err
		}
		comment.UserID = userId
		return InsertAsFeedItem(FeedItemContent(comment), fi.GroupID)
	case FeedItemTypeNotification:
		notification := &Notification{}
		err := json.Unmarshal(fi.Content, notification)
		if err != nil {
			return nil, err
		}
		return InsertAsFeedItem(FeedItemContent(notification), fi.GroupID)
	case FeedItemTypePayment:
		payment := &Payment{}
		err := json.Unmarshal(fi.Content, payment)
		if err != nil {
			return nil, err
		}
		payment.UserId = userId
		group, err := FindGroup(bson.ObjectIdHex(fi.GroupID))
		if err != nil {
			return nil, err
		}
		err = PayMember(group, payment.PayerID, payment.PayeeID, payment.AmountInCents)
		if err != nil {
			return nil, err
		}
		return InsertAsFeedItem(FeedItemContent(payment), fi.GroupID)
	case FeedItemTypePurchase:
		purchase := &Purchase{}
		err := json.Unmarshal(fi.Content, purchase)
		if err != nil {
			return nil, err
		}
		purchase.UserId = userId
		group, err := FindGroup(bson.ObjectIdHex(fi.GroupID))
		if err != nil {
			return nil, err
		}
		err = DoPurchase(group, purchase.PayerID,
			purchase.AmountInCents, purchase.Expected)
		if err != nil {
			return nil, err
		}
		return InsertAsFeedItem(FeedItemContent(purchase), fi.GroupID)
	default:
		return nil, errors.New(fmt.Sprint("invalid FeedItem type: ", fi.Type))
	}
}
Exemplo n.º 8
0
// This function check if the real type behind the interface value is the one wished by the validators
func checkType(validator *Validator, valueToTest interface{}, errors *[]*DataError) bool {
	kind := reflect.ValueOf(valueToTest).Kind()
	switch kind {
	case reflect.Slice:
		array := validator.Type[0:2] // indeed, the type representation string begins with []
		_type := validator.Type[2:]  // here we have the type after []
		if array != "[]" {
			*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: reflect.TypeOf(valueToTest).String()})
			return false
		} else {
			for _, value := range valueToTest.([]interface{}) {
				vtype := reflect.TypeOf(value).String()
				if vtype != _type {
					// _type can be bson.ObjectId... which is basicly a string. So the condition above may fail but the type is in fact correct. Let's check:
					if stringValue, ok := value.(string); ok && _type == "bson.ObjectId" && bson.IsObjectIdHex(stringValue) {
						return true
					} else {
						*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: "[] contains " + reflect.TypeOf(value).String()})
						return false
					}
				}
			}
		}
	case reflect.Map:
		// json maps are map[string]interface{}, but we could test for more...
		parts := strings.SplitAfter(validator.Type, "]")
		for key, value := range valueToTest.(map[string]interface{}) {
			vtype := reflect.TypeOf(value)

			// such as is the string key a correct ObjectId ?
			if parts[0] == "map[bson.ObjectId]" {
				if !bson.IsObjectIdHex(key) {
					*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: "one of the indexes at least is not valid ObjectId: " + key})
					return false
				}
			}

			// or test the real value behind interface{}
			if vtype.String() != parts[1] {
				*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: "one of the map values is of type: " + vtype.String()})
				return false
			}
		}
	default:
		if _type := reflect.TypeOf(valueToTest); _type != nil && _type.String() != validator.Type {
			// bson.ObjectId is match as a string, let's try to save them off the error pireflect.TypeOf(valueToTest)reflect.TypeOf(valueToTest)t
			if _type.String() == "string" && bson.IsObjectIdHex(valueToTest.(string)) && validator.Type == "bson.ObjectId" {
				return true
			} else {
				// ok, let'em fall
				*errors = append(*errors, &DataError{Type: "Validation error", Reason: "Type mismatch", Field: validator.Field, Value: _type.String()})
				return false
			}
		}
	}
	return true
}
Exemplo n.º 9
0
// Find token with credential
func (d *DefaultMongoStore) queryTokenWithCredential(table string, clientID string, userID string) Token {
	/* Condition validation */
	if len(clientID) == 0 || len(userID) == 0 || !bson.IsObjectIdHex(clientID) || !bson.IsObjectIdHex(userID) {
		return nil
	}

	token := new(DefaultToken)
	if err := mongo.EntityWithCriteria(table, bson.M{"user_id": bson.ObjectIdHex(userID), "client_id": bson.ObjectIdHex(clientID)}, token); err != nil {
		return nil
	}
	return token
}
Exemplo n.º 10
0
func DeleteAddress(w http.ResponseWriter, req *http.Request, params martini.Params, enc encoding.Encoder, shop *cart.Shop) string {

	var c cart.Customer

	customerId := params["id"]
	if !bson.IsObjectIdHex(customerId) {
		apierror.GenerateError("invalid customer reference", nil, w, req)
		return ""
	}

	c.Id = bson.ObjectIdHex(customerId)
	c.ShopId = shop.Id
	if err := c.Get(); err != nil {
		apierror.GenerateError("", err, w, req)
		return ""
	}

	addressId := params["address"]
	if !bson.IsObjectIdHex(addressId) {
		apierror.GenerateError("invalid address reference", nil, w, req)
		return ""
	}

	// Make sure this isn't the default address
	if c.DefaultAddress != nil && c.DefaultAddress.Id.Hex() == addressId {
		apierror.GenerateError("removing a default address is not allowed", nil, w, req)
		return ""
	}

	found := false
	for i, addr := range c.Addresses {
		if addr.Id.Hex() == addressId {
			c.Addresses = append(c.Addresses[:i], c.Addresses[i+1:]...)
			found = true
			break
		}
	}

	if !found {
		apierror.GenerateError("invalid address reference", nil, w, req)
		return ""
	}

	if err := c.Update(); err != nil {
		apierror.GenerateError(err.Error(), err, w, req)
		return ""
	}

	return ""
}
Exemplo n.º 11
0
// RemoveAnswer adds an answer to a form gallery. Duplicated answers
// are de-duplicated automatically and will not return an error.
func RemoveAnswer(context interface{}, db *db.DB, id, submissionID, answerID string) (*Gallery, error) {
	log.Dev(context, "RemoveAnswer", "Started : Gallery[%s]", id)

	if !bson.IsObjectIdHex(id) {
		log.Error(context, "RemoveAnswer", ErrInvalidID, "Completed")
		return nil, ErrInvalidID
	}

	if !bson.IsObjectIdHex(submissionID) {
		log.Error(context, "RemoveAnswer", ErrInvalidID, "Completed")
		return nil, ErrInvalidID
	}

	objectID := bson.ObjectIdHex(id)

	answer := Answer{
		SubmissionID: bson.ObjectIdHex(submissionID),
		AnswerID:     answerID,
	}

	if err := answer.Validate(); err != nil {
		log.Error(context, "RemoveAnswer", err, "Completed")
		return nil, err
	}

	f := func(c *mgo.Collection) error {
		u := bson.M{
			"$pull": bson.M{
				"answers": answer,
			},
		}
		log.Dev(context, "RemoveAnswer", "MGO : db.%s.update(%s, %s)", c.Name, mongo.Query(objectID), mongo.Query(u))
		return c.UpdateId(objectID, u)
	}

	if err := db.ExecuteMGO(context, Collection, f); err != nil {
		log.Error(context, "RemoveAnswer", err, "Completed")
		return nil, err
	}

	gallery, err := Retrieve(context, db, id)
	if err != nil {
		log.Error(context, "RemoveAnswer", err, "Completed")
		return nil, err
	}

	log.Dev(context, "RemoveAnswer", "Completed")
	return gallery, nil
}
Exemplo n.º 12
0
func (uc UserController) GetUser(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
	// Grab id
	id := p.ByName("location_id")

	// Verify id is ObjectId, otherwise bail
	if !bson.IsObjectIdHex(id) {
		rw.WriteHeader(404)
		return
	}

	// Grab id
	oid := bson.ObjectIdHex(id)

	// Stub user
	u := UserLocation{}
	// Fetch user
	if err := uc.session.DB("mongodatabase").C("CMPE273").FindId(oid).One(&u); err != nil {
		rw.WriteHeader(404)
		return
	}

	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(u)

	// Write content-type, statuscode, payload
	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(200)
	fmt.Fprintf(rw, "%s", uj)
}
Exemplo n.º 13
0
func (c *InterfaceController) Delete(w http.ResponseWriter, r *http.Request) {
	// Get ID
	id := mux.Vars(r)["id"]

	// Validate ObjectId
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Get object id
	oid := bson.ObjectIdHex(id)

	// Initialize empty struct
	s := models.Interface{}

	// Get entry
	if err := c.session.DB(c.database).C("interfaces").FindId(oid).One(&s); err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Remove entry
	if err := c.session.DB(c.database).C("interfaces").RemoveId(oid); err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Write status
	jsonWriter(w, r, s, http.StatusOK, c.envelope)
}
Exemplo n.º 14
0
// URL: /p/{packageId}
// 显示第三方包详情
func showPackageHandler(handler *Handler) {
	vars := mux.Vars(handler.Request)

	packageId := vars["packageId"]

	if !bson.IsObjectIdHex(packageId) {
		http.NotFound(handler.ResponseWriter, handler.Request)
		return
	}

	c := handler.DB.C(CONTENTS)

	package_ := Package{}
	err := c.Find(bson.M{"_id": bson.ObjectIdHex(packageId), "content.type": TypePackage}).One(&package_)

	if err != nil {
		message(handler, "没找到该包", "请检查链接是否正确", "error")
		fmt.Println("showPackageHandler:", err.Error())
		return
	}

	var categories []PackageCategory

	c = handler.DB.C(PACKAGE_CATEGORIES)
	c.Find(nil).All(&categories)

	handler.renderTemplate("package/show.html", BASE, map[string]interface{}{
		"package":    package_,
		"categories": categories,
		"active":     "package",
	})
}
Exemplo n.º 15
0
func (uc UserController) UpdateLocations(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	id := p.ByName("id")

	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(404)
		return
	}

	oid := bson.ObjectIdHex(id)
	l := structure.Location{}
	json.NewDecoder(r.Body).Decode(&l)
	str := getURL(l.Address, l.City, l.State)
	getLocation(&l, str)
	l.Id = oid
	if err := uc.session.DB("cmpe273_project").C("hello").Update(bson.M{"_id": l.Id}, bson.M{"$set": bson.M{"address": l.Address, "city": l.City, "state": l.State, "zip": l.Zip, "coordinate.lat": l.Coordinate.Lat, "coordinate.lng": l.Coordinate.Lng}}); err != nil {
		w.WriteHeader(404)
		return
	}
	if err := uc.session.DB("cmpe273_project").C("hello").FindId(oid).One(&l); err != nil {
		w.WriteHeader(404)
		return
	}
	lj, _ := json.Marshal(l)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(201)
	fmt.Fprintf(w, "%s", lj)
}
Exemplo n.º 16
0
func (c *appContext) unlockHandler(w http.ResponseWriter, r *http.Request) {

	p := r.URL.Path
	selector := p[8:]
	fmt.Println(p)
	fmt.Println(selector)

	//verify selector is ObjectId, otherwise bail
	if !bson.IsObjectIdHex(selector) {
		fmt.Println("selector is not valid bson ObjectId hex")
		w.WriteHeader(404)
		return
	}
	oid := bson.ObjectIdHex(selector)
	//todo: make more improved~!!!!
	info := Submitter{} //stub
	s := c.db.Copy()
	defer s.Close()
	err := s.DB("db-init-2").C("submitter").FindId(oid).One(&info);
	if err != nil {
		w.WriteHeader(404)
		return
	}
	w.Header().Set("Content-Type", "text")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", "path=\n")
	fmt.Fprintf(w, "%s", selector)
	fmt.Fprintf(w, "%s", info)
	return
}
//Update an already existing address
func (uc LocationController) UpdateLocation(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	var i InputAddress
	var o OutputAddress
	id := p.ByName("location_id")
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(404)
		return
	}
	oid := bson.ObjectIdHex(id)
	if err := uc.session.DB("mongolocations").C("locations").FindId(oid).One(&o); err != nil {
		w.WriteHeader(404)
		return
	}
	json.NewDecoder(r.Body).Decode(&i)
	googResCoor := getGoogleCoordinates(i.Address + "+" + i.City + "+" + i.State + "+" + i.Zip)
	fmt.Println("resp is: ", googResCoor.Coordinate.Lat, googResCoor.Coordinate.Lang)
	o.Address = i.Address
	o.City = i.City
	o.State = i.State
	o.Zip = i.Zip
	o.Coordinate.Lat = googResCoor.Coordinate.Lat
	o.Coordinate.Lang = googResCoor.Coordinate.Lang
	c := uc.session.DB("mongolocations").C("locations")
	id2 := bson.M{"_id": oid}
	err := c.Update(id2, o)
	if err != nil {
		panic(err)
	}
	uj, _ := json.Marshal(o)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(201)
	fmt.Fprintf(w, "%s", uj)
}
Exemplo n.º 18
0
// 更新笔记, api
func (this *NotebookService) UpdateNotebookApi(userId, notebookId, title, parentNotebookId string, seq, usn int) (bool, string, info.Notebook) {
	if notebookId == "" {
		return false, "notebookIdNotExists", info.Notebook{}
	}

	// 先判断usn是否和数据库的一样, 如果不一样, 则冲突, 不保存
	notebook := this.GetNotebookById(notebookId)
	// 不存在
	if notebook.NotebookId == "" {
		return false, "notExists", notebook
	} else if notebook.Usn != usn {
		return false, "conflict", notebook
	}
	notebook.Usn = userService.IncrUsn(userId)
	notebook.Title = title

	updates := bson.M{"Title": title, "Usn": notebook.Usn, "Seq": seq, "UpdatedTime": time.Now()}
	if parentNotebookId != "" && bson.IsObjectIdHex(parentNotebookId) {
		updates["ParentNotebookId"] = bson.ObjectIdHex(parentNotebookId)
	} else {
		updates["ParentNotebookId"] = ""
	}
	ok := db.UpdateByIdAndUserIdMap(db.Notebooks, notebookId, userId, updates)
	if ok {
		return ok, "", this.GetNotebookById(notebookId)
	}
	return false, "", notebook
}
Exemplo n.º 19
0
// RemoveFlag removes a flag from a given Submission in
// the MongoDB database collection.
func RemoveFlag(context interface{}, db *db.DB, id, flag string) (*Submission, error) {
	log.Dev(context, "RemoveFlag", "Started : Submission[%s]", id)

	if !bson.IsObjectIdHex(id) {
		log.Error(context, "RemoveFlag", ErrInvalidID, "Completed")
		return nil, ErrInvalidID
	}

	objectID := bson.ObjectIdHex(id)

	f := func(c *mgo.Collection) error {
		u := bson.M{
			"$pull": bson.M{
				"flags": flag,
			},
		}
		log.Dev(context, "RemoveFlag", "MGO : db.%s.update(%s, %s)", c.Name, mongo.Query(objectID), mongo.Query(u))
		return c.UpdateId(objectID, u)
	}

	if err := db.ExecuteMGO(context, Collection, f); err != nil {
		log.Error(context, "RemoveFlag", err, "Completed")
		return nil, err
	}

	submission, err := Retrieve(context, db, id)
	if err != nil {
		log.Error(context, "RemoveFlag", err, "Completed")
		return nil, err
	}

	log.Dev(context, "RemoveFlag", "Completed")
	return submission, nil
}
Exemplo n.º 20
0
// UpdateStatus updates a form submissions status inside the MongoDB database
// collection.
func UpdateStatus(context interface{}, db *db.DB, id, status string) (*Submission, error) {
	log.Dev(context, "UpdateStatus", "Started : Submission[%s]", id)

	if !bson.IsObjectIdHex(id) {
		log.Error(context, "UpdateStatus", ErrInvalidID, "Completed")
		return nil, ErrInvalidID
	}

	objectID := bson.ObjectIdHex(id)

	f := func(c *mgo.Collection) error {
		u := bson.M{
			"$set": bson.M{
				"status":       status,
				"date_updated": time.Now(),
			},
		}
		log.Dev(context, "UpdateStatus", "MGO : db.%s.update(%s, %s)", c.Name, mongo.Query(objectID), mongo.Query(u))
		return c.UpdateId(objectID, u)
	}

	if err := db.ExecuteMGO(context, Collection, f); err != nil {
		log.Error(context, "UpdateStatus", err, "Completed")
		return nil, err
	}

	submission, err := Retrieve(context, db, id)
	if err != nil {
		log.Error(context, "UpdateStatus", err, "Completed")
		return nil, err
	}

	log.Dev(context, "UpdateStatus", "Completed")
	return submission, nil
}
Exemplo n.º 21
0
// Create adds a new Submission based on a given Form into
// the MongoDB database collection.
func Create(context interface{}, db *db.DB, formID string, submission *Submission) error {
	log.Dev(context, "Create", "Started : Form[%s]", formID)

	if !bson.IsObjectIdHex(formID) {
		log.Error(context, "Create", ErrInvalidID, "Completed")
		return ErrInvalidID
	}

	if err := submission.Validate(); err != nil {
		return err
	}

	// FIXME: handle Number field maybe with https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/ to resolve race condition
	count, err := Count(context, db, formID)
	if err != nil {
		log.Error(context, "Create", err, "Completed")
		return err
	}

	submission.Number = count + 1

	f := func(c *mgo.Collection) error {
		log.Dev(context, "Create", "MGO : db.%s.insert(%s)", c.Name, mongo.Query(submission))
		return c.Insert(submission)
	}

	if err := db.ExecuteMGO(context, Collection, f); err != nil {
		log.Error(context, "Create", err, "Completed")
		return err
	}

	log.Dev(context, "Create", "Completed")
	return nil
}
Exemplo n.º 22
0
// Update patches a group in database
func Update(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Bind request body to a group update
	var group models.GroupUpdate
	err := c.Bind(&group)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Get group id and convert from string to objectId
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// Update the object, only if its a admin
	groupID := bson.ObjectIdHex(rawGID)
	err = mangos.Update(constants.CGroups, bson.M{
		"$and": []bson.M{
			bson.M{"_id": groupID},
			bson.M{"admins": digitsID},
		},
	}, bson.M{"$set": group})
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(group)
}
Exemplo n.º 23
0
// RetrieveMany retrieves a list of Submission's from the MongoDB database collection.
func RetrieveMany(context interface{}, db *db.DB, ids []string) ([]Submission, error) {
	log.Dev(context, "RetrieveMany", "Started")

	var objectIDs = make([]bson.ObjectId, len(ids))

	for i, id := range ids {
		if !bson.IsObjectIdHex(id) {
			log.Error(context, "RetrieveMany", ErrInvalidID, "Completed")
			return nil, ErrInvalidID
		}

		objectIDs[i] = bson.ObjectIdHex(id)
	}

	var submissions []Submission
	f := func(c *mgo.Collection) error {
		q := bson.M{
			"_id": bson.M{
				"$in": objectIDs,
			},
		}
		log.Dev(context, "RetrieveMany", "MGO : db.%s.find(%s)", c.Name, mongo.Query(q))
		return c.Find(q).All(&submissions)
	}

	if err := db.ExecuteMGO(context, Collection, f); err != nil {
		log.Error(context, "RetrieveMany", err, "Completed")
		return nil, err
	}

	log.Dev(context, "RetrieveMany", "Started")
	return submissions, nil
}
Exemplo n.º 24
0
// Retrieve writes the requested group from database
func Retrieve(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Get group id and convert it from string to objectid
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	groupID := bson.ObjectIdHex(rawGID)
	var group models.Group
	err := mangos.FindOne(constants.CGroups, bson.M{"_id": groupID}, &group)
	if err != nil {
		return msg.InternalError(err)
	}

	// check if user is member (is not part of the query because we need to light bson query)
	for _, member := range group.Members {
		if member == digitsID {
			return msg.Ok(group)
		}
	}

	return msg.Forbidden("you must be part of the group")
}
Exemplo n.º 25
0
// Count returns the count of current submissions for a given
// form id in the Form Submissions MongoDB database collection.
func Count(context interface{}, db *db.DB, formID string) (int, error) {
	log.Dev(context, "Count", "Completed : Form[%s]", formID)

	if !bson.IsObjectIdHex(formID) {
		log.Error(context, "Count", ErrInvalidID, "Completed")
		return 0, ErrInvalidID
	}

	formObjectID := bson.ObjectIdHex(formID)

	var count int
	f := func(c *mgo.Collection) error {
		var err error

		q := bson.M{
			"form_id": formObjectID,
		}
		log.Dev(context, "Count", "MGO : db.%s.find(%s).count()", c.Name, mongo.Query(q))
		count, err = c.Find(q).Count()
		return err
	}

	if err := db.ExecuteMGO(context, Collection, f); err != nil {
		log.Error(context, "Count", err, "Completed")
		return 0, err
	}

	log.Dev(context, "Count", "Completed")
	return count, nil
}
func getLoc(w http.ResponseWriter, r *http.Request, p httprouter.Params) {

	uc := NewUserController(getSession())
	id := p.ByName("id")

	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(404)
		return
	}

	oid := bson.ObjectIdHex(id)

	v := Reply{}

	if err := uc.session.DB("cmpe273").C("users").FindId(oid).One(&v); err != nil {
		w.WriteHeader(404)
		return
	}

	uj, _ := json.Marshal(v)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", uj)

}
Exemplo n.º 27
0
// GetUser retrieves an individual user resource
func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// Get the user's id from the parameters
	id := p.ByName("id")

	// Check to ensure that this is a BSON object
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(404)
		return
	}

	// Grab the object's id
	oid := bson.ObjectIdHex(id)

	// Stub an example user
	u := models.User{}

	// Fetch the user data
	if err := uc.session.DB("go-deploy").C("users").FindId(oid).One(&u); err != nil {
		w.WriteHeader(404)
		return
	}

	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(u)

	// Write content-type, statuscode, payload
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", uj)
}
Exemplo n.º 28
0
func GetUserById(w http.ResponseWriter, r *http.Request) {
	fmt.Println("------------------ GetUserById ------------------")

	vars := mux.Vars(r)
	if bson.IsObjectIdHex(vars["id"]) {

		id := bson.ObjectIdHex(vars["id"])

		result := model.User{}

		result = data.FindOneBy(bson.M{"_id": id})

		j, err := json.Marshal(result)

		if err != nil {
			log.Fatal(err)
		}

		fmt.Fprintf(w, string(j))
	} else {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

}
Exemplo n.º 29
0
// GetUser retrieves an individual user resource
func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// Grab id
	id := p.ByName("id")

	// Verify id is ObjectId, otherwise bail
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(404)
		return
	}

	// Grab id
	oid := bson.ObjectIdHex(id)

	// Stub user
	u := models.User{}

	// Fetch user
	if err := uc.session.DB("go_rest_tutorial").C("users").FindId(oid).One(&u); err != nil {
		w.WriteHeader(404)
		return
	}

	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(u)

	// Write content-type, statuscode, payload
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", uj)
}
Exemplo n.º 30
0
func NewContext(req *http.Request) (*Context, error) {
	vars := mux.Vars(req)
	sess, err := sessionStore.Get(req, "gsmtpd")
	ctx := &Context{
		Vars:      vars,
		Session:   sess,
		DataStore: DataStore,
		ClientIp:  parseRemoteAddr(req),
		IsJson:    headerMatch(req, "Accept", "application/json"),
		Ds:        DataStore.Storage.(*data.MongoDB),
	}

	if err != nil {
		return ctx, err
	}

	//try to fill in the user from the session
	if user, ok := sess.Values["user"].(string); ok {
		if bson.IsObjectIdHex(user) {
			uid := bson.ObjectIdHex(user)
			err := ctx.Ds.Users.Find(bson.M{"_id": uid}).One(&ctx.User)

			if err != nil {
				ctx.User = nil
				return ctx, nil
			}
		} else {
			ctx.User = nil
		}
	}

	return ctx, err
}