MM-31063: Change constants to use CamelCase (#16608)

* MM-31063: Change constants to use CamelCase

* store package

* change allcaps to camel case (#16615)

* New tools.mod

Co-authored-by: Ibrahim Serdar Acikgoz <serdaracikgoz86@gmail.com>
Этот коммит содержится в:
Agniva De Sarker
2021-01-04 11:32:29 +05:30
коммит произвёл GitHub
родитель 8b6ac5f5d2
Коммит c1dd23a3c8
158 изменённых файлов: 1485 добавлений и 1479 удалений

Просмотреть файл

@@ -49,7 +49,11 @@ issues:
- linters:
- golint
text: "should have|should be|should replace|stutters|underscore|ALL_CAPS|annoying|error strings should not be capitalized"
text: "should have|should be|should replace|stutters|underscore|annoying|error strings should not be capitalized"
- linters:
- golint
path: "model/"
- linters:
- misspell

Просмотреть файл

@@ -1481,7 +1481,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) {
isNewMembership := false
if _, err = c.App.GetChannelMember(member.ChannelId, member.UserId); err != nil {
if err.Id == app.MISSING_CHANNEL_MEMBER_ERROR {
if err.Id == app.MissingChannelMemberError {
isNewMembership = true
} else {
c.Err = err

Просмотреть файл

@@ -2285,8 +2285,8 @@ func TestUpdateChannelRoles(t *testing.T) {
defer th.TearDown()
Client := th.Client
const CHANNEL_ADMIN = "channel_user channel_admin"
const CHANNEL_MEMBER = "channel_user"
const ChannelAdmin = "channel_user channel_admin"
const ChannelMember = "channel_user"
// User 1 creates a channel, making them channel admin by default.
channel := th.CreatePublicChannel()
@@ -2295,44 +2295,44 @@ func TestUpdateChannelRoles(t *testing.T) {
th.App.AddUserToChannel(th.BasicUser2, channel)
// User 1 promotes User 2
pass, resp := Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
pass, resp := Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, ChannelAdmin)
CheckNoError(t, resp)
require.True(t, pass, "should have passed")
member, resp := Client.GetChannelMember(channel.Id, th.BasicUser2.Id, "")
CheckNoError(t, resp)
require.Equal(t, CHANNEL_ADMIN, member.Roles, "roles don't match")
require.Equal(t, ChannelAdmin, member.Roles, "roles don't match")
// User 1 demotes User 2
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_MEMBER)
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, ChannelMember)
CheckNoError(t, resp)
th.LoginBasic2()
// User 2 cannot demote User 1
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelMember)
CheckForbiddenStatus(t, resp)
// User 2 cannot promote self
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, ChannelAdmin)
CheckForbiddenStatus(t, resp)
th.LoginBasic()
// User 1 demotes self
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelMember)
CheckNoError(t, resp)
// System Admin promotes User 1
_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelAdmin)
CheckNoError(t, resp)
// System Admin demotes User 1
_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelMember)
CheckNoError(t, resp)
// System Admin promotes User 1
_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelAdmin)
CheckNoError(t, resp)
th.LoginBasic()
@@ -2340,16 +2340,16 @@ func TestUpdateChannelRoles(t *testing.T) {
_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, "junk")
CheckBadRequestStatus(t, resp)
_, resp = Client.UpdateChannelRoles(channel.Id, "junk", CHANNEL_MEMBER)
_, resp = Client.UpdateChannelRoles(channel.Id, "junk", ChannelMember)
CheckBadRequestStatus(t, resp)
_, resp = Client.UpdateChannelRoles("junk", th.BasicUser.Id, CHANNEL_MEMBER)
_, resp = Client.UpdateChannelRoles("junk", th.BasicUser.Id, ChannelMember)
CheckBadRequestStatus(t, resp)
_, resp = Client.UpdateChannelRoles(channel.Id, model.NewId(), CHANNEL_MEMBER)
_, resp = Client.UpdateChannelRoles(channel.Id, model.NewId(), ChannelMember)
CheckNotFoundStatus(t, resp)
_, resp = Client.UpdateChannelRoles(model.NewId(), th.BasicUser.Id, CHANNEL_MEMBER)
_, resp = Client.UpdateChannelRoles(model.NewId(), th.BasicUser.Id, ChannelMember)
CheckForbiddenStatus(t, resp)
}

Просмотреть файл

