Exemplo n.º 1
0
func loadTestUsersCommand(c *Context, command *model.Command) bool {
	cmd1 := cmds["loadTestCommand"] + " users"
	cmd2 := cmds["loadTestCommand"] + " users fuzz"

	if strings.Index(command.Command, cmd1) == 0 && !command.Suggest {
		cmd := cmd1
		doFuzz := false
		if strings.Index(command.Command, cmd2) == 0 {
			doFuzz = true
			cmd = cmd2
		}
		usersr, err := parseRange(command.Command, cmd)
		if err == false {
			usersr = utils.Range{10, 15}
		}
		client := model.NewClient(c.GetSiteURL())
		userCreator := NewAutoUserCreator(client, c.Session.TeamId)
		userCreator.Fuzzy = doFuzz
		userCreator.CreateTestUsers(usersr)
		return true
	} else if strings.Index(cmd1, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd1, Description: c.T("api.command.load_test_users_command.users.description")})
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: c.T("api.command.load_test_users_command.fuzz.description")})
	} else if strings.Index(cmd2, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: c.T("api.command.load_test_users_command.fuzz.description")})
	}

	return false
}
Exemplo n.º 2
0
func (me *LoadTestProvider) ChannelsCommand(c *Context, channelId string, message string) *model.CommandResponse {
	cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels"))

	doFuzz := false
	if strings.Index(cmd, "fuzz") == 0 {
		doFuzz = true
		cmd = strings.TrimSpace(strings.TrimPrefix(cmd, "fuzz"))
	}

	channelsr, err := parseRange(cmd, "")
	if err == false {
		channelsr = utils.Range{2, 5}
	}

	var team *model.Team
	if tr := <-Srv.Store.Team().Get(c.TeamId); tr.Err != nil {
		return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
	} else {
		team = tr.Data.(*model.Team)
	}

	client := model.NewClient(c.GetSiteURL())
	client.SetTeamId(team.Id)
	client.MockSession(c.Session.Token)
	channelCreator := NewAutoChannelCreator(client, team)
	channelCreator.Fuzzy = doFuzz
	channelCreator.CreateTestChannels(channelsr)

	return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
}
Exemplo n.º 3
0
func loadTestChannelsCommand(c *Context, command *model.Command) bool {
	cmd1 := cmds["loadTestCommand"] + " channels"
	cmd2 := cmds["loadTestCommand"] + " channels fuzz"

	if strings.Index(command.Command, cmd1) == 0 && !command.Suggest {
		cmd := cmd1
		doFuzz := false
		if strings.Index(command.Command, cmd2) == 0 {
			doFuzz = true
			cmd = cmd2
		}
		channelsr, err := parseRange(command.Command, cmd)
		if err == false {
			channelsr = utils.Range{20, 30}
		}
		client := model.NewClient(c.GetSiteURL())
		client.MockSession(c.Session.Token)
		channelCreator := NewAutoChannelCreator(client, c.Session.TeamId)
		channelCreator.Fuzzy = doFuzz
		channelCreator.CreateTestChannels(channelsr)
		return true
	} else if strings.Index(cmd1, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd1, Description: c.T("api.command.load_test_channels_command.channel.description")})
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: c.T("api.command.load_test_channels_command.fuzz.description")})
	} else if strings.Index(cmd2, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: c.T("api.command.load_test_channels_command.fuzz.description")})
	}

	return false
}
Exemplo n.º 4
0
func loadTestChannelsCommand(c *Context, command *model.Command) bool {
	cmd1 := "/loadtest channels"
	cmd2 := "/loadtest channels fuzz"

	if strings.Index(command.Command, cmd1) == 0 && !command.Suggest {
		cmd := cmd1
		doFuzz := false
		if strings.Index(command.Command, cmd2) == 0 {
			doFuzz = true
			cmd = cmd2
		}
		channelsr, err := parseRange(command.Command, cmd)
		if err == false {
			channelsr = utils.Range{20, 30}
		}
		client := model.NewClient(c.GetSiteURL())
		client.MockSession(c.Session.Token)
		channelCreator := NewAutoChannelCreator(client, c.Session.TeamId)
		channelCreator.Fuzzy = doFuzz
		channelCreator.CreateTestChannels(channelsr)
		return true
	} else if strings.Index(cmd1, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd1, Description: "Add a specified number of random channels to current team <MinChannels> <MaxChannels>"})
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random channels with fuzz text to current team <Min Channels> <Max Channels>"})
	} else if strings.Index(cmd2, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random channels with fuzz text to current team <Min Channels> <Max Channels>"})
	}

	return false
}
Exemplo n.º 5
0
func loadTestUsersCommand(c *Context, command *model.Command) bool {
	cmd1 := "/loadtest users"
	cmd2 := "/loadtest users fuzz"

	if strings.Index(command.Command, cmd1) == 0 && !command.Suggest {
		cmd := cmd1
		doFuzz := false
		if strings.Index(command.Command, cmd2) == 0 {
			doFuzz = true
			cmd = cmd2
		}
		usersr, err := parseRange(command.Command, cmd)
		if err == false {
			usersr = utils.Range{10, 15}
		}
		client := model.NewClient(c.GetSiteURL())
		userCreator := NewAutoUserCreator(client, c.Session.TeamId)
		userCreator.Fuzzy = doFuzz
		userCreator.CreateTestUsers(usersr)
		return true
	} else if strings.Index(cmd1, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd1, Description: "Add a specified number of random users to current team <Min Users> <Max Users>"})
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random users with fuzz text to current team <Min Users> <Max Users>"})
	} else if strings.Index(cmd2, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add a specified number of random users with fuzz text to current team <Min Users> <Max Users>"})
	}

	return false
}
Exemplo n.º 6
0
func loadTestPostsCommand(c *Context, command *model.Command) bool {
	cmd1 := "/loadtest posts"
	cmd2 := "/loadtest posts fuzz"

	if strings.Index(command.Command, cmd1) == 0 && !command.Suggest {
		cmd := cmd1
		doFuzz := false
		if strings.Index(command.Command, cmd2) == 0 {
			cmd = cmd2
			doFuzz = true
		}

		postsr, err := parseRange(command.Command, cmd)
		if err == false {
			postsr = utils.Range{20, 30}
		}

		tokens := strings.Fields(strings.TrimPrefix(command.Command, cmd))
		rimages := utils.Range{0, 0}
		if len(tokens) >= 3 {
			if numImages, err := strconv.Atoi(tokens[2]); err == nil {
				rimages = utils.Range{numImages, numImages}
			}
		}

		var usernames []string
		if result := <-Srv.Store.User().GetProfiles(c.Session.TeamId); result.Err == nil {
			profileUsers := result.Data.(map[string]*model.User)
			usernames = make([]string, len(profileUsers))
			i := 0
			for _, userprof := range profileUsers {
				usernames[i] = userprof.Username
				i++
			}
		}

		client := model.NewClient(c.GetSiteURL())
		client.MockSession(c.Session.Token)
		testPoster := NewAutoPostCreator(client, command.ChannelId)
		testPoster.Fuzzy = doFuzz
		testPoster.Users = usernames

		numImages := utils.RandIntFromRange(rimages)
		numPosts := utils.RandIntFromRange(postsr)
		for i := 0; i < numPosts; i++ {
			testPoster.HasImage = (i < numImages)
			testPoster.CreateRandomPost()
		}
		return true
	} else if strings.Index(cmd1, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd1, Description: "Add some random posts to current channel <Min Posts> <Max Posts> <Min Images> <Max Images>"})
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add some random posts with fuzz text to current channel <Min Posts> <Max Posts> <Min Images> <Max Images>"})
	} else if strings.Index(cmd2, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{Suggestion: cmd2, Description: "Add some random posts with fuzz text to current channel <Min Posts> <Max Posts> <Min Images> <Max Images>"})
	}

	return false
}
Exemplo n.º 7
0
func Setup() {
	if Srv == nil {
		utils.LoadConfig("config.json")
		NewServer()
		StartServer()
		InitApi()
		Client = model.NewClient("http://localhost:" + utils.Cfg.ServiceSettings.Port + "/api/v1")
	}
}
Exemplo n.º 8
0
func Setup() {
	if Srv == nil {
		utils.LoadConfig("config.json")
		utils.Cfg.TeamSettings.MaxUsersPerTeam = 50
		NewServer()
		StartServer()
		InitApi()
		Client = model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)
	}
}
Exemplo n.º 9
0
func Setup() {
	if api.Srv == nil {
		utils.LoadConfig("config.json")
		api.NewServer()
		api.StartServer()
		api.InitApi()
		InitWeb()
		URL = "http://localhost" + utils.Cfg.ServiceSettings.ListenAddress
		ApiClient = model.NewClient(URL)
	}
}
Exemplo n.º 10
0
func Setup() {
	if Srv == nil {
		utils.LoadConfig("config.json")
		utils.InitTranslations()
		utils.Cfg.TeamSettings.MaxUsersPerTeam = 50
		NewServer()
		StartServer()
		InitApi()
		Client = model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)

		Srv.Store.MarkSystemRanUnitTests()
	}
}
Exemplo n.º 11
0
func FindTeamByDomain(c *Context, domain string, all string) bool {

	if domain == "" || len(domain) > 64 {
		c.SetInvalidParam("findTeamByDomain", "domain")
		return false
	}

	if model.IsReservedDomain(domain) {
		c.Err = model.NewAppError("findTeamByDomain", "This URL is unavailable. Please try another.", "d="+domain)
		return false
	}

	if all == "false" {
		if result := <-Srv.Store.Team().GetByDomain(domain); result.Err != nil {
			return false
		} else {
			return true
		}
	} else {
		if doesSubDomainExist(domain) {
			return true
		}

		protocol := "http"

		if utils.Cfg.ServiceSettings.UseSSL {
			protocol = "https"
		}

		for key, _ := range utils.Cfg.ServiceSettings.Shards {
			url := fmt.Sprintf("%v://%v.%v/api/v1", protocol, key, utils.Cfg.ServiceSettings.Domain)

			if strings.Index(utils.Cfg.ServiceSettings.Domain, "localhost") == 0 {
				url = fmt.Sprintf("%v://%v/api/v1", protocol, utils.Cfg.ServiceSettings.Domain)
			}

			client := model.NewClient(url)

			if result, err := client.FindTeamByDomain(domain, false); err != nil {
				c.Err = err
				return false
			} else {
				if result.Data.(bool) {
					return true
				}
			}
		}

		return false
	}
}
Exemplo n.º 12
0
func Setup() {
	if api.Srv == nil {
		utils.LoadConfig("config.json")
		utils.InitTranslations()
		api.NewServer()
		api.StartServer()
		api.InitApi()
		InitWeb()
		URL = "http://localhost" + utils.Cfg.ServiceSettings.ListenAddress
		ApiClient = model.NewClient(URL)

		api.Srv.Store.MarkSystemRanUnitTests()
	}
}
Exemplo n.º 13
0
func (me *LoadTestProvider) PostsCommand(c *Context, channelId string, message string) *model.CommandResponse {
	cmd := strings.TrimSpace(strings.TrimPrefix(message, "posts"))

	doFuzz := false
	if strings.Index(cmd, "fuzz") == 0 {
		doFuzz = true
		cmd = strings.TrimSpace(strings.TrimPrefix(cmd, "fuzz"))
	}

	postsr, err := parseRange(cmd, "")
	if err == false {
		postsr = utils.Range{20, 30}
	}

	tokens := strings.Fields(cmd)
	rimages := utils.Range{0, 0}
	if len(tokens) >= 3 {
		if numImages, err := strconv.Atoi(tokens[2]); err == nil {
			rimages = utils.Range{numImages, numImages}
		}
	}

	var usernames []string
	if result := <-Srv.Store.User().GetProfiles(c.TeamId); result.Err == nil {
		profileUsers := result.Data.(map[string]*model.User)
		usernames = make([]string, len(profileUsers))
		i := 0
		for _, userprof := range profileUsers {
			usernames[i] = userprof.Username
			i++
		}
	}

	client := model.NewClient(c.GetSiteURL())
	client.SetTeamId(c.TeamId)
	client.MockSession(c.Session.Token)
	testPoster := NewAutoPostCreator(client, channelId)
	testPoster.Fuzzy = doFuzz
	testPoster.Users = usernames

	numImages := utils.RandIntFromRange(rimages)
	numPosts := utils.RandIntFromRange(postsr)
	for i := 0; i < numPosts; i++ {
		testPoster.HasImage = (i < numImages)
		testPoster.CreateRandomPost()
	}

	return &model.CommandResponse{Text: "Added posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
}
Exemplo n.º 14
0
func Setup() {
	if api.Srv == nil {
		utils.TranslationsPreInit()
		utils.LoadConfig("config.json")
		utils.InitTranslations(utils.Cfg.LocalizationSettings)
		api.NewServer(false)
		api.StartServer()
		api.InitApi()
		InitWeb()
		URL = "http://localhost" + utils.Cfg.ServiceSettings.ListenAddress
		ApiClient = model.NewClient(URL)

		api.Srv.Store.MarkSystemRanUnitTests()

		*utils.Cfg.TeamSettings.EnableOpenServer = true
	}
}
Exemplo n.º 15
0
func emailTeams(c *Context, w http.ResponseWriter, r *http.Request) {

	m := model.MapFromJson(r.Body)

	email := strings.ToLower(strings.TrimSpace(m["email"]))

	if email == "" {
		c.SetInvalidParam("findTeam", "email")
		return
	}

	protocol := "http"

	if utils.Cfg.ServiceSettings.UseSSL {
		protocol = "https"
	}

	subjectPage := NewServerTemplatePage("find_teams_subject", c.TeamUrl)
	bodyPage := NewServerTemplatePage("find_teams_body", c.TeamUrl)

	for key, _ := range utils.Cfg.ServiceSettings.Shards {
		url := fmt.Sprintf("%v://%v.%v/api/v1", protocol, key, utils.Cfg.ServiceSettings.Domain)

		if strings.Index(utils.Cfg.ServiceSettings.Domain, "localhost") == 0 {
			url = fmt.Sprintf("%v://%v/api/v1", protocol, utils.Cfg.ServiceSettings.Domain)
		}

		client := model.NewClient(url)

		if result, err := client.FindTeams(email); err != nil {
			l4g.Error("An error occured while finding teams at %v err=%v", key, err)
		} else {
			data := result.Data.([]string)
			for _, domain := range data {
				bodyPage.Props[fmt.Sprintf("%v://%v.%v", protocol, domain, utils.Cfg.ServiceSettings.Domain)] = ""
			}
		}
	}

	if err := utils.SendMail(email, subjectPage.Render(), bodyPage.Render()); err != nil {
		l4g.Error("An error occured while sending an email in emailTeams err=%v", err)
	}

	w.Write([]byte(model.MapToJson(m)))
}
Exemplo n.º 16
0
func (me *LoadTestProvider) ChannelsCommand(c *Context, channelId string, message string) *model.CommandResponse {
	cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels"))

	doFuzz := false
	if strings.Index(cmd, "fuzz") == 0 {
		doFuzz = true
		cmd = strings.TrimSpace(strings.TrimPrefix(cmd, "fuzz"))
	}

	channelsr, err := parseRange(cmd, "")
	if err == false {
		channelsr = utils.Range{2, 5}
	}
	client := model.NewClient(c.GetSiteURL())
	client.MockSession(c.Session.Token)
	channelCreator := NewAutoChannelCreator(client, c.Session.TeamId)
	channelCreator.Fuzzy = doFuzz
	channelCreator.CreateTestChannels(channelsr)

	return &model.CommandResponse{Text: "Adding channels...", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
}
Exemplo n.º 17
0
func (u *User) loginToMattermost() error {
	b := &backoff.Backoff{
		Min:    time.Second,
		Max:    5 * time.Minute,
		Jitter: true,
	}
	// login to mattermost
	//u.Credentials = &MmCredentials{Server: url, Team: team, Login: email, Pass: pass}
	MmClient := model.NewClient("https://" + u.Credentials.Server)
	var myinfo *model.Result
	var appErr *model.AppError
	for {
		logger.Debug("retrying login", u.Credentials.Team, u.Credentials.Login, u.Credentials.Server)
		myinfo, appErr = MmClient.LoginByEmail(u.Credentials.Team, u.Credentials.Login, u.Credentials.Pass)
		if appErr != nil {
			d := b.Duration()
			if !strings.Contains(appErr.DetailedError, "connection refused") &&
				!strings.Contains(appErr.DetailedError, "invalid character") {
				return errors.New(appErr.Message)
			}
			logger.Infof("LOGIN: %s, reconnecting in %s", appErr, d)
			time.Sleep(d)
			continue
		}
		break
	}
	// reset timer
	b.Reset()
	u.MmUser = myinfo.Data.(*model.User)

	myinfo, _ = MmClient.GetMyTeam("")
	u.MmTeam = myinfo.Data.(*model.Team)

	// setup websocket connection
	wsurl := "wss://" + u.Credentials.Server + "/api/v1/websocket"
	header := http.Header{}
	header.Set(model.HEADER_AUTH, "BEARER "+MmClient.AuthToken)

	var WsClient *websocket.Conn
	var err error
	for {
		WsClient, _, err = websocket.DefaultDialer.Dial(wsurl, header)
		if err != nil {
			d := b.Duration()
			logger.Infof("WSS: %s, reconnecting in %s", err, d)
			time.Sleep(d)
			continue
		}
		break
	}
	b.Reset()

	u.MmClient = MmClient
	u.MmWsClient = WsClient

	// populating users
	u.updateMMUsers()

	// populating channels
	u.updateMMChannels()

	// fetch users and channels from mattermost
	u.addUsersToChannels()

	return nil
}
Exemplo n.º 18
0
func TestGetChannelExtraInfo(t *testing.T) {
	Setup()

	team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "*****@*****.**", Type: model.TEAM_OPEN}
	team = Client.Must(Client.CreateTeam(team)).Data.(*model.Team)

	user := &model.User{TeamId: team.Id, Email: model.NewId() + "*****@*****.**", Nickname: "Corey Hulen", Password: "******"}
	user = Client.Must(Client.CreateUser(user, "")).Data.(*model.User)
	store.Must(Srv.Store.User().VerifyEmail(user.Id))

	Client.LoginByEmail(team.Name, user.Email, "pwd")

	channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
	channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)

	rget := Client.Must(Client.GetChannelExtraInfo(channel1.Id, ""))
	data := rget.Data.(*model.ChannelExtra)
	if data.Id != channel1.Id {
		t.Fatal("couldnt't get extra info")
	}

	//
	// Testing etag caching
	//

	currentEtag := rget.Etag

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) != nil {
		t.Log(cache_result.Data)
		t.Fatal("response should be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	Client2 := model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)

	user2 := &model.User{TeamId: team.Id, Email: model.NewId() + "*****@*****.**", Nickname: "Tester 2", Password: "******"}
	user2 = Client2.Must(Client2.CreateUser(user2, "")).Data.(*model.User)
	store.Must(Srv.Store.User().VerifyEmail(user2.Id))

	Client2.LoginByEmail(team.Name, user2.Email, "pwd")
	Client2.Must(Client2.JoinChannel(channel1.Id))

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) == nil {
		t.Log(cache_result.Data)
		t.Fatal("response should not be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) != nil {
		t.Log(cache_result.Data)
		t.Fatal("response should be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	Client2.Must(Client2.LeaveChannel(channel1.Id))

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) == nil {
		t.Log(cache_result.Data)
		t.Fatal("response should not be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) != nil {
		t.Log(cache_result.Data)
		t.Fatal("response should be empty")
	} else {
		currentEtag = cache_result.Etag
	}
}
Exemplo n.º 19
0
func (m *MMClient) Login() error {
	if m.WsQuit {
		return nil
	}
	b := &backoff.Backoff{
		Min:    time.Second,
		Max:    5 * time.Minute,
		Jitter: true,
	}
	uriScheme := "https://"
	wsScheme := "wss://"
	if m.NoTLS {
		uriScheme = "http://"
		wsScheme = "ws://"
	}
	// login to mattermost
	m.Client = model.NewClient(uriScheme + m.Credentials.Server)
	m.Client.HttpClient.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: m.SkipTLSVerify}}
	var myinfo *model.Result
	var appErr *model.AppError
	var logmsg = "trying login"
	for {
		m.log.Debugf("%s %s %s %s", logmsg, m.Credentials.Team, m.Credentials.Login, m.Credentials.Server)
		if strings.Contains(m.Credentials.Pass, model.SESSION_COOKIE_TOKEN) {
			m.log.Debugf(logmsg+" with ", model.SESSION_COOKIE_TOKEN)
			token := strings.Split(m.Credentials.Pass, model.SESSION_COOKIE_TOKEN+"=")
			m.Client.HttpClient.Jar = m.createCookieJar(token[1])
			m.Client.MockSession(token[1])
			myinfo, appErr = m.Client.GetMe("")
			if myinfo.Data.(*model.User) == nil {
				m.log.Errorf("LOGIN TOKEN: %s is invalid", m.Credentials.Pass)
				return errors.New("invalid " + model.SESSION_COOKIE_TOKEN)
			}
		} else {
			myinfo, appErr = m.Client.Login(m.Credentials.Login, m.Credentials.Pass)
		}
		if appErr != nil {
			d := b.Duration()
			m.log.Debug(appErr.DetailedError)
			if !strings.Contains(appErr.DetailedError, "connection refused") &&
				!strings.Contains(appErr.DetailedError, "invalid character") {
				if appErr.Message == "" {
					return errors.New(appErr.DetailedError)
				}
				return errors.New(appErr.Message)
			}
			m.log.Debugf("LOGIN: %s, reconnecting in %s", appErr, d)
			time.Sleep(d)
			logmsg = "retrying login"
			continue
		}
		break
	}
	// reset timer
	b.Reset()

	initLoad, _ := m.Client.GetInitialLoad()
	initData := initLoad.Data.(*model.InitialLoad)
	m.User = initData.User
	for _, v := range initData.Teams {
		m.log.Debugf("trying %s (id: %s)", v.Name, v.Id)
		if v.Name == m.Credentials.Team {
			m.Client.SetTeamId(v.Id)
			m.Team = v
			m.log.Debugf("GetallTeamListings: found id %s for team %s", v.Id, v.Name)
			break
		}
	}
	if m.Team == nil {
		return errors.New("team not found")
	}

	// setup websocket connection
	wsurl := wsScheme + m.Credentials.Server + "/api/v3/users/websocket"
	header := http.Header{}
	header.Set(model.HEADER_AUTH, "BEARER "+m.Client.AuthToken)

	m.log.Debug("WsClient: making connection")
	var err error
	for {
		wsDialer := &websocket.Dialer{Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{InsecureSkipVerify: m.SkipTLSVerify}}
		m.WsClient, _, err = wsDialer.Dial(wsurl, header)
		if err != nil {
			d := b.Duration()
			m.log.Debugf("WSS: %s, reconnecting in %s", err, d)
			time.Sleep(d)
			continue
		}
		break
	}
	b.Reset()

	// populating users
	m.UpdateUsers()

	// populating channels
	m.UpdateChannels()

	return nil
}
Exemplo n.º 20
0
func (me *TestHelper) CreateClient() *model.Client {
	return model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)
}
Exemplo n.º 21
0
func loadTestSetupCommand(c *Context, command *model.Command) bool {
	cmd := "/loadtest setup"

	if strings.Index(command.Command, cmd) == 0 && !command.Suggest {
		tokens := strings.Fields(strings.TrimPrefix(command.Command, cmd))
		doTeams := contains(tokens, "teams")
		doFuzz := contains(tokens, "fuzz")

		numArgs := 0
		if doTeams {
			numArgs++
		}
		if doFuzz {
			numArgs++
		}

		var numTeams int
		var numChannels int
		var numUsers int
		var numPosts int

		// Defaults
		numTeams = 10
		numChannels = 10
		numUsers = 10
		numPosts = 10

		if doTeams {
			if (len(tokens) - numArgs) >= 4 {
				numTeams, _ = strconv.Atoi(tokens[numArgs+0])
				numChannels, _ = strconv.Atoi(tokens[numArgs+1])
				numUsers, _ = strconv.Atoi(tokens[numArgs+2])
				numPosts, _ = strconv.Atoi(tokens[numArgs+3])
			}
		} else {
			if (len(tokens) - numArgs) >= 3 {
				numChannels, _ = strconv.Atoi(tokens[numArgs+0])
				numUsers, _ = strconv.Atoi(tokens[numArgs+1])
				numPosts, _ = strconv.Atoi(tokens[numArgs+2])
			}
		}
		client := model.NewClient(c.GetSiteURL())

		if doTeams {
			if err := CreateBasicUser(client); err != nil {
				l4g.Error("Failed to create testing enviroment")
				return true
			}
			client.LoginByEmail(BTEST_TEAM_NAME, BTEST_USER_EMAIL, BTEST_USER_PASSWORD)
			enviroment, err := CreateTestEnviromentWithTeams(
				client,
				utils.Range{numTeams, numTeams},
				utils.Range{numChannels, numChannels},
				utils.Range{numUsers, numUsers},
				utils.Range{numPosts, numPosts},
				doFuzz)
			if err != true {
				l4g.Error("Failed to create testing enviroment")
				return true
			} else {
				l4g.Info("Testing enviroment created")
				for i := 0; i < len(enviroment.Teams); i++ {
					l4g.Info("Team Created: " + enviroment.Teams[i].Name)
					l4g.Info("\t User to login: "******", " + USER_PASSWORD)
				}
			}
		} else {
			client.MockSession(c.Session.Token)
			CreateTestEnviromentInTeam(
				client,
				c.Session.TeamId,
				utils.Range{numChannels, numChannels},
				utils.Range{numUsers, numUsers},
				utils.Range{numPosts, numPosts},
				doFuzz)
		}
		return true
	} else if strings.Index(cmd, command.Command) == 0 {
		command.AddSuggestion(&model.SuggestCommand{
			Suggestion:  cmd,
			Description: "Creates a testing enviroment in current team. [teams] [fuzz] <Num Channels> <Num Users> <NumPosts>"})
	}

	return false
}
Exemplo n.º 22
0
func manualTest(c *api.Context, w http.ResponseWriter, r *http.Request) {
	// Let the world know
	l4g.Info("Setting up for manual test...")

	// URL Parameters
	params, err := url.ParseQuery(r.URL.RawQuery)
	if err != nil {
		c.Err = model.NewAppError("/manual", "Unable to parse URL", "")
		return
	}

	// Grab a uuid (if available) to seed the random number generator so we don't get conflicts.
	uid, ok := params["uid"]
	if ok {
		hasher := fnv.New32a()
		hasher.Write([]byte(uid[0] + strconv.Itoa(int(time.Now().UTC().UnixNano()))))
		hash := hasher.Sum32()
		rand.Seed(int64(hash))
	} else {
		l4g.Debug("No uid in url")
	}

	// Create a client for tests to use
	client := model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)

	// Check for username parameter and create a user if present
	username, ok1 := params["username"]
	teamDisplayName, ok2 := params["teamname"]
	var teamID string
	var userID string
	if ok1 && ok2 {
		l4g.Info("Creating user and team")
		// Create team for testing
		team := &model.Team{
			DisplayName: teamDisplayName[0],
			Name:        utils.RandomName(utils.Range{20, 20}, utils.LOWERCASE),
			Email:       utils.RandomEmail(utils.Range{20, 20}, utils.LOWERCASE),
			Type:        model.TEAM_OPEN,
		}

		if result := <-api.Srv.Store.Team().Save(team); result.Err != nil {
			c.Err = result.Err
			return
		} else {

			createdTeam := result.Data.(*model.Team)

			channel := &model.Channel{DisplayName: "Town Square", Name: "town-square", Type: model.CHANNEL_OPEN, TeamId: createdTeam.Id}
			if _, err := api.CreateChannel(c, channel, false); err != nil {
				c.Err = err
				return
			}

			teamID = createdTeam.Id
		}

		// Create user for testing
		user := &model.User{
			TeamId:   teamID,
			Email:    utils.RandomEmail(utils.Range{20, 20}, utils.LOWERCASE),
			Nickname: username[0],
			Password: api.USER_PASSWORD}

		result, err := client.CreateUser(user, "")
		if err != nil {
			c.Err = err
			return
		}
		api.Srv.Store.User().VerifyEmail(result.Data.(*model.User).Id)
		newuser := result.Data.(*model.User)
		userID = newuser.Id

		// Login as user to generate auth token
		_, err = client.LoginById(newuser.Id, api.USER_PASSWORD)
		if err != nil {
			c.Err = err
			return
		}

		// Respond with an auth token this can be overriden by a specific test as required
		sessionCookie := &http.Cookie{
			Name:     model.SESSION_COOKIE_TOKEN,
			Value:    client.AuthToken,
			Path:     "/",
			MaxAge:   *utils.Cfg.ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24,
			HttpOnly: true,
		}
		http.SetCookie(w, sessionCookie)
		http.Redirect(w, r, "/channels/town-square", http.StatusTemporaryRedirect)
	}

	// Setup test environment
	env := TestEnvironment{
		Params:        params,
		Client:        client,
		CreatedTeamId: teamID,
		CreatedUserId: userID,
		Context:       c,
		Writer:        w,
		Request:       r,
	}

	// Grab the test ID and pick the test
	testname, ok := params["test"]
	var err2 *model.AppError
	switch testname[0] {
	case "autolink":
		err2 = testAutoLink(env)
		// ADD YOUR NEW TEST HERE!
	case "general":
		err2 = nil
	}

	if err != nil {
		c.Err = err2
		return
	}
}
Exemplo n.º 23
0
func (me *LoadTestProvider) SetupCommand(c *Context, channelId string, message string) *model.CommandResponse {
	tokens := strings.Fields(strings.TrimPrefix(message, "setup"))
	doTeams := contains(tokens, "teams")
	doFuzz := contains(tokens, "fuzz")

	numArgs := 0
	if doTeams {
		numArgs++
	}
	if doFuzz {
		numArgs++
	}

	var numTeams int
	var numChannels int
	var numUsers int
	var numPosts int

	// Defaults
	numTeams = 10
	numChannels = 10
	numUsers = 10
	numPosts = 10

	if doTeams {
		if (len(tokens) - numArgs) >= 4 {
			numTeams, _ = strconv.Atoi(tokens[numArgs+0])
			numChannels, _ = strconv.Atoi(tokens[numArgs+1])
			numUsers, _ = strconv.Atoi(tokens[numArgs+2])
			numPosts, _ = strconv.Atoi(tokens[numArgs+3])
		}
	} else {
		if (len(tokens) - numArgs) >= 3 {
			numChannels, _ = strconv.Atoi(tokens[numArgs+0])
			numUsers, _ = strconv.Atoi(tokens[numArgs+1])
			numPosts, _ = strconv.Atoi(tokens[numArgs+2])
		}
	}
	client := model.NewClient(c.GetSiteURL())

	if doTeams {
		if err := CreateBasicUser(client); err != nil {
			return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
		}
		client.LoginByEmail(BTEST_TEAM_NAME, BTEST_USER_EMAIL, BTEST_USER_PASSWORD)
		environment, err := CreateTestEnvironmentWithTeams(
			client,
			utils.Range{numTeams, numTeams},
			utils.Range{numChannels, numChannels},
			utils.Range{numUsers, numUsers},
			utils.Range{numPosts, numPosts},
			doFuzz)
		if err != true {
			return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
		} else {
			l4g.Info("Testing environment created")
			for i := 0; i < len(environment.Teams); i++ {
				l4g.Info("Team Created: " + environment.Teams[i].Name)
				l4g.Info("\t User to login: "******", " + USER_PASSWORD)
			}
		}
	} else {
		client.MockSession(c.Session.Token)
		CreateTestEnvironmentInTeam(
			client,
			c.Session.TeamId,
			utils.Range{numChannels, numChannels},
			utils.Range{numUsers, numUsers},
			utils.Range{numPosts, numPosts},
			doFuzz)
	}

	return &model.CommandResponse{Text: "Creating enviroment...", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
}
Exemplo n.º 24
0
// PostFile Post files and message in Mattermost server
func (m *MatterMail) PostFile(from, subject, message, emailname string, emailbody *string, attach *[]enmime.MIMEPart) error {

	client := model.NewClient(m.cfg.Server)

	m.debg.Println(client)

	m.debg.Printf("Login user:%v team:%v url:%v\n", m.cfg.MattermostUser, m.cfg.Team, m.cfg.Server)

	result, apperr := client.Login(m.cfg.MattermostUser, m.cfg.MattermostPass)
	if apperr != nil {
		return apperr
	}

	m.user = result.Data.(*model.User)

	m.info.Println("Post new message")

	defer client.Logout()

	// Get Team
	teams := client.Must(client.GetAllTeams()).Data.(map[string]*model.Team)

	teamMatch := false
	for _, t := range teams {
		if t.Name == m.cfg.Team {
			client.SetTeamId(t.Id)
			teamMatch = true
			break
		}
	}

	if !teamMatch {
		return fmt.Errorf("Did not find team with name %v", m.cfg.Team)
	}

	//Discover channel id by channel name
	var channelID, channelName string
	channelList := client.Must(client.GetChannels("")).Data.(*model.ChannelList)

	// redirect email by the subject
	if !m.cfg.NoRedirectChannel {
		m.debg.Println("Try to find channel/user by subject")
		channelName = getChannelFromSubject(subject)
		channelID = m.getChannelID(client, channelList, channelName)
	}

	// check filters
	if channelID == "" && m.cfg.Filter != nil {
		m.debg.Println("Did not find channel/user from Email Subject. Look for filter")
		channelName = m.cfg.Filter.GetChannel(from, subject)
		channelID = m.getChannelID(client, channelList, channelName)
	}

	// get default Channel config
	if channelID == "" {
		m.debg.Printf("Did not find channel/user in filters. Look for channel '%v'\n", m.cfg.Channel)
		channelName = m.cfg.Channel
		channelID = m.getChannelID(client, channelList, channelName)
	}

	if channelID == "" && !m.cfg.NoRedirectChannel {
		m.debg.Printf("Did not find channel/user with name '%v'. Trying channel town-square\n", m.cfg.Channel)
		channelName = "town-square"
		channelID = m.getChannelID(client, channelList, channelName)
	}

	if channelID == "" {
		return fmt.Errorf("Did not find any channel to post")
	}

	m.debg.Printf("Post email in %v", channelName)

	if m.cfg.NoAttachment || (len(*attach) == 0 && len(emailname) == 0) {
		return m.postMessage(client, channelID, message, nil)
	}

	var fileIds []string

	uploadFile := func(filename string, data []byte) error {
		if len(data) == 0 {
			return nil
		}

		resp, err := client.UploadPostAttachment(data, channelID, filename)
		if resp == nil {
			return err
		}

		if len(resp.FileInfos) != 1 {
			return fmt.Errorf("error on upload file - fileinfos len different of one %v", resp.FileInfos)
		}

		fileIds = append(fileIds, resp.FileInfos[0].Id)
		return nil
	}

	if len(emailname) > 0 {
		if err := uploadFile(emailname, []byte(*emailbody)); err != nil {
			return err
		}
	}

	for _, a := range *attach {
		if err := uploadFile(a.FileName(), a.Content()); err != nil {
			return err
		}
	}

	return m.postMessage(client, channelID, message, fileIds)
}
Exemplo n.º 25
0
func TestGetChannelExtraInfo(t *testing.T) {
	th := Setup().InitBasic()
	Client := th.BasicClient
	team := th.BasicTeam

	channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
	channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)

	rget := Client.Must(Client.GetChannelExtraInfo(channel1.Id, -1, ""))
	data := rget.Data.(*model.ChannelExtra)
	if data.Id != channel1.Id {
		t.Fatal("couldnt't get extra info")
	} else if len(data.Members) != 1 {
		t.Fatal("got incorrect members")
	} else if data.MemberCount != 1 {
		t.Fatal("got incorrect member count")
	}

	//
	// Testing etag caching
	//

	currentEtag := rget.Etag

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) != nil {
		t.Log(cache_result.Data)
		t.Fatal("response should be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	Client2 := model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)

	user2 := &model.User{Email: "success+" + model.NewId() + "@simulator.amazonses.com", Nickname: "Tester 2", Password: "******"}
	user2 = Client2.Must(Client2.CreateUser(user2, "")).Data.(*model.User)
	LinkUserToTeam(user2, team)
	Client2.SetTeamId(team.Id)
	store.Must(Srv.Store.User().VerifyEmail(user2.Id))

	Client2.Login(user2.Email, "passwd1")
	Client2.Must(Client2.JoinChannel(channel1.Id))

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) == nil {
		t.Log(cache_result.Data)
		t.Fatal("response should not be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) != nil {
		t.Log(cache_result.Data)
		t.Fatal("response should be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	Client2.Must(Client2.LeaveChannel(channel1.Id))

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) == nil {
		t.Log(cache_result.Data)
		t.Fatal("response should not be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) != nil {
		t.Log(cache_result.Data)
		t.Fatal("response should be empty")
	} else {
		currentEtag = cache_result.Etag
	}

	Client2.Must(Client2.JoinChannel(channel1.Id))

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 2, currentEtag); err != nil {
		t.Fatal(err)
	} else if extra := cache_result.Data.(*model.ChannelExtra); extra == nil {
		t.Fatal("response should not be empty")
	} else if len(extra.Members) != 2 {
		t.Fatal("should've returned 2 members")
	} else if extra.MemberCount != 2 {
		t.Fatal("should've returned member count of 2")
	} else {
		currentEtag = cache_result.Etag
	}

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 1, currentEtag); err != nil {
		t.Fatal(err)
	} else if extra := cache_result.Data.(*model.ChannelExtra); extra == nil {
		t.Fatal("response should not be empty")
	} else if len(extra.Members) != 1 {
		t.Fatal("should've returned only 1 member")
	} else if extra.MemberCount != 2 {
		t.Fatal("should've returned member count of 2")
	} else {
		currentEtag = cache_result.Etag
	}

	if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 1, currentEtag); err != nil {
		t.Fatal(err)
	} else if cache_result.Data.(*model.ChannelExtra) != nil {
		t.Log(cache_result.Data)
		t.Fatal("response should be empty")
	} else {
		currentEtag = cache_result.Etag
	}

}
Exemplo n.º 26
0
func (m *MMClient) Login() error {
	m.WsConnected = false
	if m.WsQuit {
		return nil
	}
	b := &backoff.Backoff{
		Min:    time.Second,
		Max:    5 * time.Minute,
		Jitter: true,
	}
	uriScheme := "https://"
	wsScheme := "wss://"
	if m.NoTLS {
		uriScheme = "http://"
		wsScheme = "ws://"
	}
	// login to mattermost
	m.Client = model.NewClient(uriScheme + m.Credentials.Server)
	m.Client.HttpClient.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: m.SkipTLSVerify}}
	var myinfo *model.Result
	var appErr *model.AppError
	var logmsg = "trying login"
	for {
		m.log.Debugf("%s %s %s %s", logmsg, m.Credentials.Team, m.Credentials.Login, m.Credentials.Server)
		if strings.Contains(m.Credentials.Pass, model.SESSION_COOKIE_TOKEN) {
			m.log.Debugf(logmsg+" with %s", model.SESSION_COOKIE_TOKEN)
			token := strings.Split(m.Credentials.Pass, model.SESSION_COOKIE_TOKEN+"=")
			if len(token) != 2 {
				return errors.New("incorrect MMAUTHTOKEN. valid input is MMAUTHTOKEN=yourtoken")
			}
			m.Client.HttpClient.Jar = m.createCookieJar(token[1])
			m.Client.MockSession(token[1])
			myinfo, appErr = m.Client.GetMe("")
			if appErr != nil {
				return errors.New(appErr.DetailedError)
			}
			if myinfo.Data.(*model.User) == nil {
				m.log.Errorf("LOGIN TOKEN: %s is invalid", m.Credentials.Pass)
				return errors.New("invalid " + model.SESSION_COOKIE_TOKEN)
			}
		} else {
			myinfo, appErr = m.Client.Login(m.Credentials.Login, m.Credentials.Pass)
		}
		if appErr != nil {
			d := b.Duration()
			m.log.Debug(appErr.DetailedError)
			if !strings.Contains(appErr.DetailedError, "connection refused") &&
				!strings.Contains(appErr.DetailedError, "invalid character") {
				if appErr.Message == "" {
					return errors.New(appErr.DetailedError)
				}
				return errors.New(appErr.Message)
			}
			m.log.Debugf("LOGIN: %s, reconnecting in %s", appErr, d)
			time.Sleep(d)
			logmsg = "retrying login"
			continue
		}
		break
	}
	// reset timer
	b.Reset()

	err := m.initUser()
	if err != nil {
		return err
	}

	if m.Team == nil {
		return errors.New("team not found")
	}
	// set our team id as default route
	m.Client.SetTeamId(m.Team.Id)

	// setup websocket connection
	wsurl := wsScheme + m.Credentials.Server + "/api/v3/users/websocket"
	header := http.Header{}
	header.Set(model.HEADER_AUTH, "BEARER "+m.Client.AuthToken)

	m.log.Debug("WsClient: making connection")
	for {
		wsDialer := &websocket.Dialer{Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{InsecureSkipVerify: m.SkipTLSVerify}}
		m.WsClient, _, err = wsDialer.Dial(wsurl, header)
		if err != nil {
			d := b.Duration()
			m.log.Debugf("WSS: %s, reconnecting in %s", err, d)
			time.Sleep(d)
			continue
		}
		break
	}
	b.Reset()

	// only start to parse WS messages when login is completely done
	m.WsConnected = true

	return nil
}