Example #1
0
func (application Application) FindGroupById(id bson.ObjectId) (Group, bool) {
	result := Group{}
	query := bson.M{"_id": bson.ObjectId(id)}

	database.FindBy(application.Id.Hex()+"_groups", &result, query)

	return result, result.Id == bson.ObjectId("")
}
Example #2
0
//Game
func (c *Game) To24bytesId() {
	if len(c.Id) == 12 {
		c.Id = bson.ObjectId(c.Id.Hex())
	}
	if len(c.OwnerId) == 12 {
		c.OwnerId = bson.ObjectId(c.OwnerId.Hex())
	}
}
Example #3
0
//UploadToken
func (c *UploadToken) To24bytesId() {
	if len(c.GameId) == 12 {
		c.GameId = bson.ObjectId(c.GameId.Hex())
	}
	if len(c.UserId) == 12 {
		c.UserId = bson.ObjectId(c.UserId.Hex())
	}
}
Example #4
0
//Child
func (c *Child) To24bytesId() {
	if len(c.Id) == 12 {
		c.Id = bson.ObjectId(c.Id.Hex())
	}
	if len(c.ParentId) == 12 {
		c.ParentId = bson.ObjectId(c.ParentId.Hex())
	}
	for _, ge := range c.Games {
		ge.To24bytesId()
	}
}
Example #5
0
func (s *AuthService) User(token string) (u bson.ObjectId, err error) {
	t, err := jwt.Parse(token, s.signFunc)
	if err != nil {
		return bson.ObjectId(""), err
	}

	if s.hasExpired(t) {
		return bson.ObjectId(""), &exceptions.TokenExpiredException{"Token is expired."}
	}

	return bson.ObjectIdHex(t.Claims["user"].(string)), nil
}
Example #6
0
func FilesGetHandler(c echo.Context) error {

	// Create the User Session
	session := session.NewSession(c)

	// Validate that the request signature is valid
	session.ValidateFileRequest()

	redirect := false

	if !session.AuthFailed {
		// Get the endpoint for that record
		endpoint := session.GetEndpoint()

		if plugin.CheckPlugin("get_file", endpoint) {
			plugin.RunPlugin("get_file", endpoint, session)
		} else {
			// Get the ID of the record that owns the file
			record_id := bson.ObjectIdHex(session.GetParam("record_id").(string))

			// Get the record from the endpoint collection
			record := endpoint.FindReadRecordById(record_id, session.User)

			// Check if the record exists
			if record.Id != bson.ObjectId("") {

				// Get the ID of the file
				file_id := bson.ObjectIdHex(session.GetParam("file_id").(string))

				// Get the file from the database
				file := record.FindFileById(file_id)

				// Validate that the file exists
				if file.Id != bson.ObjectId("") {

					// Redirect to the file path
					c.Redirect(301, file.DownloadURL())
					redirect = true

					// Log the request
					session.LogRequest()
				}
			}

			if !redirect {
				session.Write()
			}
		}
	}

	return nil
}
Example #7
0
func (self *DocumentBase) persistRelation(value reflect.Value, autoSave bool) (error, bson.ObjectId) {

	// Detect the type of the value which is stored within the slice
	switch typedValue := value.Interface().(type) {

	// Deserialize objects to id
	case IDocumentBase:
		{
			// Save children when flag is enabled
			if autoSave {
				err := typedValue.Save()

				if err != nil {
					return err, bson.ObjectId("")
				}
			}

			objectId := typedValue.GetId()

			if !objectId.Valid() {
				panic("DB: Can not persist the relation object because the child was not saved before (invalid id).")
			}

			return nil, objectId
		}

	// Only save the id
	case bson.ObjectId:
		{
			if !typedValue.Valid() {
				panic("DB: Can not persist the relation object because the child was not saved before (invalid id).")
			}

			return nil, typedValue
		}

	case string:
		{
			if !bson.IsObjectIdHex(typedValue) {
				return &InvalidIdError{&QueryError{fmt.Sprintf("Invalid id`s given")}}, bson.ObjectId("")
			} else {
				return nil, bson.ObjectIdHex(typedValue)
			}
		}

	default:
		{
			panic(fmt.Sprintf("DB: Only type 'bson.ObjectId' and 'IDocumentBase' can be stored in slices. You used %v", value.Interface()))
		}
	}
}
Example #8
0
//GameRelease
func (c *GameRelease) To24bytesId() {
	if len(c.ReleaseId) == 12 {
		c.ReleaseId = bson.ObjectId(c.ReleaseId.Hex())
	}
	if len(c.GameId) == 12 {
		c.GameId = bson.ObjectId(c.GameId.Hex())
	}
	if len(c.ReleasedBy) == 12 {
		c.ReleasedBy = bson.ObjectId(c.ReleasedBy.Hex())
	}
	if len(c.ValidatedBy) == 12 {
		c.ValidatedBy = bson.ObjectId(c.ValidatedBy.Hex())
	}
}
Example #9
0
func (application Application) GetSuperUser() User {
	result := User{}
	query := bson.M{"super_user": true}

	database.FindBy(application.Id.Hex()+"_users", &result, query)

	if result.Id == bson.ObjectId("") {
		result = User{}
		result.SuperUser = true
		result.ApplicationId = bson.ObjectId(application.Id)
		result.Save()
	}

	return result
}
Example #10
0
func GetSessionGMId(req *http.Request) (bson.ObjectId, error) {
	if v, err := GetGMSessionValue(req, GM_ID_SESSION_KEY); err != nil || v == nil {
		return bson.ObjectId(""), errors.New("Invalid session id format")
	} else {
		if str, found := v.(string); found {
			if bson.IsObjectIdHex(str) {
				return bson.ObjectIdHex(str), nil
			} else {
				return bson.ObjectId(""), errors.New("Invalid session id format")
			}
		} else {
			return bson.ObjectId(""), errors.New("Invalid session id format")
		}
	}
}
Example #11
0
func IdFromBase64(b64 string) Id {
	var dst = make([]byte, len(b64))
	if n, err := base64.URLEncoding.Decode(dst, []byte(b64)); err == nil {
		return Id{bson.ObjectId(dst[:n])}
	}
	return Id{}
}
Example #12
0
func FindFeedItemById(id bson.ObjectId) (FeedItem, error) {
	var err error
	Col = Session.DB("test").C("FeedItem")
	feedItem := FeedItem{}
	err = Col.Find(bson.M{"_id": bson.ObjectId(id)}).One(&feedItem)
	return feedItem, err
}
func convertToObjectId(id string) bson.ObjectId {
	objectIdFormat, err := hex.DecodeString(id)
	if err != nil || len(objectIdFormat) != 12 {
		panic(fmt.Sprintf("Invalid input to ObjectIdHex: %q", id))
	}
	return bson.ObjectId(objectIdFormat)
}
Example #14
0
//Only can be one payment between two people
func FindPaymentById(id bson.ObjectId) (Payment, error) {
	var err error
	Col = Session.DB("test").C("Payment")
	payment := Payment{}
	err = Col.Find(bson.M{"_id": bson.ObjectId(id)}).One(&payment)
	return payment, err
}
Example #15
0
func FindPurchaseById(id bson.ObjectId) (Purchase, error) {
	var err error
	Col = Session.DB("test").C("Purchase")
	purchase := Purchase{}
	err = Col.Find(bson.M{"_id": bson.ObjectId(id)}).One(&purchase)
	return purchase, err
}
Example #16
0
func (application Application) ExecuteCronTrigger() {
	result := findTriggerForApplicationIdAndEvent(application.Id, "cron")

	if result.Id != bson.ObjectId("") {
		result.Run(application.Id.Hex(), "")
	}
}
Example #17
0
File: db.go Project: z0rr0/luss
// CheckID converts string s to ObjectId if it is possible,
// otherwise it returns error.
func CheckID(s string) (bson.ObjectId, error) {
	d, err := hex.DecodeString(s)
	if err != nil || len(d) != 12 {
		return "", errors.New("invalid database ID")
	}
	return bson.ObjectId(d), nil
}
func FindContact(id bson.ObjectId) (Contact, error) {
	var err error
	Col = Session.DB("test").C("Contact")
	contact := Contact{}
	err = Col.Find(bson.M{"_id": bson.ObjectId(id)}).One(&contact)
	return contact, err
}
Example #19
0
func FindUserByID(id bson.ObjectId) (*User, error) {
	var err error
	Col = Session.DB("test").C("User")
	user := &User{}
	err = Col.Find(bson.M{"_id": bson.ObjectId(id)}).One(user)
	return user, err
}
Example #20
0
func (u *Url) Serialize() (map[string]interface{}, error) {
	record := UrlRecord{}
	records := []UrlRecord{}
	err := mongo.Find(record, bson.M{"url_id": bson.ObjectId(u.Id)}).Sort("-date_created").Limit(2).All(&records)
	if err != nil {
		return nil, err
	}
	bundle := make(map[string]interface{})
	bundle["Id"] = u.Id
	bundle["Url"] = u.Url
	bundle["Title"] = u.Title
	bundle["WaitTime"] = u.WaitTime
	bundle["TryCount"] = u.TryCount
	bundle["ApplicationId"] = u.ApplicationId
	bundle["Headers"] = u.Headers
	if len(records) >= 1 {
		record1 := records[0]
		bundle["Time"] = record1.DateCreated
		bundle["Last"] = record1.Time
		bundle["Status"] = record1.StatusCode
	}

	if len(records) >= 2 {

		record1, record2 := records[0], records[1]
		bundle["Previous"] = record2.Time
		bundle["Faster"] = record1.Time < record2.Time
	}

	return bundle, nil
}
func PostLeader(leader Leader, res http.ResponseWriter, r render.Render, db *mgo.Database) {
	// Check for existing leader
	existing := FindLeader(leader.Name, db)

	// Not exists, create it
	if existing.ID == "" {
		leader.ID = bson.NewObjectId()
		leader.Timestamp = time.Now()
		err := db.C("leaders").Insert(leader)
		if err == nil {
			r.JSON(200, leader)
		} else {
			r.JSON(500, nil)
		}

		// Exists, update it
	} else {
		existing.Score = leader.Score
		existing.Timestamp = time.Now()
		err := db.C("leaders").Update(bson.M{"_id": bson.ObjectId(existing.ID)}, existing)

		if err == nil {
			r.JSON(200, existing)
		} else {
			r.JSON(500, nil)
		}
	}

}
Example #22
0
func TestGetGame(t *testing.T) {
	tests := []struct {
		id  bson.ObjectId
		gm  *apipb.Game
		err error
	}{
		{
			id:  bson.ObjectIdHex("000000000000000000000009"),
			err: models.ErrorNotFound,
		},
		{
			id:  bson.ObjectId("00000000000000000000001"),
			err: models.ErrorNotFound,
		},
	}

	for i, val := range tests {
		d := connect(t)
		repo := d.GetGameRepo()

		g, err := repo.GetGame(val.id.Hex())
		if val.err != nil {
			if !reflect.DeepEqual(val.err, err) {
				t.Errorf("case %d: want = %v got = %v", i, val.err, err)
			}
			continue
		}
		if err != nil {
			if g != nil {
				t.Fatalf("case %d: unexpected error: %v", i, err)
			}
		}
	}
}
func (object *Record) SaveAndTriggerWithOptions(endpoint string, trigger bool, force_create bool) {
	connection := database.GetConnection()
	defer connection.Release()

	object.UpdatedAt = time.Now().Unix()

	collection := connection.C(object.Collection())

	var err error

	if object.Id == bson.ObjectId("") {
		object.Id = bson.NewObjectId()
		object.CreatedAt = time.Now().Unix()
		err = collection.Insert(object)
		if trigger {
			//object.UpdateReferenceMap()
			go object.FindAndExecuteTriggerForEvent(endpoint + ":create")
		}
	} else {
		err = collection.UpdateId(object.Id, object)
		//fmt.Println("SAVE", object.Content)
		if trigger {
			//object.UpdateReferenceMap()
			if force_create {
				go object.FindAndExecuteTriggerForEvent(endpoint + ":create")
			} else {
				go object.FindAndExecuteTriggerForEvent(endpoint + ":update")
			}
		}
	}
	if err != nil {
		fmt.Println("MGO ERROR", endpoint, err, object.Id)
	}
}
Example #24
0
func GroupJoinHandler(c echo.Context) error {
	session := session.NewSession(c)

	request := session.GetParam("request").(map[string]interface{})
	password := ""

	if g, ok := request["group"]; ok {
		group := g.(map[string]interface{})

		if group["password"] != nil {
			password = group["password"].(string)
		}
	}

	if session.User.Id != bson.ObjectId("") {
		id := bson.ObjectIdHex(session.GetParam("group_id").(string))
		group, _ := session.GetApplication().FindGroupById(id)

		if group.CanJoin(session.User, password) {
			users := []model.User{session.User}

			group.AddUsers(users)

			group.Save()

			session.SetRecords("groups", []interface{}{group})
		}
	}

	session.Write()

	return nil
}
func (r *Record) GetDependantReferenceMaps(connection *database.Connection) []ReferenceMap {

	endpoint_id := r.EndpointId
	application_id := r.ApplicationId

	endpoint := r.GetEndpointFromCache()

	var results []ReferenceMap

	if endpoint.CachedSourceReferenceMaps {
		logger.Debug("[Cache][Reference Maps][Source] Hit: ", r.EndpointId.Hex())
		results = endpoint.SourceReferencedMaps
	} else {
		logger.Debug("[Cache][Reference Maps][Source] Miss: ", r.EndpointId.Hex())
		query := map[string]bson.ObjectId{"source_id": endpoint_id}

		// Get the collection name
		collection := application_id.Hex() + "_maps"

		// Query the database
		database.Query(connection, collection, query).All(&results)

		if endpoint.Id != bson.ObjectId("") {
			key := r.ApplicationId.Hex() + ".endpoints." + endpoint_id.Hex()
			endpoint.SourceReferencedMaps = results
			endpoint.CachedSourceReferenceMaps = true
			b, _ := json.Marshal(endpoint)
			cache.Set(key, string(b), 5*time.Minute)

			logger.Debug("[Cache][Reference Maps][Source] Set: ", r.EndpointId.Hex())
		}
	}

	return results
}
Example #26
0
func FindCommentByUserId(id bson.ObjectId) (Comment, error) {
	var err error
	Col = Session.DB("test").C("Comment")
	comment := Comment{}
	err = Col.Find(bson.M{"userid": bson.ObjectId(id)}).One(&comment)
	return comment, err
}
Example #27
0
func (record Record) FindAndExecuteTriggerForEvent(event string) {
	result := findTriggerForApplicationIdAndEvent(record.ApplicationId, event)

	if result.Id != bson.ObjectId("") {
		result.RunWithContent(record.Id.Hex(), record.CreatedBy.Hex(), record.Content)
	}
}
Example #28
0
func FindNotificationById(id bson.ObjectId) (Notification, error) {
	var err error
	Col = Session.DB("test").C("Notification")
	notification := Notification{}
	err = Col.Find(bson.M{"_id": bson.ObjectId(id)}).One(&notification)
	return notification, err
}
Example #29
0
func Getlocations(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	session, err := mgo.Dial("mongodb://*****:*****@ds045054.mongolab.com:45054/mydatabase")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("mydatabase").C("people")
	id := p.ByName("name")
	oid := bson.ObjectIdHex(id)
	var result MyJsonName
	c.FindId(oid).One(&result)

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

	fmt.Println("Id2:", result.Id.String())
	oid = bson.ObjectId(result.Id)

	b2, err := json.Marshal(result)
	if err != nil {
	}
	rw.WriteHeader(http.StatusOK)

	fmt.Fprintf(rw, string(b2))
	fmt.Println("Method Name: " + req.Method)
}
Example #30
0
func Getlocations(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	session, err := mgo.Dial("mongodb://*****:*****@ds029804.mongolab.com:29804/cmpe273")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	c := session.DB("cmpe273").C("people")
	id := p.ByName("name")
	oid := bson.ObjectIdHex(id)
	var result JsonName
	c.FindId(oid).One(&result)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("SeqNo:", result.Id.String())
	oid = bson.ObjectId(result.Id)

	b2, err := json.Marshal(result)
	if err != nil {
	}

	fmt.Fprintf(rw, string(b2))
	fmt.Println("Method : " + req.Method)
}