@@ -16,7 +16,7 @@ import (
)
const (
EMOJI_MAX_AUTOCOMPLETE_ITEMS = 100
EmojiMaxAutocompleteItems = 100
)
func (api *API) InitEmoji() {
@@ -256,7 +256,7 @@ func searchEmojis(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
emojis, err := c.App.SearchEmoji(emojiSearch.Term, emojiSearch.PrefixOnly, web.PER_PAGE_MAXIMUM)
emojis, err := c.App.SearchEmoji(emojiSearch.Term, emojiSearch.PrefixOnly, web.PerPageMaximum)
if err != nil {
c.Err = err
return
@@ -273,7 +273,7 @@ func autocompleteEmojis(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
emojis, err := c.App.SearchEmoji(name, true, EMOJI_MAX_AUTOCOMPLETE_ITEMS)
emojis, err := c.App.SearchEmoji(name, true, EmojiMaxAutocompleteItems)
if err != nil {
c.Err = err
return

Просмотреть файл

@@ -22,13 +22,13 @@ import (
)
const (
FILE_TEAM_ID = "noteam"
FileTeamId = "noteam"
PREVIEW_IMAGE_TYPE = "image/jpeg"
THUMBNAIL_IMAGE_TYPE = "image/jpeg"
PreviewImageType = "image/jpeg"
ThumbnailImageType = "image/jpeg"
)
var UNSAFE_CONTENT_TYPES = [...]string{
var UnsafeContentTypes = [...]string{
"application/javascript",
"application/ecmascript",
"text/javascript",
@@ -37,7 +37,7 @@ var UNSAFE_CONTENT_TYPES = [...]string{
"text/html",
}
var MEDIA_CONTENT_TYPES = [...]string{
var MediaContentTypes = [...]string{
"image/jpeg",
"image/png",
"image/bmp",
@@ -169,7 +169,7 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F
auditRec.AddMeta("client_id", clientId)
info, appErr := c.App.UploadFileX(c.Params.ChannelId, c.Params.Filename, r.Body,
app.UploadFileSetTeamId(FILE_TEAM_ID),
app.UploadFileSetTeamId(FileTeamId),
app.UploadFileSetUserId(c.App.Session().UserId),
app.UploadFileSetTimestamp(timestamp),
app.UploadFileSetContentLength(r.ContentLength),
@@ -332,7 +332,7 @@ NEXT_PART:
auditRec.AddMeta("client_id", clientId)
info, appErr := c.App.UploadFileX(c.Params.ChannelId, filename, part,
app.UploadFileSetTeamId(FILE_TEAM_ID),
app.UploadFileSetTeamId(FileTeamId),
app.UploadFileSetUserId(c.App.Session().UserId),
app.UploadFileSetTimestamp(timestamp),
app.UploadFileSetContentLength(-1),
@@ -435,7 +435,7 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader,
auditRec.AddMeta("client_id", clientId)
info, appErr := c.App.UploadFileX(c.Params.ChannelId, fileHeader.Filename, f,
app.UploadFileSetTeamId(FILE_TEAM_ID),
app.UploadFileSetTeamId(FileTeamId),
app.UploadFileSetUserId(c.App.Session().UserId),
app.UploadFileSetTimestamp(timestamp),
app.UploadFileSetContentLength(-1),
@@ -532,7 +532,7 @@ func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) {
}
defer fileReader.Close()
err = writeFileResponse(info.Name, THUMBNAIL_IMAGE_TYPE, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r)
err = writeFileResponse(info.Name, ThumbnailImageType, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r)
if err != nil {
c.Err = err
return
@@ -611,7 +611,7 @@ func getFilePreview(c *Context, w http.ResponseWriter, r *http.Request) {
}
defer fileReader.Close()
err = writeFileResponse(info.Name, PREVIEW_IMAGE_TYPE, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r)
err = writeFileResponse(info.Name, PreviewImageType, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r)
if err != nil {
c.Err = err
return
@@ -701,7 +701,7 @@ func writeFileResponse(filename string, contentType string, contentSize int64, l
if contentType == "" {
contentType = "application/octet-stream"
} else {
for _, unsafeContentType := range UNSAFE_CONTENT_TYPES {
for _, unsafeContentType := range UnsafeContentTypes {
if strings.HasPrefix(contentType, unsafeContentType) {
contentType = "text/plain"
break
@@ -717,7 +717,7 @@ func writeFileResponse(filename string, contentType string, contentSize int64, l
} else {
isMediaType := false
for _, mediaContentType := range MEDIA_CONTENT_TYPES {
for _, mediaContentType := range MediaContentTypes {
if strings.HasPrefix(contentType, mediaContentType) {
isMediaType = true
break

Просмотреть файл

@@ -635,7 +635,7 @@ func TestUploadFiles(t *testing.T) {
_, fname := filepath.Split(dbInfo.Path)
ext := filepath.Ext(fname)
name := fname[:len(fname)-len(ext)]
expectedDir := fmt.Sprintf("%v/teams/%v/channels/%v/users/%s/%s", date, FILE_TEAM_ID, channel.Id, ri.CreatorId, ri.Id)
expectedDir := fmt.Sprintf("%v/teams/%v/channels/%v/users/%s/%s", date, FileTeamId, channel.Id, ri.CreatorId, ri.Id)
expectedPath := fmt.Sprintf("%s/%s", expectedDir, fname)
assert.Equal(t, dbInfo.Path, expectedPath,
fmt.Sprintf("File %v saved to:%q, expected:%q", dbInfo.Name, dbInfo.Path, expectedPath))

Просмотреть файл

@@ -44,8 +44,8 @@ func getJob(c *Context, w http.ResponseWriter, r *http.Request) {
func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) {
config := c.App.Config()
const FILE_PATH = "export"
const FILE_MIME = "application/zip"
const FilePath = "export"
const FileMime = "application/zip"
c.RequireJobId()
if c.Err != nil {
@@ -75,7 +75,7 @@ func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) {
}
fileName := job.Id + ".zip"
filePath := filepath.Join(FILE_PATH, fileName)
filePath := filepath.Join(FilePath, fileName)
fileReader, err := c.App.FileReader(filePath)
if err != nil {
c.Err = err
@@ -86,7 +86,7 @@ func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) {
// We are able to pass 0 for content size due to the fact that Golang's serveContent (https://golang.org/src/net/http/fs.go)
// already sets that for us
err = writeFileResponse(fileName, FILE_MIME, 0, time.Unix(0, job.LastActivityAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, true, w, r)
err = writeFileResponse(fileName, FileMime, 0, time.Unix(0, job.LastActivityAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, true, w, r)
if err != nil {
c.Err = err
return

Просмотреть файл

@@ -11,10 +11,10 @@ import (
"github.com/mattermost/mattermost-server/v5/services/cache"
)
const OPEN_GRAPH_METADATA_CACHE_SIZE = 10000
const OpenGraphMetadataCacheSize = 10000
var openGraphDataCache = cache.NewLRU(cache.LRUOptions{
Size: OPEN_GRAPH_METADATA_CACHE_SIZE,
Size: OpenGraphMetadataCacheSize,
})
func (api *API) InitOpenGraph() {

Просмотреть файл

@@ -19,7 +19,7 @@ import (
)
const (
MAXIMUM_PLUGIN_FILE_SIZE = 50 * 1024 * 1024
MaximumPluginFileSize = 50 * 1024 * 1024
)
func (api *API) InitPlugin() {
@@ -55,7 +55,7 @@ func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if err := r.ParseMultipartForm(MAXIMUM_PLUGIN_FILE_SIZE); err != nil {
if err := r.ParseMultipartForm(MaximumPluginFileSize); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

Просмотреть файл

@@ -253,7 +253,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht
return
}
postList, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: app.PAGE_DEFAULT, PerPage: c.Params.LimitBefore, SkipFetchThreads: skipFetchThreads})
postList, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: app.PageDefault, PerPage: c.Params.LimitBefore, SkipFetchThreads: skipFetchThreads})
if err != nil {
c.Err = err
return

Просмотреть файл

@@ -400,32 +400,32 @@ func testCreatePostWithOutgoingHook(
}
func TestCreatePostWithOutgoingHook_form_urlencoded(t *testing.T) {
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, true)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, true)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsStartsWith, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TriggerwordsExactMatch, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TriggerwordsStartsWith, false)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, true)
testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsStartsWith, true)
}
func TestCreatePostWithOutgoingHook_json(t *testing.T) {
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, true)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, true)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TriggerwordsStartsWith, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "", []string{"file_id_1"}, app.TriggerwordsExactMatch, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TriggerwordsStartsWith, false)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, true)
testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TriggerwordsStartsWith, true)
}
// hooks created before we added the ContentType field should be considered as
// application/x-www-form-urlencoded
func TestCreatePostWithOutgoingHook_no_content_type(t *testing.T) {
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, true)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, true)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsStartsWith, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TriggerwordsStartsWith, false)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, true)
testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, true)
}
func TestCreatePostPublic(t *testing.T) {

Просмотреть файл

@@ -23,13 +23,13 @@ import (
)
const (
REDIRECT_LOCATION_CACHE_SIZE = 10000
DEFAULT_SERVER_BUSY_SECONDS = 3600
MAX_SERVER_BUSY_SECONDS = 86400
RedirectLocationCacheSize = 10000
DefaultServerBusySeconds = 3600
MaxServerBusySeconds = 86400
)
var redirectLocationDataCache = cache.NewLRU(cache.LRUOptions{
Size: REDIRECT_LOCATION_CACHE_SIZE,
Size: RedirectLocationCacheSize,
})
func (api *API) InitSystem() {
@@ -512,12 +512,12 @@ func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) {
// number of seconds to keep server marked busy
secs := r.URL.Query().Get("seconds")
if secs == "" {
secs = strconv.FormatInt(DEFAULT_SERVER_BUSY_SECONDS, 10)
secs = strconv.FormatInt(DefaultServerBusySeconds, 10)
}
i, err := strconv.ParseInt(secs, 10, 64)
if err != nil || i <= 0 || i > MAX_SERVER_BUSY_SECONDS {
c.SetInvalidUrlParam(fmt.Sprintf("seconds must be 1 - %d", MAX_SERVER_BUSY_SECONDS))
if err != nil || i <= 0 || i > MaxServerBusySeconds {
c.SetInvalidUrlParam(fmt.Sprintf("seconds must be 1 - %d", MaxServerBusySeconds))
return
}

Просмотреть файл

@@ -588,7 +588,7 @@ func TestSetServerBusyInvalidParam(t *testing.T) {
defer th.TearDown()
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
params := []int{-1, 0, MAX_SERVER_BUSY_SECONDS + 1}
params := []int{-1, 0, MaxServerBusySeconds + 1}
for _, p := range params {
ok, resp := c.SetServerBusy(p)
CheckBadRequestStatus(t, resp)

Просмотреть файл

@@ -20,9 +20,9 @@ import (
)
const (
MAX_ADD_MEMBERS_BATCH = 256
MAXIMUM_BULK_IMPORT_SIZE = 10 * 1024 * 1024
groupIDsParamPattern = "[^a-zA-Z0-9,]*"
MaxAddMembersBatch = 256
MaximumBulkImportSize = 10 * 1024 * 1024
groupIDsParamPattern = "[^a-zA-Z0-9,]*"
)
var groupIDsQueryParamRegex *regexp.Regexp
@@ -695,7 +695,7 @@ func addTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) {
var err *model.AppError
members := model.TeamMembersFromJson(r.Body)
if len(members) > MAX_ADD_MEMBERS_BATCH {
if len(members) > MaxAddMembersBatch {
c.SetInvalidParam("too many members in batch")
return
}
@@ -1094,7 +1094,7 @@ func importTeam(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if err := r.ParseMultipartForm(MAXIMUM_BULK_IMPORT_SIZE); err != nil {
if err := r.ParseMultipartForm(MaximumBulkImportSize); err != nil {
c.Err = model.NewAppError("importTeam", "api.team.import_team.parse.app_error", nil, err.Error(), http.StatusInternalServerError)
return
}

Просмотреть файл

@@ -1855,7 +1855,7 @@ func TestAddTeamMember(t *testing.T) {
Client.Login(otherUser.Email, otherUser.Password)
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": team.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -1878,7 +1878,7 @@ func TestAddTeamMember(t *testing.T) {
require.Nil(t, tm, "should have not returned team member")
// expired token of more than 50 hours
token = model.NewToken(app.TOKEN_TYPE_TEAM_INVITATION, "")
token = model.NewToken(app.TokenTypeTeamInvitation, "")
token.CreateAt = model.GetMillis() - 1000*60*60*50
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -1889,7 +1889,7 @@ func TestAddTeamMember(t *testing.T) {
// invalid team id
testId := GenerateTestId()
token = model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": testId}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -1931,7 +1931,7 @@ func TestAddTeamMember(t *testing.T) {
// Attempt to use a token on a group-constrained team
token = model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": team.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -2359,42 +2359,42 @@ func TestUpdateTeamMemberRoles(t *testing.T) {
Client := th.Client
SystemAdminClient := th.SystemAdminClient
const TEAM_MEMBER = "team_user"
const TEAM_ADMIN = "team_user team_admin"
const TeamMember = "team_user"
const TeamAdmin = "team_user team_admin"
// user 1 tries to promote user 2
ok, resp := Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_ADMIN)
ok, resp := Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamAdmin)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should have returned false")
// user 1 tries to promote himself
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TEAM_ADMIN)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TeamAdmin)
CheckForbiddenStatus(t, resp)
// user 1 tries to demote someone
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TEAM_MEMBER)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TeamMember)
CheckForbiddenStatus(t, resp)
// system admin promotes user 1
ok, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TEAM_ADMIN)
ok, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TeamAdmin)
CheckNoError(t, resp)
require.True(t, ok, "should have returned true")
// user 1 (team admin) promotes user 2
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_ADMIN)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamAdmin)
CheckNoError(t, resp)
// user 1 (team admin) demotes user 2 (team admin)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_MEMBER)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamMember)
CheckNoError(t, resp)
// user 1 (team admin) tries to demote system admin (not member of a team)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TEAM_MEMBER)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TeamMember)
CheckNotFoundStatus(t, resp)
// user 1 (team admin) demotes system admin (member of a team)
th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TEAM_MEMBER)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TeamMember)
CheckNoError(t, resp)
// Note from API v3
// Note to anyone who thinks this (above) test is wrong:
@@ -2403,19 +2403,19 @@ func TestUpdateTeamMemberRoles(t *testing.T) {
// System admins should be able to manipulate permission no matter what their team level permissions are.
// system admin promotes user 2
_, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_ADMIN)
_, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamAdmin)
CheckNoError(t, resp)
// system admin demotes user 2 (team admin)
_, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_MEMBER)
_, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamMember)
CheckNoError(t, resp)
// user 1 (team admin) tries to promote himself to a random team
_, resp = Client.UpdateTeamMemberRoles(model.NewId(), th.BasicUser.Id, TEAM_ADMIN)
_, resp = Client.UpdateTeamMemberRoles(model.NewId(), th.BasicUser.Id, TeamAdmin)
CheckForbiddenStatus(t, resp)
// user 1 (team admin) tries to promote a random user
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, model.NewId(), TEAM_ADMIN)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, model.NewId(), TeamAdmin)
CheckNotFoundStatus(t, resp)
// user 1 (team admin) tries to promote invalid team permission
@@ -2423,7 +2423,7 @@ func TestUpdateTeamMemberRoles(t *testing.T) {
CheckBadRequestStatus(t, resp)
// user 1 (team admin) demotes himself
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TEAM_MEMBER)
_, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TeamMember)
CheckNoError(t, resp)
}

Просмотреть файл

@@ -50,7 +50,7 @@ func createTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) {
}
oldTermsOfService, err := c.App.GetLatestTermsOfService()
if err != nil && err.Id != app.ERROR_TERMS_OF_SERVICE_NO_ROWS_FOUND {
if err != nil && err.Id != app.ErrorTermsOfServiceNoRowsFound {
c.Err = err
return
}

Просмотреть файл

@@ -137,7 +137,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) {
}
auditRec.AddMeta("token_type", token.Type)
if token.Type == app.TOKEN_TYPE_GUEST_INVITATION {
if token.Type == app.TokenTypeGuestInvitation {
if c.App.Srv().License() == nil {
c.Err = model.NewAppError("CreateUserWithToken", "api.user.create_user.guest_accounts.license.app_error", nil, "", http.StatusBadRequest)
return

Просмотреть файл

@@ -194,7 +194,7 @@ func TestCreateUserWithToken(t *testing.T) {
t.Run("CreateWithTokenHappyPath", func(t *testing.T) {
user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -219,7 +219,7 @@ func TestCreateUserWithToken(t *testing.T) {
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -244,7 +244,7 @@ func TestCreateUserWithToken(t *testing.T) {
t.Run("NoToken", func(t *testing.T) {
user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -260,7 +260,7 @@ func TestCreateUserWithToken(t *testing.T) {
timeNow := time.Now()
past49Hours := timeNow.Add(-49*time.Hour).UnixNano() / int64(time.Millisecond)
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
token.CreateAt = past49Hours
@@ -290,7 +290,7 @@ func TestCreateUserWithToken(t *testing.T) {
user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -310,7 +310,7 @@ func TestCreateUserWithToken(t *testing.T) {
user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -327,7 +327,7 @@ func TestCreateUserWithToken(t *testing.T) {
user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
token := model.NewToken(
app.TOKEN_TYPE_TEAM_INVITATION,
app.TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))

Просмотреть файл

@@ -12,8 +12,8 @@ import (
)
const (
DAY_MILLISECONDS = 24 * 60 * 60 * 1000
MONTH_MILLISECONDS = 31 * DAY_MILLISECONDS
DayMilliseconds = 24 * 60 * 60 * 1000
MonthMilliseconds = 31 * DayMilliseconds
)
func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppError) {
@@ -93,14 +93,14 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo
dailyActiveChan := make(chan store.StoreResult, 1)
go func() {
dailyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false})
dailyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false})
dailyActiveChan <- store.StoreResult{Data: dailyActive, NErr: err2}
close(dailyActiveChan)
}()
monthlyActiveChan := make(chan store.StoreResult, 1)
go func() {
monthlyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false})
monthlyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false})
monthlyActiveChan <- store.StoreResult{Data: monthlyActive, NErr: err2}
close(monthlyActiveChan)
}()

Просмотреть файл

@@ -158,7 +158,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot,
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("PatchBot", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("PatchBot", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("PatchBot", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -235,7 +235,7 @@ func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("PatchBot", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("PatchBot", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("PatchBot", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -17,8 +17,8 @@ import (
)
const (
BRAND_FILE_PATH = "brand/"
BRAND_FILE_NAME = "image.png"
BrandFilePath = "brand/"
BrandFileName = "image.png"
)
func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError {
@@ -59,9 +59,9 @@ func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError {
}
t := time.Now()
a.MoveFile(BRAND_FILE_PATH+BRAND_FILE_NAME, BRAND_FILE_PATH+t.Format("2006-01-02T15:04:05")+".png")
a.MoveFile(BrandFilePath+BrandFileName, BrandFilePath+t.Format("2006-01-02T15:04:05")+".png")
if _, err := a.WriteFile(buf, BRAND_FILE_PATH+BRAND_FILE_NAME); err != nil {
if _, err := a.WriteFile(buf, BrandFilePath+BrandFileName); err != nil {
return model.NewAppError("SaveBrandImage", "brand.save_brand_image.save_image.app_error", nil, "", http.StatusInternalServerError)
}
@@ -73,7 +73,7 @@ func (a *App) GetBrandImage() ([]byte, *model.AppError) {
return nil, model.NewAppError("GetBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "", http.StatusNotImplemented)
}
img, err := a.ReadFile(BRAND_FILE_PATH + BRAND_FILE_NAME)
img, err := a.ReadFile(BrandFilePath + BrandFileName)
if err != nil {
return nil, err
}
@@ -82,7 +82,7 @@ func (a *App) GetBrandImage() ([]byte, *model.AppError) {
}
func (a *App) DeleteBrandImage() *model.AppError {
filePath := BRAND_FILE_PATH + BRAND_FILE_NAME
filePath := BrandFilePath + BrandFileName
fileExists, err := a.FileExists(filePath)

Просмотреть файл

@@ -13,7 +13,7 @@ import (
)
const (
TIMESTAMP_FORMAT = "Mon Jan 2 15:04:05 -0700 MST 2006"
TimestampFormat = "Mon Jan 2 15:04:05 -0700 MST 2006"
)
// Busy represents the busy state of the server. A server marked busy
@@ -55,7 +55,7 @@ func (b *Busy) Set(dur time.Duration) {
b.setWithoutNotify(dur)
if b.cluster != nil {
sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), Expires_ts: b.expires.UTC().Format(TIMESTAMP_FORMAT)}
sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), Expires_ts: b.expires.UTC().Format(TimestampFormat)}
b.notifyServerBusyChange(sbs)
}
}
@@ -141,7 +141,7 @@ func (b *Busy) ToJson() string {
sbs := &model.ServerBusyState{
Busy: atomic.LoadInt32(&b.busy) != 0,
Expires: b.expires.Unix(),
Expires_ts: b.expires.UTC().Format(TIMESTAMP_FORMAT),
Expires_ts: b.expires.UTC().Format(TimestampFormat),
}
return sbs.ToJson()
}

Просмотреть файл

@@ -72,7 +72,7 @@ func (a *App) JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return model.NewAppError("JoinDefaultChannels", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("JoinDefaultChannels", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("JoinDefaultChannels", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -249,7 +249,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan
return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.existing.app_error", nil, "id="+invErr.Value.(string), http.StatusBadRequest)
}
case errors.As(nErr, &cErr):
return sc, model.NewAppError("CreateChannel", store.CHANNEL_EXISTS_ERROR, nil, cErr.Error(), http.StatusBadRequest)
return sc, model.NewAppError("CreateChannel", store.ChannelExistsError, nil, cErr.Error(), http.StatusBadRequest)
case errors.As(nErr, &ltErr):
return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.limit.app_error", nil, ltErr.Error(), http.StatusBadRequest)
case errors.As(nErr, &appErr): // in case we haven't converted to plain error.
@@ -265,7 +265,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("CreateChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("CreateChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("CreateChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -324,7 +324,7 @@ func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Chann
var err *model.AppError
channel, err = a.createDirectChannel(userId, otherUserId)
if err != nil {
if err.Id == store.CHANNEL_EXISTS_ERROR {
if err.Id == store.ChannelExistsError {
return channel, nil
}
return nil, err
@@ -401,7 +401,7 @@ func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Cha
case errors.As(nErr, &cErr):
switch cErr.Resource {
case "Channel":
return channel, model.NewAppError("CreateChannel", store.CHANNEL_EXISTS_ERROR, nil, cErr.Error(), http.StatusBadRequest)
return channel, model.NewAppError("CreateChannel", store.ChannelExistsError, nil, cErr.Error(), http.StatusBadRequest)
case "ChannelMembers":
return nil, model.NewAppError("CreateChannel", "app.channel.save_member.exists.app_error", nil, cErr.Error(), http.StatusBadRequest)
}
@@ -457,7 +457,7 @@ func (a *App) WaitForChannelMembership(channelId string, userId string) {
func (a *App) CreateGroupChannel(userIds []string, creatorId string) (*model.Channel, *model.AppError) {
channel, err := a.createGroupChannel(userIds, creatorId)
if err != nil {
if err.Id == store.CHANNEL_EXISTS_ERROR {
if err.Id == store.ChannelExistsError {
return channel, nil
}
return nil, err
@@ -515,7 +515,7 @@ func (a *App) createGroupChannel(userIds []string, creatorId string) (*model.Cha
return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.existing.app_error", nil, "id="+invErr.Value.(string), http.StatusBadRequest)
}
case errors.As(nErr, &cErr):
return channel, model.NewAppError("CreateChannel", store.CHANNEL_EXISTS_ERROR, nil, cErr.Error(), http.StatusBadRequest)
return channel, model.NewAppError("CreateChannel", store.ChannelExistsError, nil, cErr.Error(), http.StatusBadRequest)
case errors.As(nErr, &ltErr):
return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.limit.app_error", nil, ltErr.Error(), http.StatusBadRequest)
case errors.As(nErr, &appErr): // in case we haven't converted to plain error.
@@ -713,7 +713,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userId string) (*model.Chan
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("RestoreChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("RestoreChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("RestoreChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -1164,7 +1164,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe
case errors.As(nErr, &appErr):
return nil, appErr
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("updateChannelMember", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("updateChannelMember", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("updateChannelMember", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -1204,7 +1204,7 @@ func (a *App) DeleteChannel(channel *model.Channel, userId string) *model.AppErr
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return model.NewAppError("DeleteChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("DeleteChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("DeleteChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -1740,7 +1740,7 @@ func (a *App) GetChannelMember(channelId string, userId string) (*model.ChannelM
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &nfErr):
return nil, model.NewAppError("GetChannelMember", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("GetChannelMember", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("GetChannelMember", "app.channel.get_member.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -1883,7 +1883,7 @@ func (a *App) JoinChannel(channel *model.Channel, userId string) *model.AppError
var nfErr *store.ErrNotFound
switch {
case errors.As(uresult.NErr, &nfErr):
return model.NewAppError("CreateChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("CreateChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("CreateChannel", "app.user.get.app_error", nil, uresult.NErr.Error(), http.StatusInternalServerError)
}
@@ -2004,7 +2004,7 @@ func (a *App) LeaveChannel(channelId string, userId string) *model.AppError {
var nfErr *store.ErrNotFound
switch {
case errors.As(uresult.NErr, &nfErr):
return model.NewAppError("LeaveChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("LeaveChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("LeaveChannel", "app.user.get.app_error", nil, uresult.NErr.Error(), http.StatusInternalServerError)
}
@@ -2144,7 +2144,7 @@ func (a *App) removeUserFromChannel(userIdToRemove string, removerUserId string,
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return model.NewAppError("removeUserFromChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("removeUserFromChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("removeUserFromChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -2785,7 +2785,7 @@ func (a *App) ToggleMuteChannel(channelId, userId string) (*model.ChannelMember,
case errors.As(nErr, &appErr):
return nil, appErr
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("ToggleMuteChannel", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("ToggleMuteChannel", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("ToggleMuteChannel", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -2839,7 +2839,7 @@ func (a *App) setChannelsMuted(channelIds []string, userId string, muted bool) (
case errors.As(nErr, &appErr):
return nil, appErr
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("setChannelsMuted", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("setChannelsMuted", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("setChannelsMuted", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -11,7 +11,7 @@ import (
)
const (
DISCOVERY_SERVICE_WRITE_PING = 60 * time.Second
DiscoveryServiceWritePing = 60 * time.Second
)
type ClusterDiscoveryService struct {
@@ -58,7 +58,7 @@ func (cds *ClusterDiscoveryService) Start() {
go func() {
mlog.Debug("ClusterDiscoveryService ping writer started", mlog.String("ClusterDiscovery", cds.ClusterDiscovery.ToJson()))
ticker := time.NewTicker(DISCOVERY_SERVICE_WRITE_PING)
ticker := time.NewTicker(DiscoveryServiceWritePing)
defer func() {
ticker.Stop()
if _, err := cds.srv.Store.ClusterDiscovery().Delete(&cds.ClusterDiscovery); err != nil {

Просмотреть файл

@@ -394,7 +394,7 @@ func (a *App) tryExecuteCustomCommand(args *model.CommandArgs, trigger string, m
var nfErr *store.ErrNotFound
switch {
case errors.As(ur.NErr, &nfErr):
return nil, nil, model.NewAppError("tryExecuteCustomCommand", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, nil, model.NewAppError("tryExecuteCustomCommand", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, nil, model.NewAppError("tryExecuteCustomCommand", "app.user.get.app_error", nil, ur.NErr.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -26,7 +26,7 @@ import (
)
const (
ERROR_TERMS_OF_SERVICE_NO_ROWS_FOUND = "app.terms_of_service.get.no_rows.app_error"
ErrorTermsOfServiceNoRowsFound = "app.terms_of_service.get.no_rows.app_error"
)
func (s *Server) Config() *model.Config {

Просмотреть файл

@@ -3,6 +3,6 @@
package app
const MISSING_CHANNEL_MEMBER_ERROR = "app.channel.get_member.missing.app_error"
const MISSING_ACCOUNT_ERROR = "app.user.missing_account.const"
const MISSING_AUTH_ACCOUNT_ERROR = "app.user.get_by_auth.missing_account.app_error"
const MissingChannelMemberError = "app.channel.get_member.missing.app_error"
const MissingAccountError = "app.user.missing_account.const"
const MissingAuthAccountError = "app.user.get_by_auth.missing_account.app_error"

Просмотреть файл

@@ -17,9 +17,9 @@ import (
)
const (
// HTTP_REQUEST_TIMEOUT defines a high timeout for downloading large files
// HTTPRequestTimeout defines a high timeout for downloading large files
// from an external URL to avoid slow connections from failing to install.
HTTP_REQUEST_TIMEOUT = 1 * time.Hour
HTTPRequestTimeout = 1 * time.Hour
)
func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) {
@@ -36,7 +36,7 @@ func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) {
}
client := a.HTTPService().MakeClient(true)
client.Timeout = HTTP_REQUEST_TIMEOUT
client.Timeout = HTTPRequestTimeout
var resp *http.Response
err = utils.ProgressiveRetry(func() error {

Просмотреть файл

@@ -359,7 +359,7 @@ func (es *EmailService) SendInviteEmails(team *model.Team, senderName string, se
bodyPage.Props["TeamURL"] = siteURL + "/" + team.Name
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": team.Id, "email": invite}),
)
@@ -429,7 +429,7 @@ func (es *EmailService) sendGuestInviteEmails(team *model.Team, channels []*mode
}
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{
"teamId": team.Id,
"channels": strings.Join(channelIds, " "),
@@ -576,7 +576,7 @@ func (es *EmailService) CreateVerifyEmailToken(userId string, newEmail string) (
return nil, model.NewAppError("CreateVerifyEmailToken", "api.user.create_email_token.error", nil, "", http.StatusInternalServerError)
}
token := model.NewToken(TOKEN_TYPE_VERIFY_EMAIL, string(jsonData))
token := model.NewToken(TokenTypeVerifyEmail, string(jsonData))
if err = es.srv.Store.Token().Save(token); err != nil {
var appErr *model.AppError

Просмотреть файл

@@ -20,7 +20,7 @@ import (
)
const (
EMAIL_BATCHING_TASK_NAME = "Email Batching"
EmailBatchingTaskName = "Email Batching"
)
func (es *EmailService) InitEmailBatching() {
@@ -72,7 +72,7 @@ func NewEmailBatchingJob(es *EmailService, bufferSize int) *EmailBatchingJob {
func (job *EmailBatchingJob) Start() {
mlog.Debug("Email batching job starting. Checking for pending emails periodically.", mlog.Int("interval_in_seconds", *job.server.Config().EmailSettings.EmailBatchingInterval))
newTask := model.CreateRecurringTask(EMAIL_BATCHING_TASK_NAME, job.CheckPendingEmails, time.Duration(*job.server.Config().EmailSettings.EmailBatchingInterval)*time.Second)
newTask := model.CreateRecurringTask(EmailBatchingTaskName, job.CheckPendingEmails, time.Duration(*job.server.Config().EmailSettings.EmailBatchingInterval)*time.Second)
job.taskMutex.Lock()
oldTask := job.task

Просмотреть файл

@@ -67,9 +67,9 @@ const (
maxUploadInitialBufferSize = 1024 * 1024 // 1Mb
// Deprecated
IMAGE_THUMBNAIL_PIXEL_WIDTH = 120
IMAGE_THUMBNAIL_PIXEL_HEIGHT = 100
IMAGE_PREVIEW_PIXEL_WIDTH = 1920
ImageThumbnailPixelWidth = 120
ImageThumbnailPixelHeight = 100
ImagePreviewPixelWidth = 1920
)
func (a *App) FileBackend() (filesstore.FileBackend, *model.AppError) {

Просмотреть файл

@@ -570,7 +570,7 @@ func (*TestHelper) ResetEmojisMigration() {
mainHelper.GetClusterInterface().SendClearRoleCacheMessage()
if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": EMOJIS_PERMISSIONS_MIGRATION_KEY}); err != nil {
if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": EmojisPermissionsMigrationKey}); err != nil {
panic(err)
}
}

Просмотреть файл

@@ -936,7 +936,7 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, teamMember
case errors.As(nErr, &appErr):
return appErr
case errors.As(nErr, &nfErr):
return model.NewAppError("importUserChannels", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("importUserChannels", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("importUserChannels", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -1466,13 +1466,13 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m
if len(userIds) == 2 {
ch, err := a.createDirectChannel(userIds[0], userIds[1])
if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR {
if err != nil && err.Id != store.ChannelExistsError {
return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_direct_channel.error", nil, err.Error(), http.StatusBadRequest)
}
channel = ch
} else {
ch, err := a.createGroupChannel(userIds, userIds[0])
if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR {
if err != nil && err.Id != store.ChannelExistsError {
return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_group_channel.error", nil, err.Error(), http.StatusBadRequest)
}
channel = ch
@@ -1571,13 +1571,13 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun
var ch *model.Channel
if len(userIds) == 2 {
ch, err = a.GetOrCreateDirectChannel(userIds[0], userIds[1])
if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR {
if err != nil && err.Id != store.ChannelExistsError {
return line.LineNumber, model.NewAppError("BulkImport", "app.import.import_direct_post.create_direct_channel.error", nil, err.Error(), http.StatusBadRequest)
}
channel = ch
} else {
ch, err = a.createGroupChannel(userIds, userIds[0])
if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR {
if err != nil && err.Id != store.ChannelExistsError {
return line.LineNumber, model.NewAppError("BulkImport", "app.import.import_direct_post.create_group_channel.error", nil, err.Error(), http.StatusBadRequest)
}
channel = ch

Просмотреть файл

@@ -3102,7 +3102,7 @@ func TestImportImportDirectChannel(t *testing.T) {
user3.Id,
}
channel, appErr := th.App.createGroupChannel(userIds, th.BasicUser.Id)
require.Equal(t, appErr.Id, store.CHANNEL_EXISTS_ERROR)
require.Equal(t, appErr.Id, store.ChannelExistsError)
require.Equal(t, channel.Header, *data.Header)
// Import a channel with some favorites.
@@ -3403,7 +3403,7 @@ func TestImportImportDirectPost(t *testing.T) {
user3.Id,
}
channel, appErr = th.App.createGroupChannel(userIds, th.BasicUser.Id)
require.Equal(t, appErr.Id, store.CHANNEL_EXISTS_ERROR)
require.Equal(t, appErr.Id, store.ChannelExistsError)
groupChannel = channel
// Get the number of posts in the system.

Просмотреть файл

@@ -192,7 +192,7 @@ func (a *App) DoPostActionWithCookie(postId, actionId, userId, selectedOption st
var nfErr *store.ErrNotFound
switch {
case errors.As(ur.NErr, &nfErr):
return "", model.NewAppError("DoPostActionWithCookie", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return "", model.NewAppError("DoPostActionWithCookie", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return "", model.NewAppError("DoPostActionWithCookie", "app.user.get.app_error", nil, ur.NErr.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -31,13 +31,13 @@ var (
)
const (
OPEN_TRACING_PARAMS_MARKER = "@openTracingParams"
APP_ERROR_TYPE = "*model.AppError"
ERROR_TYPE = "error"
OpenTracingParamsMarker = "@openTracingParams"
AppErrorType = "*model.AppError"
ErrorType = "error"
)
func isError(typeName string) bool {
return strings.Contains(typeName, APP_ERROR_TYPE) || strings.Contains(typeName, ERROR_TYPE)
return strings.Contains(typeName, AppErrorType) || strings.Contains(typeName, ErrorType)
}
func init() {
@@ -108,8 +108,8 @@ func extractMethodMetadata(method *ast.Field, src []byte) methodData {
if method.Doc != nil {
for _, comment := range method.Doc.List {
s := comment.Text
if idx := strings.Index(s, OPEN_TRACING_PARAMS_MARKER); idx != -1 {
for _, p := range strings.Split(s[idx+len(OPEN_TRACING_PARAMS_MARKER):], ",") {
if idx := strings.Index(s, OpenTracingParamsMarker); idx != -1 {
for _, p := range strings.Split(s[idx+len(OpenTracingParamsMarker):], ",") {
paramsToTrace[strings.TrimSpace(p)] = true
}
}
@@ -148,7 +148,7 @@ func extractMethodMetadata(method *ast.Field, src []byte) methodData {
}
}
if !found {
log.Fatalf("Unable to find a parameter called '%s' (method '%s') that is mentioned in the '%s' comment. Maybe it was renamed?", paramName, method.Names[0].Name, OPEN_TRACING_PARAMS_MARKER)
log.Fatalf("Unable to find a parameter called '%s' (method '%s') that is mentioned in the '%s' comment. Maybe it was renamed?", paramName, method.Names[0].Name, OpenTracingParamsMarker)
}
}
return methodData{Params: params, Results: results, ParamsToTrace: paramsToTrace}

Просмотреть файл

@@ -83,7 +83,7 @@ func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken
token = &model.Token{
Token: cwsToken,
CreateAt: model.GetMillis(),
Type: TOKEN_TYPE_CWS_ACCESS,
Type: TokenTypeCWSAccess,
}
err := a.Srv().Store.Token().Save(token)
if err != nil {
@@ -125,7 +125,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError)
if id != "" {
user, err := a.GetUser(id)
if err != nil {
if err.Id != MISSING_ACCOUNT_ERROR {
if err.Id != MissingAccountError {
err.StatusCode = http.StatusInternalServerError
return nil, err
}

Просмотреть файл

@@ -47,7 +47,7 @@ func TestCWSLogin(t *testing.T) {
th.App.Srv().SetLicense(license)
t.Run("Should authenticate user when CWS login is enabled and tokens are equal", func(t *testing.T) {
token := model.NewToken(TOKEN_TYPE_CWS_ACCESS, "")
token := model.NewToken(TokenTypeCWSAccess, "")
defer th.App.DeleteToken(token)
os.Setenv("CWS_CLOUD_TOKEN", token.Token)
user, err := th.App.AuthenticateUserForLogin("", th.BasicUser.Username, "", "", token.Token, false)
@@ -60,7 +60,7 @@ func TestCWSLogin(t *testing.T) {
})
t.Run("Should not authenticate the user when CWS token was used", func(t *testing.T) {
token := model.NewToken(TOKEN_TYPE_CWS_ACCESS, "")
token := model.NewToken(TokenTypeCWSAccess, "")
os.Setenv("CWS_CLOUD_TOKEN", token.Token)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
defer th.App.DeleteToken(token)

Просмотреть файл

@@ -12,9 +12,9 @@ import (
"github.com/mattermost/mattermost-server/v5/utils"
)
const EMOJIS_PERMISSIONS_MIGRATION_KEY = "EmojisPermissionsMigrationComplete"
const GUEST_ROLES_CREATION_MIGRATION_KEY = "GuestRolesCreationMigrationComplete"
const SYSTEM_CONSOLE_ROLES_CREATION_MIGRATION_KEY = "SystemConsoleRolesCreationMigrationComplete"
const EmojisPermissionsMigrationKey = "EmojisPermissionsMigrationComplete"
const GuestRolesCreationMigrationKey = "GuestRolesCreationMigrationComplete"
const SystemConsoleRolesCreationMigrationKey = "SystemConsoleRolesCreationMigrationComplete"
// This function migrates the default built in roles from code/config to the database.
func (a *App) DoAdvancedPermissionsMigration() {
@@ -91,7 +91,7 @@ func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error {
func (a *App) DoEmojisPermissionsMigration() {
// If the migration is already marked as completed, don't do it again.
if _, err := a.Srv().Store.System().GetByName(EMOJIS_PERMISSIONS_MIGRATION_KEY); err == nil {
if _, err := a.Srv().Store.System().GetByName(EmojisPermissionsMigrationKey); err == nil {
return
}
@@ -145,7 +145,7 @@ func (a *App) DoEmojisPermissionsMigration() {
}
system := model.System{
Name: EMOJIS_PERMISSIONS_MIGRATION_KEY,
Name: EmojisPermissionsMigrationKey,
Value: "true",
}
@@ -156,7 +156,7 @@ func (a *App) DoEmojisPermissionsMigration() {
func (a *App) DoGuestRolesCreationMigration() {
// If the migration is already marked as completed, don't do it again.
if _, err := a.Srv().Store.System().GetByName(GUEST_ROLES_CREATION_MIGRATION_KEY); err == nil {
if _, err := a.Srv().Store.System().GetByName(GuestRolesCreationMigrationKey); err == nil {
return
}
@@ -232,7 +232,7 @@ func (a *App) DoGuestRolesCreationMigration() {
}
system := model.System{
Name: GUEST_ROLES_CREATION_MIGRATION_KEY,
Name: GuestRolesCreationMigrationKey,
Value: "true",
}
@@ -243,7 +243,7 @@ func (a *App) DoGuestRolesCreationMigration() {
func (a *App) DoSystemConsoleRolesCreationMigration() {
// If the migration is already marked as completed, don't do it again.
if _, err := a.Srv().Store.System().GetByName(SYSTEM_CONSOLE_ROLES_CREATION_MIGRATION_KEY); err == nil {
if _, err := a.Srv().Store.System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil {
return
}
@@ -274,7 +274,7 @@ func (a *App) DoSystemConsoleRolesCreationMigration() {
}
system := model.System{
Name: SYSTEM_CONSOLE_ROLES_CREATION_MIGRATION_KEY,
Name: SystemConsoleRolesCreationMigrationKey,
Value: "true",
}

Просмотреть файл

@@ -24,9 +24,9 @@ import (
)
const (
OAUTH_COOKIE_MAX_AGE_SECONDS = 30 * 60 // 30 minutes
COOKIE_OAUTH = "MMOAUTH"
OPENID_SCOPE = "openid"
OauthCookieMaxAgeSeconds = 30 * 60 // 30 minutes
CookieOauth = "MMOAUTH"
OpenIDScope = "openid"
)
func (a *App) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) {
@@ -567,7 +567,7 @@ func (a *App) getSSOProvider(service string) (einterfaces.OauthProvider, *model.
return nil, model.NewAppError("getSSOProvider", "api.user.authorize_oauth_user.unsupported.app_error", nil, "service="+service, http.StatusNotImplemented)
}
providerType := service
if strings.Contains(*sso.Scope, OPENID_SCOPE) {
if strings.Contains(*sso.Scope, OpenIDScope) {
providerType = model.SERVICE_OPENID
}
provider := einterfaces.GetOauthProvider(providerType)
@@ -603,7 +603,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamId string, to
user, err := a.GetUserByAuth(model.NewString(*authUser.AuthData), service)
if err != nil {
if err.Id == MISSING_AUTH_ACCOUNT_ERROR {
if err.Id == MissingAuthAccountError {
user, err = a.CreateOAuthUser(service, bytes.NewReader(buf.Bytes()), teamId, tokenUser)
} else {
return nil, err
@@ -654,7 +654,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email
user, nErr := a.Srv().Store.User().GetByEmail(email)
if nErr != nil {
return nil, model.NewAppError("CompleteSwitchWithOAuth", MISSING_ACCOUNT_ERROR, nil, nErr.Error(), http.StatusInternalServerError)
return nil, model.NewAppError("CompleteSwitchWithOAuth", MissingAccountError, nil, nErr.Error(), http.StatusInternalServerError)
}
if err := a.RevokeAllSessions(user.Id); err != nil {
@@ -728,12 +728,12 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi
cookieValue := model.NewId()
subpath, _ := utils.GetSubpathFromConfig(a.Config())
expiresAt := time.Unix(model.GetMillis()/1000+int64(OAUTH_COOKIE_MAX_AGE_SECONDS), 0)
expiresAt := time.Unix(model.GetMillis()/1000+int64(OauthCookieMaxAgeSeconds), 0)
oauthCookie := &http.Cookie{
Name: COOKIE_OAUTH,
Name: CookieOauth,
Value: cookieValue,
Path: subpath,
MaxAge: OAUTH_COOKIE_MAX_AGE_SECONDS,
MaxAge: OauthCookieMaxAgeSeconds,
Expires: expiresAt,
HttpOnly: true,
Secure: secure,
@@ -804,7 +804,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest)
}
cookie, cookieErr := r.Cookie(COOKIE_OAUTH)
cookie, cookieErr := r.Cookie(CookieOauth)
if cookieErr != nil {
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest)
}
@@ -822,7 +822,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
subpath, _ := utils.GetSubpathFromConfig(a.Config())
httpCookie := &http.Cookie{
Name: COOKIE_OAUTH,
Name: CookieOauth,
Value: "",
Path: subpath,
MaxAge: -1,

Просмотреть файл

@@ -179,7 +179,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
if cookie != "" {
request.AddCookie(&http.Cookie{
Name: COOKIE_OAUTH,
Name: CookieOauth,
Value: cookie,
})
}

Просмотреть файл

@@ -59,12 +59,12 @@ func (a *App) ResetPermissionsSystem() *model.AppError {
}
// Remove the "System" table entry that marks the emoji permissions migration as done.
if _, err := a.Srv().Store.System().PermanentDeleteByName(EMOJIS_PERMISSIONS_MIGRATION_KEY); err != nil {
if _, err := a.Srv().Store.System().PermanentDeleteByName(EmojisPermissionsMigrationKey); err != nil {
return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, err.Error(), http.StatusInternalServerError)
}
// Remove the "System" table entry that marks the guest roles permissions migration as done.
if _, err := a.Srv().Store.System().PermanentDeleteByName(GUEST_ROLES_CREATION_MIGRATION_KEY); err != nil {
if _, err := a.Srv().Store.System().PermanentDeleteByName(GuestRolesCreationMigrationKey); err != nil {
return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, err.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -20,57 +20,57 @@ type permissionTransformation struct {
type permissionsMap []permissionTransformation
const (
PERMISSION_MANAGE_SYSTEM = "manage_system"
PERMISSION_MANAGE_TEAM = "manage_team"
PERMISSION_MANAGE_EMOJIS = "manage_emojis"
PERMISSION_MANAGE_OTHERS_EMOJIS = "manage_others_emojis"
PERMISSION_CREATE_EMOJIS = "create_emojis"
PERMISSION_DELETE_EMOJIS = "delete_emojis"
PERMISSION_DELETE_OTHERS_EMOJIS = "delete_others_emojis"
PERMISSION_MANAGE_WEBHOOKS = "manage_webhooks"
PERMISSION_MANAGE_OTHERS_WEBHOOKS = "manage_others_webhooks"
PERMISSION_MANAGE_INCOMING_WEBHOOKS = "manage_incoming_webhooks"
PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS = "manage_others_incoming_webhooks"
PERMISSION_MANAGE_OUTGOING_WEBHOOKS = "manage_outgoing_webhooks"
PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS = "manage_others_outgoing_webhooks"
PERMISSION_LIST_PUBLIC_TEAMS = "list_public_teams"
PERMISSION_LIST_PRIVATE_TEAMS = "list_private_teams"
PERMISSION_JOIN_PUBLIC_TEAMS = "join_public_teams"
PERMISSION_JOIN_PRIVATE_TEAMS = "join_private_teams"
PERMISSION_PERMANENT_DELETE_USER = "permanent_delete_user"
PERMISSION_CREATE_BOT = "create_bot"
PERMISSION_READ_BOTS = "read_bots"
PERMISSION_READ_OTHERS_BOTS = "read_others_bots"
PERMISSION_MANAGE_BOTS = "manage_bots"
PERMISSION_MANAGE_OTHERS_BOTS = "manage_others_bots"
PERMISSION_DELETE_PUBLIC_CHANNEL = "delete_public_channel"
PERMISSION_DELETE_PRIVATE_CHANNEL = "delete_private_channel"
PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES = "manage_public_channel_properties"
PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES = "manage_private_channel_properties"
PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE = "convert_public_channel_to_private"
PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC = "convert_private_channel_to_public"
PERMISSION_VIEW_MEMBERS = "view_members"
PERMISSION_INVITE_USER = "invite_user"
PERMISSION_INVITE_GUEST = "invite_guest"
PERMISSION_PROMOTE_GUEST = "promote_guest"
PERMISSION_DEMOTE_TO_GUEST = "demote_to_guest"
PERMISSION_USE_CHANNEL_MENTIONS = "use_channel_mentions"
PERMISSION_CREATE_POST = "create_post"
PERMISSION_CREATE_POST_PUBLIC = "create_post_public"
PERMISSION_USE_GROUP_MENTIONS = "use_group_mentions"
PERMISSION_ADD_REACTION = "add_reaction"
PERMISSION_REMOVE_REACTION = "remove_reaction"
PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS = "manage_public_channel_members"
PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS = "manage_private_channel_members"
PERMISSION_READ_JOBS = "read_jobs"
PERMISSION_MANAGE_JOBS = "manage_jobs"
PERMISSION_READ_OTHER_USERS_TEAMS = "read_other_users_teams"
PERMISSION_EDIT_OTHER_USERS = "edit_other_users"
PERMISSION_READ_PUBLIC_CHANNEL_GROUPS = "read_public_channel_groups"
PERMISSION_READ_PRIVATE_CHANNEL_GROUPS = "read_private_channel_groups"
PERMISSION_EDIT_BRAND = "edit_brand"
PERMISSION_MANAGE_SHARED_CHANNELS = "manage_shared_channels"
PERMISSION_MANAGE_REMOTE_CLUSTERS = "manage_remote_clusters"
PermissionManageSystem = "manage_system"
PermissionManageTeam = "manage_team"
PermissionManageEmojis = "manage_emojis"
PermissionManageOthersEmojis = "manage_others_emojis"
PermissionCreateEmojis = "create_emojis"
PermissionDeleteEmojis = "delete_emojis"
PermissionDeleteOthersEmojis = "delete_others_emojis"
PermissionManageWebhooks = "manage_webhooks"
PermissionManageOthersWebhooks = "manage_others_webhooks"
PermissionManageIncomingWebhooks = "manage_incoming_webhooks"
PermissionManageOthersIncomingWebhooks = "manage_others_incoming_webhooks"
PermissionManageOutgoingWebhooks = "manage_outgoing_webhooks"
PermissionManageOthersOutgoingWebhooks = "manage_others_outgoing_webhooks"
PermissionListPublicTeams = "list_public_teams"
PermissionListPrivateTeams = "list_private_teams"
PermissionJoinPublicTeams = "join_public_teams"
PermissionJoinPrivateTeams = "join_private_teams"
PermissionPermanentDeleteUser = "permanent_delete_user"
PermissionCreateBot = "create_bot"
PermissionReadBots = "read_bots"
PermissionReadOthersBots = "read_others_bots"
PermissionManageBots = "manage_bots"
PermissionManageOthersBots = "manage_others_bots"
PermissionDeletePublicChannel = "delete_public_channel"
PermissionDeletePrivateChannel = "delete_private_channel"
PermissionManagePublicChannelProperties = "manage_public_channel_properties"
PermissionManagePrivateChannelProperties = "manage_private_channel_properties"
PermissionConvertPublicChannelToPrivate = "convert_public_channel_to_private"
PermissionConvertPrivateChannelToPublic = "convert_private_channel_to_public"
PermissionViewMembers = "view_members"
PermissionInviteUser = "invite_user"
PermissionInviteGuest = "invite_guest"
PermissionPromoteGuest = "promote_guest"
PermissionDemoteToGuest = "demote_to_guest"
PermissionUseChannelMentions = "use_channel_mentions"
PermissionCreatePost = "create_post"
PermissionCreatePost_PUBLIC = "create_post_public"
PermissionUseGroupMentions = "use_group_mentions"
PermissionAddReaction = "add_reaction"
PermissionRemoveReaction = "remove_reaction"
PermissionManagePublicChannelMembers = "manage_public_channel_members"
PermissionManagePrivateChannelMembers = "manage_private_channel_members"
PermissionReadJobs = "read_jobs"
PermissionManageJobs = "manage_jobs"
PermissionReadOtherUsersTeams = "read_other_users_teams"
PermissionEditOtherUsers = "edit_other_users"
PermissionReadPublicChannelGroups = "read_public_channel_groups"
PermissionReadPrivateChannelGroups = "read_private_channel_groups"
PermissionEditBrand = "edit_brand"
PermissionManageSharedChannels = "manage_shared_channels"
PermissionManageRemoteClusters = "manage_remote_clusters"
)
func isRole(roleName string) func(*model.Role, map[string]map[string]bool) bool {
@@ -191,14 +191,14 @@ func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, ro
func (a *App) getEmojisPermissionsSplitMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_EMOJIS),
Add: []string{PERMISSION_CREATE_EMOJIS, PERMISSION_DELETE_EMOJIS},
Remove: []string{PERMISSION_MANAGE_EMOJIS},
On: permissionExists(PermissionManageEmojis),
Add: []string{PermissionCreateEmojis, PermissionDeleteEmojis},
Remove: []string{PermissionManageEmojis},
},
permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_OTHERS_EMOJIS),
Add: []string{PERMISSION_DELETE_OTHERS_EMOJIS},
Remove: []string{PERMISSION_MANAGE_OTHERS_EMOJIS},
On: permissionExists(PermissionManageOthersEmojis),
Add: []string{PermissionDeleteOthersEmojis},
Remove: []string{PermissionManageOthersEmojis},
},
}, nil
}
@@ -206,14 +206,14 @@ func (a *App) getEmojisPermissionsSplitMigration() (permissionsMap, error) {
func (a *App) getWebhooksPermissionsSplitMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_WEBHOOKS),
Add: []string{PERMISSION_MANAGE_INCOMING_WEBHOOKS, PERMISSION_MANAGE_OUTGOING_WEBHOOKS},
Remove: []string{PERMISSION_MANAGE_WEBHOOKS},
On: permissionExists(PermissionManageWebhooks),
Add: []string{PermissionManageIncomingWebhooks, PermissionManageOutgoingWebhooks},
Remove: []string{PermissionManageWebhooks},
},
permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_OTHERS_WEBHOOKS),
Add: []string{PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS, PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS},
Remove: []string{PERMISSION_MANAGE_OTHERS_WEBHOOKS},
On: permissionExists(PermissionManageOthersWebhooks),
Add: []string{PermissionManageOthersIncomingWebhooks, PermissionManageOthersOutgoingWebhooks},
Remove: []string{PermissionManageOthersWebhooks},
},
}, nil
}
@@ -222,12 +222,12 @@ func (a *App) getListJoinPublicPrivateTeamsPermissionsMigration() (permissionsMa
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{PERMISSION_LIST_PRIVATE_TEAMS, PERMISSION_JOIN_PRIVATE_TEAMS},
Add: []string{PermissionListPrivateTeams, PermissionJoinPrivateTeams},
Remove: []string{},
},
permissionTransformation{
On: isRole(model.SYSTEM_USER_ROLE_ID),
Add: []string{PERMISSION_LIST_PUBLIC_TEAMS, PERMISSION_JOIN_PUBLIC_TEAMS},
Add: []string{PermissionListPublicTeams, PermissionJoinPublicTeams},
Remove: []string{},
},
}, nil
@@ -236,8 +236,8 @@ func (a *App) getListJoinPublicPrivateTeamsPermissionsMigration() (permissionsMa
func (a *App) removePermanentDeleteUserMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionExists(PERMISSION_PERMANENT_DELETE_USER),
Remove: []string{PERMISSION_PERMANENT_DELETE_USER},
On: permissionExists(PermissionPermanentDeleteUser),
Remove: []string{PermissionPermanentDeleteUser},
},
}, nil
}
@@ -246,7 +246,7 @@ func (a *App) getAddBotPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{PERMISSION_CREATE_BOT, PERMISSION_READ_BOTS, PERMISSION_READ_OTHERS_BOTS, PERMISSION_MANAGE_BOTS, PERMISSION_MANAGE_OTHERS_BOTS},
Add: []string{PermissionCreateBot, PermissionReadBots, PermissionReadOthersBots, PermissionManageBots, PermissionManageOthersBots},
Remove: []string{},
},
}, nil
@@ -255,20 +255,20 @@ func (a *App) getAddBotPermissionsMigration() (permissionsMap, error) {
func (a *App) applyChannelManageDeleteToChannelUser() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES))),
Add: []string{PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES},
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePrivateChannelProperties))),
Add: []string{PermissionManagePrivateChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PERMISSION_DELETE_PRIVATE_CHANNEL))),
Add: []string{PERMISSION_DELETE_PRIVATE_CHANNEL},
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePrivateChannel))),
Add: []string{PermissionDeletePrivateChannel},
},
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES))),
Add: []string{PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES},
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePublicChannelProperties))),
Add: []string{PermissionManagePublicChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PERMISSION_DELETE_PUBLIC_CHANNEL))),
Add: []string{PERMISSION_DELETE_PUBLIC_CHANNEL},
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePublicChannel))),
Add: []string{PermissionDeletePublicChannel},
},
}, nil
}
@@ -276,20 +276,20 @@ func (a *App) applyChannelManageDeleteToChannelUser() (permissionsMap, error) {
func (a *App) removeChannelManageDeleteFromTeamUser() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES)),
Remove: []string{PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES},
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePrivateChannelProperties)),
Remove: []string{PermissionManagePrivateChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_DELETE_PRIVATE_CHANNEL)),
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePrivateChannel)),
Remove: []string{model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id},
},
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES)),
Remove: []string{PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES},
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePublicChannelProperties)),
Remove: []string{PermissionManagePublicChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_DELETE_PUBLIC_CHANNEL)),
Remove: []string{PERMISSION_DELETE_PUBLIC_CHANNEL},
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePublicChannel)),
Remove: []string{PermissionDeletePublicChannel},
},
}, nil
}
@@ -298,11 +298,11 @@ func (a *App) getViewMembersPermissionMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_USER_ROLE_ID),
Add: []string{PERMISSION_VIEW_MEMBERS},
Add: []string{PermissionViewMembers},
},
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{PERMISSION_VIEW_MEMBERS},
Add: []string{PermissionViewMembers},
},
}, nil
}
@@ -311,7 +311,7 @@ func (a *App) getAddManageGuestsPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{PERMISSION_PROMOTE_GUEST, PERMISSION_DEMOTE_TO_GUEST, PERMISSION_INVITE_GUEST},
Add: []string{PermissionPromoteGuest, PermissionDemoteToGuest, PermissionInviteGuest},
},
}, nil
}
@@ -327,11 +327,11 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) {
}
moderatedPermissionsMinusCreatePost := []string{
PERMISSION_ADD_REACTION,
PERMISSION_REMOVE_REACTION,
PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS,
PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS,
PERMISSION_USE_CHANNEL_MENTIONS,
PermissionAddReaction,
PermissionRemoveReaction,
PermissionManagePublicChannelMembers,
PermissionManagePrivateChannelMembers,
PermissionUseChannelMentions,
}
teamAndChannelAdminConditionalTransformations := func(teamAdminID, channelAdminID, channelUserID, channelGuestID string) []permissionTransformation {
@@ -373,14 +373,14 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) {
// ensure all team scheme channel admins have create_post because it's not exposed via the UI
trans := permissionTransformation{
On: isRole(ts.DefaultChannelAdminRole),
Add: []string{PERMISSION_CREATE_POST},
Add: []string{PermissionCreatePost},
}
transformations = append(transformations, trans)
// ensure all team scheme team admins have create_post because it's not exposed via the UI
trans = permissionTransformation{
On: isRole(ts.DefaultTeamAdminRole),
Add: []string{PERMISSION_CREATE_POST},
Add: []string{PermissionCreatePost},
}
transformations = append(transformations, trans)
@@ -396,13 +396,13 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) {
// ensure team admins have create_post
transformations = append(transformations, permissionTransformation{
On: isRole(model.TEAM_ADMIN_ROLE_ID),
Add: []string{PERMISSION_CREATE_POST},
Add: []string{PermissionCreatePost},
})
// ensure channel admins have create_post
transformations = append(transformations, permissionTransformation{
On: isRole(model.CHANNEL_ADMIN_ROLE_ID),
Add: []string{PERMISSION_CREATE_POST},
Add: []string{PermissionCreatePost},
})
// conditionally add all other moderated permissions to team and channel admins
@@ -416,13 +416,13 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) {
// ensure system admin has all of the moderated permissions
transformations = append(transformations, permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: append(moderatedPermissionsMinusCreatePost, PERMISSION_CREATE_POST),
Add: append(moderatedPermissionsMinusCreatePost, PermissionCreatePost),
})
// add the new use_channel_mentions permission to everyone who has create_post
transformations = append(transformations, permissionTransformation{
On: permissionOr(permissionExists(PERMISSION_CREATE_POST), permissionExists(PERMISSION_CREATE_POST_PUBLIC)),
Add: []string{PERMISSION_USE_CHANNEL_MENTIONS},
On: permissionOr(permissionExists(PermissionCreatePost), permissionExists(PermissionCreatePost_PUBLIC)),
Add: []string{PermissionUseChannelMentions},
})
return transformations, nil
@@ -434,9 +434,9 @@ func (a *App) getAddUseGroupMentionsPermissionMigration() (permissionsMap, error
On: permissionAnd(
isNotRole(model.CHANNEL_GUEST_ROLE_ID),
isNotSchemeRole("Channel Guest Role for Scheme"),
permissionOr(permissionExists(PERMISSION_CREATE_POST), permissionExists(PERMISSION_CREATE_POST_PUBLIC)),
permissionOr(permissionExists(PermissionCreatePost), permissionExists(PermissionCreatePost_PUBLIC)),
),
Add: []string{PERMISSION_USE_GROUP_MENTIONS},
Add: []string{PermissionUseGroupMentions},
},
}, nil
}
@@ -458,32 +458,32 @@ func (a *App) getAddSystemConsolePermissionsMigration() (permissionsMap, error)
// add read_jobs to all roles with manage_jobs
transformations = append(transformations, permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_JOBS),
Add: []string{PERMISSION_READ_JOBS},
On: permissionExists(PermissionManageJobs),
Add: []string{PermissionReadJobs},
})
// add read_other_users_teams to all roles with edit_other_users
transformations = append(transformations, permissionTransformation{
On: permissionExists(PERMISSION_EDIT_OTHER_USERS),
Add: []string{PERMISSION_READ_OTHER_USERS_TEAMS},
On: permissionExists(PermissionEditOtherUsers),
Add: []string{PermissionReadOtherUsersTeams},
})
// add read_public_channel_groups to all roles with manage_public_channel_members
transformations = append(transformations, permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS),
Add: []string{PERMISSION_READ_PUBLIC_CHANNEL_GROUPS},
On: permissionExists(PermissionManagePublicChannelMembers),
Add: []string{PermissionReadPublicChannelGroups},
})
// add read_private_channel_groups to all roles with manage_private_channel_members
transformations = append(transformations, permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS),
Add: []string{PERMISSION_READ_PRIVATE_CHANNEL_GROUPS},
On: permissionExists(PermissionManagePrivateChannelMembers),
Add: []string{PermissionReadPrivateChannelGroups},
})
// add edit_brand to all roles with manage_system
transformations = append(transformations, permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_SYSTEM),
Add: []string{PERMISSION_EDIT_BRAND},
On: permissionExists(PermissionManageSystem),
Add: []string{PermissionEditBrand},
})
return transformations, nil
@@ -492,8 +492,8 @@ func (a *App) getAddSystemConsolePermissionsMigration() (permissionsMap, error)
func (a *App) getAddConvertChannelPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionExists(PERMISSION_MANAGE_TEAM),
Add: []string{PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE, PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC},
On: permissionExists(PermissionManageTeam),
Add: []string{PermissionConvertPublicChannelToPrivate, PermissionConvertPrivateChannelToPublic},
},
}, nil
}
@@ -511,7 +511,7 @@ func (a *App) getAddManageSharedChannelsPermissionsMigration() (permissionsMap,
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{PERMISSION_MANAGE_SHARED_CHANNELS},
Add: []string{PermissionManageSharedChannels},
},
}, nil
}
@@ -529,7 +529,7 @@ func (a *App) getAddManageRemoteClustersPermissionsMigration() (permissionsMap,
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{PERMISSION_MANAGE_REMOTE_CLUSTERS},
Add: []string{PermissionManageRemoteClusters},
},
}, nil
}

Просмотреть файл

@@ -21,9 +21,9 @@ import (
)
const (
PENDING_POST_IDS_CACHE_SIZE = 25000
PENDING_POST_IDS_CACHE_TTL = 30 * time.Second
PAGE_DEFAULT = 0
PendingPostIDsCacheSize = 25000
PendingPostIDsCacheTTL = 30 * time.Second
PageDefault = 0
)
func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) {
@@ -58,7 +58,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnl
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("CreatePostAsUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("CreatePostAsUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("CreatePostAsUser", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -128,7 +128,7 @@ func (a *App) deduplicateCreatePost(post *model.Post) (foundPost *model.Post, er
var postId string
nErr := a.Srv().seenPendingPostIdsCache.Get(post.PendingPostId, &postId)
if nErr == cache.ErrKeyNotFound {
a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, unknownPostId, PENDING_POST_IDS_CACHE_TTL)
a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, unknownPostId, PendingPostIDsCacheTTL)
return nil, nil
}
@@ -176,7 +176,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
return
}
a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, savedPost.Id, PENDING_POST_IDS_CACHE_TTL)
a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, savedPost.Id, PendingPostIDsCacheTTL)
}()
post.SanitizeProps()
@@ -196,7 +196,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("CreatePost", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("CreatePost", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("CreatePost", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -318,7 +318,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
// Update the mapping from pending post id to the actual post id, for any clients that
// might be duplicating requests.
a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, rpost.Id, PENDING_POST_IDS_CACHE_TTL)
a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, rpost.Id, PendingPostIDsCacheTTL)
// We make a copy of the post for the plugin hook to avoid a race condition.
rPostCopy := rpost.Clone()
@@ -999,13 +999,13 @@ func (a *App) GetPostsForChannelAroundLastUnread(channelId, userId string, limit
// channel organically, those replies will be added below.
postList.Order = []string{lastUnreadPostId}
if postListBefore, err := a.GetPostsBeforePost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PAGE_DEFAULT, PerPage: limitBefore, SkipFetchThreads: skipFetchThreads}); err != nil {
if postListBefore, err := a.GetPostsBeforePost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PageDefault, PerPage: limitBefore, SkipFetchThreads: skipFetchThreads}); err != nil {
return nil, err
} else if postListBefore != nil {
postList.Extend(postListBefore)
}
if postListAfter, err := a.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PAGE_DEFAULT, PerPage: limitAfter - 1, SkipFetchThreads: skipFetchThreads}); err != nil {
if postListAfter, err := a.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PageDefault, PerPage: limitAfter - 1, SkipFetchThreads: skipFetchThreads}); err != nil {
return nil, err
} else if postListAfter != nil {
postList.Extend(postListAfter)

Просмотреть файл

@@ -27,12 +27,12 @@ type linkMetadataCache struct {
PostImage *model.PostImage
}
const LINK_CACHE_SIZE = 10000
const LINK_CACHE_DURATION = 1 * time.Hour
const LinkCacheSize = 10000
const LinkCacheDuration = 1 * time.Hour
const MaxMetadataImageSize = MaxOpenGraphResponseSize
var linkCache = cache.NewLRU(cache.LRUOptions{
Size: LINK_CACHE_SIZE,
Size: LinkCacheSize,
})
func (a *App) InitPostMetadata() {
@@ -514,7 +514,7 @@ func cacheLinkMetadata(requestURL string, timestamp int64, og *opengraph.OpenGra
PostImage: image,
}
linkCache.SetWithExpiry(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), metadata, LINK_CACHE_DURATION)
linkCache.SetWithExpiry(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), metadata, LinkCacheDuration)
}
func (a *App) parseLinkMetadata(requestURL string, body io.Reader, contentType string) (*opengraph.OpenGraph, *model.PostImage, error) {

Просмотреть файл

@@ -177,7 +177,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
require.Nil(t, err)
require.Equal(t, "message", post.Message)
time.Sleep(PENDING_POST_IDS_CACHE_TTL)
time.Sleep(PendingPostIDsCacheTTL)
duplicatePost, err := th.App.CreatePostAsUser(&model.Post{
UserId: th.BasicUser.Id,

Просмотреть файл

@@ -22,8 +22,8 @@ import (
date_constraints "github.com/reflog/dateconstraints"
)
const MAX_REPEAT_VIEWINGS = 3
const MIN_SECONDS_BETWEEN_REPEAT_VIEWINGS = 60 * 60
const MaxRepeatViewings = 3
const MinSecondsBetweenRepeatViewings = 60 * 60
// http request cache
var noticesCache = utils.RequestCache{}
@@ -237,10 +237,10 @@ func (a *App) GetProductNotices(userId, teamId string, client model.NoticeClient
if view != nil {
repeatable := notice.Repeatable != nil && *notice.Repeatable
if repeatable {
if view.Viewed > MAX_REPEAT_VIEWINGS {
if view.Viewed > MaxRepeatViewings {
continue
}
if (time.Now().UTC().Unix() - view.Timestamp) < MIN_SECONDS_BETWEEN_REPEAT_VIEWINGS {
if (time.Now().UTC().Unix() - view.Timestamp) < MinSecondsBetweenRepeatViewings {
continue
}
} else if view.Viewed > 0 {

Просмотреть файл

@@ -17,18 +17,18 @@ import (
)
const (
SECURITY_URL = "https://securityupdatecheck.mattermost.com"
SECURITY_UPDATE_PERIOD = 86400000 // 24 hours in milliseconds.
PropSecurityURL = "https://securityupdatecheck.mattermost.com"
SecurityUpdatePeriod = 86400000 // 24 hours in milliseconds.
PROP_SECURITY_ID = "id"
PROP_SECURITY_BUILD = "b"
PROP_SECURITY_ENTERPRISE_READY = "be"
PROP_SECURITY_DATABASE = "db"
PROP_SECURITY_OS = "os"
PROP_SECURITY_USER_COUNT = "uc"
PROP_SECURITY_TEAM_COUNT = "tc"
PROP_SECURITY_ACTIVE_USER_COUNT = "auc"
PROP_SECURITY_UNIT_TESTS = "ut"
PropSecurityID = "id"
PropSecurityBuild = "b"
PropSecurityEnterpriseReady = "be"
PropSecurityDatabase = "db"
PropSecurityOS = "os"
PropSecurityUserCount = "uc"
PropSecurityTeamCount = "tc"
PropSecurityActiveUserCount = "auc"
PropSecurityUnitTests = "ut"
)
func (s *Server) DoSecurityUpdateCheck() {
@@ -44,21 +44,21 @@ func (s *Server) DoSecurityUpdateCheck() {
lastSecurityTime, _ := strconv.ParseInt(props[model.SYSTEM_LAST_SECURITY_TIME], 10, 0)
currentTime := model.GetMillis()
if (currentTime - lastSecurityTime) > SECURITY_UPDATE_PERIOD {
if (currentTime - lastSecurityTime) > SecurityUpdatePeriod {
mlog.Debug("Checking for security update from Mattermost")
v := url.Values{}
v.Set(PROP_SECURITY_ID, s.TelemetryId())
v.Set(PROP_SECURITY_BUILD, model.CurrentVersion+"."+model.BuildNumber)
v.Set(PROP_SECURITY_ENTERPRISE_READY, model.BuildEnterpriseReady)
v.Set(PROP_SECURITY_DATABASE, *s.Config().SqlSettings.DriverName)
v.Set(PROP_SECURITY_OS, runtime.GOOS)
v.Set(PropSecurityID, s.TelemetryId())
v.Set(PropSecurityBuild, model.CurrentVersion+"."+model.BuildNumber)
v.Set(PropSecurityEnterpriseReady, model.BuildEnterpriseReady)
v.Set(PropSecurityDatabase, *s.Config().SqlSettings.DriverName)
v.Set(PropSecurityOS, runtime.GOOS)
if len(props[model.SYSTEM_RAN_UNIT_TESTS]) > 0 {
v.Set(PROP_SECURITY_UNIT_TESTS, "1")
v.Set(PropSecurityUnitTests, "1")
} else {
v.Set(PROP_SECURITY_UNIT_TESTS, "0")
v.Set(PropSecurityUnitTests, "0")
}
systemSecurityLastTime := &model.System{Name: model.SYSTEM_LAST_SECURITY_TIME, Value: strconv.FormatInt(currentTime, 10)}
@@ -69,18 +69,18 @@ func (s *Server) DoSecurityUpdateCheck() {
}
if count, err := s.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil {
v.Set(PROP_SECURITY_USER_COUNT, strconv.FormatInt(count, 10))
v.Set(PropSecurityUserCount, strconv.FormatInt(count, 10))
}
if ucr, err := s.Store.Status().GetTotalActiveUsersCount(); err == nil {
v.Set(PROP_SECURITY_ACTIVE_USER_COUNT, strconv.FormatInt(ucr, 10))
v.Set(PropSecurityActiveUserCount, strconv.FormatInt(ucr, 10))
}
if teamCount, err := s.Store.Team().AnalyticsTeamCount(false); err == nil {
v.Set(PROP_SECURITY_TEAM_COUNT, strconv.FormatInt(teamCount, 10))
v.Set(PropSecurityTeamCount, strconv.FormatInt(teamCount, 10))
}
res, err := http.Get(SECURITY_URL + "/security?" + v.Encode())
res, err := http.Get(PropSecurityURL + "/security?" + v.Encode())
if err != nil {
mlog.Error("Failed to get security update information from Mattermost.")
return
@@ -99,7 +99,7 @@ func (s *Server) DoSecurityUpdateCheck() {
return
}
resBody, err := http.Get(SECURITY_URL + "/bulletins/" + bulletin.Id)
resBody, err := http.Get(PropSecurityURL + "/bulletins/" + bulletin.Id)
if err != nil {
mlog.Error("Failed to get security bulletin details")
return

Просмотреть файл

@@ -62,7 +62,7 @@ import (
var MaxNotificationsPerChannelDefault int64 = 1000000
// declaring this as var to allow overriding in tests
var SENTRY_DSN = "placeholder_sentry_dsn"
var SentryDSN = "placeholder_sentry_dsn"
type Server struct {
sqlStore *sqlstore.SqlStore
@@ -232,11 +232,11 @@ func NewServer(options ...Option) (*Server, error) {
fakeApp.HubStart()
if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry {
if strings.Contains(SENTRY_DSN, "placeholder") {
if strings.Contains(SentryDSN, "placeholder") {
mlog.Warn("Sentry reporting is enabled, but SENTRY_DSN is not set. Disabling reporting.")
} else {
if err := sentry.Init(sentry.ClientOptions{
Dsn: SENTRY_DSN,
Dsn: SentryDSN,
Release: model.BuildHash,
AttachStacktrace: true,
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
@@ -297,7 +297,7 @@ func NewServer(options ...Option) (*Server, error) {
return nil, errors.Wrap(err, "Unable to create session cache")
}
if s.seenPendingPostIdsCache, err = s.CacheProvider.NewCache(&cache.CacheOptions{
Size: PENDING_POST_IDS_CACHE_SIZE,
Size: PendingPostIDsCacheSize,
}); err != nil {
return nil, errors.Wrap(err, "Unable to create pending post ids cache")
}
@@ -329,8 +329,8 @@ func NewServer(options ...Option) (*Server, error) {
if err2 != nil {
return nil, errors.Wrap(err2, "cannot parse DB version")
}
if intVer < sqlstore.MINIMUM_REQUIRED_POSTGRES_VERSION {
return nil, fmt.Errorf("minimum required postgres version is %s; found %s", sqlstore.VersionString(sqlstore.MINIMUM_REQUIRED_POSTGRES_VERSION), sqlstore.VersionString(intVer))
if intVer < sqlstore.MinimumRequiredPostgresVersion {
return nil, fmt.Errorf("minimum required postgres version is %s; found %s", sqlstore.VersionString(sqlstore.MinimumRequiredPostgresVersion), sqlstore.VersionString(intVer))
}
}
@@ -738,11 +738,11 @@ func (s *Server) enableLoggingMetrics() {
}
}
const TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN = time.Second
const TimeToWaitForConnectionsToCloseOnServerShutdown = time.Second
func (s *Server) StopHTTPServer() {
if s.Server != nil {
ctx, cancel := context.WithTimeout(context.Background(), TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN)
ctx, cancel := context.WithTimeout(context.Background(), TimeToWaitForConnectionsToCloseOnServerShutdown)
defer cancel()
didShutdown := false
for s.didFinishListen != nil && !didShutdown {
@@ -952,7 +952,7 @@ func (s *Server) Start() error {
var handler http.Handler = s.RootRouter
if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry && !strings.Contains(SENTRY_DSN, "placeholder") {
if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry && !strings.Contains(SentryDSN, "placeholder") {
sentryHandler := sentryhttp.New(sentryhttp.Options{
Repanic: true,
})
@@ -1277,11 +1277,11 @@ func doCommandWebhookCleanup(s *Server) {
}
const (
SESSIONS_CLEANUP_BATCH_SIZE = 1000
SessionsCleanupBatchSize = 1000
)
func doSessionCleanup(s *Server) {
s.Store.Session().Cleanup(model.GetMillis(), SESSIONS_CLEANUP_BATCH_SIZE)
s.Store.Session().Cleanup(model.GetMillis(), SessionsCleanupBatchSize)
}
func doCheckWarnMetricStatus(a *App) {

Просмотреть файл

@@ -382,7 +382,7 @@ func TestSentry(t *testing.T) {
_, port, _ := net.SplitHostPort(server.Listener.Addr().String())
dsn, err := sentry.NewDsn(fmt.Sprintf("http://test:test@localhost:%s/123", port))
require.NoError(t, err)
SENTRY_DSN = dsn.String()
SentryDSN = dsn.String()
s, err := NewServer(func(server *Server) error {
configStore, _ := config.NewFileStore("config.json", true)
@@ -433,7 +433,7 @@ func TestSentry(t *testing.T) {
_, port, _ := net.SplitHostPort(server.Listener.Addr().String())
dsn, err := sentry.NewDsn(fmt.Sprintf("http://test:test@localhost:%s/123", port))
require.NoError(t, err)
SENTRY_DSN = dsn.String()
SentryDSN = dsn.String()
s, err := NewServer(func(server *Server) error {
configStore, _ := config.NewFileStore("config.json", true)

Просмотреть файл

@@ -420,7 +420,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("CreateUserAccessToken", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("CreateUserAccessToken", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("CreateUserAccessToken", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -469,7 +469,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("createSessionForUserAccessToken", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("createSessionForUserAccessToken", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("createSessionForUserAccessToken", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -27,11 +27,11 @@ func NewAutoChannelCreator(a *app.App, team *model.Team, userId string) *AutoCha
team: team,
userId: userId,
Fuzzy: false,
DisplayNameLen: CHANNEL_DISPLAY_NAME_LEN,
DisplayNameLen: ChannelDisplayNameLen,
DisplayNameCharset: utils.ALPHANUMERIC,
NameLen: CHANNEL_NAME_LEN,
NameLen: ChannelNameLen,
NameCharset: utils.LOWERCASE,
ChannelType: CHANNEL_TYPE,
ChannelType: ChannelType,
}
}

Просмотреть файл

@@ -9,24 +9,24 @@ import (
)
const (
USER_PASSWORD = "passwd"
CHANNEL_TYPE = model.CHANNEL_OPEN
BTEST_TEAM_DISPLAY_NAME = "TestTeam"
BTEST_TEAM_NAME = "z-z-testdomaina"
BTEST_TEAM_EMAIL = "test@nowhere.com"
BTEST_TEAM_TYPE = model.TEAM_OPEN
BTEST_USER_NAME = "Mr. Testing Tester"
BTEST_USER_EMAIL = "success+ttester@simulator.amazonses.com"
BTEST_USER_PASSWORD = "passwd"
UserPassword = "passwd"
ChannelType = model.CHANNEL_OPEN
BTestTeamDisplayName = "TestTeam"
BTestTeamName = "z-z-testdomaina"
BTestTeamEmail = "test@nowhere.com"
BTestTeamType = model.TEAM_OPEN
BTestUserName = "Mr. Testing Tester"
BTestUserEmail = "success+ttester@simulator.amazonses.com"
BTestUserPassword = "passwd"
)
var (
TEAM_NAME_LEN = utils.Range{Begin: 10, End: 20}
TEAM_DOMAIN_NAME_LEN = utils.Range{Begin: 10, End: 20}
TEAM_EMAIL_LEN = utils.Range{Begin: 15, End: 30}
USER_NAME_LEN = utils.Range{Begin: 5, End: 20}
USER_EMAIL_LEN = utils.Range{Begin: 15, End: 30}
CHANNEL_DISPLAY_NAME_LEN = utils.Range{Begin: 10, End: 20}
CHANNEL_NAME_LEN = utils.Range{Begin: 5, End: 20}
TEST_IMAGE_FILENAMES = []string{"test.png", "testjpg.jpg", "testgif.gif"}
TeamNameLen = utils.Range{Begin: 10, End: 20}
TeamDomainNameLen = utils.Range{Begin: 10, End: 20}
TeamEmailLen = utils.Range{Begin: 15, End: 30}
UserNameLen = utils.Range{Begin: 5, End: 20}
UserEmailLen = utils.Range{Begin: 15, End: 30}
ChannelDisplayNameLen = utils.Range{Begin: 10, End: 20}
ChannelNameLen = utils.Range{Begin: 5, End: 20}
TestImageFileNames = []string{"test.png", "testjpg.jpg", "testgif.gif"}
)

Просмотреть файл

@@ -36,7 +36,7 @@ func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeam
if err != nil {
return TestEnvironment{}, err
}
client.LoginById(randomUser.Id, USER_PASSWORD)
client.LoginById(randomUser.Id, UserPassword)
teamEnvironment, err := CreateTestEnvironmentInTeam(a, client, team, rangeChannels, rangeUsers, rangePosts, fuzzy)
if err != nil {
return TestEnvironment{}, err
@@ -76,7 +76,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model.
// Have every user join every channel
for _, user := range users {
for _, channel := range channels {
_, resp := client.LoginById(user.Id, USER_PASSWORD)
_, resp := client.LoginById(user.Id, UserPassword)
if resp.Error != nil {
return TeamEnvironment{}, resp.Error
}
@@ -92,7 +92,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model.
numImages := utils.RandIntFromRange(rangePosts) / 4
for j := 0; j < numPosts; j++ {
user := users[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(users) - 1})]
_, resp := client.LoginById(user.Id, USER_PASSWORD)
_, resp := client.LoginById(user.Id, UserPassword)
if resp.Error != nil {
return TeamEnvironment{}, resp.Error
}

Просмотреть файл

@@ -37,7 +37,7 @@ func NewAutoPostCreator(a *app.App, channelid, userid string) *AutoPostCreator {
Fuzzy: false,
TextLength: utils.Range{Begin: 100, End: 200},
HasImage: false,
ImageFilenames: TEST_IMAGE_FILENAMES,
ImageFilenames: TestImageFileNames,
Users: []string{},
Mentions: utils.Range{Begin: 0, End: 5},
Tags: utils.Range{Begin: 0, End: 7},

Просмотреть файл

@@ -28,11 +28,11 @@ func NewAutoTeamCreator(client *model.Client4) *AutoTeamCreator {
return &AutoTeamCreator{
client: client,
Fuzzy: false,
NameLength: TEAM_NAME_LEN,
NameLength: TeamNameLen,
NameCharset: utils.LOWERCASE,
DomainLength: TEAM_DOMAIN_NAME_LEN,
DomainLength: TeamDomainNameLen,
DomainCharset: utils.LOWERCASE,
EmailLength: TEAM_EMAIL_LEN,
EmailLength: TeamEmailLen,
EmailCharset: utils.LOWERCASE,
}
}

Просмотреть файл

@@ -29,9 +29,9 @@ func NewAutoUserCreator(a *app.App, client *model.Client4, team *model.Team) *Au
app: a,
client: client,
team: team,
EmailLength: USER_EMAIL_LEN,
EmailLength: UserEmailLen,
EmailCharset: utils.LOWERCASE,
NameLength: USER_NAME_LEN,
NameLength: UserNameLen,
NameCharset: utils.LOWERCASE,
Fuzzy: false,
}
@@ -39,17 +39,17 @@ func NewAutoUserCreator(a *app.App, client *model.Client4, team *model.Team) *Au
// Basic test team and user so you always know one
func CreateBasicUser(a *app.App, client *model.Client4) *model.AppError {
found, _ := client.TeamExists(BTEST_TEAM_NAME, "")
found, _ := client.TeamExists(BTestTeamName, "")
if found {
return nil
}
newteam := &model.Team{DisplayName: BTEST_TEAM_DISPLAY_NAME, Name: BTEST_TEAM_NAME, Email: BTEST_TEAM_EMAIL, Type: BTEST_TEAM_TYPE}
newteam := &model.Team{DisplayName: BTestTeamDisplayName, Name: BTestTeamName, Email: BTestTeamEmail, Type: BTestTeamType}
basicteam, resp := client.CreateTeam(newteam)
if resp.Error != nil {
return resp.Error
}
newuser := &model.User{Email: BTEST_USER_EMAIL, Nickname: BTEST_USER_NAME, Password: BTEST_USER_PASSWORD}
newuser := &model.User{Email: BTestUserEmail, Nickname: BTestUserName, Password: BTestUserPassword}
ruser, resp := client.CreateUser(newuser)
if resp.Error != nil {
return resp.Error
@@ -91,7 +91,7 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) {
user := &model.User{
Email: userEmail,
Nickname: userName,
Password: USER_PASSWORD}
Password: UserPassword}
ruser, resp := cfg.client.CreateUserWithInviteId(user, cfg.team.InviteId)
if resp.Error != nil {

Просмотреть файл

@@ -13,7 +13,7 @@ type AwayProvider struct {
}
const (
CMD_AWAY = "away"
CmdAway = "away"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*AwayProvider) GetTrigger() string {
return CMD_AWAY
return CmdAway
}
func (*AwayProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_AWAY,
Trigger: CmdAway,
AutoComplete: true,
AutoCompleteDesc: T("api.command_away.desc"),
DisplayName: T("api.command_away.name"),

Просмотреть файл

@@ -14,7 +14,7 @@ type HeaderProvider struct {
}
const (
CMD_HEADER = "header"
CmdHeader = "header"
)
func init() {
@@ -22,12 +22,12 @@ func init() {
}
func (*HeaderProvider) GetTrigger() string {
return CMD_HEADER
return CmdHeader
}
func (*HeaderProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_HEADER,
Trigger: CmdHeader,
AutoComplete: true,
AutoCompleteDesc: T("api.command_channel_header.desc"),
AutoCompleteHint: T("api.command_channel_header.hint"),

Просмотреть файл

@@ -14,7 +14,7 @@ type PurposeProvider struct {
}
const (
CMD_PURPOSE = "purpose"
CmdPurpose = "purpose"
)
func init() {
@@ -22,12 +22,12 @@ func init() {
}
func (*PurposeProvider) GetTrigger() string {
return CMD_PURPOSE
return CmdPurpose
}
func (*PurposeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_PURPOSE,
Trigger: CmdPurpose,
AutoComplete: true,
AutoCompleteDesc: T("api.command_channel_purpose.desc"),
AutoCompleteHint: T("api.command_channel_purpose.hint"),

Просмотреть файл

@@ -14,7 +14,7 @@ type RenameProvider struct {
}
const (
CMD_RENAME = "rename"
CmdRename = "rename"
)
func init() {
@@ -22,14 +22,14 @@ func init() {
}
func (*RenameProvider) GetTrigger() string {
return CMD_RENAME
return CmdRename
}
func (*RenameProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
renameAutocompleteData := model.NewAutocompleteData(CMD_RENAME, T("api.command_channel_rename.hint"), T("api.command_channel_rename.desc"))
renameAutocompleteData := model.NewAutocompleteData(CmdRename, T("api.command_channel_rename.hint"), T("api.command_channel_rename.desc"))
renameAutocompleteData.AddTextArgument(T("api.command_channel_rename.hint"), "[text]", "")
return &model.Command{
Trigger: CMD_RENAME,
Trigger: CmdRename,
AutoComplete: true,
AutoCompleteDesc: T("api.command_channel_rename.desc"),
AutoCompleteHint: T("api.command_channel_rename.hint"),

Просмотреть файл

@@ -15,7 +15,7 @@ type CodeProvider struct {
}
const (
CMD_CODE = "code"
CmdCode = "code"
)
func init() {
@@ -23,12 +23,12 @@ func init() {
}
func (*CodeProvider) GetTrigger() string {
return CMD_CODE
return CmdCode
}
func (*CodeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_CODE,
Trigger: CmdCode,
AutoComplete: true,
AutoCompleteDesc: T("api.command_code.desc"),
AutoCompleteHint: T("api.command_code.hint"),

Просмотреть файл

@@ -13,7 +13,7 @@ type DndProvider struct {
}
const (
CMD_DND = "dnd"
CmdDND = "dnd"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*DndProvider) GetTrigger() string {
return CMD_DND
return CmdDND
}
func (*DndProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_DND,
Trigger: CmdDND,
AutoComplete: true,
AutoCompleteDesc: T("api.command_dnd.desc"),
DisplayName: T("api.command_dnd.name"),

Просмотреть файл

@@ -20,7 +20,7 @@ type EchoProvider struct {
}
const (
CMD_ECHO = "echo"
CmdEcho = "echo"
)
func init() {
@@ -28,12 +28,12 @@ func init() {
}
func (*EchoProvider) GetTrigger() string {
return CMD_ECHO
return CmdEcho
}
func (*EchoProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_ECHO,
Trigger: CmdEcho,
AutoComplete: true,
AutoCompleteDesc: T("api.command_echo.desc"),
AutoCompleteHint: T("api.command_echo.hint"),

Просмотреть файл

@@ -18,8 +18,8 @@ type CollapseProvider struct {
}
const (
CMD_EXPAND = "expand"
CMD_COLLAPSE = "collapse"
CmdExpand = "expand"
CmdCollapse = "collapse"
)
func init() {
@@ -28,16 +28,16 @@ func init() {
}
func (*ExpandProvider) GetTrigger() string {
return CMD_EXPAND
return CmdExpand
}
func (*CollapseProvider) GetTrigger() string {
return CMD_COLLAPSE
return CmdCollapse
}
func (*ExpandProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_EXPAND,
Trigger: CmdExpand,
AutoComplete: true,
AutoCompleteDesc: T("api.command_expand.desc"),
DisplayName: T("api.command_expand.name"),
@@ -46,7 +46,7 @@ func (*ExpandProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Com
func (*CollapseProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_COLLAPSE,
Trigger: CmdCollapse,
AutoComplete: true,
AutoCompleteDesc: T("api.command_collapse.desc"),
DisplayName: T("api.command_collapse.name"),

Просмотреть файл

@@ -17,7 +17,7 @@ type groupmsgProvider struct {
}
const (
CMD_GROUPMSG = "groupmsg"
CmdGroupMsg = "groupmsg"
)
func init() {
@@ -25,12 +25,12 @@ func init() {
}
func (*groupmsgProvider) GetTrigger() string {
return CMD_GROUPMSG
return CmdGroupMsg
}
func (*groupmsgProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_GROUPMSG,
Trigger: CmdGroupMsg,
AutoComplete: true,
AutoCompleteDesc: T("api.command_groupmsg.desc"),
AutoCompleteHint: T("api.command_groupmsg.hint"),

Просмотреть файл

@@ -13,7 +13,7 @@ type HelpProvider struct {
}
const (
CMD_HELP = "help"
CmdHelp = "help"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (h *HelpProvider) GetTrigger() string {
return CMD_HELP
return CmdHelp
}
func (h *HelpProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_HELP,
Trigger: CmdHelp,
AutoComplete: true,
AutoCompleteDesc: T("api.command_help.desc"),
DisplayName: T("api.command_help.name"),

Просмотреть файл

@@ -17,7 +17,7 @@ type InviteProvider struct {
}
const (
CMD_INVITE = "invite"
CmdInvite = "invite"
)
func init() {
@@ -25,12 +25,12 @@ func init() {
}
func (*InviteProvider) GetTrigger() string {
return CMD_INVITE
return CmdInvite
}
func (*InviteProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_INVITE,
Trigger: CmdInvite,
AutoComplete: true,
AutoCompleteDesc: T("api.command_invite.desc"),
AutoCompleteHint: T("api.command_invite.hint"),

Просмотреть файл

@@ -16,7 +16,7 @@ type InvitePeopleProvider struct {
}
const (
CMD_INVITE_PEOPLE = "invite_people"
CmdInvite_PEOPLE = "invite_people"
)
func init() {
@@ -24,7 +24,7 @@ func init() {
}
func (*InvitePeopleProvider) GetTrigger() string {
return CMD_INVITE_PEOPLE
return CmdInvite_PEOPLE
}
func (*InvitePeopleProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
@@ -33,7 +33,7 @@ func (*InvitePeopleProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *mod
autoComplete = false
}
return &model.Command{
Trigger: CMD_INVITE_PEOPLE,
Trigger: CmdInvite_PEOPLE,
AutoComplete: autoComplete,
AutoCompleteDesc: T("api.command.invite_people.desc"),
AutoCompleteHint: T("api.command.invite_people.hint"),

Просмотреть файл

@@ -15,7 +15,7 @@ type JoinProvider struct {
}
const (
CMD_JOIN = "join"
CmdJoin = "join"
)
func init() {
@@ -23,12 +23,12 @@ func init() {
}
func (*JoinProvider) GetTrigger() string {
return CMD_JOIN
return CmdJoin
}
func (*JoinProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_JOIN,
Trigger: CmdJoin,
AutoComplete: true,
AutoCompleteDesc: T("api.command_join.desc"),
AutoCompleteHint: T("api.command_join.hint"),

Просмотреть файл

@@ -13,7 +13,7 @@ type LeaveProvider struct {
}
const (
CMD_LEAVE = "leave"
CmdLeave = "leave"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*LeaveProvider) GetTrigger() string {
return CMD_LEAVE
return CmdLeave
}
func (*LeaveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_LEAVE,
Trigger: CmdLeave,
AutoComplete: true,
AutoCompleteDesc: T("api.command_leave.desc"),
DisplayName: T("api.command_leave.name"),

Просмотреть файл

@@ -72,7 +72,7 @@ var usage = `Mattermost testing commands to help configure the system
`
const (
CMD_TEST = "test"
CmdTest = "test"
)
var (
@@ -91,7 +91,7 @@ func init() {
}
func (*LoadTestProvider) GetTrigger() string {
return CMD_TEST
return CmdTest
}
func (*LoadTestProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
@@ -99,7 +99,7 @@ func (*LoadTestProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.C
return nil
}
return &model.Command{
Trigger: CMD_TEST,
Trigger: CmdTest,
AutoComplete: false,
AutoCompleteDesc: "Debug Load Testing",
AutoCompleteHint: "help",
@@ -110,7 +110,7 @@ func (*LoadTestProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.C
func (lt *LoadTestProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
commandResponse, err := lt.doCommand(a, args, message)
if err != nil {
mlog.Error("failed command /"+CMD_TEST, mlog.Err(err))
mlog.Error("failed command /"+CmdTest, mlog.Err(err))
}
return commandResponse
@@ -213,7 +213,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa
if err := CreateBasicUser(a, client); err != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
}
_, resp := client.Login(BTEST_USER_EMAIL, BTEST_USER_PASSWORD)
_, resp := client.Login(BTestUserEmail, BTestUserPassword)
if resp.Error != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error
}
@@ -232,7 +232,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa
mlog.Info("Testing environment created")
for i := 0; i < len(environment.Teams); i++ {
mlog.Info("Team Created: " + environment.Teams[i].Name)
mlog.Info("\t User to login: " + environment.Environments[i].Users[0].Email + ", " + USER_PASSWORD)
mlog.Info("\t User to login: " + environment.Environments[i].Users[0].Email + ", " + UserPassword)
}
} else {
team, err := a.Srv().Store.Team().Get(args.TeamId)

Просмотреть файл

@@ -13,7 +13,7 @@ type LogoutProvider struct {
}
const (
CMD_LOGOUT = "logout"
CmdLogout = "logout"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*LogoutProvider) GetTrigger() string {
return CMD_LOGOUT
return CmdLogout
}
func (*LogoutProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_LOGOUT,
Trigger: CmdLogout,
AutoComplete: true,
AutoCompleteDesc: T("api.command_logout.desc"),
AutoCompleteHint: "",

Просмотреть файл

@@ -13,7 +13,7 @@ type MeProvider struct {
}
const (
CMD_ME = "me"
CmdMe = "me"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*MeProvider) GetTrigger() string {
return CMD_ME
return CmdMe
}
func (*MeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_ME,
Trigger: CmdMe,
AutoComplete: true,
AutoCompleteDesc: T("api.command_me.desc"),
AutoCompleteHint: T("api.command_me.hint"),

Просмотреть файл

@@ -18,7 +18,7 @@ type msgProvider struct {
}
const (
CMD_MSG = "msg"
CmdMsg = "msg"
)
func init() {
@@ -26,12 +26,12 @@ func init() {
}
func (*msgProvider) GetTrigger() string {
return CMD_MSG
return CmdMsg
}
func (*msgProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_MSG,
Trigger: CmdMsg,
AutoComplete: true,
AutoCompleteDesc: T("api.command_msg.desc"),
AutoCompleteHint: T("api.command_msg.hint"),

Просмотреть файл

@@ -15,7 +15,7 @@ type MuteProvider struct {
}
const (
CMD_MUTE = "mute"
CmdMute = "mute"
)
func init() {
@@ -23,12 +23,12 @@ func init() {
}
func (*MuteProvider) GetTrigger() string {
return CMD_MUTE
return CmdMute
}
func (*MuteProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_MUTE,
Trigger: CmdMute,
AutoComplete: true,
AutoCompleteDesc: T("api.command_mute.desc"),
AutoCompleteHint: T("api.command_mute.hint"),

Просмотреть файл

@@ -13,7 +13,7 @@ type OfflineProvider struct {
}
const (
CMD_OFFLINE = "offline"
CmdOffline = "offline"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*OfflineProvider) GetTrigger() string {
return CMD_OFFLINE
return CmdOffline
}
func (*OfflineProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_OFFLINE,
Trigger: CmdOffline,
AutoComplete: true,
AutoCompleteDesc: T("api.command_offline.desc"),
DisplayName: T("api.command_offline.name"),

Просмотреть файл

@@ -13,7 +13,7 @@ type OnlineProvider struct {
}
const (
CMD_ONLINE = "online"
CmdOnline = "online"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*OnlineProvider) GetTrigger() string {
return CMD_ONLINE
return CmdOnline
}
func (*OnlineProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_ONLINE,
Trigger: CmdOnline,
AutoComplete: true,
AutoCompleteDesc: T("api.command_online.desc"),
DisplayName: T("api.command_online.name"),

Просмотреть файл

@@ -14,7 +14,7 @@ type OpenProvider struct {
}
const (
CMD_OPEN = "open"
CmdOpen = "open"
)
func init() {
@@ -22,12 +22,12 @@ func init() {
}
func (open *OpenProvider) GetTrigger() string {
return CMD_OPEN
return CmdOpen
}
func (open *OpenProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
cmd := open.JoinProvider.GetCommand(a, T)
cmd.Trigger = CMD_OPEN
cmd.Trigger = CmdOpen
cmd.DisplayName = T("api.command_open.name")
return cmd
}

Просмотреть файл

@@ -20,8 +20,8 @@ type KickProvider struct {
}
const (
CMD_REMOVE = "remove"
CMD_KICK = "kick"
CmdRemove = "remove"
CmdKick = "kick"
)
func init() {
@@ -30,16 +30,16 @@ func init() {
}
func (*RemoveProvider) GetTrigger() string {
return CMD_REMOVE
return CmdRemove
}
func (*KickProvider) GetTrigger() string {
return CMD_KICK
return CmdKick
}
func (*RemoveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_REMOVE,
Trigger: CmdRemove,
AutoComplete: true,
AutoCompleteDesc: T("api.command_remove.desc"),
AutoCompleteHint: T("api.command_remove.hint"),
@@ -49,7 +49,7 @@ func (*RemoveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Com
func (*KickProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_KICK,
Trigger: CmdKick,
AutoComplete: true,
AutoCompleteDesc: T("api.command_remove.desc"),
AutoCompleteHint: T("api.command_remove.hint"),

Просмотреть файл

@@ -13,7 +13,7 @@ type SearchProvider struct {
}
const (
CMD_SEARCH = "search"
CmdSearch = "search"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (search *SearchProvider) GetTrigger() string {
return CMD_SEARCH
return CmdSearch
}
func (search *SearchProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_SEARCH,
Trigger: CmdSearch,
AutoComplete: true,
AutoCompleteDesc: T("api.command_search.desc"),
AutoCompleteHint: T("api.command_search.hint"),

Просмотреть файл

@@ -13,7 +13,7 @@ type SettingsProvider struct {
}
const (
CMD_SETTINGS = "settings"
CmdSettings = "settings"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (settings *SettingsProvider) GetTrigger() string {
return CMD_SETTINGS
return CmdSettings
}
func (settings *SettingsProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_SETTINGS,
Trigger: CmdSettings,
AutoComplete: true,
AutoCompleteDesc: T("api.command_settings.desc"),
AutoCompleteHint: "",

Просмотреть файл

@@ -13,7 +13,7 @@ type ShortcutsProvider struct {
}
const (
CMD_SHORTCUTS = "shortcuts"
CmdShortcuts = "shortcuts"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*ShortcutsProvider) GetTrigger() string {
return CMD_SHORTCUTS
return CmdShortcuts
}
func (*ShortcutsProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_SHORTCUTS,
Trigger: CmdShortcuts,
AutoComplete: true,
AutoCompleteDesc: T("api.command_shortcuts.desc"),
AutoCompleteHint: "",

Просмотреть файл

@@ -13,7 +13,7 @@ type ShrugProvider struct {
}
const (
CMD_SHRUG = "shrug"
CmdShrug = "shrug"
)
func init() {
@@ -21,12 +21,12 @@ func init() {
}
func (*ShrugProvider) GetTrigger() string {
return CMD_SHRUG
return CmdShrug
}
func (*ShrugProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{
Trigger: CMD_SHRUG,
Trigger: CmdShrug,
AutoComplete: true,
AutoCompleteDesc: T("api.command_shrug.desc"),
AutoCompleteHint: T("api.command_shrug.hint"),

Просмотреть файл

@@ -510,7 +510,7 @@ func (a *App) AddUserToTeam(teamId string, userId string, userRequestorId string
var nfErr *store.ErrNotFound
switch {
case errors.As(result.NErr, &nfErr):
return nil, model.NewAppError("AddUserToTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("AddUserToTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("AddUserToTeam", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError)
}
@@ -545,11 +545,11 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team,
return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_invalid.app_error", nil, err.Error(), http.StatusBadRequest)
}
if token.Type != TOKEN_TYPE_TEAM_INVITATION && token.Type != TOKEN_TYPE_GUEST_INVITATION {
if token.Type != TokenTypeTeamInvitation && token.Type != TokenTypeGuestInvitation {
return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusBadRequest)
}
if model.GetMillis()-token.CreateAt >= INVITATION_EXPIRY_TIME {
if model.GetMillis()-token.CreateAt >= InvitationExpiryTime {
a.DeleteToken(token)
return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusBadRequest)
}
@@ -591,17 +591,17 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team,
var nfErr *store.ErrNotFound
switch {
case errors.As(result.NErr, &nfErr):
return nil, model.NewAppError("AddUserToTeamByToken", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("AddUserToTeamByToken", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("AddUserToTeamByToken", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError)
}
}
user := result.Data.(*model.User)
if user.IsGuest() && token.Type == TOKEN_TYPE_TEAM_INVITATION {
if user.IsGuest() && token.Type == TokenTypeTeamInvitation {
return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.invalid_invitation_type.app_error", nil, "", http.StatusBadRequest)
}
if !user.IsGuest() && token.Type == TOKEN_TYPE_GUEST_INVITATION {
if !user.IsGuest() && token.Type == TokenTypeGuestInvitation {
return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.invalid_invitation_type.app_error", nil, "", http.StatusBadRequest)
}
@@ -609,7 +609,7 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team,
return nil, err
}
if token.Type == TOKEN_TYPE_GUEST_INVITATION {
if token.Type == TokenTypeGuestInvitation {
channels, err := a.Srv().Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " "), false)
if err != nil {
return nil, model.NewAppError("AddUserToTeamByToken", "app.channel.get_channels_by_ids.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -662,7 +662,7 @@ func (a *App) AddUserToTeamByInviteId(inviteId string, userId string) (*model.Te
var nfErr *store.ErrNotFound
switch {
case errors.As(result.NErr, &nfErr):
return nil, model.NewAppError("AddUserToTeamByInviteId", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("AddUserToTeamByInviteId", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("AddUserToTeamByInviteId", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError)
}
@@ -1184,7 +1184,7 @@ func (a *App) RemoveUserFromTeam(teamId string, userId string, requestorId strin
var nfErr *store.ErrNotFound
switch {
case errors.As(result.NErr, &nfErr):
return model.NewAppError("RemoveUserFromTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("RemoveUserFromTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("RemoveUserFromTeam", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError)
}
@@ -1210,7 +1210,7 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return model.NewAppError("RemoveTeamMemberFromTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("RemoveTeamMemberFromTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("RemoveTeamMemberFromTeam", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
@@ -1389,7 +1389,7 @@ func (a *App) prepareInviteNewUsersToTeam(teamId, senderId string) (*model.User,
var nfErr *store.ErrNotFound
switch {
case errors.As(result.NErr, &nfErr):
return nil, nil, model.NewAppError("prepareInviteNewUsersToTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, nil, model.NewAppError("prepareInviteNewUsersToTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, nil, model.NewAppError("prepareInviteNewUsersToTeam", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError)
}
@@ -1514,7 +1514,7 @@ func (a *App) prepareInviteGuestsToChannels(teamId string, guestsInvite *model.G
var nfErr *store.ErrNotFound
switch {
case errors.As(result.NErr, &nfErr):
return nil, nil, nil, model.NewAppError("prepareInviteGuestsToChannels", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, nil, nil, model.NewAppError("prepareInviteGuestsToChannels", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, nil, nil, model.NewAppError("prepareInviteGuestsToChannels", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError)
}
@@ -1845,11 +1845,11 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) {
return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest)
}
if token.Type != TOKEN_TYPE_TEAM_INVITATION && token.Type != TOKEN_TYPE_GUEST_INVITATION {
if token.Type != TokenTypeTeamInvitation && token.Type != TokenTypeGuestInvitation {
return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest)
}
if model.GetMillis()-token.CreateAt >= INVITATION_EXPIRY_TIME {
if model.GetMillis()-token.CreateAt >= InvitationExpiryTime {
a.DeleteToken(token)
return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.expired_link.app_error", nil, "", http.StatusBadRequest)
}
@@ -2005,10 +2005,10 @@ func (a *App) RemoveTeamIcon(teamId string) *model.AppError {
}
func (a *App) InvalidateAllEmailInvites() *model.AppError {
if err := a.Srv().Store.Token().RemoveAllTokensByType(TOKEN_TYPE_TEAM_INVITATION); err != nil {
if err := a.Srv().Store.Token().RemoveAllTokensByType(TokenTypeTeamInvitation); err != nil {
return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, err.Error(), http.StatusBadRequest)
}
if err := a.Srv().Store.Token().RemoveAllTokensByType(TOKEN_TYPE_GUEST_INVITATION); err != nil {
if err := a.Srv().Store.Token().RemoveAllTokensByType(TokenTypeGuestInvitation); err != nil {
return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, err.Error(), http.StatusBadRequest)
}
return nil

Просмотреть файл

@@ -200,7 +200,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("invalid token type", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_VERIFY_EMAIL,
TokenTypeVerifyEmail,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
)
@@ -213,11 +213,11 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("expired token", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
)
token.CreateAt = model.GetMillis() - INVITATION_EXPIRY_TIME - 1
token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1
require.Nil(t, th.App.Srv().Store.Token().Save(token))
defer th.App.DeleteToken(token)
@@ -227,7 +227,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("invalid team id", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": model.NewId()}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -239,7 +239,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("invalid user id", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -251,7 +251,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("valid request", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -268,7 +268,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("invalid add a guest using a regular invite", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -278,7 +278,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("invalid add a regular user using a guest invite", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -293,7 +293,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
}()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.RestrictCreationToDomains = "restricted.com" })
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -309,7 +309,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
}()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.RestrictCreationToDomains = "restricted.com" })
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
)
guestEmail := rguest.Email
@@ -335,7 +335,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
}()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictCreationToDomains = "restricted.com" })
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
)
_, err = th.App.Srv().Store.User().Update(rguest, false)
@@ -350,7 +350,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
t.Run("valid request from guest invite", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -373,7 +373,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
require.Nil(t, err, "Should update the team")
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -397,7 +397,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
defer th.App.PermanentDeleteUser(&user)
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -412,7 +412,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
team := th.CreateTeam()
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": team.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -1102,7 +1102,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) {
t1 := model.Token{
Token: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
CreateAt: model.GetMillis(),
Type: TOKEN_TYPE_GUEST_INVITATION,
Type: TokenTypeGuestInvitation,
Extra: "",
}
err := th.App.Srv().Store.Token().Save(&t1)
@@ -1111,7 +1111,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) {
t2 := model.Token{
Token: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
CreateAt: model.GetMillis(),
Type: TOKEN_TYPE_TEAM_INVITATION,
Type: TokenTypeTeamInvitation,
Extra: "",
}
err = th.App.Srv().Store.Token().Save(&t2)

Просмотреть файл

@@ -38,14 +38,14 @@ import (
)
const (
TOKEN_TYPE_PASSWORD_RECOVERY = "password_recovery"
TOKEN_TYPE_VERIFY_EMAIL = "verify_email"
TOKEN_TYPE_TEAM_INVITATION = "team_invitation"
TOKEN_TYPE_GUEST_INVITATION = "guest_invitation"
TOKEN_TYPE_CWS_ACCESS = "cws_access_token"
PASSWORD_RECOVER_EXPIRY_TIME = 1000 * 60 * 60 // 1 hour
INVITATION_EXPIRY_TIME = 1000 * 60 * 60 * 48 // 48 hours
IMAGE_PROFILE_PIXEL_DIMENSION = 128
TokenTypePasswordRecovery = "password_recovery"
TokenTypeVerifyEmail = "verify_email"
TokenTypeTeamInvitation = "team_invitation"
TokenTypeGuestInvitation = "guest_invitation"
TokenTypeCWSAccess = "cws_access_token"
PasswordRecoverExpiryTime = 1000 * 60 * 60 // 1 hour
InvitationExpiryTime = 1000 * 60 * 60 * 48 // 48 hours
ImageProfilePixelDimension = 128
)
func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model.User, *model.AppError) {
@@ -53,11 +53,11 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model.
return nil, err
}
if token.Type != TOKEN_TYPE_TEAM_INVITATION && token.Type != TOKEN_TYPE_GUEST_INVITATION {
if token.Type != TokenTypeTeamInvitation && token.Type != TokenTypeGuestInvitation {
return nil, model.NewAppError("CreateUserWithToken", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusBadRequest)
}
if model.GetMillis()-token.CreateAt >= INVITATION_EXPIRY_TIME {
if model.GetMillis()-token.CreateAt >= InvitationExpiryTime {
a.DeleteToken(token)
return nil, model.NewAppError("CreateUserWithToken", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusBadRequest)
}
@@ -85,7 +85,7 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model.
var ruser *model.User
var err *model.AppError
if token.Type == TOKEN_TYPE_TEAM_INVITATION {
if token.Type == TokenTypeTeamInvitation {
ruser, err = a.CreateUser(user)
} else {
ruser, err = a.CreateGuest(user)
@@ -100,7 +100,7 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model.
a.AddDirectChannels(team.Id, ruser)
if token.Type == TOKEN_TYPE_GUEST_INVITATION {
if token.Type == TokenTypeGuestInvitation {
for _, channel := range channels {
_, err := a.AddChannelMember(ruser.Id, channel, "", "")
if err != nil {
@@ -448,7 +448,7 @@ func (a *App) GetUser(userId string) (*model.User, *model.AppError) {
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &nfErr):
return nil, model.NewAppError("GetUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("GetUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("GetUser", "app.user.get.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -477,9 +477,9 @@ func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) {
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &nfErr):
return nil, model.NewAppError("GetUserByEmail", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("GetUserByEmail", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("GetUserByEmail", MISSING_ACCOUNT_ERROR, nil, err.Error(), http.StatusInternalServerError)
return nil, model.NewAppError("GetUserByEmail", MissingAccountError, nil, err.Error(), http.StatusInternalServerError)
}
}
return user, nil
@@ -492,9 +492,9 @@ func (a *App) GetUserByAuth(authData *string, authService string) (*model.User,
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &invErr):
return nil, model.NewAppError("GetUserByAuth", MISSING_AUTH_ACCOUNT_ERROR, nil, invErr.Error(), http.StatusBadRequest)
return nil, model.NewAppError("GetUserByAuth", MissingAuthAccountError, nil, invErr.Error(), http.StatusBadRequest)
case errors.As(err, &nfErr):
return nil, model.NewAppError("GetUserByAuth", MISSING_AUTH_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusInternalServerError)
return nil, model.NewAppError("GetUserByAuth", MissingAuthAccountError, nil, nfErr.Error(), http.StatusInternalServerError)
default:
return nil, model.NewAppError("GetUserByAuth", "app.user.get_by_auth.other.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -755,7 +755,7 @@ func (a *App) ActivateMfa(userId, token string) *model.AppError {
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &nfErr):
return model.NewAppError("ActivateMfa", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return model.NewAppError("ActivateMfa", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return model.NewAppError("ActivateMfa", "app.user.get.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -830,10 +830,10 @@ func CreateProfileImage(username string, userId string, initialFont string) ([]b
}
color := colors[int64(seed)%int64(len(colors))]
dstImg := image.NewRGBA(image.Rect(0, 0, IMAGE_PROFILE_PIXEL_DIMENSION, IMAGE_PROFILE_PIXEL_DIMENSION))
dstImg := image.NewRGBA(image.Rect(0, 0, ImageProfilePixelDimension, ImageProfilePixelDimension))
srcImg := image.White
draw.Draw(dstImg, dstImg.Bounds(), &image.Uniform{color}, image.Point{}, draw.Src)
size := float64(IMAGE_PROFILE_PIXEL_DIMENSION / 2)
size := float64(ImageProfilePixelDimension / 2)
c := freetype.NewContext()
c.SetFont(font)
@@ -842,7 +842,7 @@ func CreateProfileImage(username string, userId string, initialFont string) ([]b
c.SetDst(dstImg)
c.SetSrc(srcImg)
pt := freetype.Pt(IMAGE_PROFILE_PIXEL_DIMENSION/5, IMAGE_PROFILE_PIXEL_DIMENSION*2/3)
pt := freetype.Pt(ImageProfilePixelDimension/5, ImageProfilePixelDimension*2/3)
_, err = c.DrawString(initial, pt)
if err != nil {
return nil, model.NewAppError("CreateProfileImage", "api.user.create_profile_image.initial.app_error", nil, err.Error(), http.StatusInternalServerError)
@@ -1247,7 +1247,7 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User,
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &nfErr):
return nil, model.NewAppError("UpdateUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("UpdateUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("UpdateUser", "app.user.get.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -1450,7 +1450,7 @@ func (a *App) ResetPasswordFromToken(userSuppliedTokenString, newPassword string
if err != nil {
return err
}
if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME {
if model.GetMillis()-token.CreateAt >= PasswordRecoverExpiryTime {
return model.NewAppError("resetPassword", "api.user.reset_password.link_expired.app_error", nil, "", http.StatusBadRequest)
}
@@ -1523,7 +1523,7 @@ func (a *App) CreatePasswordRecoveryToken(userId, email string) (*model.Token, *
return nil, model.NewAppError("CreatePasswordRecoveryToken", "api.user.create_password_token.error", nil, "", http.StatusInternalServerError)
}
token := model.NewToken(TOKEN_TYPE_PASSWORD_RECOVERY, string(jsonData))
token := model.NewToken(TokenTypePasswordRecovery, string(jsonData))
if err := a.Srv().Store.Token().Save(token); err != nil {
var appErr *model.AppError
@@ -1543,7 +1543,7 @@ func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppEr
if err != nil {
return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.invalid_link.app_error", nil, err.Error(), http.StatusBadRequest)
}
if rtoken.Type != TOKEN_TYPE_PASSWORD_RECOVERY {
if rtoken.Type != TokenTypePasswordRecovery {
return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.broken_token.app_error", nil, "", http.StatusBadRequest)
}
return rtoken, nil
@@ -1758,7 +1758,7 @@ func (a *App) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppErr
if err != nil {
return err
}
if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME {
if model.GetMillis()-token.CreateAt >= PasswordRecoverExpiryTime {
return model.NewAppError("VerifyEmailFromToken", "api.user.verify_email.link_expired.app_error", nil, "", http.StatusBadRequest)
}
@@ -1802,7 +1802,7 @@ func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError)
if err != nil {
return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.bad_link.app_error", nil, err.Error(), http.StatusBadRequest)
}
if rtoken.Type != TOKEN_TYPE_VERIFY_EMAIL {
if rtoken.Type != TokenTypeVerifyEmail {
return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.broken_token.app_error", nil, "", http.StatusBadRequest)
}
return rtoken, nil
@@ -2337,7 +2337,7 @@ func (a *App) ConvertBotToUser(bot *model.Bot, userPatch *model.UserPatch, sysad
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.NewAppError("ConvertBotToUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound)
return nil, model.NewAppError("ConvertBotToUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound)
default:
return nil, model.NewAppError("ConvertBotToUser", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}

Просмотреть файл

@@ -716,7 +716,7 @@ func TestCreateUserWithToken(t *testing.T) {
t.Run("invalid token type", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_VERIFY_EMAIL,
TokenTypeVerifyEmail,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -727,10 +727,10 @@ func TestCreateUserWithToken(t *testing.T) {
t.Run("expired token", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
)
token.CreateAt = model.GetMillis() - INVITATION_EXPIRY_TIME - 1
token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1
require.Nil(t, th.App.Srv().Store.Token().Save(token))
defer th.App.DeleteToken(token)
_, err := th.App.CreateUserWithToken(&user, token)
@@ -739,7 +739,7 @@ func TestCreateUserWithToken(t *testing.T) {
t.Run("invalid team id", func(t *testing.T) {
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": model.NewId(), "email": user.Email}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -751,7 +751,7 @@ func TestCreateUserWithToken(t *testing.T) {
t.Run("valid regular user request", func(t *testing.T) {
invitationEmail := model.NewId() + "other-email@test.com"
token := model.NewToken(
TOKEN_TYPE_TEAM_INVITATION,
TokenTypeTeamInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -771,7 +771,7 @@ func TestCreateUserWithToken(t *testing.T) {
t.Run("valid guest request", func(t *testing.T) {
invitationEmail := model.NewId() + "other-email@test.com"
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))
@@ -801,11 +801,11 @@ func TestCreateUserWithToken(t *testing.T) {
forbiddenInvitationEmail := model.NewId() + "other-email@test.com"
grantedInvitationEmail := model.NewId() + "other-email@restricted.com"
forbiddenDomainToken := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": forbiddenInvitationEmail, "channels": th.BasicChannel.Id}),
)
grantedDomainToken := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": grantedInvitationEmail, "channels": th.BasicChannel.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(forbiddenDomainToken))
@@ -848,7 +848,7 @@ func TestCreateUserWithToken(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictCreationToDomains = "restricted.com" })
invitationEmail := model.NewId() + "other-email@test.com"
token := model.NewToken(
TOKEN_TYPE_GUEST_INVITATION,
TokenTypeGuestInvitation,
model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}),
)
require.Nil(t, th.App.Srv().Store.Token().Save(token))

Просмотреть файл

@@ -18,8 +18,8 @@ import (
)
const (
TRIGGERWORDS_EXACT_MATCH = 0
TRIGGERWORDS_STARTS_WITH = 1
TriggerwordsExactMatch = 0
TriggerwordsStartsWith = 1
MaxIntegrationResponseSize = 1024 * 1024 // Posts can be <100KB at most, so this is likely more than enough
)
@@ -55,10 +55,10 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m
if hook.ChannelId == post.ChannelId && len(hook.TriggerWords) == 0 {
relevantHooks = append(relevantHooks, hook)
triggerWord = ""
} else if hook.TriggerWhen == TRIGGERWORDS_EXACT_MATCH && hook.TriggerWordExactMatch(firstWord) {
} else if hook.TriggerWhen == TriggerwordsExactMatch && hook.TriggerWordExactMatch(firstWord) {
relevantHooks = append(relevantHooks, hook)
triggerWord = hook.GetTriggerWord(firstWord, true)
} else if hook.TriggerWhen == TRIGGERWORDS_STARTS_WITH && hook.TriggerWordStartsWith(firstWord) {
} else if hook.TriggerWhen == TriggerwordsStartsWith && hook.TriggerWordStartsWith(firstWord) {
relevantHooks = append(relevantHooks, hook)
triggerWord = hook.GetTriggerWord(firstWord, false)
}

Просмотреть файл

@@ -11,7 +11,7 @@ import (
"github.com/mattermost/mattermost-server/v5/model"
)
const CHANNEL_ARG_SEPARATOR = ":"
const ChannelArgSeparator = ":"
func getChannelsFromChannelArgs(a *app.App, channelArgs []string) []*model.Channel {
channels := make([]*model.Channel, 0, len(channelArgs))
@@ -23,7 +23,7 @@ func getChannelsFromChannelArgs(a *app.App, channelArgs []string) []*model.Chann
}
func parseChannelArg(channelArg string) (string, string) {
result := strings.SplitN(channelArg, CHANNEL_ARG_SEPARATOR, 2)
result := strings.SplitN(channelArg, ChannelArgSeparator, 2)
if len(result) == 1 {
return "", channelArg
}

Просмотреть файл

@@ -11,7 +11,7 @@ import (
"github.com/mattermost/mattermost-server/v5/model"
)
const COMMAND_ARGS_SEPARATOR = ":"
const CommandArgsSeparator = ":"
func getCommandsFromCommandArgs(a *app.App, commandArgs []string) []*model.Command {
commands := make([]*model.Command, 0, len(commandArgs))
@@ -25,7 +25,7 @@ func getCommandsFromCommandArgs(a *app.App, commandArgs []string) []*model.Comma
}
func parseCommandArg(commandArg string) (string, string) {
result := strings.SplitN(commandArg, COMMAND_ARGS_SEPARATOR, 2)
result := strings.SplitN(commandArg, CommandArgsSeparator, 2)
if len(result) == 1 {
return "", commandArg

Просмотреть файл

@@ -24,8 +24,8 @@ import (
)
const (
DEACTIVATED_USER = "deactivated"
GUEST_USER = "guest"
DeactivatedUser = "deactivated"
GuestUser = "guest"
)
var SampleDataCmd = &cobra.Command{
@@ -296,12 +296,12 @@ func sampleDataCmdF(command *cobra.Command, args []string) error {
allUsers = append(allUsers, *userLine.User.Username)
}
for i := 0; i < guests; i++ {
userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, GUEST_USER)
userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, GuestUser)
encoder.Encode(userLine)
allUsers = append(allUsers, *userLine.User.Username)
}
for i := 0; i < deactivatedUsers; i++ {
userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, DEACTIVATED_USER)
userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, DeactivatedUser)
encoder.Encode(userLine)
allUsers = append(allUsers, *userLine.User.Username)
}
@@ -401,7 +401,7 @@ func createUser(idx int, teamMemberships int, channelMemberships int, teamsAndCh
var email string
switch userType {
case GUEST_USER:
case GuestUser:
password = fmt.Sprintf("SampleGu@st-%d", idx)
email = fmt.Sprintf("guest-%d@sample.mattermost.com", idx)
roles = "system_guest"
@@ -410,7 +410,7 @@ func createUser(idx int, teamMemberships int, channelMemberships int, teamsAndCh
password = "SampleGu@st1"
email = "guest@sample.mattermost.com"
}
case DEACTIVATED_USER:
case DeactivatedUser:
password = fmt.Sprintf("SampleDe@ctivated-%d", idx)
email = fmt.Sprintf("deactivated-%d@sample.mattermost.com", idx)
default:
@@ -492,12 +492,12 @@ func createUser(idx int, teamMemberships int, channelMemberships int, teamsAndCh
team := possibleTeams[position]
possibleTeams = append(possibleTeams[:position], possibleTeams[position+1:]...)
if teamChannels, err := teamsAndChannels[team]; err {
teams = append(teams, createTeamMembership(channelMemberships, teamChannels, &team, userType == GUEST_USER))
teams = append(teams, createTeamMembership(channelMemberships, teamChannels, &team, userType == GuestUser))
}
}
var deleteAt int64
if userType == DEACTIVATED_USER {
if userType == DeactivatedUser {
deleteAt = model.GetMillis()
}

Просмотреть файл

@@ -38,8 +38,8 @@ func SetupServerTest(t testing.TB) *ServerTestHelper {
// Let jobs poll for termination every 0.2s (instead of every 15s by default)
// Otherwise we would have to wait the whole polling duration before the test
// terminates.
originalInterval := jobs.DEFAULT_WATCHER_POLLING_INTERVAL
jobs.DEFAULT_WATCHER_POLLING_INTERVAL = 200
originalInterval := jobs.DefaultWatcherPollingInterval
jobs.DefaultWatcherPollingInterval = 200
th := &ServerTestHelper{
disableConfigWatch: true,
@@ -50,7 +50,7 @@ func SetupServerTest(t testing.TB) *ServerTestHelper {
}
func (th *ServerTestHelper) TearDownServerTest() {
jobs.DEFAULT_WATCHER_POLLING_INTERVAL = th.originalInterval
jobs.DefaultWatcherPollingInterval = th.originalInterval
}
func TestRunServerSuccess(t *testing.T) {

Просмотреть файл

@@ -17,7 +17,7 @@ import (
"github.com/spf13/cobra"
)
const CUSTOM_DEFAULTS_ENV_VAR = "MM_CUSTOM_DEFAULTS_PATH"
const CustomDefaultsEnvVar = "MM_CUSTOM_DEFAULTS_PATH"
// prettyPrintStruct will return a prettyPrint version of a given struct
func prettyPrintStruct(t interface{}) string {
@@ -123,7 +123,7 @@ func getConfigDSN(command *cobra.Command, env map[string]string) string {
}
func loadCustomDefaults() (*model.Config, error) {
customDefaultsPath := os.Getenv(CUSTOM_DEFAULTS_ENV_VAR)
customDefaultsPath := os.Getenv(CustomDefaultsEnvVar)
if customDefaultsPath == "" {
return nil, nil
}

Просмотреть файл

@@ -4,7 +4,7 @@ go 1.14
require (
github.com/jstemmer/go-junit-report v0.9.1 // indirect
github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201013204121-e463fcd00ba8 // indirect
github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20210103185547-4c12aa739237 // indirect
github.com/philhofer/fwd v1.0.0 // indirect
github.com/reflog/struct2interface v0.6.1 // indirect
github.com/tinylib/msgp v1.1.2 // indirect

Просмотреть файл

@@ -74,6 +74,8 @@ github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201001222518-667645
github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201001222518-66764584f346/go.mod h1:3gKozJI8n2Y/vW37GfnFWAdehGXe5yZlt+HykK6Y3DM=
github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201013204121-e463fcd00ba8 h1:6wiKDdS/MMY0Jht12lRZJq1zv5eHEd4fK60SwkUVGjA=
github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201013204121-e463fcd00ba8/go.mod h1:3gKozJI8n2Y/vW37GfnFWAdehGXe5yZlt+HykK6Y3DM=
github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20210103185547-4c12aa739237 h1:w6GQs7SU6abD0QXKoqwd4bpEzNaW1xKwpeftBpIX1Do=
github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20210103185547-4c12aa739237/go.mod h1:3gKozJI8n2Y/vW37GfnFWAdehGXe5yZlt+HykK6Y3DM=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=

Просмотреть файл

@@ -15,7 +15,7 @@ import (
)
const (
CANCEL_WATCHER_POLLING_INTERVAL = 5000
CancelWatcherPollingInterval = 5000
)
func (srv *JobServer) CreateJob(jobType string, jobData map[string]string) (*model.Job, *model.AppError) {
@@ -166,7 +166,7 @@ func (srv *JobServer) CancellationWatcher(ctx context.Context, jobId string, can
case <-ctx.Done():
mlog.Debug("CancellationWatcher for Job Aborting as job has finished.", mlog.String("job_id", jobId))
return
case <-time.After(CANCEL_WATCHER_POLLING_INTERVAL * time.Millisecond):
case <-time.After(CancelWatcherPollingInterval * time.Millisecond):
mlog.Debug("CancellationWatcher for Job started polling.", mlog.String("job_id", jobId))
if jobStatus, err := srv.Store.Job().Get(jobId); err == nil {
if jobStatus.Status == model.JOB_STATUS_CANCEL_REQUESTED {

Просмотреть файл

@@ -13,7 +13,7 @@ import (
// Default polling interval for jobs termination.
// (Defining as `var` rather than `const` allows tests to lower the interval.)
var DEFAULT_WATCHER_POLLING_INTERVAL = 15000
var DefaultWatcherPollingInterval = 15000
type Watcher struct {
srv *JobServer

Просмотреть файл

@@ -37,7 +37,7 @@ func (srv *JobServer) InitWorkers() *Workers {
workers := &Workers{
ConfigService: srv.ConfigService,
}
workers.Watcher = srv.MakeWatcher(workers, DEFAULT_WATCHER_POLLING_INTERVAL)
workers.Watcher = srv.MakeWatcher(workers, DefaultWatcherPollingInterval)
if srv.DataRetentionJob != nil {
workers.DataRetention = srv.DataRetentionJob.MakeWorker()

Просмотреть файл

@@ -105,7 +105,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) {
user := &model.User{
Email: "success+" + model.NewId() + "simulator.amazonses.com",
Nickname: username[0],
Password: slashcommands.USER_PASSWORD}
Password: slashcommands.UserPassword}
user, resp := client.CreateUser(user)
if resp.Error != nil {
@@ -119,7 +119,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) {
userID = user.Id
// Login as user to generate auth token
_, resp = client.LoginById(user.Id, slashcommands.USER_PASSWORD)
_, resp = client.LoginById(user.Id, slashcommands.UserPassword)
if resp.Error != nil {
c.Err = resp.Error
return

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше