Ejemplo n.º 1
0
func UpdateUsernameInBothDbs(currentUsername, newUsername string) error {
	err := modelhelper.UpdateUser(
		bson.M{"username": currentUsername},
		bson.M{"username": newUsername},
	)

	if err != nil {
		return err
	}

	err = modelhelper.UpdateAccount(
		modelhelper.Selector{"profile.nickname": currentUsername},
		modelhelper.Selector{"$set": modelhelper.Selector{"profile.nickname": newUsername}},
	)

	if err != nil {
		return err
	}

	acc := NewAccount()
	if err := acc.ByNick(currentUsername); err != nil {
		return err
	}

	acc.Nick = newUsername

	return acc.Update()
}
Ejemplo n.º 2
0
func updateUserSlackToken(user *kodingmodels.User, groupName string, m string) error {
	selector := bson.M{"username": user.Name}
	key := fmt.Sprintf("foreignAuth.slack.%s.token", groupName)
	update := bson.M{key: m}

	return modelhelper.UpdateUser(selector, update)
}
Ejemplo n.º 3
0
func TestGetAnyUserTokenFromGroup(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	id := bson.NewObjectId()
	username := id.Hex()
	user := &models.User{
		ObjectId: id,
		Name:     username,
		Email:    username + "@" + username + ".com",
	}

	err := modelhelper.CreateUser(user)
	if err != nil {
		t.Error(err)
	}

	groupName := bson.NewObjectId().Hex()

	key := fmt.Sprintf("foreignAuth.slack.%s.token", groupName)
	token := "token-123qwe"
	selector := bson.M{"username": username}
	update := bson.M{key: token}

	if err := modelhelper.UpdateUser(selector, update); err != nil {
		t.Error("Error while updating user")
	}

	id2 := bson.NewObjectId()
	username2 := id2.Hex()
	user2 := &models.User{
		ObjectId: id2,
		Name:     username2,
		Email:    username2 + "@" + username2 + ".com",
	}

	err = modelhelper.CreateUser(user2)
	if err != nil {
		t.Error(err)
	}

	groupName2 := bson.NewObjectId().Hex()
	key2 := fmt.Sprintf("foreignAuth.slack.%s.token", groupName2)
	token2 := "token-123qwe11"
	selector2 := bson.M{"username": username2}
	update2 := bson.M{key2: token2}

	if err := modelhelper.UpdateUser(selector2, update2); err != nil {
		t.Error("Error while updating user")
	}

	users, err := modelhelper.GetAnySlackTokenWithGroup(groupName)
	if err != nil {
		t.Error("Error while getting user token")
	}

	if len(users) != 1 {
		t.Error("Length of user should be 1")
	}

	err = modelhelper.RemoveUser(username)
	if err != nil {
		t.Error(err)
	}
}
Ejemplo n.º 4
0
func TestAccountTesting(t *testing.T) {
	runner, handler := getTestHandler()
	defer runner.Close()

	// init mongo connection
	appConfig := config.MustRead(runner.Conf.Path)
	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	Convey("given some fake account", t, func() {
		acc, _, name := models.CreateRandomGroupDataWithChecks()
		So(name, ShouldNotBeNil)
		So(acc, ShouldNotBeNil)

		Convey("it should save the document to algolia", func() {
			err := handler.AccountCreated(acc)
			So(err, ShouldBeNil)

			Convey("it should be able to fetch algolia data", func() {
				// make sure account is there
				So(doBasicTestForAccount(handler, acc.OldId), ShouldBeNil)

				_, err = modelhelper.GetUser(acc.Nick)
				So(err, ShouldBeNil)

				// update user's email
				selector := bson.M{"username": acc.Nick}
				newEmail := "mehmetalixsavasx1x2x" + models.RandomGroupName() + "@koding.com"
				updateQuery := bson.M{"email": newEmail}

				err = modelhelper.UpdateUser(selector, updateQuery)
				So(err, ShouldBeNil)

				err = handler.AccountUpdated(acc)
				So(err, ShouldBeNil)

				index, err := handler.indexes.GetIndex(IndexAccounts)
				So(err, ShouldBeNil)

				params := make(map[string]interface{})
				record, err := index.Search("mehmetalixsavasx1x2x", params)
				So(err, ShouldBeNil)

				hist, ok := record.(map[string]interface{})["hits"]

				usernames := make([]string, 0)
				objects := make([]string, 0)

				if ok {
					hinter, ok := hist.([]interface{})
					if ok {
						for _, v := range hinter {
							val, k := v.(map[string]interface{})
							if k {
								object := val["objectID"].(string)
								value := val["nick"].(string)

								usernames = append(usernames, value)
								objects = append(objects, object)

								_, err = index.DeleteObject(object)
								So(err, ShouldBeNil)
							}

						}
					}
				}

				So(usernames, ShouldNotBeNil)
				So(objects, ShouldNotBeNil)

			})

			Convey("it should be able to fetch many account with given query", func() {
				So(doBasicTestForAccount(handler, acc.OldId), ShouldBeNil)

				// we create 10 acc for algolia test
				for i := 0; i < 10; i++ {
					ac, _, _ := models.CreateRandomGroupDataWithChecks()

					err := handler.AccountCreated(ac)
					So(err, ShouldBeNil)

					selector := bson.M{"username": ac.Nick}
					newEmail := "mehmetali-test" + models.RandomGroupName() + "@koding.com"
					updateQuery := bson.M{"email": newEmail}
					err = modelhelper.UpdateUser(selector, updateQuery)
					So(err, ShouldBeNil)

					err = handler.AccountUpdated(ac)
					So(err, ShouldBeNil)
					time.Sleep(1 * time.Second)
				}

				//required for getting algolia datas correctly
				time.Sleep(5 * time.Second)

				_, err = modelhelper.GetUser(acc.Nick)
				So(err, ShouldBeNil)

				index, err := handler.indexes.GetIndex(IndexAccounts)
				So(err, ShouldBeNil)

				params := make(map[string]interface{})
				record, err := index.Search("mehmetali-test", params)
				So(err, ShouldBeNil)

				hist, ok := record.(map[string]interface{})["hits"]

				usernames := make([]string, 0)
				objects := make([]string, 0)

				if ok {
					hinter, ok := hist.([]interface{})
					if ok {
						for _, v := range hinter {
							val, k := v.(map[string]interface{})
							if k {
								object := val["objectID"].(string)
								value := val["nick"].(string)

								usernames = append(usernames, value)
								objects = append(objects, object)
							}

						}
					}
				}

				So(len(usernames), ShouldBeGreaterThan, 0)
				So(len(objects), ShouldBeGreaterThan, 0)

				Convey("it should be able to delete many account with given query", func() {

					So(doBasicTestForAccount(handler, acc.OldId), ShouldBeNil)

					for i := 0; i < 10; i++ {
						ac, _, _ := models.CreateRandomGroupDataWithChecks()

						err := handler.AccountCreated(ac)
						So(err, ShouldBeNil)

						selector := bson.M{"username": ac.Nick}
						newEmail := "mehmetali-test" + models.RandomGroupName() + "@koding.com"
						updateQuery := bson.M{"email": newEmail}
						err = modelhelper.UpdateUser(selector, updateQuery)
						So(err, ShouldBeNil)

						err = handler.AccountUpdated(ac)
						So(err, ShouldBeNil)
						time.Sleep(1 * time.Second)
					}

					time.Sleep(5 * time.Second)

					_, err = modelhelper.GetUser(acc.Nick)
					So(err, ShouldBeNil)

					_, err := handler.indexes.GetIndex(IndexAccounts)
					So(err, ShouldBeNil)

					usernames := make([]string, 0)
					objects := make([]string, 0)

					nbHits, _ := record.(map[string]interface{})["nbHits"]
					nbPages, _ := record.(map[string]interface{})["nbPages"]

					var pages float64 = nbPages.(float64)
					var nbHit float64 = nbHits.(float64)

					for pages > 0 && nbHit != 0 {
						record, err := index.Search("mehmetali-test", params)
						hist, ok := record.(map[string]interface{})["hits"]

						// fmt.Println("hist is :", hist)
						nbHits, _ := record.(map[string]interface{})["nbHits"]
						nbPages, _ := record.(map[string]interface{})["nbPages"]

						pages = nbPages.(float64)
						nbHit = nbHits.(float64)

						if ok {
							hinter, ok := hist.([]interface{})
							if ok {
								for _, v := range hinter {
									val, k := v.(map[string]interface{})
									if k {
										object := val["objectID"].(string)
										value := val["nick"].(string)

										usernames = append(usernames, value)
										objects = append(objects, object)
										_, err = index.DeleteObject(object)
										So(err, ShouldBeNil)
									}

								}
							}
						}
					}

					lenghtUsernames := len(usernames)
					lenghtObjects := len(objects)
					So(lenghtUsernames, ShouldBeGreaterThan, 10)
					So(lenghtObjects, ShouldBeGreaterThan, 10)

				})

				Convey("it should have delete algolia accounts", func() {
					fmt.Println("=============>>>>>>>>>>>>>>>>>>>")
					fmt.Println("=============>>>>>>>>>>>>>>>>>>>")
					fmt.Println("it should have delete algolia accounts")
					fmt.Println("=============>>>>>>>>>>>>>>>>>>>")
					fmt.Println("=============>>>>>>>>>>>>>>>>>>>")
					// make sure account is there
					So(doBasicTestForAccount(handler, acc.OldId), ShouldBeNil)

					for i := 0; i < 10; i++ {
						rand.Seed(time.Now().UnixNano())
						strconv.FormatInt(rand.Int63(), 10)
						name := "guter-" + strconv.FormatInt(rand.Int63(), 10)
						ac, _ := models.CreateAccountInBothDbsWithNick(name)

						err := handler.AccountCreated(ac)
						So(err, ShouldBeNil)

						selector := bson.M{"username": ac.Nick}
						newEmail := "mehmetali-test" + models.RandomGroupName() + "@koding.com"
						updateQuery := bson.M{"email": newEmail}
						err = modelhelper.UpdateUser(selector, updateQuery)
						So(err, ShouldBeNil)

						err = handler.AccountUpdated(ac)
						So(err, ShouldBeNil)
						time.Sleep(1 * time.Second)
					}

					time.Sleep(5 * time.Second)

					_, err = handler.indexes.GetIndex(IndexAccounts)
					So(err, ShouldBeNil)

					// record, _ := index.Search("mehmetalisa", map[string]interface{}{"restrictSearchableAttributes": "email"})
					// params := make(map[string]interface{})
					params := map[string]interface{}{"restrictSearchableAttributes": "nick"}
					record, _ := index.Search("guter-", params)

					hits, _ := record.(map[string]interface{})["nbHits"]
					hit := hits.(float64)
					So(hit, ShouldBeGreaterThan, 0)

					err = handler.DeleteNicksWithQuery("guter-")
					So(err, ShouldBeNil)

					// necessary for getting datas from algolia,
					time.Sleep(5 * time.Second)

					r, err := index.Search("guter-", params)
					So(err, ShouldBeNil)
					nbHits, _ := r.(map[string]interface{})["nbHits"]
					nbHit := nbHits.(float64)
					So(nbHit, ShouldBeLessThan, 10)
				})
			})
		})
	})
}
Ejemplo n.º 5
0
func TestAccountUpdated(t *testing.T) {
	runner, handler := getTestHandler()
	defer runner.Close()

	// init mongo connection
	appConfig := config.MustRead(runner.Conf.Path)
	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	Convey("given some fake account", t, func() {
		acc, err := models.CreateAccountInBothDbs()
		So(acc, ShouldNotBeNil)
		So(err, ShouldBeNil)

		Convey("it should save the document to algolia if not created before", func() {
			err := handler.AccountUpdated(acc)
			So(err, ShouldBeNil)

			Convey("it should have email in it", func() {
				// make sure account is there
				So(doBasicTestForAccount(handler, acc.OldId), ShouldBeNil)

				// update user's email
				selector := bson.M{"username": acc.Nick}
				newEmail := models.RandomGroupName() + "@bar.com"
				updateQuery := bson.M{"email": newEmail}
				err = modelhelper.UpdateUser(selector, updateQuery)
				So(err, ShouldBeNil)

				err = handler.AccountUpdated(acc)
				So(err, ShouldBeNil)

				err = makeSureWithSearch(
					handler,
					IndexAccounts,
					newEmail,
					map[string]interface{}{"restrictSearchableAttributes": "email"},
					func(record map[string]interface{}, err error) bool {
						if err != nil {
							return false
						}

						if record == nil {
							return false
						}

						hits, ok := record["nbHits"]
						if hits == nil || !ok {
							return false
						}

						if hits.(float64) <= 0 {
							return false
						}

						return true
					})
				So(err, ShouldBeNil)
			})
		})

		Convey("updating the account again should success", func() {
			err := handler.AccountCreated(acc)
			So(err, ShouldBeNil)
			So(doBasicTestForAccount(handler, acc.OldId), ShouldBeNil)
		})

		Convey("it should delete the document when user account is deleted", func() {
			// first ensure account object is created
			err = handler.AccountCreated(acc)
			So(err, ShouldBeNil)
			So(doBasicTestForAccount(handler, acc.OldId), ShouldBeNil)

			newNick := "guest-" + models.RandomName() + "-rm"
			err = models.UpdateUsernameInBothDbs(acc.Nick, newNick)
			So(err, ShouldBeNil)

			acc.Nick = newNick

			err = handler.AccountUpdated(acc)
			So(err, ShouldBeNil)

			So(doBasicTestForAccountDeletion(handler, acc.OldId), ShouldBeNil)

			Convey("deleting the account again should success", func() {
				err = handler.AccountUpdated(acc)
				So(err, ShouldBeNil)
				So(doBasicTestForAccountDeletion(handler, acc.OldId), ShouldBeNil)
			})
		})

		Convey("it should not return any error when deleted user does not exist on Algolia", func() {
			newNick := "guest-" + models.RandomName() + "-rm"
			err = models.UpdateUsernameInBothDbs(acc.Nick, newNick)
			So(err, ShouldBeNil)

			acc.Nick = newNick

			err = handler.AccountUpdated(acc)
			So(err, ShouldBeNil)

			So(doBasicTestForAccountDeletion(handler, acc.OldId), ShouldBeNil)
		})

	})
}
Ejemplo n.º 6
0
// HandleCreator finds the creator of the channel, and tries to find its
// company name according to its email address
func (c *Controller) HandleCreator(channel *models.Channel) error {
	// we need to check environment, because we dont want to request to clearbit for our dev
	if channel.TypeConstant != models.Channel_TYPE_GROUP || c.config.Environment != "production" {
		return nil
	}

	creator, err := models.Cache.Account.ById(channel.CreatorId)
	if err != nil {
		return nil
	}
	user, err := modelhelper.GetUser(creator.Nick)
	if err != nil {
		return nil
	}
	// if user already has company, no need to fetch user's company info again.
	if user.CompanyId.Hex() != "" {
		return nil
	}
	// if user has no company data, then try to fetch info about company of user.
	userData, err := c.clearbit.Enrichment().Combined(user.Email)
	if err != nil {
		return err
	}

	if userData.Company == nil {
		return nil
	}

	if userData.Company.Name == nil {
		return nil
	}

	// if code line reach to here, it means that we got user's company data,
	// after that we are going to update user's data.
	var company *mongomodels.Company

	company, err = modelhelper.GetCompanyByNameOrSlug(*userData.Company.Name)
	if err != nil && err != mgo.ErrNotFound {
		return err
	}
	// if company is not found in db, then create new one
	// after creation, update user's company with company id
	if err == mgo.ErrNotFound {
		err := checkValuesForCompany(userData.Company)
		if err != nil {
			return nil
		}

		// parse company data of clearbit package into our company model struct
		companyData := parseClearbitCompany(userData.Company)

		// create company in db if it doesn't exist
		company, err = modelhelper.CreateCompany(companyData)
		if err != nil {
			return err
		}
	}

	// update the company info of user if company exist in mongo
	selector := bson.M{"username": user.Name}
	update := bson.M{"companyId": company.Id}
	if err := modelhelper.UpdateUser(selector, update); err != nil {
		return err
	}
	return nil
}