예제 #1
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
}
예제 #2
0
파일: method.go 프로젝트: elvizlai/MGBlog
//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)
		}
	})
}
예제 #3
0
파일: ads.go 프로젝트: aleksandrpak/ads
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
}
예제 #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 (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)
}
예제 #6
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
}
예제 #7
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
}
예제 #8
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
}
예제 #9
0
파일: user.go 프로젝트: faiq/minikick
func (u User) DidBack(backedProject bson.ObjectId) bool {
	for _, backed := range u.BackedProjects {
		if backed.Project.Hex() == backedProject.Hex() {
			return true
		}
	}
	return false
}
예제 #10
0
파일: user.go 프로젝트: faiq/minikick
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
////////////////////////////////////////////////////////
//          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
}
예제 #12
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
}
예제 #13
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{}
}
예제 #14
0
파일: customer.go 프로젝트: ninnemana/API
// 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))
}
예제 #15
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())
}
예제 #16
0
파일: user.go 프로젝트: koding/koding
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)
}
예제 #17
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
}
예제 #18
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})

}
예제 #19
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))
}
예제 #20
0
파일: filestore.go 프로젝트: coddo/gost
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
}
예제 #21
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)
	}
}
예제 #22
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
}
예제 #23
0
파일: filestore.go 프로젝트: coddo/gost
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
}
예제 #24
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 ""
}
예제 #25
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",
		},
	}
}
예제 #26
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)
}
예제 #27
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
}
예제 #28
0
파일: server.go 프로젝트: zotgene/loadcat
func GetServer(id bson.ObjectId) (*Server, error) {
	srv := &Server{}
	err := DB.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("servers"))
		v := b.Get([]byte(id.Hex()))
		if v == nil {
			srv = nil
			return nil
		}
		err := bson.Unmarshal(v, srv)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return srv, nil
}
예제 #29
0
파일: balancer.go 프로젝트: zotgene/loadcat
func GetBalancer(id bson.ObjectId) (*Balancer, error) {
	bal := &Balancer{}
	err := DB.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("balancers"))
		v := b.Get([]byte(id.Hex()))
		if v == nil {
			bal = nil
			return nil
		}
		err := bson.Unmarshal(v, bal)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return bal, nil
}
예제 #30
0
func (application Application) FindSessionById(id bson.ObjectId) (Session, bool) {
	result := Session{}

	key := application.Id.Hex() + ".sessions." + id.Hex()
	cache_result, err := cache.Get(key)

	if err {
		query := bson.M{"_id": bson.ObjectId(id)}
		database.FindBy(application.Id.Hex()+"_sessions", &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.(Session)
	}

	return result, result.Id == bson.ObjectId("")
}