Пример #1
0
//setting token for login user
func SetToken(id bson.ObjectId, token string) {
	model.UserC.Do(func(c *mgo.Collection) {
		if err := c.UpdateId(id, bson.M{"$set": bson.M{"token": token}}); err != nil {
			model.ErrorLog(model.UserC, err, id.Hex()+";"+token)
		}
	})
}
Пример #2
0
func (rc *ResourceController) UpdateHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {

	var id bson.ObjectId

	idString := mux.Vars(r)["id"]
	if bson.IsObjectIdHex(idString) {
		id = bson.ObjectIdHex(idString)
	} else {
		http.Error(rw, "Invalid id", http.StatusBadRequest)
	}

	decoder := json.NewDecoder(r.Body)
	resource := models.NewStructForResourceName(rc.Name)
	err := decoder.Decode(resource)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
	}

	c := Database.C(models.PluralizeLowerResourceName(rc.Name))
	reflect.ValueOf(resource).Elem().FieldByName("Id").SetString(id.Hex())
	err = c.Update(bson.M{"_id": id.Hex()}, resource)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
	}

	context.Set(r, rc.Name, resource)
	context.Set(r, "Resource", rc.Name)
	context.Set(r, "Action", "update")

	rw.Header().Set("Content-Type", "application/json; charset=utf-8")
	rw.Header().Set("Access-Control-Allow-Origin", "*")
	json.NewEncoder(rw).Encode(resource)
}
Пример #3
0
/* 查询某用户的文章总数 */
func (this *Article) FindUserArticleCount(id bson.ObjectId) int {
	var count int
	AutoCache("article-FindUserArticleCount"+id.Hex(), &count, 60, func() {
		count, _ = articleC.Find(bson.M{"u": id}).Count()
	})
	return count
}
Пример #4
0
func findTriggerForApplicationIdAndEvent(application_id_bson bson.ObjectId, event string) Trigger {
	application_id := application_id_bson.Hex()

	key := application_id + ".triggers." + event
	result := Trigger{}

	cache_result, err := cache.Get(key)

	if err {
		query := bson.M{"event": event, "type": "trigger"}

		collection := application_id
		collection += "_triggers"

		database.FindBy(collection, &result, query)

		b, _ := json.Marshal(result)
		cache.Set(key, string(b), 5*time.Minute)
	} else if cache_result.CachedItem == nil {
		json.Unmarshal([]byte(cache_result.Value.(string)), &result)
		cache_result.CachedItem = result
	} else {
		result = cache_result.CachedItem.(Trigger)
	}
	return result
}
Пример #5
0
func deleteDocument(i *ec2.Instance, db *mongodb.MongoDB) error {
	if i == nil {
		return errors.New("nil instance")
	}

	var id bson.ObjectId

	for _, tag := range i.Tags {
		key := strings.ToLower(aws.StringValue(tag.Key))
		value := strings.ToLower(aws.StringValue(tag.Value))

		if key != "koding-machineid" || value == "" {
			continue
		}

		id = bson.ObjectIdHex(value)
		break
	}

	if !id.Valid() {
		return errors.New("unable to find valid jMachine.ObjectId")
	}

	return db.Run(modelhelper.MachinesColl, func(c *mgo.Collection) error { return c.RemoveId(id) })
}
Пример #6
0
func FindPaymentByPayeeIdAndPayerId(payeeid bson.ObjectId, payerid bson.ObjectId) (Payment, error) {
	var err error
	Col = Session.DB("test").C("Payment")
	payment := Payment{}
	err = Col.Find(bson.M{"payeeid": payeeid.Hex(), "payerid": payerid.Hex()}).One(&payment)
	return payment, err
}
Пример #7
0
func getInfo(t string, viewId *bson.ObjectId, ad *models.Ad, r *http.Request) *adInfo {
	scheme := r.URL.Scheme
	if scheme == "" {
		scheme = "http"
	}

	actionURL := fmt.Sprintf("%v://%v/ads/click/%v", scheme, r.Host, viewId.Hex())

	switch t {
	case feed:
		return &adInfo{
			ActionURL:   actionURL,
			BannerURL:   ad.FeedBannerURL,
			Description: ad.FeedDescription,
		}

	case fullscreen:
		return &adInfo{
			ActionURL:   actionURL,
			BannerURL:   ad.FullscreenBannerURL,
			Description: ad.FullscreenDescription,
		}
	}

	return nil
}
Пример #8
0
////////////////////////////////////////////////////////
//          GROUP FUNCTIONS           //
////////////////////////////////////////////////////////
func AddGroup(groupName string, uid bson.ObjectId) (bson.ObjectId, error) {
	var err error
	Col = Session.DB("test").C("Group")
	id := bson.NewObjectId()
	err = Col.Insert(&Group{ID: id, GroupName: groupName, UserIDs: []string{uid.Hex()}, Expected: []int{0}, Actual: []int{0}, Feed: []FeedItem{}})
	AddGroupToUser(uid, id)
	return id, err
}
Пример #9
0
func AddGroupToUser(userId bson.ObjectId, groupId bson.ObjectId) error {
	var err error
	Col = Session.DB("test").C("User")
	query := bson.M{"_id": bson.ObjectId(userId)}
	change := bson.M{"$push": bson.M{"groups": groupId.Hex()}}
	err = Col.Update(query, change)
	return err
}
Пример #10
0
func (u User) BackIndex(backedProject bson.ObjectId) int {
	for i, backed := range u.BackedProjects {
		if backed.Project.Hex() == backedProject.Hex() {
			return i
		}
	}
	return -1
}
Пример #11
0
func (u User) DidBack(backedProject bson.ObjectId) bool {
	for _, backed := range u.BackedProjects {
		if backed.Project.Hex() == backedProject.Hex() {
			return true
		}
	}
	return false
}
Пример #12
0
// 添加共享d笔记
func (this *NoteService) AddSharedNote(note info.Note, myUserId bson.ObjectId) info.Note {
	// 判断我是否有权限添加
	if shareService.HasUpdateNotebookPerm(note.UserId.Hex(), myUserId.Hex(), note.NotebookId.Hex()) {
		note.CreatedUserId = myUserId // 是我给共享我的人创建的
		return this.AddNote(note, false)
	}
	return info.Note{}
}
Пример #13
0
//删除权限信息
func RoleDelete(id bson.ObjectId) error {
	_, err := CloneDB().C(RolePermiColl).RemoveAll(bson.M{"roleid": id.Hex()})
	if err != nil {
		return err
	}
	err = CloneDB().C(RoleColl).Remove(bson.M{"_id": id})
	return err
}
Пример #14
0
func FindFeedItemByGroupId(groupid bson.ObjectId) ([]FeedItem, error) {
	var err error
	Col = Session.DB("test").C("FeedItem")
	feedItem := []FeedItem{}
	// Find way to order by date...?
	err = Col.Find(bson.M{"groupid": groupid.Hex()}).Sort("-timestamp").All(&feedItem)
	return feedItem, err
}
Пример #15
0
// Get a list of all customers for a
// given shop.
// Params (optional):
// @since_id bson.ObjectId
// @created_at_min time.Time 2006-01-02 15:04
// @created_at_max time.Time 2006-01-02 15:04
// @updated_at_min time.Time 2006-01-02 15:04
// @updated_at_max time.Time 2006-01-02 15:04
// @page int
// @limit int
func GetCustomers(w http.ResponseWriter, req *http.Request, params martini.Params, enc encoding.Encoder, shop *cart.Shop) string {

	var since_id bson.ObjectId
	var created_at_min *time.Time
	var created_at_max *time.Time
	var updated_at_min *time.Time
	var updated_at_max *time.Time
	limit := 50
	page := 0
	qs := req.URL.Query()

	if since := qs.Get("since_id"); since != "" {
		if bson.IsObjectIdHex(since) {
			since_id = bson.ObjectIdHex(since)
		}
	}

	if created_min, err := time.Parse(TimeLayout, qs.Get("created_at_min")); err == nil {
		if created_max, err := time.Parse(TimeLayout, qs.Get("created_at_max")); err == nil {
			created_at_min = &created_min
			created_at_max = &created_max
		}
	}
	if updated_min, err := time.Parse(TimeLayout, qs.Get("updated_at_min")); err == nil {
		if updated_max, err := time.Parse(TimeLayout, qs.Get("updated_at_max")); err == nil {
			updated_at_min = &updated_min
			updated_at_max = &updated_max
		}
	}

	if l := qs.Get("limit"); l != "" {
		lmt, err := strconv.Atoi(l)
		if err == nil && lmt != 0 {
			limit = lmt
		}
	}
	if p := qs.Get("page"); p != "" {
		pg, err := strconv.Atoi(p)
		if err == nil && pg != 0 {
			page = pg
		}
	}

	var custs []cart.Customer
	var err error
	if since_id.Hex() != "" {
		custs, err = cart.CustomersSinceId(shop.Id, since_id, page, limit, created_at_min, created_at_max, updated_at_min, updated_at_max)
	} else {
		custs, err = cart.GetCustomers(shop.Id, page, limit, created_at_min, created_at_max, updated_at_min, updated_at_max)
	}

	if err != nil {
		apierror.GenerateError("", err, w, req)
		return ""
	}

	return encoding.Must(enc.Encode(custs))
}
Пример #16
0
func logAssociation(id bson.ObjectId, master bool) *memstore.MemoryToken {
	if master {
		memStoreUser.NewToken(id.Hex())
		memStoreAssociationUser.NewToken(id.Hex())
		return memStoreSuperUser.NewToken(id.Hex())
	}
	memStoreUser.NewToken(id.Hex())
	return memStoreAssociationUser.NewToken(id.Hex())
}
Пример #17
0
func GetAccountByUserId(id bson.ObjectId) (*models.Account, error) {
	user := new(models.User)
	err := Mongo.One(UserColl, id.Hex(), user)
	if err != nil {
		return nil, err
	}

	return GetAccount(user.Name)
}
Пример #18
0
func AddMemberToGroupByID(groupId bson.ObjectId, userId bson.ObjectId) error {
	var err error
	g, err := FindGroup(groupId)
	Col = Session.DB("test").C("Group")
	query := bson.M{"_id": g.ID}
	change := bson.M{"$push": bson.M{"userids": userId.Hex(), "expected": 0, "actual": 0}}
	err = Col.Update(query, change)
	return err
}
Пример #19
0
// Get all customers since a defined Id.
func CustomersSinceId(shopId bson.ObjectId, since_id bson.ObjectId, page, limit int, created_at_min, created_at_max, updated_at_min, updated_at_max *time.Time) ([]Customer, error) {
	custs := []Customer{}
	sess, err := mgo.DialWithInfo(database.MongoConnectionString())
	if err != nil {
		return custs, err
	}
	defer sess.Close()

	c := sess.DB("CurtCart").C("customer")
	qs := bson.M{
		"shop_id": shopId.String(),
		"_id": bson.M{
			"$gt": since_id.String(),
		},
		"$or": []bson.M{
			bson.M{"customer.addresses.deleted": false},
			bson.M{"customer.addresses.deleted": bson.M{
				"$exists": false,
			}},
		},
	}
	if created_at_min != nil || created_at_max != nil {
		createdQs := bson.M{}
		if created_at_min != nil {
			createdQs["&qt"] = created_at_min.String()
		}
		if created_at_max != nil {
			createdQs["&lt"] = created_at_max.String()
		}
		qs["created_at"] = createdQs
	}
	if updated_at_min != nil || updated_at_max != nil {
		updatedQs := bson.M{}
		if updated_at_min != nil {
			updatedQs["&qt"] = updated_at_min.String()
		}
		if updated_at_max != nil {
			updatedQs["&lt"] = updated_at_max.String()
		}
		qs["updated_at"] = updatedQs
	}

	if page == 1 {
		page = 0
	}
	err = c.Find(qs).Skip(page * limit).Limit(limit).All(&custs)
	if err != nil {
		return []Customer{}, err
	}

	for i, _ := range custs {
		custs[i].Password = ""
	}

	return custs, err
}
Пример #20
0
func ModuleDelete(id bson.ObjectId) error {
	if err := RolePerDeleteByModule(id.Hex()); err != nil {
		return err
	}
	if _, err := CloneDB().C(FuncColl).RemoveAll(bson.M{"moduleid": id.Hex()}); err != nil {
		return err
	}
	return CloneDB().C(ModuleColl).Remove(bson.M{"_id": id})

}
Пример #21
0
func (s *AuthService) createToken(id bson.ObjectId) (token string, err error) {
	expiration, err := strconv.Atoi(s.config.Expiration)
	if err != nil {
		expiration = 72
	}
	t := jwt.New(jwt.SigningMethodHS256)
	t.Claims["user"] = id.Hex()
	t.Claims["exp"] = time.Now().Add(time.Hour * time.Duration(int64(expiration))).Unix()
	return t.SignedString([]byte(s.config.Secret))
}
Пример #22
0
func saveUserTokens(storeLocation string, userID bson.ObjectId, tokens []string) error {
	userIndexFile := fileLocation(storeLocation, userID.Hex())

	jsonData, err := util.SerializeJSON(tokens)
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(userIndexFile, jsonData, os.ModeDevice)
	return err
}
Пример #23
0
func testGetTransactionWithGoodIDParam(t *testing.T, id bson.ObjectId) {
	params := url.Values{}
	params.Add("transactionId", id.Hex())

	rw := tests.PerformTestRequest(endpointPath, ActionGet, api.GET, http.StatusOK, params, nil, t)

	body := rw.Body.String()
	if len(body) == 0 {
		t.Error("Response body is empty or in a corrupt format:", body)
	}
}
Пример #24
0
func AuthorNameById(id bson.ObjectId, authors []Author) string {
	if !id.Valid() {
		return "anon"
	}
	for _, author := range authors {
		if author.ID == id {
			fmt.Printf("matched author name %s to %s\n", author.Name, id)
			return author.Name
		}
	}
	fmt.Printf("did not match author name to %s\n", id)
	return "anon"
}
Пример #25
0
func RemoveMemberFromGroup(groupId bson.ObjectId, userId bson.ObjectId) error {
	var err error
	g, err := FindGroup(groupId)
	for i, oldUser := range g.UserIDs {
		if userId.Hex() == oldUser {
			g.UserIDs = append(g.UserIDs[:i], g.UserIDs[i+1:]...)
			g.Actual = append(g.Actual[:i], g.Actual[i+1:]...)
			g.Expected = append(g.Expected[:i], g.Expected[i+1:]...)
			GetGroupChanges(g)
			return err
		}
	}
	err = errors.New("Did not find member in Group")
	return err
}
Пример #26
0
func getUserTokens(storeLocation string, userID bson.ObjectId) ([]string, error) {
	userIndexFile := fileLocation(storeLocation, userID.Hex())

	fileContent, err := ioutil.ReadFile(userIndexFile)
	if err != nil {
		return nil, err
	}

	var userTokens []string
	err = util.DeserializeJSON(fileContent, userTokens)
	if err != nil {
		return nil, err
	}

	return userTokens, nil
}
Пример #27
0
func articleUpdate(userId string, articleId string, title string, content string, circles []interface{}, public bool) string {
	var err error
	var objId bson.ObjectId
	user := bson.ObjectIdHex(userId)
	// update article
	if bson.IsObjectIdHex(articleId) {
		objId = bson.ObjectIdHex(articleId)
		// get last content
		ret := &Article{}
		err = db.article.FindId(objId).One(ret)
		if err == nil {
			lastContent := ret.Content
			err = db.article.Update(
				bson.M{"_id": objId, "user": user},
				bson.M{
					"$set": bson.M{
						"title":        title,
						"content":      content,
						"last_content": lastContent,
						"updated":      time.Now(),
						"circle":       circles,
						"public":       public,
					},
				},
			)
		}
	} else {
		// create article
		objId = bson.NewObjectId()
		now := time.Now()
		err = db.article.Insert(bson.M{
			"_id":          objId,
			"user":         user,
			"title":        title,
			"content":      content,
			"last_content": content,
			"created":      now,
			"updated":      now,
			"circle":       circles,
			"public":       public,
		})
	}
	if err == nil {
		return objId.Hex()
	}
	return ""
}
Пример #28
0
func (self TrainsSpResource) getStatusLink(lineId string, statusId bson.ObjectId) []models.Link {
	id := statusId.Hex()
	return []models.Link{
		{
			Url:  config.ApiRoot + "/v1/states/sp/transports/trains/lines/" + lineId + "/statuses/" + id,
			Note: "self",
		},
		{
			Url:  config.ApiRoot + "/v1/states/sp/transports/trains/lines/" + lineId + "/statuses",
			Note: "statuses",
		},
		{
			Url:  config.ApiRoot + "/v1/states/sp/transports/trains/lines/" + lineId,
			Note: "line",
		},
	}
}
Пример #29
0
func GetComputeStackByUserGroup(userID, groupID bson.ObjectId) (*models.ComputeStack, error) {
	user, err := GetUserById(userID.Hex())
	if err != nil {
		return nil, err
	}

	group, err := GetGroupById(groupID.Hex())
	if err != nil {
		return nil, err
	}

	account, err := GetAccount(user.Name)
	if err != nil {
		return nil, err
	}

	return GetComputeStackByGroup(group.Slug, account.Id)
}
Пример #30
0
func FindApplicationById(id bson.ObjectId) Application {
	result := Application{}

	key := id.Hex()
	cache_result, err := cache.Get(key)

	if err {
		database.Find(result.Collection(), &result, id)
		b, _ := json.Marshal(result)
		cache.Set(key, string(b), 60*time.Minute)
	} else if cache_result.CachedItem == nil {
		json.Unmarshal([]byte(cache_result.Value.(string)), &result)
		cache_result.CachedItem = result
	} else {
		result = cache_result.CachedItem.(Application)
	}

	return result
}