예제 #1
0
// Update modifies account data to the lates version by default all requests
// coming to this handler are trusted & validity of the parameters are not
// checked.
//
func Update(u *url.URL, h http.Header, req *models.Account) (int, http.Header, interface{}, error) {
	accountId, err := request.GetURIInt64(u, "id")
	if err != nil {
		return response.NewBadRequest(err)
	}

	if accountId == 0 {
		return response.NewBadRequest(models.ErrAccountIdIsNotSet)
	}

	acc := models.NewAccount()
	if err := acc.ById(accountId); err != nil {
		return response.NewBadRequest(err)
	}

	acc.Nick = req.Nick

	if err := models.ValidateAccount(acc); err != nil {
		if err != models.ErrGuestsAreNotAllowed {
			return response.NewBadRequest(err)
		}
	}

	acc.Settings = req.Settings

	if err := acc.Update(); err != nil {
		return response.NewBadRequest(err)
	}

	return response.NewOK(acc)
}
예제 #2
0
// makeSureAccount checks if incoming account is in postgres, if not creates it
// lazily and sets socialapi id of it in mongo
func makeSureAccount(groupName string, username string) (*models.Account, error) {
	// try to fetch account from postgres
	acc := models.NewAccount()
	err := acc.ByNick(username)
	if err == nil {
		return acc, nil
	}

	if err != bongo.RecordNotFound {
		return acc, err
	}

	// if account is not in postgres, try to create it

	// we need account first
	macc, err := modelhelper.GetAccount(username)
	if err != nil {
		return nil, err
	}

	acc = models.NewAccount() // account is nil, set it
	acc.OldId = macc.Id.Hex()
	acc.Nick = username
	if err := acc.Create(); err != nil {
		return nil, err
	}

	// set it to cache, in case we may need it
	if err := models.Cache.Account.SetToCache(acc); err != nil {
		return nil, err
	}

	// we just created the account in postgres, so update mongo with
	// socialApiId
	s := modelhelper.Selector{
		"profile.nickname": username,
	}
	o := modelhelper.Selector{"$set": modelhelper.Selector{
		"socialApiId": strconv.FormatInt(acc.Id, 10),
	}}
	if err := modelhelper.UpdateAccount(s, o); err != nil {
		return nil, err
	}

	return acc, nil
}
예제 #3
0
func TestAccountCreation(t *testing.T) {
	tests.WithRunner(t, func(r *runner.Runner) {
		Convey("while  creating account", t, func() {
			Convey("First Create User", func() {
				Convey("Should not error if you pass old id", func() {
					account := models.NewAccount()
					account.OldId = AccountOldId.Hex()
					account, err := rest.CreateAccount(account)
					So(err, ShouldBeNil)
					So(account, ShouldNotBeNil)
					Convey("User should be in postgre when fetch from postgre", func() {
						accounts, err := models.FetchAccountsWithBongoOffset(100, 0)
						So(err, ShouldBeNil)
						So(accounts, ShouldNotBeNil)
						Convey("Created account should be in account list", func() {
							var doesExist bool
							for _, ac := range accounts {
								if ac.OldId == account.OldId {
									doesExist = true
								}
							}
							So(doesExist, ShouldBeTrue)
						})
					})
					Convey("User should not be in postgre if doesn't exist in mongo", func() {
						err := account.DeleteIfNotInMongo()
						So(err, ShouldBeNil)
						Convey("Created account should not be in account list after checking mongodb", func() {
							accounts, err := models.FetchAccountsWithBongoOffset(100, 0)
							So(err, ShouldBeNil)

							var doesExist bool
							for _, ac := range accounts {
								if ac.OldId == account.OldId {
									doesExist = true
								}
							}
							So(doesExist, ShouldBeFalse)
						})
					})
					Convey("Users creation should be succussfully", func() {
						err := accountCreatorWithCount(10)
						So(err, ShouldBeNil)
						Convey("Users should be in postgre with many accounts", func() {
							accounts, err := models.FetchAccountsWithBongoOffset(100, 0)
							So(err, ShouldBeNil)
							So(len(accounts), ShouldBeGreaterThan, 9)
						})
						Convey("Users should not be in postgre after deleting accounts", func() {
							err := models.DeleteDiffedDBAccounts()
							So(err, ShouldBeNil)
						})
					})
				})
			})
		})
	})
}
예제 #4
0
func accountCreatorWithCount(count int) error {
	for i := 0; i < count; i++ {
		account := models.NewAccount()
		account.OldId = bson.NewObjectId().Hex()
		account, err := rest.CreateAccount(account)
		if err != nil {
			return err
		}
	}
	return nil
}
예제 #5
0
func createAccount() (*models.Account, error) {
	// create and account instance
	account := models.NewAccount()
	// create a fake mongo id
	oldId := bson.NewObjectId()
	// assign it to our test user
	account.OldId = oldId.Hex()
	account.Nick = oldId.Hex()
	if err := account.Create(); err != nil {
		return nil, err
	}

	return account, nil
}
예제 #6
0
func TestAccountCreation(t *testing.T) {
	Convey("while  creating account", t, func() {
		Convey("First Create User", func() {

			Convey("Should error if you dont pass old id", func() {
				account := models.NewAccount()
				account, err := rest.CreateAccount(account)
				So(err, ShouldNotBeNil)
				So(account, ShouldBeNil)
			})

			Convey("Should not error if you pass old id", func() {
				account := models.NewAccount()
				account.OldId = AccountOldId.Hex()
				account, err := rest.CreateAccount(account)
				So(err, ShouldBeNil)
				So(account, ShouldNotBeNil)
			})

			Convey("Should return same id with same old id", func() {
				// first create account
				account := models.NewAccount()
				account.OldId = AccountOldId.Hex()
				firstAccount, err := rest.CreateAccount(account)
				So(err, ShouldBeNil)
				So(firstAccount, ShouldNotBeNil)

				// then try to create it again
				secondAccount, err := rest.CreateAccount(account)
				So(err, ShouldBeNil)
				So(secondAccount, ShouldNotBeNil)

				So(firstAccount.Id, ShouldEqual, secondAccount.Id)
			})
		})
	})
}
예제 #7
0
func createChannelOwner(group *kodingmodels.Group) (*models.Account, error) {
	owner, err := modelhelper.GetGroupOwner(group)
	if err != nil {
		return nil, fmt.Errorf("err while fetching koding owner: %s", err.Error())
	}

	acc := models.NewAccount()
	acc.OldId = owner.Id.Hex()
	acc.Nick = owner.Profile.Nickname
	if err := acc.FetchOrCreate(); err != nil {
		return nil, fmt.Errorf("err while fetching owner from postgres: %s", err.Error())
	}

	return acc, nil
}
예제 #8
0
// getAccount tries to retrieve account information from incoming request,
// should always return a valid account, not nil
func getAccount(r *http.Request, groupName string) *models.Account {
	clientID := getClientID(r)

	// if cookie doenst exists return empty account
	if clientID == "" {
		return models.NewAccount()
	}

	session, err := models.Cache.Session.ById(clientID)
	if err != nil {
		return models.NewAccount()
	}

	// if session doesnt have username, return empty account
	if session.Username == "" {
		return models.NewAccount()
	}

	acc, err := makeSureAccount(groupName, session.Username)
	if err != nil {
		if err != bongo.RecordNotFound && err != mgo.ErrNotFound {
			runner.MustGetLogger().Error("Err while getting account: %s, err :%s", session.Username, err.Error())
		}

		return models.NewAccount()
	}

	groupChannel, err := models.Cache.Channel.ByGroupName(groupName)
	if err != nil {
		if err != bongo.RecordNotFound && err != models.ErrGroupNotFound {
			runner.MustGetLogger().Error("Err while getting group channel: %s, err :%s", groupName, err.Error())

			return models.NewAccount()
		}

		// for creating the group channel for the first time, we should not return
		// here with empty account
		return acc
	}

	if err := makeSureMembership(groupChannel, acc.Id); err != nil {
		runner.MustGetLogger().Error("Err while making sure account: %s, err :%s", groupName, err.Error())
		return models.NewAccount()
	}

	return acc
}
예제 #9
0
func (f *Controller) handleParticipantOperation(p *models.ChannelParticipant) error {
	if p.ChannelId == 0 {
		f.log.Info("channel id is 0, data: %+v", p)
		return nil
	}

	if p.AccountId == 0 {
		f.log.Info("account id is 0, data: %+v", p)
		return nil
	}

	// fetch account from database
	a := models.NewAccount()
	if err := a.ById(p.AccountId); err != nil {
		f.log.Error("err while fetching account: %s", err.Error())
		return nil
	}

	if a.Id == 0 {
		f.log.Critical("account found but id is 0 %+v", a)
		return nil
	}

	channelId := strconv.FormatInt(p.ChannelId, 10)
	if channelId == "" {
		f.log.Error("Channel Participant has malformed data %+v", p)
		return nil
	}

	tagMap := addUniqueTagMap(channelId) // as default add the new channel to tags

	// if status of the participant is not active remove it from user
	if p.StatusConstant != models.ChannelParticipant_STATUS_ACTIVE {
		tagMap = removeTagMap(channelId)
	}

	cleanupGuest := true
	return f.handleAccount(a, cleanupGuest, tagMap)
}
예제 #10
0
func (mwc *Controller) AccountIdByOldId(oldId string) (int64, error) {
	acc, err := models.Cache.Account.ByOldId(oldId)
	if err == nil {
		return acc.Id, nil
	}

	acc1, err := modelhelper.GetAccountById(oldId)
	if err != nil {
		return 0, fmt.Errorf("Participant account %s cannot be fetched: %s", oldId, err)
	}

	a := models.NewAccount()
	a.OldId = oldId
	a.Nick = acc1.Profile.Nickname
	if err := a.FetchOrCreate(); err != nil {
		return 0, err
	}

	if err := models.Cache.Account.SetToCache(a); err != nil {
		return 0, err
	}

	return a.Id, nil
}
예제 #11
0
func TestPinnedActivityChannel(t *testing.T) {
	tests.WithRunner(t, func(r *runner.Runner) {

		SkipConvey("while  testing pinned activity channel", t, func() {
			groupName := models.RandomGroupName()

			account := models.NewAccount()
			account.OldId = AccountOldId.Hex()
			account, err := rest.CreateAccount(account)
			So(err, ShouldBeNil)
			So(account, ShouldNotBeNil)
			So(account.Id, ShouldNotEqual, 0)

			ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
			So(err, ShouldBeNil)
			So(ses, ShouldNotBeNil)

			nonOwnerAccount := models.NewAccount()
			nonOwnerAccount.OldId = AccountOldId.Hex()
			nonOwnerAccount, err = rest.CreateAccount(nonOwnerAccount)
			So(err, ShouldBeNil)
			So(nonOwnerAccount, ShouldNotBeNil)

			nonOwnerSes, err := modelhelper.FetchOrCreateSession(nonOwnerAccount.Nick, groupName)
			So(err, ShouldBeNil)
			So(nonOwnerSes, ShouldNotBeNil)

			groupChannel, err := rest.CreateChannelByGroupNameAndType(
				account.Id,
				groupName,
				models.Channel_TYPE_GROUP,
				ses.ClientId,
			)
			So(err, ShouldBeNil)
			So(groupChannel, ShouldNotBeNil)

			post, err := rest.CreatePost(groupChannel.Id, ses.ClientId)
			So(err, ShouldBeNil)
			So(post, ShouldNotBeNil)

			Convey("requester should have one", func() {
				account := account
				channel, err := rest.FetchPinnedActivityChannel(account.Id, groupName)
				So(err, ShouldBeNil)
				So(channel, ShouldNotBeNil)
				So(channel.Id, ShouldNotEqual, 0)
				So(channel.TypeConstant, ShouldEqual, models.Channel_TYPE_PINNED_ACTIVITY)
				So(channel.CreatorId, ShouldEqual, account.Id)
			})

			Convey("owner should be able to update it", nil)

			Convey("non-owner should not be able to update it", nil)

			Convey("owner should not be able to add new participants into it", func() {
				channel, err := rest.FetchPinnedActivityChannel(account.Id, groupName)
				So(err, ShouldBeNil)
				So(channel, ShouldNotBeNil)
				channelParticipant, err := rest.AddChannelParticipant(channel.Id, ses.ClientId, nonOwnerAccount.Id)
				// there should be an err
				So(err, ShouldNotBeNil)
				// channel should be nil
				So(channelParticipant, ShouldBeNil)
			})

			Convey("normal user shouldnt be able to add new participants to it", func() {
				channel, err := rest.FetchPinnedActivityChannel(account.Id, groupName)
				So(err, ShouldBeNil)
				So(channel, ShouldNotBeNil)
				channelParticipant, err := rest.AddChannelParticipant(channel.Id, nonOwnerSes.ClientId, nonOwnerAccount.Id)
				// there should be an err
				So(err, ShouldNotBeNil)
				// channel should be nil
				So(channelParticipant, ShouldBeNil)
			})

			Convey("owner should  not be able to remove participant from it", func() {
				channel, err := rest.FetchPinnedActivityChannel(account.Id, groupName)
				So(err, ShouldBeNil)
				So(channel, ShouldNotBeNil)
				channelParticipant, err := rest.DeleteChannelParticipant(channel.Id, ses.ClientId, nonOwnerAccount.Id)
				// there should be an err
				So(err, ShouldNotBeNil)
				// channel should be nil
				So(channelParticipant, ShouldBeNil)
			})

			Convey("normal user shouldnt be able to remove participants from it", func() {
				channel, err := rest.FetchPinnedActivityChannel(account.Id, groupName)
				So(err, ShouldBeNil)
				So(channel, ShouldNotBeNil)
				channelParticipant, err := rest.DeleteChannelParticipant(channel.Id, nonOwnerSes.ClientId, nonOwnerAccount.Id)
				// there should be an err
				So(err, ShouldNotBeNil)
				// channel should be nil
				So(channelParticipant, ShouldBeNil)
			})

			Convey("owner should be able to add new message into it", func() {
				_, err := rest.AddPinnedMessage(account.Id, post.Id, "koding")
				// there should be an err
				So(err, ShouldBeNil)

				_, err = rest.RemovePinnedMessage(account.Id, post.Id, "koding")
				So(err, ShouldBeNil)

			})

			Convey("owner should be able to list messages", func() {
				groupName := "testgroup" + strconv.FormatInt(rand.Int63(), 10)

				pinnedChannel, err := rest.FetchPinnedActivityChannel(account.Id, groupName)
				So(err, ShouldBeNil)
				So(pinnedChannel, ShouldNotBeNil)

				groupChannel, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_DEFAULT,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(groupChannel, ShouldNotBeNil)

				post1, err := rest.CreatePostWithBody(groupChannel.Id, nonOwnerAccount.Id, "create a message #1times")
				So(err, ShouldBeNil)
				So(post1, ShouldNotBeNil)

				_, err = rest.AddPinnedMessage(nonOwnerAccount.Id, post1.Id, groupName)
				// there should be an err
				So(err, ShouldBeNil)

				post2, err := rest.CreatePostWithBody(groupChannel.Id, nonOwnerAccount.Id, "create a message #1another")
				So(err, ShouldBeNil)
				So(post2, ShouldNotBeNil)

				_, err = rest.AddPinnedMessage(nonOwnerAccount.Id, post2.Id, groupName)
				// there should be an err
				So(err, ShouldBeNil)

				//time.Sleep(time.Second * 5)

				history, err := rest.FetchPinnedMessages(account.Id, groupName)
				// there should be an err
				So(err, ShouldBeNil)
				// channel should be nil
				So(history, ShouldNotBeNil)

				// message count should be 2
				So(len(history.MessageList), ShouldEqual, 2)

				// unread count should be 0
				So(history.UnreadCount, ShouldEqual, 0)

				// old id should be the same one
				So(history.MessageList[0].AccountOldId, ShouldContainSubstring, nonOwnerAccount.OldId)

				// replies count should be 0
				So(len(history.MessageList[0].Replies), ShouldEqual, 0)
			})

			Convey("Messages shouldnt be added as pinned twice ", func() {
				// use account id as message id
				_, err := rest.AddPinnedMessage(account.Id, post.Id, "koding")
				// there should be an err
				So(err, ShouldBeNil)
				// use account id as message id, pin message is idempotent, if it is
				// in the channel, wont give error
				_, err = rest.AddPinnedMessage(account.Id, post.Id, "koding")
				// there should not be an err
				So(err, ShouldBeNil)
			})

			Convey("Non-exist message should not be added as pinned ", nil)

		})
	})
}
예제 #12
0
func TestCollaboration(t *testing.T) {
	r := runner.New("collaboration-tests")
	err := r.Init()
	if err != nil {
		panic(err)
	}

	defer r.Close()

	appConfig := config.MustRead(r.Conf.Path)

	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	// init with defaults
	mongoCache := cache.NewMongoCacheWithTTL(modelhelper.Mongo.Session)
	defer mongoCache.StopGC()

	handler := New(r.Log, mongoCache, appConfig, r.Kite)

	Convey("while pinging collaboration", t, func() {
		// owner
		owner := apimodels.NewAccount()
		owner.OldId = AccountOldId.Hex()
		owner, err := rest.CreateAccount(owner)
		So(err, ShouldBeNil)
		So(owner, ShouldNotBeNil)

		groupName := apimodels.RandomGroupName()

		ownerSession, err := modelhelper.FetchOrCreateSession(owner.Nick, groupName)
		So(err, ShouldBeNil)
		So(ownerSession, ShouldNotBeNil)

		rand.Seed(time.Now().UnixNano())

		req := &models.Ping{
			AccountId: 1,
			FileId:    fmt.Sprintf("%d", rand.Int63()),
		}

		Convey("while testing Ping", func() {
			Convey("reponse should be success with valid ping", func() {
				err = handler.Ping(req)
				So(err, ShouldBeNil)
			})

			Convey("reponse should be success with invalid FileId", func() {
				req.FileId = ""
				err = handler.Ping(req)
				So(err, ShouldBeNil)
			})

			Convey("reponse should be success with invalid AccountId", func() {
				req.AccountId = 0
				err = handler.Ping(req)
				So(err, ShouldBeNil)
			})

			Convey("reponse should be success with invalid session", func() {
				req := req
				// prepare an invalid session here
				req.CreatedAt = time.Now().UTC()

				err = mongoCache.SetEx(PrepareFileKey(req.FileId), ExpireSessionKeyDuration, req.CreatedAt.Add(-terminateSessionDuration))

				err = handler.Ping(req)
				So(err, ShouldBeNil)
			})

			Convey("after sleep time", func() {
				req := req

				Convey("expired session should get invalidSessoin", func() {
					st := sleepTime
					sleepTime = time.Millisecond * 110

					tsd := terminateSessionDuration
					terminateSessionDuration = 100

					// set durations back to the original value
					defer func() {
						sleepTime = st
						terminateSessionDuration = tsd
					}()

					req.CreatedAt = time.Now().UTC()
					// prepare a valid key
					err = mongoCache.SetEx(
						PrepareFileKey(req.FileId),
						terminateSessionDuration, // expire the key after this period
						req.CreatedAt.Unix())

					// while sleeping here, redis key should be removed
					// and we can understand that the Collab session is expired
					time.Sleep(sleepTime)

					req := req
					err = handler.wait(req)
					So(err, ShouldEqual, errSessionInvalid)
				})

				Convey("deadlined session should get errDeadlineReached", func() {
					st := sleepTime
					sleepTime = time.Millisecond * 110

					dd := deadLineDuration
					deadLineDuration = 100

					// set durations back to the original value
					defer func() {
						sleepTime = st
						deadLineDuration = dd
					}()

					req := req
					err := handler.wait(req)
					So(err, ShouldEqual, errDeadlineReached)
				})
			})
		})

		Convey("while testing checkIfKeyIsValid", func() {

			req := req
			req.CreatedAt = time.Now().UTC()

			// prepare a valid key
			err := mongoCache.SetEx(
				PrepareFileKey(req.FileId),
				ExpireSessionKeyDuration, // expire the key after this period
				req.CreatedAt.Unix(),     // value - unix time
			)

			So(err, ShouldBeNil)

			Convey("valid key should return nil", func() {
				err = handler.checkIfKeyIsValid(req)
				So(err, ShouldBeNil)
			})

			Convey("invalid key should return errSessionInvalid", func() {
				req := req
				// override fileId
				req.FileId = fmt.Sprintf("%d", rand.Int63())
				err = handler.checkIfKeyIsValid(req)
				So(err, ShouldEqual, errSessionInvalid)
			})

			Convey("invalid (non-timestamp) value should return errSessionInvalid", func() {
				req := req
				req.CreatedAt = time.Now().UTC()
				err = mongoCache.SetEx(
					PrepareFileKey(req.FileId),
					ExpireSessionKeyDuration, // expire the key after this period
					"req.CreatedAt.Unix()",   // replace timestamp with unix time
				)

				err = handler.checkIfKeyIsValid(req)

				So(err, ShouldEqual, errSessionInvalid)
			})

			Convey("old ping time should return errSessionInvalid", func() {
				req := req
				req.CreatedAt = time.Now().UTC()
				err = mongoCache.SetEx(
					PrepareFileKey(req.FileId),
					ExpireSessionKeyDuration, // expire the key after this period
					req.CreatedAt.Add(-terminateSessionDuration).Unix(),
				)

				err = handler.checkIfKeyIsValid(req)
				So(err, ShouldEqual, errSessionInvalid)
			})

			Convey("previous ping time is in safe area", func() {
				req := req
				testPingTimes(req, -1, mongoCache, handler, nil)
			})

			Convey("0 ping time is in safe area", func() {
				req := req
				testPingTimes(req, 0, mongoCache, handler, nil)
			})

			Convey("2 ping time is in safe area", func() {
				req := req
				testPingTimes(req, 2, mongoCache, handler, nil)
			})

			Convey("3 ping time is in safe area", func() {
				req := req
				testPingTimes(req, 3, mongoCache, handler, nil)
			})

			Convey("4 ping time is not in safe area - because we already reverted the time ", func() {
				req := req
				testPingTimes(req, 4, mongoCache, handler, errSessionInvalid)
			})

			Convey("5 ping time is not in safe area ", func() {
				req := req
				testPingTimes(req, 5, mongoCache, handler, errSessionInvalid)
			})
		})
	})
}
예제 #13
0
func TestCollaborationDriveService(t *testing.T) {
	r := runner.New("collaboration-drive-tests")
	err := r.Init()
	if err != nil {
		panic(err)
	}

	defer r.Close()

	appConfig := config.MustRead(r.Conf.Path)
	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	// init with defaults
	mongoCache := cache.NewMongoCacheWithTTL(modelhelper.Mongo.Session)
	defer mongoCache.StopGC()

	handler := New(r.Log, mongoCache, appConfig, r.Kite)

	SkipConvey("while pinging collaboration", t, func() {
		// owner
		owner := apimodels.NewAccount()
		owner.OldId = AccountOldId.Hex()
		owner, err := rest.CreateAccount(owner)
		So(err, ShouldBeNil)
		So(owner, ShouldNotBeNil)

		groupName := apimodels.RandomGroupName()

		ownerSession, err := modelhelper.FetchOrCreateSession(owner.Nick, groupName)
		So(err, ShouldBeNil)
		So(ownerSession, ShouldNotBeNil)

		rand.Seed(time.Now().UnixNano())

		req := &models.Ping{
			AccountId: 1,
			FileId:    fmt.Sprintf("%d", rand.Int63()),
		}

		Convey("while testing drive operations", func() {
			req := req
			req.CreatedAt = time.Now().UTC()
			Convey("should be able to create the file", func() {
				f, err := createTestFile(handler)
				if err != nil {
					t.Skip("Err happened, skipping: %s", err.Error())
				}

				req.FileId = f.Id
				Convey("should be able to get the created file", func() {
					f2, err := handler.getFile(f.Id)
					if err != nil {
						t.Skip("Err happened, skipping: %s", err.Error())
					}

					So(f2, ShouldNotBeNil)

					Convey("should be able to delete the created file", func() {
						err = handler.deleteFile(req.FileId)
						if err != nil {
							t.Skip("Err happened, skipping: %s", err.Error())
						}

						Convey("should not be able to get the deleted file", func() {
							deadLine := time.After(TestTimeout)
							tick := time.Tick(time.Millisecond * 100)
							for {
								select {
								case <-tick:
									f2, err := handler.getFile(f.Id)
									if err != nil {
										t.Skip("Err happened, skipping: %s", err.Error())
									}

									So(f2, ShouldBeNil)
								case <-deadLine:
									t.Skip("Could not get file after %s", TestTimeout)
								}
							}
						})
						Convey("deleting the deleted file should not give error", func() {
							err = handler.deleteFile(req.FileId)
							if err != nil {
								t.Skip("Err happened, skipping: %s", err.Error())
							}

							So(err, ShouldBeNil)
						})
					})
				})
			})
		})
	})
}
예제 #14
0
func TestChannelCreation(t *testing.T) {
	tests.WithRunner(t, func(r *runner.Runner) {
		Convey("while  testing channel", t, func() {
			Convey("First Create Users", func() {
				account, err := models.CreateAccountInBothDbs()
				So(err, ShouldBeNil)

				groupName := models.RandomGroupName()

				ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
				So(err, ShouldBeNil)
				So(ses, ShouldNotBeNil)

				groupChannel := models.CreateTypedGroupedChannelWithTest(
					account.Id,
					models.Channel_TYPE_GROUP,
					groupName,
				)

				So(err, ShouldBeNil)
				So(groupChannel, ShouldNotBeNil)

				nonOwnerAccount := models.NewAccount()
				nonOwnerAccount.OldId = AccountOldId2.Hex()
				nonOwnerAccount, err = rest.CreateAccount(nonOwnerAccount)
				So(err, ShouldBeNil)
				So(nonOwnerAccount, ShouldNotBeNil)

				noses, err := modelhelper.FetchOrCreateSession(
					nonOwnerAccount.Nick,
					groupName,
				)

				So(err, ShouldBeNil)
				So(noses, ShouldNotBeNil)

				Convey("we should be able to create it", func() {
					channel1, err := rest.CreateChannelByGroupNameAndType(
						account.Id,
						groupName,
						models.Channel_TYPE_PRIVATE_MESSAGE,
						ses.ClientId,
					)
					So(err, ShouldBeNil)
					So(channel1, ShouldNotBeNil)

					_, err = rest.AddChannelParticipant(channel1.Id, ses.ClientId, account.Id)
					So(err, ShouldBeNil)

					Convey("owner should be able to update it", func() {
						updatedPurpose := "another purpose from the paradise"
						channel1.Purpose = updatedPurpose

						channel2, err := rest.UpdateChannel(channel1, ses.ClientId)
						So(err, ShouldBeNil)
						So(channel2, ShouldNotBeNil)

						So(channel1.Purpose, ShouldEqual, channel1.Purpose)

						Convey("owner should be able to update payload", func() {
							if channel1.Payload == nil {
								channel1.Payload = gorm.Hstore{}
							}

							value := "value"
							channel1.Payload = gorm.Hstore{
								"key": &value,
							}
							channel2, err := rest.UpdateChannel(channel1, ses.ClientId)
							So(err, ShouldBeNil)
							So(channel2, ShouldNotBeNil)
							So(channel1.Payload, ShouldNotBeNil)
							So(*channel1.Payload["key"], ShouldEqual, value)
						})
					})
					Convey("participant should be able to update only purpose, not name or payload", func() {
						_, err = rest.AddChannelParticipant(channel1.Id, ses.ClientId, nonOwnerAccount.Id)
						So(err, ShouldBeNil)

						updatedPurpose := "ChannelPurposeUpdated"
						updatedName := "ChannelNameUpdated"
						channel1.Name = updatedName
						channel1.Purpose = updatedPurpose

						channel2, err := rest.UpdateChannel(channel1, noses.ClientId)
						So(err, ShouldBeNil)
						So(channel2, ShouldNotBeNil)
						So(channel2.Name, ShouldNotBeNil)
						// participant cannot update channel name
						// can update only purpose of the channel
						So(channel2.Name, ShouldNotEqual, updatedName)
						So(channel2.Purpose, ShouldEqual, updatedPurpose)
					})

					Convey("owner should be get channel by name", func() {
						channel2, err := rest.FetchChannelByName(
							account.Id,
							channel1.Name,
							channel1.GroupName,
							channel1.TypeConstant,
							ses.ClientId,
						)
						So(err, ShouldBeNil)
						So(channel2, ShouldNotBeNil)
						So(channel1.Id, ShouldEqual, channel2.Id)
						So(channel1.Name, ShouldEqual, channel2.Name)
						So(channel1.GroupName, ShouldEqual, channel2.GroupName)
						So(channel1.GroupName, ShouldEqual, channel2.GroupName)
					})

					Convey("unread count should be set", func() {
						channelContainer, err := rest.FetchChannelContainerByName(account.Id, channel1.Name, channel1.GroupName, channel1.TypeConstant, ses.ClientId)
						So(err, ShouldBeNil)
						So(channelContainer, ShouldNotBeNil)
						So(channelContainer.UnreadCount, ShouldEqual, 0)

						post, err := rest.CreatePost(channel1.Id, ses.ClientId)
						So(err, ShouldBeNil)
						So(post, ShouldNotBeNil)

						channelContainer, err = rest.FetchChannelContainerByName(account.Id, channel1.Name, channel1.GroupName, channel1.TypeConstant, ses.ClientId)
						So(err, ShouldBeNil)
						So(channelContainer, ShouldNotBeNil)
						So(channelContainer.UnreadCount, ShouldEqual, 1)
					})

					Convey("non-owner should not be able to update it", func() {
						updatedPurpose := "another purpose from the paradise"
						channel1.Purpose = updatedPurpose
						channel1.CreatorId = nonOwnerAccount.Id

						channel2, err := rest.UpdateChannel(channel1, noses.ClientId)
						So(err, ShouldNotBeNil)
						So(channel2, ShouldBeNil)
					})

					Convey("non-owner should not be able to get channel by name", func() {
						_, err := rest.FetchChannelByName(
							nonOwnerAccount.Id,
							channel1.Name,
							channel1.GroupName,
							channel1.TypeConstant,
							noses.ClientId,
						)
						So(err, ShouldNotBeNil)
					})

				})

				Convey("normal user shouldnt be able to add new participants to pinned activity channel", func() {
					channel1, err := rest.CreateChannelByGroupNameAndType(
						account.Id,
						groupName,
						models.Channel_TYPE_PINNED_ACTIVITY,
						ses.ClientId,
					)
					So(err, ShouldBeNil)
					So(channel1, ShouldNotBeNil)

					channelParticipant, err := rest.AddChannelParticipant(channel1.Id, noses.ClientId, nonOwnerAccount.Id)
					// there should be an err
					So(err, ShouldNotBeNil)
					// channel should be nil
					So(channelParticipant, ShouldBeNil)
				})

				Convey("owner should be able list participants", func() {
					channel1, err := rest.CreateChannelByGroupNameAndType(
						account.Id,
						groupName,
						models.Channel_TYPE_DEFAULT,
						ses.ClientId,
					)
					So(err, ShouldBeNil)
					So(channel1, ShouldNotBeNil)

					// add first participant
					channelParticipant1, err := rest.AddChannelParticipant(channel1.Id, ses.ClientId, nonOwnerAccount.Id)
					// there should be an err
					So(err, ShouldBeNil)
					// channel should be nil
					So(channelParticipant1, ShouldNotBeNil)

					nonOwnerAccount2 := models.NewAccount()
					nonOwnerAccount2.OldId = AccountOldId3.Hex()
					nonOwnerAccount2, err = rest.CreateAccount(nonOwnerAccount2)
					So(err, ShouldBeNil)
					So(nonOwnerAccount2, ShouldNotBeNil)

					channelParticipant2, err := rest.AddChannelParticipant(channel1.Id, ses.ClientId, nonOwnerAccount2.Id)
					// there should be an err
					So(err, ShouldBeNil)
					// channel should be nil
					So(channelParticipant2, ShouldNotBeNil)

					participants, err := rest.ListChannelParticipants(channel1.Id, ses.ClientId)
					// there should be an err
					So(err, ShouldBeNil)
					So(participants, ShouldNotBeNil)

					// owner
					// nonOwner1
					// nonOwner2
					So(len(participants), ShouldEqual, 3)
				})

				Convey("normal user should be able to list participants", func() {
					channel1, err := rest.CreateChannelByGroupNameAndType(
						account.Id,
						groupName,
						models.Channel_TYPE_DEFAULT,
						ses.ClientId,
					)
					So(err, ShouldBeNil)
					So(channel1, ShouldNotBeNil)

					// add first participant
					channelParticipant1, err := rest.AddChannelParticipant(channel1.Id, ses.ClientId, nonOwnerAccount.Id)
					// there should be an err
					So(err, ShouldBeNil)
					// channel should be nil
					So(channelParticipant1, ShouldNotBeNil)

					nonOwnerAccount2 := models.NewAccount()
					nonOwnerAccount2.OldId = AccountOldId3.Hex()
					nonOwnerAccount2, err = rest.CreateAccount(nonOwnerAccount2)
					So(err, ShouldBeNil)
					So(nonOwnerAccount2, ShouldNotBeNil)

					nonOwnerSes2, err := modelhelper.FetchOrCreateSession(nonOwnerAccount2.Nick, groupName)
					So(err, ShouldBeNil)
					So(nonOwnerSes2, ShouldNotBeNil)

					channelParticipant2, err := rest.AddChannelParticipant(channel1.Id, ses.ClientId, nonOwnerAccount2.Id)
					// there should be an err
					So(err, ShouldBeNil)
					// channel should be nil
					So(channelParticipant2, ShouldNotBeNil)

					participants, err := rest.ListChannelParticipants(channel1.Id, nonOwnerSes2.ClientId)
					// there should be an err
					So(err, ShouldBeNil)
					So(participants, ShouldNotBeNil)

					// owner
					// nonOwner1
					// nonOwner2
					So(len(participants), ShouldEqual, 3)
				})
			})
		})
	})
}
예제 #15
0
func TestChannelParticipantOperations(t *testing.T) {
	tests.WithRunner(t, func(r *runner.Runner) {
		Convey("while testing channel participants", t, func() {
			Convey("First Create Users and initiate conversation", func() {
				ownerAccount, groupChannel, groupName := models.CreateRandomGroupDataWithChecks()

				ownerSes, err := modelhelper.FetchOrCreateSession(ownerAccount.Nick, groupName)
				So(err, ShouldBeNil)
				So(ownerSes, ShouldNotBeNil)

				secondAccount, err := models.CreateAccountInBothDbs()
				tests.ResultedWithNoErrorCheck(secondAccount, err)
				_, err = groupChannel.AddParticipant(secondAccount.Id)
				So(err, ShouldBeNil)

				thirdAccount, err := models.CreateAccountInBothDbs()
				tests.ResultedWithNoErrorCheck(thirdAccount, err)
				_, err = groupChannel.AddParticipant(thirdAccount.Id)
				So(err, ShouldBeNil)

				forthAccount, err := models.CreateAccountInBothDbs()
				tests.ResultedWithNoErrorCheck(forthAccount, err)
				_, err = groupChannel.AddParticipant(forthAccount.Id)
				So(err, ShouldBeNil)

				devrim, err := models.CreateAccountInBothDbsWithNick("devrim")
				tests.ResultedWithNoErrorCheck(devrim, err)
				_, err = groupChannel.AddParticipant(devrim.Id)
				So(err, ShouldBeNil)

				ses, err := modelhelper.FetchOrCreateSession(ownerAccount.Nick, groupName)
				tests.ResultedWithNoErrorCheck(ses, err)

				secondSes, err := modelhelper.FetchOrCreateSession(secondAccount.Nick, groupName)
				tests.ResultedWithNoErrorCheck(secondSes, err)

				pmr := models.ChannelRequest{}

				pmr.AccountId = ownerAccount.Id

				pmr.Body = "new conversation"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim"}

				channelContainer, err := rest.SendPrivateChannelRequest(pmr, ownerSes.ClientId)
				So(err, ShouldBeNil)
				So(channelContainer, ShouldNotBeNil)

				Convey("First user should be able to add second and third users to conversation", func() {
					_, err = rest.AddChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id, thirdAccount.Id)
					So(err, ShouldBeNil)
					participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
					So(err, ShouldBeNil)
					So(participants, ShouldNotBeNil)
					// it is four because first user is "devrim" here
					So(len(participants), ShouldEqual, 4)

					Convey("First user should not be able to re-add second participant", func() {
						_, err = rest.AddChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id)
						So(err, ShouldBeNil)

						participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
						So(err, ShouldBeNil)
						So(participants, ShouldNotBeNil)
						So(len(participants), ShouldEqual, 4)
					})

					Convey("Second user should be able to leave conversation", func() {
						// token of account -> secondAccount
						_, err = rest.DeleteChannelParticipant(channelContainer.Channel.Id, secondSes.ClientId, secondAccount.Id)
						So(err, ShouldBeNil)

						participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
						So(err, ShouldBeNil)
						So(participants, ShouldNotBeNil)
						So(len(participants), ShouldEqual, 3)

						Convey("A user who is not participant of a conversation should not be able to add another user to the conversation", func() {
							_, err = rest.AddChannelParticipant(channelContainer.Channel.Id, secondSes.ClientId, forthAccount.Id)
							So(err, ShouldNotBeNil)

							participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
							So(err, ShouldBeNil)
							So(participants, ShouldNotBeNil)
							So(len(participants), ShouldEqual, 3)
						})
					})

					Convey("Channel owner should be able to kick another conversation participant", func() {
						_, err = rest.DeleteChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id)
						So(err, ShouldBeNil)

						participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
						So(err, ShouldBeNil)
						So(participants, ShouldNotBeNil)
						So(len(participants), ShouldEqual, 3)
					})

					Convey("when a user is blocked", func() {
						_, err = rest.BlockChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id)
						So(err, ShouldBeNil)

						Convey("it should not be in channel participant list", func() {
							participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
							So(err, ShouldBeNil)
							So(participants, ShouldNotBeNil)
							So(len(participants), ShouldEqual, 3)
						})

						Convey("should not be able to add it back", func() {
							_, err = rest.AddChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id)
							So(err, ShouldNotBeNil)
						})

						Convey("should be able to unblock", func() {
							_, err = rest.UnblockChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id)
							So(err, ShouldBeNil)

							Convey("it should not be in channel participant list still", func() {
								participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
								So(err, ShouldBeNil)
								So(participants, ShouldNotBeNil)
								So(len(participants), ShouldEqual, 3)
							})

							Convey("when we add the same user as participant", func() {
								_, err = rest.AddChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id, thirdAccount.Id)
								So(err, ShouldBeNil)

								Convey("it should be in channel participant list", func() {
									participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
									So(err, ShouldBeNil)
									So(participants, ShouldNotBeNil)
									So(len(participants), ShouldEqual, 4)
								})
							})
						})
					})

					Convey("Second user should not be able to kick another conversation participant", func() {
						_, err = rest.DeleteChannelParticipant(channelContainer.Channel.Id, secondSes.ClientId, thirdAccount.Id)
						So(err, ShouldNotBeNil)
					})

				})
				Convey("First user should be able to invite second user", func() {
					_, err = rest.InviteChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, secondAccount.Id)
					So(err, ShouldBeNil)
					participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
					So(err, ShouldBeNil)
					So(participants, ShouldNotBeNil)
					// it is four because first user is "devrim" here
					So(len(participants), ShouldEqual, 2)

					Convey("Second user should be able to reject invitation", func() {
						ses, err := modelhelper.FetchOrCreateSession(secondAccount.Nick, groupName)
						So(err, ShouldBeNil)
						So(ses, ShouldNotBeNil)

						err = rest.RejectInvitation(channelContainer.Channel.Id, ses.ClientId)
						So(err, ShouldBeNil)

						participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
						So(err, ShouldBeNil)
						So(participants, ShouldNotBeNil)
						So(len(participants), ShouldEqual, 2)
					})

					Convey("Second user should be able to accept invitation", func() {
						ses, err := modelhelper.FetchOrCreateSession(secondAccount.Nick, groupName)
						So(err, ShouldBeNil)
						So(ses, ShouldNotBeNil)

						err = rest.AcceptInvitation(channelContainer.Channel.Id, ses.ClientId)
						So(err, ShouldBeNil)

						participants, err := rest.ListChannelParticipants(channelContainer.Channel.Id, ownerSes.ClientId)
						So(err, ShouldBeNil)
						So(participants, ShouldNotBeNil)
						So(len(participants), ShouldEqual, 3)
					})
				})

				// TODO Until we find a better way for handling async stuff, this test is skipped. Instead of sleep, we should use some
				// timeouts for testing these kind of stuff.
				SkipConvey("All private messages must be deleted when all participant users leave the channel", func() {
					account := models.NewAccount()
					err = account.ByNick("devrim")
					So(err, ShouldBeNil)

					_, err = rest.DeleteChannelParticipant(channelContainer.Channel.Id, ses.ClientId, account.Id)
					So(err, ShouldBeNil)

					_, err = rest.DeleteChannelParticipant(channelContainer.Channel.Id, ownerSes.ClientId, ownerAccount.Id)
					So(err, ShouldBeNil)

					time.Sleep(1 * time.Second)

					testChannel := models.NewChannel()
					err := testChannel.ById(channelContainer.Channel.Id)
					So(err, ShouldEqual, bongo.RecordNotFound)

					testChannelList := models.NewChannelMessageList()
					err = bongo.B.Unscoped().Where("channel_id = ?", channelContainer.Channel.Id).Find(testChannelList).Error
					So(err, ShouldEqual, bongo.RecordNotFound)

					testMessage := models.NewChannelMessage()
					err = bongo.B.Unscoped().Where("initial_channel_id = ?", channelContainer.Channel.Id).Find(testMessage).Error
					So(err, ShouldEqual, bongo.RecordNotFound)
				})
				Convey("Users should not be able to add/remove users to/from bot channels", func() {
					ownerAccount, _, groupName := models.CreateRandomGroupDataWithChecks()

					participant := models.NewAccount()
					participant.OldId = AccountOldId.Hex()
					participant, err = rest.CreateAccount(participant)
					So(err, ShouldBeNil)
					So(participant, ShouldNotBeNil)

					ses, err := modelhelper.FetchOrCreateSession(ownerAccount.Nick, groupName)
					So(err, ShouldBeNil)

					ch, err := rest.CreateChannelByGroupNameAndType(ownerAccount.Id, groupName, models.Channel_TYPE_BOT, ses.ClientId)
					So(err, ShouldBeNil)
					So(ch, ShouldNotBeNil)

					// account is -> ownerAccount.Id
					_, err = rest.AddChannelParticipant(ch.Id, ses.ClientId, participant.Id)
					So(strings.Contains(err.Error(), "can not add participants for bot channel"), ShouldBeTrue)
				})

				Convey("Users should be able to add/remove users to/from topic channels", func() {
					ownerAccount, _, groupName := models.CreateRandomGroupDataWithChecks()

					participant := models.NewAccount()
					participant.OldId = AccountOldId.Hex()
					participant, err = rest.CreateAccount(participant)
					So(err, ShouldBeNil)
					So(participant, ShouldNotBeNil)

					ses, err := modelhelper.FetchOrCreateSession(ownerAccount.Nick, groupName)
					So(err, ShouldBeNil)

					ch, err := rest.CreateChannelByGroupNameAndType(ownerAccount.Id, groupName, models.Channel_TYPE_TOPIC, ses.ClientId)
					So(err, ShouldBeNil)
					So(ch, ShouldNotBeNil)

					// account is -> ownerAccount.Id
					_, err = rest.AddChannelParticipant(ch.Id, ses.ClientId, participant.Id)
					So(err, ShouldBeNil)

					Convey("adding same user again should success", func() {
						_, err = rest.AddChannelParticipant(ch.Id, ses.ClientId, participant.Id)
						So(err, ShouldBeNil)
					})

					_, err = rest.DeleteChannelParticipant(ch.Id, ses.ClientId, participant.Id)
					So(err, ShouldBeNil)

					Convey("removing same user again should success", func() {
						_, err = rest.DeleteChannelParticipant(ch.Id, ses.ClientId, participant.Id)
						So(err, ShouldBeNil)
					})
				})
				Convey("while removing users from group channels", func() {
					ownerAccount, _, groupName := models.CreateRandomGroupDataWithChecks()

					participant := models.NewAccount()
					participant.OldId = AccountOldId.Hex()
					participant, err = rest.CreateAccount(participant)
					So(err, ShouldBeNil)
					So(participant, ShouldNotBeNil)

					participant2 := models.NewAccount()
					participant2.OldId = AccountOldId.Hex()
					participant2, err = rest.CreateAccount(participant2)
					So(err, ShouldBeNil)
					So(participant2, ShouldNotBeNil)

					ownerSes, err := modelhelper.FetchOrCreateSession(ownerAccount.Nick, groupName)
					So(err, ShouldBeNil)

					ses, err := modelhelper.FetchOrCreateSession(participant.Nick, groupName)
					So(err, ShouldBeNil)

					ch, err := rest.CreateChannelByGroupNameAndType(ownerAccount.Id, groupName, models.Channel_TYPE_GROUP, ownerSes.ClientId)
					So(err, ShouldBeNil)
					So(ch, ShouldNotBeNil)

					// ownerSes session is admin's session data
					_, err = rest.AddChannelParticipant(ch.Id, ownerSes.ClientId, participant.Id)
					So(err, ShouldBeNil)

					_, err = rest.AddChannelParticipant(ch.Id, ownerSes.ClientId, participant2.Id)
					So(err, ShouldBeNil)
					Convey("owner should  be able to remove user from group channel", func() {
						// ownerSes session is admin's session data
						_, err = rest.DeleteChannelParticipant(ch.Id, ownerSes.ClientId, participant2.Id)
						So(err, ShouldBeNil)
					})

					Convey("nonOwner should not be able to remove user from group channel", func() {
						// ses session is participant's session data
						_, err = rest.DeleteChannelParticipant(ch.Id, ses.ClientId, participant2.Id)
						So(err, ShouldNotBeNil)
					})
				})
			})
		})
	})
}
예제 #16
0
func TestGroupChannel(t *testing.T) {
	tests.WithRunner(t, func(r *runner.Runner) {
		Convey("while  testing pinned activity channel", t, func() {
			groupName := models.RandomGroupName()

			account, err := models.CreateAccountInBothDbs()
			So(err, ShouldBeNil)

			ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
			So(err, ShouldBeNil)
			So(ses, ShouldNotBeNil)

			models.CreateTypedGroupedChannelWithTest(
				account.Id,
				models.Channel_TYPE_GROUP,
				groupName,
			)

			Convey("channel should be there", func() {
				channel1, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_GROUP,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(channel1, ShouldNotBeNil)

				channel2, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_GROUP,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(channel2, ShouldNotBeNil)
			})

			Convey("group channel should be shown before announcement", func() {
				account, err := models.CreateAccountInBothDbs()
				So(err, ShouldBeNil)

				ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
				So(err, ShouldBeNil)
				So(ses, ShouldNotBeNil)

				_, err = rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_GROUP,
					ses.ClientId,
				)
				So(err, ShouldBeNil)

				_, err = rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_ANNOUNCEMENT,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				channels, err := rest.FetchChannelsByQuery(account.Id, &request.Query{
					GroupName: groupName,
					Type:      models.Channel_TYPE_GROUP,
				},
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(len(channels), ShouldEqual, 2)
				So(channels[0].TypeConstant, ShouldEqual, models.Channel_TYPE_GROUP)
				So(channels[1].TypeConstant, ShouldEqual, models.Channel_TYPE_ANNOUNCEMENT)

			})

			Convey("owner should be able to update it", func() {
				channel1, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_GROUP,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(channel1, ShouldNotBeNil)
				// fetching channel returns creator id
				_, err = rest.UpdateChannel(channel1, ses.ClientId)
				So(err, ShouldBeNil)
			})

			Convey("owner should only be able to update name and purpose of the channel", nil)

			Convey("normal user should be able to update it if and only if user is creator or participant", func() {
				channel1, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_GROUP,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(channel1, ShouldNotBeNil)

				anotherAccount := models.NewAccount()
				anotherAccount.OldId = bson.NewObjectId().Hex()
				anotherAccount, err = rest.CreateAccount(anotherAccount)

				So(err, ShouldBeNil)
				So(account, ShouldNotBeNil)

				ses, err := modelhelper.FetchOrCreateSession(anotherAccount.Nick, groupName)
				So(err, ShouldBeNil)
				So(ses, ShouldNotBeNil)

				_, err = rest.UpdateChannel(channel1, ses.ClientId)
				So(err, ShouldBeNil)
			})

			Convey("owner cant delete it", func() {
				channel1, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_GROUP,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(channel1, ShouldNotBeNil)

				err = rest.DeleteChannel(account.Id, channel1.Id)
				So(err, ShouldNotBeNil)
			})

			Convey("normal user cant delete it", func() {
				channel1, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_GROUP,
					ses.ClientId,
				)
				So(err, ShouldBeNil)
				So(channel1, ShouldNotBeNil)

				err = rest.DeleteChannel(rand.Int63(), channel1.Id)
				So(err, ShouldNotBeNil)
			})

			Convey("member can post status update", nil)

			Convey("non-member can not post status update", nil)
		})
	})
}
예제 #17
0
func CreateChannelParticipant(channelId int64, token string) (*models.ChannelParticipant, error) {
	account := models.NewAccount()
	account.OldId = bson.NewObjectId().Hex()
	account, _ = CreateAccount(account)
	return AddChannelParticipant(channelId, token, account.Id)
}
예제 #18
0
func TestFollowedTopics(t *testing.T) {
	tests.WithRunner(t, func(r *runner.Runner) {

		Convey("While testing followed topics", t, func() {
			Convey("First Create User", func() {
				account, _, groupName := models.CreateRandomGroupDataWithChecks()

				ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
				So(err, ShouldBeNil)
				So(ses, ShouldNotBeNil)

				nonOwnerAccount := models.NewAccount()
				nonOwnerAccount.OldId = AccountOldId.Hex()
				nonOwnerAccount, err = rest.CreateAccount(nonOwnerAccount)
				So(err, ShouldBeNil)
				So(nonOwnerAccount, ShouldNotBeNil)

				topicChannel1, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_TOPIC,
					ses.ClientId,
				)
				So(err, ShouldBeNil)

				topicChannel2, err := rest.CreateChannelByGroupNameAndType(
					account.Id,
					groupName,
					models.Channel_TYPE_TOPIC,
					ses.ClientId,
				)
				So(err, ShouldBeNil)

				Convey("user should be able to follow one topic", func() {
					channelParticipant, err := rest.AddChannelParticipant(topicChannel1.Id, ses.ClientId, account.Id)
					// there should be an err
					So(err, ShouldBeNil)
					// channel should be nil
					So(channelParticipant, ShouldNotBeNil)

					followedChannels, err := rest.FetchFollowedChannels(account.Id, ses.ClientId)
					So(err, ShouldBeNil)
					So(followedChannels, ShouldNotBeNil)
					So(len(followedChannels), ShouldBeGreaterThanOrEqualTo, 1)
				})

				Convey("user should be able to follow two topic", func() {
					channelParticipant, err := rest.AddChannelParticipant(topicChannel1.Id, ses.ClientId, account.Id)
					So(err, ShouldBeNil)
					So(channelParticipant, ShouldNotBeNil)

					channelParticipant, err = rest.AddChannelParticipant(topicChannel2.Id, ses.ClientId, account.Id)
					So(err, ShouldBeNil)
					So(channelParticipant, ShouldNotBeNil)

					followedChannels, err := rest.FetchFollowedChannels(account.Id, ses.ClientId)
					So(err, ShouldBeNil)
					So(followedChannels, ShouldNotBeNil)
					So(len(followedChannels), ShouldBeGreaterThanOrEqualTo, 2)
				})

				Convey("user should be participant of the followed topic", func() {
					channelParticipant, err := rest.AddChannelParticipant(topicChannel1.Id, ses.ClientId, account.Id)
					// there should be an err
					So(err, ShouldBeNil)
					// channel should be nil
					So(channelParticipant, ShouldNotBeNil)

					followedChannels, err := rest.FetchFollowedChannels(account.Id, ses.ClientId)
					So(err, ShouldBeNil)
					So(followedChannels, ShouldNotBeNil)
					So(len(followedChannels), ShouldBeGreaterThanOrEqualTo, 1)
					So(followedChannels[0].IsParticipant, ShouldBeTrue)
				})

				Convey("user should not be a participant of the un-followed topic", func() {
					channelParticipant, err := rest.AddChannelParticipant(topicChannel1.Id, ses.ClientId, account.Id)
					So(err, ShouldBeNil)
					So(channelParticipant, ShouldNotBeNil)

					followedChannels, err := rest.FetchFollowedChannels(account.Id, ses.ClientId)
					So(err, ShouldBeNil)
					So(followedChannels, ShouldNotBeNil)

					currentParticipatedChannelCount := len(followedChannels)
					channelParticipant, err = rest.DeleteChannelParticipant(topicChannel1.Id, ses.ClientId, account.Id)
					So(err, ShouldBeNil)
					So(channelParticipant, ShouldNotBeNil)

					followedChannels, err = rest.FetchFollowedChannels(account.Id, ses.ClientId)
					So(err, ShouldBeNil)
					So(followedChannels, ShouldNotBeNil)
					lastParticipatedChannelCount := len(followedChannels)

					So(currentParticipatedChannelCount-lastParticipatedChannelCount, ShouldEqual, 1)
				})

				Convey("participant count of the followed topic should be greater than 0", func() {
					channelParticipant, err := rest.AddChannelParticipant(topicChannel1.Id, ses.ClientId, account.Id)
					// there should be an err
					So(err, ShouldBeNil)
					// channel should be nil
					So(channelParticipant, ShouldNotBeNil)

					followedChannels, err := rest.FetchFollowedChannels(account.Id, ses.ClientId)
					So(err, ShouldBeNil)
					So(followedChannels, ShouldNotBeNil)
					So(len(followedChannels), ShouldBeGreaterThanOrEqualTo, 1)
					So(followedChannels[0].ParticipantCount, ShouldBeGreaterThanOrEqualTo, 1)
				})
			})
		})
	})
}
예제 #19
0
func TestPrivateMesssages(t *testing.T) {
	tests.WithRunner(t, func(r *runner.Runner) {
		Convey("while testing private channels", t, func() {
			devrim, err := models.CreateAccountInBothDbsWithNick("devrim")
			So(err, ShouldBeNil)
			So(devrim, ShouldNotBeNil)
			sinan, err := models.CreateAccountInBothDbsWithNick("sinan")
			So(err, ShouldBeNil)
			So(sinan, ShouldNotBeNil)

			groupName := models.RandomGroupName()

			// cretae admin user
			account, err := models.CreateAccountInBothDbs()
			tests.ResultedWithNoErrorCheck(account, err)

			models.CreateTypedGroupedChannelWithTest(
				account.Id,
				models.Channel_TYPE_GROUP,
				groupName,
			)

			// fetch admin's session
			ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
			So(err, ShouldBeNil)
			So(ses, ShouldNotBeNil)

			groupChannel, err := rest.CreateChannelByGroupNameAndType(
				account.Id,
				groupName,
				models.Channel_TYPE_GROUP,
				ses.ClientId,
			)
			tests.ResultedWithNoErrorCheck(groupChannel, err)

			recipient := models.NewAccount()
			recipient.OldId = AccountOldId2.Hex()
			recipient, err = rest.CreateAccount(recipient)
			So(err, ShouldBeNil)
			So(recipient, ShouldNotBeNil)

			recipient2 := models.NewAccount()
			recipient2.OldId = AccountOldId3.Hex()
			recipient2, err = rest.CreateAccount(recipient2)
			So(err, ShouldBeNil)
			So(recipient2, ShouldNotBeNil)

			Convey("participants should be a member of parent group", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body message for private message @devrim @sinan"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim", "sinan"}
				_, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldNotBeNil)
			})

			_, err = groupChannel.AddParticipant(sinan.Id)
			So(err, ShouldBeNil)

			_, err = groupChannel.AddParticipant(devrim.Id)
			So(err, ShouldBeNil)

			Convey("one can send private message to one person", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body message for private message @devrim @sinan"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim", "sinan"}
				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)

			})

			Convey("0 recipient should not fail", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body for private message"
				pmr.GroupName = groupName
				pmr.Recipients = []string{}

				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)

			})

			Convey("if sender is not defined but token is added, then shouldn't fail to create PM", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = 0
				pmr.Body = "this is a body for private message"
				pmr.GroupName = ""
				pmr.Recipients = []string{}

				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)
			})

			Convey("one can send private message to multiple person", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body for private message @sinan"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"sinan"}
				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)

			})
			Convey("private message response should have created channel", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body for private message @devrim @sinan"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim", "sinan"}

				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)
				So(cmc.Channel.TypeConstant, ShouldEqual, models.Channel_TYPE_PRIVATE_MESSAGE)
				So(cmc.Channel.Id, ShouldBeGreaterThan, 0)
				So(cmc.Channel.GroupName, ShouldEqual, groupName)
				So(cmc.Channel.PrivacyConstant, ShouldEqual, models.Channel_PRIVACY_PRIVATE)

			})

			Convey("private message response should have participant status data", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body for private message @devrim @sinan"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim", "sinan"}

				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)
				So(cmc.IsParticipant, ShouldBeTrue)
			})

			Convey("private message response should have participant count", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body for @sinan private message @devrim"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim", "sinan"}
				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)
				So(cmc.ParticipantCount, ShouldEqual, 3)
			})

			Convey("private message response should have participant preview", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is @sinan a body for @devrim private message"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"sinan", "devrim"}
				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)
				So(len(cmc.ParticipantsPreview), ShouldEqual, 3)
			})

			Convey("private message response should have last Message", func() {
				body := "hi @devrim this is a body for private message also for @sinan"
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = body
				pmr.GroupName = groupName
				pmr.Recipients = []string{"sinan", "devrim"}
				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)
				So(cmc.LastMessage.Message.Body, ShouldEqual, body)
			})

			Convey("private message should be listed by all recipients", func() {
				body := "hi @devrim this is a body for private message also for @sinan"
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = body
				pmr.GroupName = groupName
				pmr.Recipients = []string{"sinan", "devrim"}
				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cmc, ShouldNotBeNil)

				pm, err := rest.GetPrivateChannels(&request.Query{AccountId: account.Id, GroupName: groupName}, ses.ClientId)
				So(err, ShouldBeNil)
				So(pm, ShouldNotBeNil)
				So(len(pm), ShouldNotEqual, 0)
				So(pm[0], ShouldNotBeNil)
				So(pm[0].Channel.TypeConstant, ShouldEqual, models.Channel_TYPE_PRIVATE_MESSAGE)
				So(pm[0].Channel.Id, ShouldEqual, cmc.Channel.Id)
				So(pm[0].Channel.GroupName, ShouldEqual, cmc.Channel.GroupName)
				So(pm[0].LastMessage.Message.Body, ShouldEqual, cmc.LastMessage.Message.Body)
				So(pm[0].Channel.PrivacyConstant, ShouldEqual, models.Channel_PRIVACY_PRIVATE)
				So(len(pm[0].ParticipantsPreview), ShouldEqual, 3)
				So(pm[0].IsParticipant, ShouldBeTrue)

			})

			Convey("user should be able to search private messages via purpose field", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "search private messages"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"sinan", "devrim"}
				pmr.Purpose = "test me up"

				cmc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)

				query := request.Query{AccountId: account.Id, GroupName: groupName}
				_, err = rest.SearchPrivateChannels(&query, ses.ClientId)
				So(err, ShouldNotBeNil)

				query.Name = "test"
				pm, err := rest.SearchPrivateChannels(&query, ses.ClientId)
				So(err, ShouldBeNil)
				So(pm, ShouldNotBeNil)
				So(len(pm), ShouldNotEqual, 0)
				So(pm[0], ShouldNotBeNil)
				So(pm[0].Channel.TypeConstant, ShouldEqual, models.Channel_TYPE_PRIVATE_MESSAGE)
				So(pm[0].Channel.Id, ShouldEqual, cmc.Channel.Id)
				So(pm[0].Channel.GroupName, ShouldEqual, cmc.Channel.GroupName)
				So(pm[0].LastMessage.Message.Body, ShouldEqual, cmc.LastMessage.Message.Body)
				So(pm[0].Channel.PrivacyConstant, ShouldEqual, models.Channel_PRIVACY_PRIVATE)
				So(pm[0].IsParticipant, ShouldBeTrue)

			})

			payload := gorm.Hstore{}
			bar := "bar"
			payload["foo"] = &bar

			Convey("given payload should be populated", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "this is a body message for private message @devrim @sinan"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim", "sinan"}
				pmr.Payload = payload

				pcr, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(pcr, ShouldNotBeNil)
				So(pcr.Channel, ShouldNotBeNil)
				So(pcr.Channel.Payload, ShouldNotBeNil)
				So(len(pcr.Channel.Payload), ShouldBeGreaterThan, 0)
				So(*pcr.Channel.Payload["foo"], ShouldEqual, bar)
			})

			Convey("user join activity should be listed by recipients", func() {
				groupName := models.RandomGroupName()

				// cretae admin user
				account, err := models.CreateAccountInBothDbs()
				tests.ResultedWithNoErrorCheck(account, err)
				// fetch admin's session
				ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
				So(err, ShouldBeNil)
				So(ses, ShouldNotBeNil)

				groupChannel := models.CreateTypedGroupedChannelWithTest(
					account.Id,
					models.Channel_TYPE_GROUP,
					groupName,
				)
				So(groupChannel, ShouldNotBeNil)

				_, err = groupChannel.AddParticipant(account.Id)
				So(err, ShouldBeNil)
				_, err = groupChannel.AddParticipant(devrim.Id)
				So(err, ShouldBeNil)
				_, err = groupChannel.AddParticipant(sinan.Id)
				So(err, ShouldBeNil)
				_, err = groupChannel.AddParticipant(recipient.Id)
				So(err, ShouldBeNil)

				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "test private message participants"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"sinan", "devrim"}
				if pmr.Payload == nil {
					pmr.Payload = gorm.Hstore{}
				}
				pic := "pictureSomethingLikeThat"
				pmr.Payload["link_embed"] = &pic

				cc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)

				So(err, ShouldBeNil)
				So(cc, ShouldNotBeNil)

				history, err := rest.GetHistory(
					cc.Channel.Id,
					&request.Query{
						AccountId: account.Id,
					},
					ses.ClientId,
				)

				So(err, ShouldBeNil)
				So(history, ShouldNotBeNil)
				So(len(history.MessageList), ShouldEqual, 2)

				// add participant
				_, err = rest.AddChannelParticipant(cc.Channel.Id, ses.ClientId, recipient.Id)
				So(err, ShouldBeNil)

				history, err = rest.GetHistory(
					cc.Channel.Id,
					&request.Query{
						AccountId: account.Id,
					},
					ses.ClientId,
				)

				So(err, ShouldBeNil)
				So(history, ShouldNotBeNil)
				So(len(history.MessageList), ShouldEqual, 3)

				So(history.MessageList[0].Message, ShouldNotBeNil)
				So(history.MessageList[0].Message.TypeConstant, ShouldEqual, models.ChannelMessage_TYPE_SYSTEM)
				So(history.MessageList[0].Message.Payload, ShouldNotBeNil)
				addedBy, ok := history.MessageList[0].Message.Payload["addedBy"]
				So(ok, ShouldBeTrue)
				So(*addedBy, ShouldEqual, account.Nick)

				systemType, ok := history.MessageList[0].Message.Payload["systemType"]
				So(ok, ShouldBeTrue)
				So(*systemType, ShouldEqual, models.ChannelRequestMessage_TYPE_JOIN)

				// we set link_embed into the payloadof the system message above.
				// But system message payload data will not have payload defined
				// by client side or else
				// As a result, system message will not be able to have link_embed payload data
				_, k := history.MessageList[0].Message.Payload["link_embed"]
				So(k, ShouldBeFalse)

				// try to add same participant
				_, err = rest.AddChannelParticipant(cc.Channel.Id, ses.ClientId, recipient.Id)
				So(err, ShouldBeNil)

				history, err = rest.GetHistory(
					cc.Channel.Id,
					&request.Query{
						AccountId: account.Id,
					},
					ses.ClientId,
				)

				So(err, ShouldBeNil)
				So(history, ShouldNotBeNil)
				So(len(history.MessageList), ShouldEqual, 3)

			})

			Convey("user should not be able to edit join messages", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "test private message participants again"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"devrim"}

				cc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cc, ShouldNotBeNil)

				_, err = rest.AddChannelParticipant(cc.Channel.Id, ses.ClientId, recipient.Id)
				So(err, ShouldBeNil)

				ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
				So(err, ShouldBeNil)
				So(ses, ShouldNotBeNil)

				history, err := rest.GetHistory(
					cc.Channel.Id,
					&request.Query{
						AccountId: account.Id,
					},
					ses.ClientId,
				)

				So(err, ShouldBeNil)
				So(history, ShouldNotBeNil)
				So(len(history.MessageList), ShouldEqual, 3)

				joinMessage := history.MessageList[0].Message
				So(joinMessage, ShouldNotBeNil)

				_, err = rest.UpdatePost(joinMessage, ses.ClientId)
				So(err, ShouldNotBeNil)
			})

			Convey("first chat message should include initial participants", func() {
				pmr := models.ChannelRequest{}
				pmr.AccountId = account.Id
				pmr.Body = "test initial participation message"
				pmr.GroupName = groupName
				pmr.Recipients = []string{"sinan", "devrim"}

				cc, err := rest.SendPrivateChannelRequest(pmr, ses.ClientId)
				So(err, ShouldBeNil)
				So(cc, ShouldNotBeNil)

				ses, err := modelhelper.FetchOrCreateSession(account.Nick, groupName)
				So(err, ShouldBeNil)
				So(ses, ShouldNotBeNil)

				history, err := rest.GetHistory(
					cc.Channel.Id,
					&request.Query{
						AccountId: account.Id,
					},
					ses.ClientId,
				)

				So(err, ShouldBeNil)
				So(history, ShouldNotBeNil)
				So(len(history.MessageList), ShouldEqual, 2)

				joinMessage := history.MessageList[1].Message
				So(joinMessage.TypeConstant, ShouldEqual, models.ChannelMessage_TYPE_SYSTEM)
				So(joinMessage.Payload, ShouldNotBeNil)
				initialParticipants, ok := joinMessage.Payload["initialParticipants"]
				So(ok, ShouldBeTrue)

				systemType, ok := history.MessageList[1].Message.Payload["systemType"]
				So(ok, ShouldBeTrue)
				So(*systemType, ShouldEqual, models.ChannelRequestMessage_TYPE_INIT)

				participants := make([]string, 0)
				err = json.Unmarshal([]byte(*initialParticipants), &participants)
				So(err, ShouldBeNil)
				So(len(participants), ShouldEqual, 2)
				So(participants, ShouldContain, "devrim")
				// So(*addedBy, ShouldEqual, account.OldId)

			})

			Convey("targetted account should be able to list private message channel of himself", nil)
		})
	})
}
예제 #20
0
func TestChannelUpdatedCalculateUnreadItemCount(t *testing.T) {
	r := runner.New("test")
	if err := r.Init(); err != nil {
		t.Fatalf("couldnt start bongo %s", err.Error())
	}
	defer r.Close()

	appConfig := config.MustRead(r.Conf.Path)
	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	groupName := models.RandomGroupName()

	Convey("while testing get account", t, func() {
		Convey("if cookie is not set, should return nil", func() {
			a := getAccount(&http.Request{}, models.Channel_KODING_NAME)
			So(a, ShouldNotBeNil)
			So(a.Id, ShouldBeZeroValue)
		})

		Convey("if cookie value is not set, should return nil", func() {
			req, _ := http.NewRequest("GET", "/", nil)

			expire := time.Now().AddDate(0, 0, 1)
			cookie := http.Cookie{
				Name:    "clientId",
				Value:   "",
				Path:    "/",
				Domain:  "localhost",
				Expires: expire,
			}

			req.AddCookie(&cookie)

			a := getAccount(req, models.Channel_KODING_NAME)
			So(a, ShouldNotBeNil)
			So(a.Id, ShouldBeZeroValue)
		})

		Convey("if session doesnt have username, should return nil", func() {
			ses, err := modelhelper.CreateSessionForAccount("", groupName)
			So(err, ShouldBeNil)
			So(ses, ShouldNotBeNil)

			req, _ := http.NewRequest("GET", "/", nil)
			expire := time.Now().AddDate(0, 0, 1)
			cookie := http.Cookie{
				Name:    "clientId",
				Value:   ses.ClientId,
				Path:    "/",
				Domain:  "localhost",
				Expires: expire,
			}

			req.AddCookie(&cookie)

			a := getAccount(req, models.Channel_KODING_NAME)
			So(a, ShouldNotBeNil)
			So(a.Id, ShouldBeZeroValue)
		})

		Convey("if session is valid, should return account", func() {
			acc, err := models.CreateAccountInBothDbs()
			So(err, ShouldBeNil)
			So(acc, ShouldNotBeNil)

			ses, err := modelhelper.CreateSessionForAccount(acc.Nick, groupName)
			So(err, ShouldBeNil)
			So(ses, ShouldNotBeNil)

			req, _ := http.NewRequest("GET", "/", nil)
			expire := time.Now().AddDate(0, 0, 1)
			cookie := http.Cookie{
				Name:    "clientId",
				Value:   ses.ClientId,
				Path:    "/",
				Domain:  "localhost",
				Expires: expire,
			}

			req.AddCookie(&cookie)

			res := getAccount(req, models.Channel_KODING_NAME)
			So(res, ShouldNotBeNil)
			So(acc.Id, ShouldEqual, res.Id)
		})
	})

	Convey("while making sure account", t, func() {
		Convey("if account is not in postgres", func() {

			nick := models.RandomName()
			oldAcc := &kodingmodels.Account{
				Id: bson.NewObjectId(),
				Profile: kodingmodels.AccountProfile{
					Nickname: nick,
				},
			}
			err := modelhelper.CreateAccount(oldAcc)
			So(err, ShouldBeNil)

			oldUser := &kodingmodels.User{
				ObjectId:       bson.NewObjectId(),
				Password:       nick,
				Salt:           nick,
				Name:           nick,
				Email:          nick + "@koding.com",
				EmailFrequency: &kodingmodels.EmailFrequency{},
			}

			err = modelhelper.CreateUser(oldUser)
			So(err, ShouldBeNil)

			groupName := models.RandomGroupName()
			_, err = makeSureAccount(groupName, nick)
			So(err, ShouldBeNil)

			Convey("should create it in postgres", func() {
				a := models.NewAccount()
				err = a.ByNick(nick)
				So(err, ShouldBeNil)
				So(a.OldId, ShouldEqual, oldAcc.Id.Hex())

				Convey("should set socialAPI id in mongo", func() {
					oldAccFromDB, err := modelhelper.GetAccount(nick)
					So(err, ShouldBeNil)
					So(oldAccFromDB.SocialApiId, ShouldEqual, strconv.FormatInt(a.Id, 10))
				})
			})
		})

		Convey("if account is in postgres", func() {
			acc, err := models.CreateAccountInBothDbs()
			So(err, ShouldBeNil)
			So(acc, ShouldNotBeNil)

			groupName := models.RandomGroupName()

			_, err = makeSureAccount(groupName, acc.Nick)
			So(err, ShouldBeNil)

			Convey("should be in postgres", func() {
				a := models.NewAccount()
				err = a.ByNick(acc.Nick)
				So(err, ShouldBeNil)
				So(a.OldId, ShouldEqual, acc.OldId)

				Convey("should have socialAPI set", func() {
					oldAccFromDB, err := modelhelper.GetAccount(acc.Nick)
					So(err, ShouldBeNil)
					So(oldAccFromDB.SocialApiId, ShouldEqual, strconv.FormatInt(a.Id, 10))
				})
			})
		})
	})

	Convey("while making sure group membership", t, func() {
		Convey("if account is not not a member", func() {
			account := models.CreateAccountWithTest()
			requester := models.CreateAccountWithTest()
			groupChannel := models.CreateTypedPublicChannelWithTest(account.Id, models.Channel_TYPE_GROUP)

			err := makeSureMembership(groupChannel, requester.Id)
			So(err, ShouldBeNil)

			Convey("should add as participant", func() {
				status, err := groupChannel.IsParticipant(requester.Id)
				So(err, ShouldBeNil)
				So(status, ShouldBeTrue)

				Convey("if account is a member", func() {
					err := makeSureMembership(groupChannel, requester.Id)
					So(err, ShouldBeNil)

					Convey("should be a participant", func() {
						status, err := groupChannel.IsParticipant(requester.Id)
						So(err, ShouldBeNil)
						So(status, ShouldBeTrue)
					})
				})
			})

		})
	})
}