Fix empty string comparison issues in the codebase (#16686)

Automatic Merge
Этот коммит содержится в:
Madhav Hugar
2021-01-25 11:15:17 +01:00
коммит произвёл GitHub
родитель 200a56fa5a
Коммит 94c24eea20
107 изменённых файлов: 368 добавлений и 368 удалений

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

@@ -173,13 +173,13 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(channel.Type) > 0 && channel.Type != oldChannel.Type { if channel.Type != "" && channel.Type != oldChannel.Type {
c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.typechange.app_error", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.typechange.app_error", nil, "", http.StatusBadRequest)
return return
} }
if oldChannel.Name == model.DEFAULT_CHANNEL { if oldChannel.Name == model.DEFAULT_CHANNEL {
if len(channel.Name) > 0 && channel.Name != oldChannel.Name { if channel.Name != "" && channel.Name != oldChannel.Name {
c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.tried.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest) c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.tried.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest)
return return
} }
@@ -190,11 +190,11 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) {
oldChannelDisplayName := oldChannel.DisplayName oldChannelDisplayName := oldChannel.DisplayName
if len(channel.DisplayName) > 0 { if channel.DisplayName != "" {
oldChannel.DisplayName = channel.DisplayName oldChannel.DisplayName = channel.DisplayName
} }
if len(channel.Name) > 0 { if channel.Name != "" {
oldChannel.Name = channel.Name oldChannel.Name = channel.Name
auditRec.AddMeta("new_channel_name", oldChannel.Name) auditRec.AddMeta("new_channel_name", oldChannel.Name)
} }

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

@@ -216,7 +216,7 @@ func listCommands(c *Context, w http.ResponseWriter, r *http.Request) {
customOnly, _ := strconv.ParseBool(r.URL.Query().Get("custom_only")) customOnly, _ := strconv.ParseBool(r.URL.Query().Get("custom_only"))
teamId := r.URL.Query().Get("team_id") teamId := r.URL.Query().Get("team_id")
if len(teamId) == 0 { if teamId == "" {
c.SetInvalidParam("team_id") c.SetInvalidParam("team_id")
return return
} }

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

@@ -181,7 +181,7 @@ func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) {
} }
var config map[string]string var config map[string]string
if len(c.App.Session().UserId) == 0 { if c.App.Session().UserId == "" {
config = c.App.LimitedClientConfigWithComputed() config = c.App.LimitedClientConfigWithComputed()
} else { } else {
config = c.App.ClientConfigWithComputed() config = c.App.ClientConfigWithComputed()

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

@@ -565,7 +565,7 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(info.PostId) == 0 { if info.PostId == "" {
c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest) c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest)
return return
} }
@@ -658,7 +658,7 @@ func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) {
hash := r.URL.Query().Get("h") hash := r.URL.Query().Get("h")
if len(hash) == 0 { if hash == "" {
c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest)
utils.RenderWebAppError(c.App.Config(), w, r, c.Err, c.App.AsymmetricSigningKey()) utils.RenderWebAppError(c.App.Config(), w, r, c.Err, c.App.AsymmetricSigningKey())
return return

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

@@ -67,7 +67,7 @@ func testDoUploadFileRequest(t testing.TB, c *model.Client4, url string, blob []
req.ContentLength = contentLength req.ContentLength = contentLength
} }
req.Header.Set("Content-Type", contentType) req.Header.Set("Content-Type", contentType)
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
req.Header.Set(model.HEADER_AUTH, c.AuthType+" "+c.AuthToken) req.Header.Set(model.HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }

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

@@ -792,7 +792,7 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) {
} }
sinceString := r.URL.Query().Get("since") sinceString := r.URL.Query().Get("since")
if len(sinceString) > 0 { if sinceString != "" {
since, parseError := strconv.ParseInt(sinceString, 10, 64) since, parseError := strconv.ParseInt(sinceString, 10, 64)
if parseError != nil { if parseError != nil {
c.SetInvalidParam("since") c.SetInvalidParam("since")

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

@@ -271,7 +271,7 @@ func unlinkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) {
func migrateIdLdap(c *Context, w http.ResponseWriter, r *http.Request) { func migrateIdLdap(c *Context, w http.ResponseWriter, r *http.Request) {
props := model.StringInterfaceFromJson(r.Body) props := model.StringInterfaceFromJson(r.Body)
toAttribute, ok := props["toAttribute"].(string) toAttribute, ok := props["toAttribute"].(string)
if !ok || len(toAttribute) == 0 { if !ok || toAttribute == "" {
c.SetInvalidParam("toAttribute") c.SetInvalidParam("toAttribute")
return return
} }

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

@@ -41,7 +41,7 @@ func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) {
url := "" url := ""
ok := false ok := false
if url, ok = props["url"].(string); len(url) == 0 || !ok { if url, ok = props["url"].(string); url == "" || !ok {
c.SetInvalidParam("url") c.SetInvalidParam("url")
return return
} }

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

@@ -136,13 +136,13 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) {
} }
afterPost := r.URL.Query().Get("after") afterPost := r.URL.Query().Get("after")
if len(afterPost) > 0 && !model.IsValidId(afterPost) { if afterPost != "" && !model.IsValidId(afterPost) {
c.SetInvalidParam("after") c.SetInvalidParam("after")
return return
} }
beforePost := r.URL.Query().Get("before") beforePost := r.URL.Query().Get("before")
if len(beforePost) > 0 && !model.IsValidId(beforePost) { if beforePost != "" && !model.IsValidId(beforePost) {
c.SetInvalidParam("before") c.SetInvalidParam("before")
return return
} }
@@ -150,7 +150,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) {
sinceString := r.URL.Query().Get("since") sinceString := r.URL.Query().Get("since")
var since int64 var since int64
var parseError error var parseError error
if len(sinceString) > 0 { if sinceString != "" {
since, parseError = strconv.ParseInt(sinceString, 10, 64) since, parseError = strconv.ParseInt(sinceString, 10, 64)
if parseError != nil { if parseError != nil {
c.SetInvalidParam("since") c.SetInvalidParam("since")
@@ -175,7 +175,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) {
if since > 0 { if since > 0 {
list, err = c.App.GetPostsSince(model.GetPostsSinceOptions{ChannelId: channelId, Time: since, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended}) list, err = c.App.GetPostsSince(model.GetPostsSinceOptions{ChannelId: channelId, Time: since, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended})
} else if len(afterPost) > 0 { } else if afterPost != "" {
etag = c.App.GetPostsEtag(channelId, collapsedThreads) etag = c.App.GetPostsEtag(channelId, collapsedThreads)
if c.HandleEtag(etag, "Get Posts After", w, r) { if c.HandleEtag(etag, "Get Posts After", w, r) {
@@ -183,7 +183,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) {
} }
list, err = c.App.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: afterPost, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads}) list, err = c.App.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: afterPost, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads})
} else if len(beforePost) > 0 { } else if beforePost != "" {
etag = c.App.GetPostsEtag(channelId, collapsedThreads) etag = c.App.GetPostsEtag(channelId, collapsedThreads)
if c.HandleEtag(etag, "Get Posts Before", w, r) { if c.HandleEtag(etag, "Get Posts Before", w, r) {
@@ -206,7 +206,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(etag) > 0 { if etag != "" {
w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.Header().Set(model.HEADER_ETAG_SERVER, etag)
} }
@@ -269,7 +269,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht
clientPostList := c.App.PreparePostListForClient(postList) clientPostList := c.App.PreparePostListForClient(postList)
if len(etag) > 0 { if etag != "" {
w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.Header().Set(model.HEADER_ETAG_SERVER, etag)
} }
w.Write([]byte(clientPostList.ToJson())) w.Write([]byte(clientPostList.ToJson()))
@@ -292,9 +292,9 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request)
var posts *model.PostList var posts *model.PostList
var err *model.AppError var err *model.AppError
if len(channelId) > 0 { if channelId != "" {
posts, err = c.App.GetFlaggedPostsForChannel(c.Params.UserId, channelId, c.Params.Page, c.Params.PerPage) posts, err = c.App.GetFlaggedPostsForChannel(c.Params.UserId, channelId, c.Params.Page, c.Params.PerPage)
} else if len(teamId) > 0 { } else if teamId != "" {
posts, err = c.App.GetFlaggedPostsForTeam(c.Params.UserId, teamId, c.Params.Page, c.Params.PerPage) posts, err = c.App.GetFlaggedPostsForTeam(c.Params.UserId, teamId, c.Params.Page, c.Params.PerPage)
} else { } else {
posts, err = c.App.GetFlaggedPosts(c.Params.UserId, c.Params.Page, c.Params.PerPage) posts, err = c.App.GetFlaggedPosts(c.Params.UserId, c.Params.Page, c.Params.PerPage)
@@ -476,7 +476,7 @@ func searchPosts(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if params.Terms == nil || len(*params.Terms) == 0 { if params.Terms == nil || *params.Terms == "" {
c.SetInvalidParam("terms") c.SetInvalidParam("terms")
return return
} }

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

@@ -23,7 +23,7 @@ func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if !model.IsValidId(reaction.UserId) || !model.IsValidId(reaction.PostId) || len(reaction.EmojiName) == 0 || len(reaction.EmojiName) > model.EMOJI_NAME_MAX_LENGTH { if !model.IsValidId(reaction.UserId) || !model.IsValidId(reaction.PostId) || reaction.EmojiName == "" || len(reaction.EmojiName) > model.EMOJI_NAME_MAX_LENGTH {
c.Err = model.NewAppError("saveReaction", "api.reaction.save_reaction.invalid.app_error", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("saveReaction", "api.reaction.save_reaction.invalid.app_error", nil, "", http.StatusBadRequest)
return return
} }

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

@@ -413,7 +413,7 @@ func getRedirectLocation(c *Context, w http.ResponseWriter, r *http.Request) {
} }
url := r.URL.Query().Get("url") url := r.URL.Query().Get("url")
if len(url) == 0 { if url == "" {
c.SetInvalidParam("url") c.SetInvalidParam("url")
return return
} }

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

@@ -657,9 +657,9 @@ func addUserToTeamFromInvite(c *Context, w http.ResponseWriter, r *http.Request)
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
auditRec.AddMeta("invite_id", inviteId) auditRec.AddMeta("invite_id", inviteId)
if len(tokenId) > 0 { if tokenId != "" {
member, err = c.App.AddTeamMemberByToken(c.App.Session().UserId, tokenId) member, err = c.App.AddTeamMemberByToken(c.App.Session().UserId, tokenId)
} else if len(inviteId) > 0 { } else if inviteId != "" {
if c.App.Session().Props[model.SESSION_PROP_IS_GUEST] == "true" { if c.App.Session().Props[model.SESSION_PROP_IS_GUEST] == "true" {
c.Err = model.NewAppError("addUserToTeamFromInvite", "api.team.add_user_to_team_from_invite.guest.app_error", nil, "", http.StatusForbidden) c.Err = model.NewAppError("addUserToTeamFromInvite", "api.team.add_user_to_team_from_invite.guest.app_error", nil, "", http.StatusForbidden)
return return

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

@@ -122,7 +122,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) {
var ruser *model.User var ruser *model.User
var err *model.AppError var err *model.AppError
if len(tokenId) > 0 { if tokenId != "" {
token, nErr := c.App.Srv().Store.Token().GetByToken(tokenId) token, nErr := c.App.Srv().Store.Token().GetByToken(tokenId)
if nErr != nil { if nErr != nil {
var status int var status int
@@ -148,7 +148,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) {
} }
} }
ruser, err = c.App.CreateUserWithToken(user, token) ruser, err = c.App.CreateUserWithToken(user, token)
} else if len(inviteId) > 0 { } else if inviteId != "" {
ruser, err = c.App.CreateUserWithInviteId(user, inviteId, redirect) ruser, err = c.App.CreateUserWithInviteId(user, inviteId, redirect)
} else if c.IsSystemAdmin() { } else if c.IsSystemAdmin() {
ruser, err = c.App.CreateUserAsAdmin(user, redirect) ruser, err = c.App.CreateUserAsAdmin(user, redirect)
@@ -431,7 +431,7 @@ func setProfileImage(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(*c.App.Config().FileSettings.DriverName) == 0 { if *c.App.Config().FileSettings.DriverName == "" {
c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -491,7 +491,7 @@ func setDefaultProfileImage(c *Context, w http.ResponseWriter, r *http.Request)
return return
} }
if len(*c.App.Config().FileSettings.DriverName) == 0 { if *c.App.Config().FileSettings.DriverName == "" {
c.Err = model.NewAppError("setDefaultProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("setDefaultProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -633,7 +633,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
channelRolesString := r.URL.Query().Get("channel_roles") channelRolesString := r.URL.Query().Get("channel_roles")
teamRolesString := r.URL.Query().Get("team_roles") teamRolesString := r.URL.Query().Get("team_roles")
if len(notInChannelId) > 0 && len(inTeamId) == 0 { if notInChannelId != "" && inTeamId == "" {
c.SetInvalidUrlParam("team_id") c.SetInvalidUrlParam("team_id")
return return
} }
@@ -726,14 +726,14 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
} }
profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin()) profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin())
} else if len(notInChannelId) > 0 { } else if notInChannelId != "" {
if !c.App.SessionHasPermissionToChannel(*c.App.Session(), notInChannelId, model.PERMISSION_READ_CHANNEL) { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), notInChannelId, model.PERMISSION_READ_CHANNEL) {
c.SetPermissionError(model.PERMISSION_READ_CHANNEL) c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
return return
} }
profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions)
} else if len(notInTeamId) > 0 { } else if notInTeamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.App.Session(), notInTeamId, model.PERMISSION_VIEW_TEAM) { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), notInTeamId, model.PERMISSION_VIEW_TEAM) {
c.SetPermissionError(model.PERMISSION_VIEW_TEAM) c.SetPermissionError(model.PERMISSION_VIEW_TEAM)
return return
@@ -745,7 +745,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
} }
profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions)
} else if len(inTeamId) > 0 { } else if inTeamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.App.Session(), inTeamId, model.PERMISSION_VIEW_TEAM) { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), inTeamId, model.PERMISSION_VIEW_TEAM) {
c.SetPermissionError(model.PERMISSION_VIEW_TEAM) c.SetPermissionError(model.PERMISSION_VIEW_TEAM)
return return
@@ -762,7 +762,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
} }
profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin())
} }
} else if len(inChannelId) > 0 { } else if inChannelId != "" {
if !c.App.SessionHasPermissionToChannel(*c.App.Session(), inChannelId, model.PERMISSION_READ_CHANNEL) { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), inChannelId, model.PERMISSION_READ_CHANNEL) {
c.SetPermissionError(model.PERMISSION_READ_CHANNEL) c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
return return
@@ -772,7 +772,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
} else { } else {
profiles, err = c.App.GetUsersInChannelPage(userGetOptions, c.IsSystemAdmin()) profiles, err = c.App.GetUsersInChannelPage(userGetOptions, c.IsSystemAdmin())
} }
} else if len(inGroupId) > 0 { } else if inGroupId != "" {
if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getUsersInGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getUsersInGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
@@ -802,7 +802,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(etag) > 0 { if etag != "" {
w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.Header().Set(model.HEADER_ETAG_SERVER, etag)
} }
c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) c.App.UpdateLastActivityAtIfNeeded(*c.App.Session())
@@ -823,7 +823,7 @@ func getUsersByIds(c *Context, w http.ResponseWriter, r *http.Request) {
IsAdmin: c.IsSystemAdmin(), IsAdmin: c.IsSystemAdmin(),
} }
if len(sinceString) > 0 { if sinceString != "" {
since, parseError := strconv.ParseInt(sinceString, 10, 64) since, parseError := strconv.ParseInt(sinceString, 10, 64)
if parseError != nil { if parseError != nil {
c.SetInvalidParam("since") c.SetInvalidParam("since")
@@ -890,7 +890,7 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(props.Term) == 0 { if props.Term == "" {
c.SetInvalidParam("term") c.SetInvalidParam("term")
return return
} }
@@ -996,14 +996,14 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) {
options.AllowFullNames = *c.App.Config().PrivacySettings.ShowFullName options.AllowFullNames = *c.App.Config().PrivacySettings.ShowFullName
} }
if len(channelId) > 0 { if channelId != "" {
if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_READ_CHANNEL) { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_READ_CHANNEL) {
c.SetPermissionError(model.PERMISSION_READ_CHANNEL) c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
return return
} }
} }
if len(teamId) > 0 { if teamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_VIEW_TEAM) { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_VIEW_TEAM) {
c.SetPermissionError(model.PERMISSION_VIEW_TEAM) c.SetPermissionError(model.PERMISSION_VIEW_TEAM)
return return
@@ -1019,11 +1019,11 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(channelId) > 0 { if channelId != "" {
// We're using the channelId to search for users inside that channel and the team // We're using the channelId to search for users inside that channel and the team
// to get the not in channel list. Also we want to include the DM and GM users for // to get the not in channel list. Also we want to include the DM and GM users for
// that team which could only be obtained having the team id. // that team which could only be obtained having the team id.
if len(teamId) == 0 { if teamId == "" {
c.Err = model.NewAppError("autocompleteUser", c.Err = model.NewAppError("autocompleteUser",
"api.user.autocomplete_users.missing_team_id.app_error", "api.user.autocomplete_users.missing_team_id.app_error",
nil, nil,
@@ -1040,7 +1040,7 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) {
autocomplete.Users = result.InChannel autocomplete.Users = result.InChannel
autocomplete.OutOfChannel = result.OutOfChannel autocomplete.OutOfChannel = result.OutOfChannel
} else if len(teamId) > 0 { } else if teamId != "" {
result, err := c.App.AutocompleteUsersInTeam(teamId, name, options) result, err := c.App.AutocompleteUsersInTeam(teamId, name, options)
if err != nil { if err != nil {
c.Err = err c.Err = err
@@ -1432,7 +1432,7 @@ func checkUserMfa(c *Context, w http.ResponseWriter, r *http.Request) {
props := model.MapFromJson(r.Body) props := model.MapFromJson(r.Body)
loginId := props["login_id"] loginId := props["login_id"]
if len(loginId) == 0 { if loginId == "" {
c.SetInvalidParam("login_id") c.SetInvalidParam("login_id")
return return
} }
@@ -1488,7 +1488,7 @@ func updateUserMfa(c *Context, w http.ResponseWriter, r *http.Request) {
code := "" code := ""
if activate { if activate {
code, ok = props["code"].(string) code, ok = props["code"].(string)
if !ok || len(code) == 0 { if !ok || code == "" {
c.SetInvalidParam("code") c.SetInvalidParam("code")
return return
} }
@@ -1576,7 +1576,7 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) {
} else { } else {
if c.Params.UserId == c.App.Session().UserId { if c.Params.UserId == c.App.Session().UserId {
currentPassword := props["current_password"] currentPassword := props["current_password"]
if len(currentPassword) <= 0 { if currentPassword == "" {
c.SetInvalidParam("current_password") c.SetInvalidParam("current_password")
return return
} }
@@ -1634,7 +1634,7 @@ func sendPasswordReset(c *Context, w http.ResponseWriter, r *http.Request) {
email := props["email"] email := props["email"]
email = strings.ToLower(email) email = strings.ToLower(email)
if len(email) == 0 { if email == "" {
c.SetInvalidParam("email") c.SetInvalidParam("email")
return return
} }
@@ -1735,7 +1735,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) {
certPem, certSubject, certEmail := c.App.CheckForClientSideCert(r) certPem, certSubject, certEmail := c.App.CheckForClientSideCert(r)
mlog.Debug("Client Cert", mlog.String("cert_subject", certSubject), mlog.String("cert_email", certEmail)) mlog.Debug("Client Cert", mlog.String("cert_subject", certSubject), mlog.String("cert_email", certEmail))
if len(certPem) == 0 || len(certEmail) == 0 { if certPem == "" || certEmail == "" {
c.Err = model.NewAppError("ClientSideCertMissing", "api.user.login.client_side_cert.certificate.app_error", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("ClientSideCertMissing", "api.user.login.client_side_cert.certificate.app_error", nil, "", http.StatusBadRequest)
return return
} }
@@ -1984,7 +1984,7 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) {
props := model.MapFromJson(r.Body) props := model.MapFromJson(r.Body)
deviceId := props["device_id"] deviceId := props["device_id"]
if len(deviceId) == 0 { if deviceId == "" {
c.SetInvalidParam("device_id") c.SetInvalidParam("device_id")
return return
} }
@@ -2095,7 +2095,7 @@ func sendVerificationEmail(c *Context, w http.ResponseWriter, r *http.Request) {
email := props["email"] email := props["email"]
email = strings.ToLower(email) email = strings.ToLower(email)
if len(email) == 0 { if email == "" {
c.SetInvalidParam("email") c.SetInvalidParam("email")
return return
} }
@@ -2238,7 +2238,7 @@ func searchUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request)
return return
} }
if len(props.Term) == 0 { if props.Term == "" {
c.SetInvalidParam("term") c.SetInvalidParam("term")
return return
} }
@@ -2709,7 +2709,7 @@ func migrateAuthToLDAP(c *Context, w http.ResponseWriter, r *http.Request) {
c.SetInvalidParam("from") c.SetInvalidParam("from")
return return
} }
if len(from) == 0 || (from != "email" && from != "gitlab" && from != "saml" && from != "google" && from != "office365") { if from == "" || (from != "email" && from != "gitlab" && from != "saml" && from != "google" && from != "office365") {
c.SetInvalidParam("from") c.SetInvalidParam("from")
return return
} }
@@ -2768,7 +2768,7 @@ func migrateAuthToSaml(c *Context, w http.ResponseWriter, r *http.Request) {
c.SetInvalidParam("from") c.SetInvalidParam("from")
return return
} }
if len(from) == 0 || (from != "email" && from != "gitlab" && from != "ldap" && from != "google" && from != "office365") { if from == "" || (from != "email" && from != "gitlab" && from != "ldap" && from != "google" && from != "office365") {
c.SetInvalidParam("from") c.SetInvalidParam("from")
return return
} }
@@ -2840,7 +2840,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) {
} }
sinceString := r.URL.Query().Get("since") sinceString := r.URL.Query().Get("since")
if len(sinceString) > 0 { if sinceString != "" {
since, parseError := strconv.ParseUint(sinceString, 10, 64) since, parseError := strconv.ParseUint(sinceString, 10, 64)
if parseError != nil { if parseError != nil {
c.SetInvalidParam("since") c.SetInvalidParam("since")
@@ -2850,7 +2850,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) {
} }
pageString := r.URL.Query().Get("page") pageString := r.URL.Query().Get("page")
if len(pageString) > 0 { if pageString != "" {
page, parseError := strconv.ParseUint(pageString, 10, 64) page, parseError := strconv.ParseUint(pageString, 10, 64)
if parseError != nil { if parseError != nil {
c.SetInvalidParam("page") c.SetInvalidParam("page")
@@ -2860,7 +2860,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) {
} }
pageSizeString := r.URL.Query().Get("pageSize") pageSizeString := r.URL.Query().Get("pageSize")
if len(pageString) > 0 { if pageString != "" {
pageSize, parseError := strconv.ParseUint(pageSizeString, 10, 64) pageSize, parseError := strconv.ParseUint(pageSizeString, 10, 64)
if parseError != nil { if parseError != nil {
c.SetInvalidParam("pageSize") c.SetInvalidParam("pageSize")

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

@@ -54,7 +54,7 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) {
role := r.URL.Query().Get("role") role := r.URL.Query().Get("role")
sort := r.URL.Query().Get("sort") sort := r.URL.Query().Get("sort")
if len(notInChannelId) > 0 && len(inTeamId) == 0 { if notInChannelId != "" && inTeamId == "" {
c.SetInvalidUrlParam("team_id") c.SetInvalidUrlParam("team_id")
return return
} }
@@ -102,16 +102,16 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) {
if withoutTeamBool, _ := strconv.ParseBool(withoutTeam); withoutTeamBool { if withoutTeamBool, _ := strconv.ParseBool(withoutTeam); withoutTeamBool {
profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin()) profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin())
} else if len(notInChannelId) > 0 { } else if notInChannelId != "" {
profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil) profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil)
} else if len(notInTeamId) > 0 { } else if notInTeamId != "" {
etag = c.App.GetUsersNotInTeamEtag(inTeamId, "") etag = c.App.GetUsersNotInTeamEtag(inTeamId, "")
if c.HandleEtag(etag, "Get Users Not in Team", w, r) { if c.HandleEtag(etag, "Get Users Not in Team", w, r) {
return return
} }
profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil) profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil)
} else if len(inTeamId) > 0 { } else if inTeamId != "" {
if sort == "last_activity_at" { if sort == "last_activity_at" {
profiles, err = c.App.GetRecentlyActiveUsersForTeamPage(inTeamId, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil) profiles, err = c.App.GetRecentlyActiveUsersForTeamPage(inTeamId, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil)
} else if sort == "create_at" { } else if sort == "create_at" {
@@ -123,7 +123,7 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) {
} }
profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin())
} }
} else if len(inChannelId) > 0 { } else if inChannelId != "" {
if sort == "status" { if sort == "status" {
profiles, err = c.App.GetUsersInChannelPageByStatus(userGetOptions, c.IsSystemAdmin()) profiles, err = c.App.GetUsersInChannelPageByStatus(userGetOptions, c.IsSystemAdmin())
} else { } else {
@@ -138,7 +138,7 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if len(etag) > 0 { if etag != "" {
w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.Header().Set(model.HEADER_ETAG_SERVER, etag)
} }
w.Write([]byte(model.UserListToJson(profiles))) w.Write([]byte(model.UserListToJson(profiles)))
@@ -158,7 +158,7 @@ func localGetUsersByIds(c *Context, w http.ResponseWriter, r *http.Request) {
IsAdmin: c.IsSystemAdmin(), IsAdmin: c.IsSystemAdmin(),
} }
if len(sinceString) > 0 { if sinceString != "" {
since, parseError := strconv.ParseInt(sinceString, 10, 64) since, parseError := strconv.ParseInt(sinceString, 10, 64)
if parseError != nil { if parseError != nil {
c.SetInvalidParam("since") c.SetInvalidParam("since")

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

@@ -173,7 +173,7 @@ func getIncomingHooks(c *Context, w http.ResponseWriter, r *http.Request) {
var hooks []*model.IncomingWebhook var hooks []*model.IncomingWebhook
var err *model.AppError var err *model.AppError
if len(teamId) > 0 { if teamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) {
c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS)
return return
@@ -436,7 +436,7 @@ func getOutgoingHooks(c *Context, w http.ResponseWriter, r *http.Request) {
var hooks []*model.OutgoingWebhook var hooks []*model.OutgoingWebhook
var err *model.AppError var err *model.AppError
if len(channelId) > 0 { if channelId != "" {
if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) {
c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS)
return return
@@ -448,7 +448,7 @@ func getOutgoingHooks(c *Context, w http.ResponseWriter, r *http.Request) {
} }
hooks, err = c.App.GetOutgoingWebhooksForChannelPageByUser(channelId, userId, c.Params.Page, c.Params.PerPage) hooks, err = c.App.GetOutgoingWebhooksForChannelPageByUser(channelId, userId, c.Params.Page, c.Params.PerPage)
} else if len(teamId) > 0 { } else if teamId != "" {
if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) {
c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS)
return return

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

@@ -31,7 +31,7 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) {
wc := c.App.NewWebConn(ws, *c.App.Session(), c.App.T, "") wc := c.App.NewWebConn(ws, *c.App.Session(), c.App.T, "")
if len(c.App.Session().UserId) > 0 { if c.App.Session().UserId != "" {
c.App.HubRegister(wc) c.App.HubRegister(wc)
} }

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

@@ -204,7 +204,7 @@ func (a *App) TestSiteURL(siteURL string) *model.AppError {
} }
func (a *App) TestEmail(userId string, cfg *model.Config) *model.AppError { func (a *App) TestEmail(userId string, cfg *model.Config) *model.AppError {
if len(*cfg.EmailSettings.SMTPServer) == 0 { if *cfg.EmailSettings.SMTPServer == "" {
return model.NewAppError("testEmail", "api.admin.test_email.missing_server", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusBadRequest) return model.NewAppError("testEmail", "api.admin.test_email.missing_server", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusBadRequest)
} }

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

@@ -454,7 +454,7 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User,
} }
if !forceAck { if !forceAck {
if len(*a.Config().EmailSettings.SMTPServer) == 0 { if *a.Config().EmailSettings.SMTPServer == "" {
return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.missing_server.app_error", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusInternalServerError) return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.missing_server.app_error", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusInternalServerError)
} }
T := utils.GetUserTranslations(sender.Locale) T := utils.GetUserTranslations(sender.Locale)

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

@@ -22,7 +22,7 @@ const (
) )
func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError {
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return model.NewAppError("SaveBrandImage", "api.admin.upload_brand_image.storage.app_error", nil, "", http.StatusNotImplemented) return model.NewAppError("SaveBrandImage", "api.admin.upload_brand_image.storage.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -69,7 +69,7 @@ func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError {
} }
func (a *App) GetBrandImage() ([]byte, *model.AppError) { func (a *App) GetBrandImage() ([]byte, *model.AppError) {
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return nil, model.NewAppError("GetBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "", http.StatusNotImplemented)
} }

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

@@ -175,7 +175,7 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userId string) (*mod
return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.direct_channel.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.direct_channel.app_error", nil, "", http.StatusBadRequest)
} }
if len(channel.TeamId) == 0 { if channel.TeamId == "" {
return nil, model.NewAppError("CreateChannelWithUser", "app.channel.create_channel.no_team_id.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("CreateChannelWithUser", "app.channel.create_channel.no_team_id.app_error", nil, "", http.StatusBadRequest)
} }
@@ -839,7 +839,7 @@ func (a *App) GetChannelModerationsForChannel(channel *model.Channel) ([]*model.
} }
var guestRole *model.Role var guestRole *model.Role
if len(guestRoleName) > 0 { if guestRoleName != "" {
guestRole, err = a.GetRoleByName(guestRoleName) guestRole, err = a.GetRoleByName(guestRoleName)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -856,7 +856,7 @@ func (a *App) GetChannelModerationsForChannel(channel *model.Channel) ([]*model.
} }
var higherScopedGuestRole *model.Role var higherScopedGuestRole *model.Role
if len(higherScopedGuestRoleName) > 0 { if higherScopedGuestRoleName != "" {
higherScopedGuestRole, err = a.GetRoleByName(higherScopedGuestRoleName) higherScopedGuestRole, err = a.GetRoleByName(higherScopedGuestRoleName)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -879,7 +879,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM
} }
var higherScopedGuestRole *model.Role var higherScopedGuestRole *model.Role
if len(higherScopedGuestRoleName) > 0 { if higherScopedGuestRoleName != "" {
higherScopedGuestRole, err = a.GetRoleByName(higherScopedGuestRoleName) higherScopedGuestRole, err = a.GetRoleByName(higherScopedGuestRoleName)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -904,7 +904,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM
var scheme *model.Scheme var scheme *model.Scheme
// Channel has no scheme so create one // Channel has no scheme so create one
if channel.SchemeId == nil || len(*channel.SchemeId) == 0 { if channel.SchemeId == nil || *channel.SchemeId == "" {
scheme, err = a.CreateChannelScheme(channel) scheme, err = a.CreateChannelScheme(channel)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -936,7 +936,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM
} }
var guestRole *model.Role var guestRole *model.Role
if len(guestRoleName) > 0 { if guestRoleName != "" {
guestRole, err = a.GetRoleByName(guestRoleName) guestRole, err = a.GetRoleByName(guestRoleName)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -2554,11 +2554,11 @@ func (a *App) ViewChannel(view *model.ChannelView, userId string, currentSession
channelIds := []string{} channelIds := []string{}
if len(view.ChannelId) > 0 { if view.ChannelId != "" {
channelIds = append(channelIds, view.ChannelId) channelIds = append(channelIds, view.ChannelId)
} }
if len(view.PrevChannelId) > 0 { if view.PrevChannelId != "" {
channelIds = append(channelIds, view.PrevChannelId) channelIds = append(channelIds, view.PrevChannelId)
} }

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

@@ -341,7 +341,7 @@ func (es *EmailService) SendInviteEmails(team *model.Team, senderName string, se
} }
for _, invite := range invites { for _, invite := range invites {
if len(invite) > 0 { if invite != "" {
subject := utils.T("api.templates.invite_subject", subject := utils.T("api.templates.invite_subject",
map[string]interface{}{"SenderName": senderName, map[string]interface{}{"SenderName": senderName,
"TeamDisplayName": team.DisplayName, "TeamDisplayName": team.DisplayName,
@@ -400,7 +400,7 @@ func (es *EmailService) sendGuestInviteEmails(team *model.Team, channels []*mode
} }
for _, invite := range invites { for _, invite := range invites {
if len(invite) > 0 { if invite != "" {
subject := utils.T("api.templates.invite_guest_subject", subject := utils.T("api.templates.invite_guest_subject",
map[string]interface{}{"SenderName": senderName, map[string]interface{}{"SenderName": senderName,
"TeamDisplayName": team.DisplayName, "TeamDisplayName": team.DisplayName,

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

@@ -39,7 +39,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma
return nil, model.NewAppError("UploadEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("UploadEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -96,7 +96,7 @@ func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *mode
return model.NewAppError("UploadEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return model.NewAppError("UploadEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return model.NewAppError("UploadEmojiImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return model.NewAppError("UploadEmojiImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -181,7 +181,7 @@ func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) {
return nil, model.NewAppError("GetEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -204,7 +204,7 @@ func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) {
return nil, model.NewAppError("GetEmojiByName", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetEmojiByName", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return nil, model.NewAppError("GetEmojiByName", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetEmojiByName", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented)
} }

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

@@ -498,7 +498,7 @@ func (a *App) UploadMultipartFiles(teamId string, channelId string, userId strin
// the same length. clientIds should either not be provided or have the same length as files and filenames. // the same length. clientIds should either not be provided or have the same length as files and filenames.
// The provided files should be closed by the caller so that they are not leaked. // The provided files should be closed by the caller so that they are not leaked.
func (a *App) UploadFiles(teamId string, channelId string, userId string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { func (a *App) UploadFiles(teamId string, channelId string, userId string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) {
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return nil, model.NewAppError("UploadFiles", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("UploadFiles", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -703,7 +703,7 @@ func (a *App) UploadFileX(channelId, name string, input io.Reader,
o(t) o(t)
} }
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return nil, t.newAppError("api.file.upload_file.storage.app_error", return nil, t.newAppError("api.file.upload_file.storage.app_error",
"", http.StatusNotImplemented) "", http.StatusNotImplemented)
} }

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

@@ -52,7 +52,7 @@ func (a *App) importScheme(data *SchemeImportData, dryRun bool) *model.AppError
scheme.Description = *data.Description scheme.Description = *data.Description
} }
if len(scheme.Id) == 0 { if scheme.Id == "" {
scheme, err = a.CreateScheme(scheme) scheme, err = a.CreateScheme(scheme)
} else { } else {
scheme, err = a.UpdateScheme(scheme) scheme, err = a.UpdateScheme(scheme)
@@ -146,7 +146,7 @@ func (a *App) importRole(data *RoleImportData, dryRun bool, isSchemeRole bool) *
role.SchemeManaged = false role.SchemeManaged = false
} }
if len(role.Id) == 0 { if role.Id == "" {
_, err = a.CreateRole(role) _, err = a.CreateRole(role)
} else { } else {
_, err = a.UpdateRole(role) _, err = a.UpdateRole(role)
@@ -406,7 +406,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
roles = *data.Roles roles = *data.Roles
hasUserRolesChanged = true hasUserRolesChanged = true
} }
} else if len(user.Roles) == 0 { } else if user.Roles == "" {
// Set SYSTEM_USER roles on newly created users by default. // Set SYSTEM_USER roles on newly created users by default.
if user.Roles != model.SYSTEM_USER_ROLE_ID { if user.Roles != model.SYSTEM_USER_ROLE_ID {
roles = model.SYSTEM_USER_ROLE_ID roles = model.SYSTEM_USER_ROLE_ID
@@ -497,7 +497,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
return err return err
} }
} }
if len(password) > 0 { if password != "" {
if err = a.UpdatePassword(user, password); err != nil { if err = a.UpdatePassword(user, password); err != nil {
return err return err
} }
@@ -1078,7 +1078,7 @@ func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamId str
reply.FileIds = append(reply.FileIds, fileID) reply.FileIds = append(reply.FileIds, fileID)
} }
if len(reply.Id) == 0 { if reply.Id == "" {
postsForCreateList = append(postsForCreateList, reply) postsForCreateList = append(postsForCreateList, reply)
} else { } else {
postsForOverwriteList = append(postsForOverwriteList, reply) postsForOverwriteList = append(postsForOverwriteList, reply)
@@ -1333,7 +1333,7 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool)
post.FileIds = append(post.FileIds, fileID) post.FileIds = append(post.FileIds, fileID)
} }
if len(post.Id) == 0 { if post.Id == "" {
postsForCreateList = append(postsForCreateList, post) postsForCreateList = append(postsForCreateList, post)
postsForCreateMap[getPostStrID(post)] = line.LineNumber postsForCreateMap[getPostStrID(post)] = line.LineNumber
} else { } else {
@@ -1629,7 +1629,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun
post.FileIds = append(post.FileIds, fileID) post.FileIds = append(post.FileIds, fileID)
} }
if len(post.Id) == 0 { if post.Id == "" {
postsForCreateList = append(postsForCreateList, post) postsForCreateList = append(postsForCreateList, post)
postsForCreateMap[getPostStrID(post)] = line.LineNumber postsForCreateMap[getPostStrID(post)] = line.LineNumber
} else { } else {

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

@@ -36,7 +36,7 @@ func validateSchemeImportData(data *SchemeImportData) *model.AppError {
return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.name_invalid.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.name_invalid.error", nil, "", http.StatusBadRequest)
} }
if data.DisplayName == nil || len(*data.DisplayName) == 0 || len(*data.DisplayName) > model.SCHEME_DISPLAY_NAME_MAX_LENGTH { if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.SCHEME_DISPLAY_NAME_MAX_LENGTH {
return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest)
} }
@@ -89,7 +89,7 @@ func validateRoleImportData(data *RoleImportData) *model.AppError {
return model.NewAppError("BulkImport", "app.import.validate_role_import_data.name_invalid.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_role_import_data.name_invalid.error", nil, "", http.StatusBadRequest)
} }
if data.DisplayName == nil || len(*data.DisplayName) == 0 || len(*data.DisplayName) > model.ROLE_DISPLAY_NAME_MAX_LENGTH { if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.ROLE_DISPLAY_NAME_MAX_LENGTH {
return model.NewAppError("BulkImport", "app.import.validate_role_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_role_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest)
} }
@@ -207,7 +207,7 @@ func validateUserImportData(data *UserImportData) *model.AppError {
if data.Email == nil { if data.Email == nil {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_missing.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_missing.error", nil, "", http.StatusBadRequest)
} else if len(*data.Email) == 0 || len(*data.Email) > model.USER_EMAIL_MAX_LENGTH { } else if *data.Email == "" || len(*data.Email) > model.USER_EMAIL_MAX_LENGTH {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_length.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_length.error", nil, "", http.StatusBadRequest)
} }
@@ -223,14 +223,14 @@ func validateUserImportData(data *UserImportData) *model.AppError {
if str == nil { if str == nil {
return true return true
} }
return len(*str) == 0 return *str == ""
} }
if (!blank(data.AuthService) && blank(data.AuthData)) || (blank(data.AuthService) && !blank(data.AuthData)) { if (!blank(data.AuthService) && blank(data.AuthData)) || (blank(data.AuthService) && !blank(data.AuthData)) {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.auth_data_and_service_dependency.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_user_import_data.auth_data_and_service_dependency.error", nil, "", http.StatusBadRequest)
} }
if data.Password != nil && len(*data.Password) == 0 { if data.Password != nil && *data.Password == "" {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.password_length.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_user_import_data.password_length.error", nil, "", http.StatusBadRequest)
} }
@@ -565,7 +565,7 @@ func validateEmojiImportData(data *EmojiImportData) *model.AppError {
return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.empty.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.empty.error", nil, "", http.StatusBadRequest)
} }
if data.Name == nil || len(*data.Name) == 0 { if data.Name == nil || *data.Name == "" {
return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.name_missing.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.name_missing.error", nil, "", http.StatusBadRequest)
} }
@@ -573,7 +573,7 @@ func validateEmojiImportData(data *EmojiImportData) *model.AppError {
return err return err
} }
if data.Image == nil || len(*data.Image) == 0 { if data.Image == nil || *data.Image == "" {
return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.image_missing.error", nil, "", http.StatusBadRequest) return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.image_missing.error", nil, "", http.StatusBadRequest)
} }

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

@@ -116,7 +116,7 @@ func TestPostAction(t *testing.T) {
assert.Equal(t, request.TeamId, th.BasicTeam.Id) assert.Equal(t, request.TeamId, th.BasicTeam.Id)
assert.Equal(t, request.TeamName, th.BasicTeam.Name) assert.Equal(t, request.TeamName, th.BasicTeam.Name)
} }
assert.True(t, len(request.TriggerId) > 0) assert.True(t, request.TriggerId != "")
if request.Type == model.POST_ACTION_TYPE_SELECT { if request.Type == model.POST_ACTION_TYPE_SELECT {
assert.Equal(t, request.DataSource, "some_source") assert.Equal(t, request.DataSource, "some_source")
assert.Equal(t, request.Context["selected_option"], "selected") assert.Equal(t, request.Context["selected_option"], "selected")

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

@@ -29,7 +29,7 @@ func (a *App) CheckForClientSideCert(r *http.Request) (string, string, string) {
subject := r.Header.Get("X-SSL-Client-Cert-Subject-DN") // mapped to $ssl_client_s_dn from nginx subject := r.Header.Get("X-SSL-Client-Cert-Subject-DN") // mapped to $ssl_client_s_dn from nginx
email := "" email := ""
if len(subject) > 0 { if subject != "" {
for _, v := range strings.Split(subject, "/") { for _, v := range strings.Split(subject, "/") {
kv := strings.Split(v, "=") kv := strings.Split(v, "=")
if len(kv) == 2 && kv[0] == "emailAddress" { if len(kv) == 2 && kv[0] == "emailAddress" {
@@ -53,7 +53,7 @@ func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken
} }
}() }()
if len(password) == 0 && !IsCWSLogin(a, cwsToken) { if password == "" && !IsCWSLogin(a, cwsToken) {
return nil, model.NewAppError("AuthenticateUserForLogin", "api.user.login.blank_pwd.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("AuthenticateUserForLogin", "api.user.login.blank_pwd.app_error", nil, "", http.StatusBadRequest)
} }
@@ -175,7 +175,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User,
}} }}
session.GenerateCSRF() session.GenerateCSRF()
if len(deviceId) > 0 { if deviceId != "" {
a.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthMobileInDays) a.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthMobileInDays)
// A special case where we logout of all other sessions with the same Id // A special case where we logout of all other sessions with the same Id

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

@@ -123,7 +123,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
} }
// get users that have comment thread mentions enabled // get users that have comment thread mentions enabled
if len(post.RootId) > 0 && parentPostList != nil { if post.RootId != "" && parentPostList != nil {
for _, threadPost := range parentPostList.Posts { for _, threadPost := range parentPostList.Posts {
profile := profileMap[threadPost.UserId] profile := profileMap[threadPost.UserId]
if profile != nil && (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ANY || (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ROOT && threadPost.Id == parentPostList.Order[0])) { if profile != nil && (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ANY || (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ROOT && threadPost.Id == parentPostList.Order[0])) {
@@ -596,7 +596,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan
} }
if len(outOfGroupsUsers) == 1 { if len(outOfGroupsUsers) == 1 {
if len(message) > 0 { if message != "" {
message += "\n" message += "\n"
} }
@@ -606,7 +606,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan
} else if len(outOfGroupsUsers) > 1 { } else if len(outOfGroupsUsers) > 1 {
preliminary, final := splitAtFinal(ogUsernames) preliminary, final := splitAtFinal(ogUsernames)
if len(message) > 0 { if message != "" {
message += "\n" message += "\n"
} }
@@ -1084,7 +1084,7 @@ func (m *ExplicitMentions) processText(text string, keywords map[string][]string
foundWithoutSuffix := false foundWithoutSuffix := false
wordWithoutSuffix := word wordWithoutSuffix := word
for len(wordWithoutSuffix) > 0 && strings.LastIndexAny(wordWithoutSuffix, ".-:_") == (len(wordWithoutSuffix)-1) { for wordWithoutSuffix != "" && strings.LastIndexAny(wordWithoutSuffix, ".-:_") == (len(wordWithoutSuffix)-1) {
wordWithoutSuffix = wordWithoutSuffix[0 : len(wordWithoutSuffix)-1] wordWithoutSuffix = wordWithoutSuffix[0 : len(wordWithoutSuffix)-1]
if m.checkForMention(wordWithoutSuffix, keywords, groups) { if m.checkForMention(wordWithoutSuffix, keywords, groups) {

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

@@ -173,7 +173,7 @@ func (a *App) AllowOAuthAppAccessToUser(userId string, authRequest *model.Author
return "", model.NewAppError("AllowOAuthAppAccessToUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) return "", model.NewAppError("AllowOAuthAppAccessToUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented)
} }
if len(authRequest.Scope) == 0 { if authRequest.Scope == "" {
authRequest.Scope = model.DEFAULT_SCOPE authRequest.Scope = model.DEFAULT_SCOPE
} }
@@ -619,7 +619,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamId string, to
if err = a.UpdateOAuthUserAttrs(bytes.NewReader(buf.Bytes()), user, provider, service, tokenUser); err != nil { if err = a.UpdateOAuthUserAttrs(bytes.NewReader(buf.Bytes()), user, provider, service, tokenUser); err != nil {
return nil, err return nil, err
} }
if len(teamId) > 0 { if teamId != "" {
err = a.AddUserToTeamByTeamId(teamId, user) err = a.AddUserToTeamByTeamId(teamId, user)
} }
} }
@@ -763,11 +763,11 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi
authUrl := endpoint + "?response_type=code&client_id=" + clientId + "&redirect_uri=" + url.QueryEscape(redirectUri) + "&state=" + url.QueryEscape(state) authUrl := endpoint + "?response_type=code&client_id=" + clientId + "&redirect_uri=" + url.QueryEscape(redirectUri) + "&state=" + url.QueryEscape(state)
if len(scope) > 0 { if scope != "" {
authUrl += "&scope=" + utils.UrlEncode(scope) authUrl += "&scope=" + utils.UrlEncode(scope)
} }
if len(loginHint) > 0 { if loginHint != "" {
authUrl += "&login_hint=" + utils.UrlEncode(loginHint) authUrl += "&login_hint=" + utils.UrlEncode(loginHint)
} }
@@ -865,7 +865,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.bad_token.app_error", nil, "token_type="+ar.TokenType+", response_body="+buf.String(), http.StatusInternalServerError) return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.bad_token.app_error", nil, "token_type="+ar.TokenType+", response_body="+buf.String(), http.StatusInternalServerError)
} }
if len(ar.AccessToken) == 0 { if ar.AccessToken == "" {
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.missing.app_error", nil, "response_body="+buf.String(), http.StatusInternalServerError) return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.missing.app_error", nil, "response_body="+buf.String(), http.StatusInternalServerError)
} }

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

@@ -95,7 +95,7 @@ func (a *App) ExportPermissions(w io.Writer) error {
roles := []*model.Role{} roles := []*model.Role{}
for _, roleName := range roleNames { for _, roleName := range roleNames {
if len(roleName) == 0 { if roleName == "" {
continue continue
} }
role, err := a.GetRoleByName(roleName) role, err := a.GetRoleByName(roleName)
@@ -206,7 +206,7 @@ func (a *App) ImportPermissions(jsonl io.Reader) error {
{schemeCreated.DefaultChannelGuestRole, schemeIn.DefaultChannelGuestRole}, {schemeCreated.DefaultChannelGuestRole, schemeIn.DefaultChannelGuestRole},
} }
for _, roleNameTuple := range roleNameTuples { for _, roleNameTuple := range roleNameTuples {
if len(roleNameTuple[0]) == 0 || len(roleNameTuple[1]) == 0 { if roleNameTuple[0] == "" || roleNameTuple[1] == "" {
continue continue
} }

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

@@ -654,7 +654,7 @@ func (api *PluginAPI) GetFileLink(fileId string) (string, *model.AppError) {
return "", err return "", err
} }
if len(info.PostId) == 0 { if info.PostId == "" {
return "", model.NewAppError("GetFileLink", "plugin_api.get_file_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest) return "", model.NewAppError("GetFileLink", "plugin_api.get_file_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest)
} }

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

@@ -1296,21 +1296,21 @@ func TestPluginAPIGetConfig(t *testing.T) {
api := th.SetupPluginAPI() api := th.SetupPluginAPI()
config := api.GetConfig() config := api.GetConfig()
if config.LdapSettings.BindPassword != nil && len(*config.LdapSettings.BindPassword) > 0 { if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" {
assert.Equal(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING) assert.Equal(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING)
} }
assert.Equal(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING) assert.Equal(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING)
if len(*config.FileSettings.AmazonS3SecretAccessKey) > 0 { if *config.FileSettings.AmazonS3SecretAccessKey != "" {
assert.Equal(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING) assert.Equal(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING)
} }
if config.EmailSettings.SMTPPassword != nil && len(*config.EmailSettings.SMTPPassword) > 0 { if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" {
assert.Equal(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING) assert.Equal(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING)
} }
if len(*config.GitLabSettings.Secret) > 0 { if *config.GitLabSettings.Secret != "" {
assert.Equal(t, *config.GitLabSettings.Secret, model.FAKE_SETTING) assert.Equal(t, *config.GitLabSettings.Secret, model.FAKE_SETTING)
} }
@@ -1333,21 +1333,21 @@ func TestPluginAPIGetUnsanitizedConfig(t *testing.T) {
api := th.SetupPluginAPI() api := th.SetupPluginAPI()
config := api.GetUnsanitizedConfig() config := api.GetUnsanitizedConfig()
if config.LdapSettings.BindPassword != nil && len(*config.LdapSettings.BindPassword) > 0 { if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" {
assert.NotEqual(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING) assert.NotEqual(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING)
} }
assert.NotEqual(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING) assert.NotEqual(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING)
if len(*config.FileSettings.AmazonS3SecretAccessKey) > 0 { if *config.FileSettings.AmazonS3SecretAccessKey != "" {
assert.NotEqual(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING) assert.NotEqual(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING)
} }
if config.EmailSettings.SMTPPassword != nil && len(*config.EmailSettings.SMTPPassword) > 0 { if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" {
assert.NotEqual(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING) assert.NotEqual(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING)
} }
if len(*config.GitLabSettings.Secret) > 0 { if *config.GitLabSettings.Secret != "" {
assert.NotEqual(t, *config.GitLabSettings.Secret, model.FAKE_SETTING) assert.NotEqual(t, *config.GitLabSettings.Secret, model.FAKE_SETTING)
} }

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

@@ -182,7 +182,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
post.SanitizeProps() post.SanitizeProps()
var pchan chan store.StoreResult var pchan chan store.StoreResult
if len(post.RootId) > 0 { if post.RootId != "" {
pchan = make(chan store.StoreResult, 1) pchan = make(chan store.StoreResult, 1)
go func() { go func() {
r, pErr := a.Srv().Store.Post().Get(post.RootId, false, false, false) r, pErr := a.Srv().Store.Post().Get(post.RootId, false, false, false)
@@ -242,7 +242,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
} }
rootPost := parentPostList.Posts[post.RootId] rootPost := parentPostList.Posts[post.RootId]
if len(rootPost.RootId) > 0 { if rootPost.RootId != "" {
return nil, model.NewAppError("createPost", "api.post.create_post.root_id.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("createPost", "api.post.create_post.root_id.app_error", nil, "", http.StatusBadRequest)
} }
@@ -439,7 +439,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A
func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error { func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error {
var team *model.Team var team *model.Team
if len(channel.TeamId) > 0 { if channel.TeamId != "" {
t, err := a.Srv().Store.Team().Get(channel.TeamId) t, err := a.Srv().Store.Team().Get(channel.TeamId)
if err != nil { if err != nil {
return err return err

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

@@ -55,7 +55,7 @@ func (s *Server) DoSecurityUpdateCheck() {
v.Set(PropSecurityDatabase, *s.Config().SqlSettings.DriverName) v.Set(PropSecurityDatabase, *s.Config().SqlSettings.DriverName)
v.Set(PropSecurityOS, runtime.GOOS) v.Set(PropSecurityOS, runtime.GOOS)
if len(props[model.SYSTEM_RAN_UNIT_TESTS]) > 0 { if props[model.SYSTEM_RAN_UNIT_TESTS] != "" {
v.Set(PropSecurityUnitTests, "1") v.Set(PropSecurityUnitTests, "1")
} else { } else {
v.Set(PropSecurityUnitTests, "0") v.Set(PropSecurityUnitTests, "0")

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

@@ -79,7 +79,7 @@ func (*HeaderProvider) DoCommand(a *app.App, args *model.CommandArgs, message st
} }
} }
if len(message) == 0 { if message == "" {
return &model.CommandResponse{ return &model.CommandResponse{
Text: args.T("api.command_channel_header.message.app_error"), Text: args.T("api.command_channel_header.message.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,

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

@@ -66,7 +66,7 @@ func (*PurposeProvider) DoCommand(a *app.App, args *model.CommandArgs, message s
} }
} }
if len(message) == 0 { if message == "" {
return &model.CommandResponse{ return &model.CommandResponse{
Text: args.T("api.command_channel_purpose.message.app_error"), Text: args.T("api.command_channel_purpose.message.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,

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

@@ -66,7 +66,7 @@ func (*RenameProvider) DoCommand(a *app.App, args *model.CommandArgs, message st
return &model.CommandResponse{Text: args.T("api.command_channel_rename.direct_group.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_rename.direct_group.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if len(message) == 0 { if message == "" {
return &model.CommandResponse{ return &model.CommandResponse{
Text: args.T("api.command_channel_rename.message.app_error"), Text: args.T("api.command_channel_rename.message.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,

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

@@ -38,7 +38,7 @@ func (*CodeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Comma
} }
func (*CodeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { func (*CodeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
if len(message) == 0 { if message == "" {
return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
rmsg := " " + strings.Join(strings.Split(message, "\n"), "\n ") rmsg := " " + strings.Join(strings.Split(message, "\n"), "\n ")

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

@@ -43,7 +43,7 @@ func (*EchoProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Comma
} }
func (*EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { func (*EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
if len(message) == 0 { if message == "" {
return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -122,7 +122,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message
} }
} }
if len(parsedMessage) > 0 { if parsedMessage != "" {
post := &model.Post{} post := &model.Post{}
post.Message = parsedMessage post.Message = parsedMessage
post.ChannelId = groupChannel.Id post.ChannelId = groupChannel.Id

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

@@ -459,7 +459,7 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag
func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
url := strings.TrimSpace(strings.TrimPrefix(message, "url")) url := strings.TrimSpace(strings.TrimPrefix(message, "url"))
if len(url) == 0 { if url == "" {
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
} }
@@ -513,7 +513,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message
func (*LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { func (*LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
url := strings.TrimSpace(strings.TrimPrefix(message, "json")) url := strings.TrimSpace(strings.TrimPrefix(message, "json"))
if len(url) == 0 { if url == "" {
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
} }

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

@@ -96,7 +96,7 @@ func (*msgProvider) DoCommand(a *app.App, args *model.CommandArgs, message strin
targetChannelId = channel.Id targetChannelId = channel.Id
} }
if len(parsedMessage) > 0 { if parsedMessage != "" {
post := &model.Post{} post := &model.Post{}
post.Message = parsedMessage post.Message = parsedMessage
post.ChannelId = targetChannelId post.ChannelId = targetChannelId

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

@@ -54,7 +54,7 @@ func (*MuteProvider) DoCommand(a *app.App, args *model.CommandArgs, message stri
channelName = splitMessage[0] channelName = splitMessage[0]
} }
if len(channelName) > 0 && len(message) > 0 { if channelName != "" && message != "" {
channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true) channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true)
if channel == nil { if channel == nil {

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

@@ -96,7 +96,7 @@ func doCommand(a *app.App, args *model.CommandArgs, message string) *model.Comma
} }
} }
if len(message) == 0 { if message == "" {
return &model.CommandResponse{ return &model.CommandResponse{
Text: args.T("api.command_remove.message.app_error"), Text: args.T("api.command_remove.message.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,

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

@@ -37,7 +37,7 @@ func (*ShrugProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Comm
func (*ShrugProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { func (*ShrugProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
rmsg := `¯\\\_(ツ)\_/¯` rmsg := `¯\\\_(ツ)\_/¯`
if len(message) > 0 { if message != "" {
rmsg = message + " " + rmsg rmsg = message + " " + rmsg
} }

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

@@ -39,7 +39,7 @@ func parseSVG(svgReader io.Reader) (SVGInfo, error) {
if viewBoxMatches := viewBoxPattern.FindStringSubmatch(parsedSVG.ViewBox); len(viewBoxMatches) == 5 { if viewBoxMatches := viewBoxPattern.FindStringSubmatch(parsedSVG.ViewBox); len(viewBoxMatches) == 5 {
svgInfo.Width, _ = strconv.Atoi(viewBoxMatches[3]) svgInfo.Width, _ = strconv.Atoi(viewBoxMatches[3])
svgInfo.Height, _ = strconv.Atoi(viewBoxMatches[4]) svgInfo.Height, _ = strconv.Atoi(viewBoxMatches[4])
} else if len(parsedSVG.Width) > 0 && len(parsedSVG.Height) > 0 { } else if parsedSVG.Width != "" && parsedSVG.Height != "" {
widthMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Width) widthMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Width)
heightMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Height) heightMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Height)
if len(widthMatches) == 2 && len(heightMatches) == 2 { if len(widthMatches) == 2 && len(heightMatches) == 2 {

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

@@ -1840,7 +1840,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) {
tokenId := query.Get("t") tokenId := query.Get("t")
inviteId := query.Get("id") inviteId := query.Get("id")
if len(tokenId) > 0 { if tokenId != "" {
token, err := a.Srv().Store.Token().GetByToken(tokenId) token, err := a.Srv().Store.Token().GetByToken(tokenId)
if err != nil { if err != nil {
return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest) return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest)
@@ -1859,7 +1859,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) {
return tokenData["teamId"], nil return tokenData["teamId"], nil
} }
if len(inviteId) > 0 { if inviteId != "" {
team, err := a.Srv().Store.Team().GetByInviteId(inviteId) team, err := a.Srv().Store.Team().GetByInviteId(inviteId)
if err == nil { if err == nil {
return team.Id, nil return team.Id, nil
@@ -1897,7 +1897,7 @@ func (a *App) SanitizeTeams(session model.Session, teams []*model.Team) []*model
} }
func (a *App) GetTeamIcon(team *model.Team) ([]byte, *model.AppError) { func (a *App) GetTeamIcon(team *model.Team) ([]byte, *model.AppError) {
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return nil, model.NewAppError("GetTeamIcon", "api.team.get_team_icon.filesettings_no_driver.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetTeamIcon", "api.team.get_team_icon.filesettings_no_driver.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -1926,7 +1926,7 @@ func (a *App) SetTeamIconFromMultiPartFile(teamId string, file multipart.File) *
return model.NewAppError("SetTeamIcon", "api.team.set_team_icon.get_team.app_error", nil, getTeamErr.Error(), http.StatusBadRequest) return model.NewAppError("SetTeamIcon", "api.team.set_team_icon.get_team.app_error", nil, getTeamErr.Error(), http.StatusBadRequest)
} }
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
return model.NewAppError("setTeamIcon", "api.team.set_team_icon.storage.app_error", nil, "", http.StatusNotImplemented) return model.NewAppError("setTeamIcon", "api.team.set_team_icon.storage.app_error", nil, "", http.StatusNotImplemented)
} }

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

@@ -393,7 +393,7 @@ func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string,
return nil, err return nil, err
} }
if len(teamId) > 0 { if teamId != "" {
err = a.AddUserToTeamByTeamId(teamId, user) err = a.AddUserToTeamByTeamId(teamId, user)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -410,7 +410,7 @@ func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string,
// CheckEmailDomain checks that an email domain matches a list of space-delimited domains as a string. // CheckEmailDomain checks that an email domain matches a list of space-delimited domains as a string.
func CheckEmailDomain(email string, domains string) bool { func CheckEmailDomain(email string, domains string) bool {
if len(domains) == 0 { if domains == "" {
return true return true
} }
@@ -762,7 +762,7 @@ func (a *App) ActivateMfa(userId, token string) *model.AppError {
} }
} }
if len(user.AuthService) > 0 && user.AuthService != model.USER_AUTH_SERVICE_LDAP { if user.AuthService != "" && user.AuthService != model.USER_AUTH_SERVICE_LDAP {
return model.NewAppError("ActivateMfa", "api.user.activate_mfa.email_and_ldap_only.app_error", nil, "", http.StatusBadRequest) return model.NewAppError("ActivateMfa", "api.user.activate_mfa.email_and_ldap_only.app_error", nil, "", http.StatusBadRequest)
} }
@@ -873,7 +873,7 @@ func getFont(initialFont string) (*truetype.Font, error) {
} }
func (a *App) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) { func (a *App) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) {
if len(*a.Config().FileSettings.DriverName) == 0 { if *a.Config().FileSettings.DriverName == "" {
img, appErr := a.GetDefaultProfileImage(user) img, appErr := a.GetDefaultProfileImage(user)
if appErr != nil { if appErr != nil {
return nil, false, appErr return nil, false, appErr

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

@@ -435,7 +435,7 @@ func (h *Hub) Start() {
connIndex.Remove(webConn) connIndex.Remove(webConn)
atomic.StoreInt64(&h.connectionCount, int64(len(connIndex.All()))) atomic.StoreInt64(&h.connectionCount, int64(len(connIndex.All())))
if len(webConn.UserId) == 0 { if webConn.UserId == "" {
continue continue
} }

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

@@ -51,7 +51,7 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m
relevantHooks := []*model.OutgoingWebhook{} relevantHooks := []*model.OutgoingWebhook{}
for _, hook := range hooks { for _, hook := range hooks {
if hook.ChannelId == post.ChannelId || len(hook.ChannelId) == 0 { if hook.ChannelId == post.ChannelId || hook.ChannelId == "" {
if hook.ChannelId == post.ChannelId && len(hook.TriggerWords) == 0 { if hook.ChannelId == post.ChannelId && len(hook.TriggerWords) == 0 {
relevantHooks = append(relevantHooks, hook) relevantHooks = append(relevantHooks, hook)
triggerWord = "" triggerWord = ""
@@ -503,7 +503,7 @@ func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook)
return nil, model.NewAppError("UpdateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("UpdateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
if len(updatedHook.ChannelId) > 0 { if updatedHook.ChannelId != "" {
channel, err := a.GetChannel(updatedHook.ChannelId) channel, err := a.GetChannel(updatedHook.ChannelId)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -658,7 +658,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq
} }
text := req.Text text := req.Text
if len(text) == 0 && req.Attachments == nil { if text == "" && req.Attachments == nil {
return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.text.app_error", nil, "", http.StatusBadRequest) return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.text.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -843,7 +843,7 @@ func migrateAuthToLdapCmdF(command *cobra.Command, args []string) error {
fromAuth := args[0] fromAuth := args[0]
matchField := args[2] matchField := args[2]
if len(fromAuth) == 0 || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "saml") { if fromAuth == "" || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "saml") {
return errors.New("Invalid from_auth argument") return errors.New("Invalid from_auth argument")
} }
@@ -852,7 +852,7 @@ func migrateAuthToLdapCmdF(command *cobra.Command, args []string) error {
fromAuth = "" fromAuth = ""
} }
if len(matchField) == 0 || (matchField != "email" && matchField != "username") { if matchField == "" || (matchField != "email" && matchField != "username") {
return errors.New("Invalid match_field argument") return errors.New("Invalid match_field argument")
} }
@@ -903,7 +903,7 @@ func migrateAuthToSamlCmdF(command *cobra.Command, args []string) error {
fromAuth := args[0] fromAuth := args[0]
if len(fromAuth) == 0 || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "ldap") { if fromAuth == "" || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "ldap") {
return errors.New("Invalid from_auth argument") return errors.New("Invalid from_auth argument")
} }

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

@@ -131,7 +131,7 @@ func FixInvalidLocales(cfg *model.Config) bool {
changed = true changed = true
} }
if len(*cfg.LocalizationSettings.AvailableLocales) > 0 { if *cfg.LocalizationSettings.AvailableLocales != "" {
isDefaultClientLocaleInAvailableLocales := false isDefaultClientLocaleInAvailableLocales := false
for _, word := range strings.Split(*cfg.LocalizationSettings.AvailableLocales, ",") { for _, word := range strings.Split(*cfg.LocalizationSettings.AvailableLocales, ",") {
if _, ok := locales[word]; !ok { if _, ok := locales[word]; !ok {

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

@@ -115,7 +115,7 @@ func (srv *JobServer) SetJobError(job *model.Job, jobError *model.AppError) *mod
job.Data = make(map[string]string) job.Data = make(map[string]string)
} }
job.Data["error"] = jobError.Message job.Data["error"] = jobError.Message
if len(jobError.DetailedError) > 0 { if jobError.DetailedError != "" {
job.Data["error"] += " — " + jobError.DetailedError job.Data["error"] += " — " + jobError.DetailedError
} }
updated, err := srv.Store.Job().UpdateOptimistically(job, model.JOB_STATUS_IN_PROGRESS) updated, err := srv.Store.Job().UpdateOptimistically(job, model.JOB_STATUS_IN_PROGRESS)

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

@@ -55,7 +55,7 @@ func (p *AdvancedPermissionsPhase2Progress) IsValid() bool {
func (worker *Worker) runAdvancedPermissionsPhase2Migration(lastDone string) (bool, string, *model.AppError) { func (worker *Worker) runAdvancedPermissionsPhase2Migration(lastDone string) (bool, string, *model.AppError) {
var progress *AdvancedPermissionsPhase2Progress var progress *AdvancedPermissionsPhase2Progress
if len(lastDone) == 0 { if lastDone == "" {
// Haven't started the migration yet. // Haven't started the migration yet.
progress = new(AdvancedPermissionsPhase2Progress) progress = new(AdvancedPermissionsPhase2Progress)
progress.CurrentTable = "TeamMembers" progress.CurrentTable = "TeamMembers"

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

@@ -38,11 +38,11 @@ type AccessResponse struct {
// correctly. // correctly.
func (ad *AccessData) IsValid() *AppError { func (ad *AccessData) IsValid() *AppError {
if len(ad.ClientId) == 0 || len(ad.ClientId) > 26 { if ad.ClientId == "" || len(ad.ClientId) > 26 {
return NewAppError("AccessData.IsValid", "model.access.is_valid.client_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("AccessData.IsValid", "model.access.is_valid.client_id.app_error", nil, "", http.StatusBadRequest)
} }
if len(ad.UserId) == 0 || len(ad.UserId) > 26 { if ad.UserId == "" || len(ad.UserId) > 26 {
return NewAppError("AccessData.IsValid", "model.access.is_valid.user_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("AccessData.IsValid", "model.access.is_valid.user_id.app_error", nil, "", http.StatusBadRequest)
} }
@@ -54,7 +54,7 @@ func (ad *AccessData) IsValid() *AppError {
return NewAppError("AccessData.IsValid", "model.access.is_valid.refresh_token.app_error", nil, "", http.StatusBadRequest) return NewAppError("AccessData.IsValid", "model.access.is_valid.refresh_token.app_error", nil, "", http.StatusBadRequest)
} }
if len(ad.RedirectUri) == 0 || len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) { if ad.RedirectUri == "" || len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) {
return NewAppError("AccessData.IsValid", "model.access.is_valid.redirect_uri.app_error", nil, "", http.StatusBadRequest) return NewAppError("AccessData.IsValid", "model.access.is_valid.redirect_uri.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -47,7 +47,7 @@ func (ad *AuthData) IsValid() *AppError {
return NewAppError("AuthData.IsValid", "model.authorize.is_valid.user_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("AuthData.IsValid", "model.authorize.is_valid.user_id.app_error", nil, "", http.StatusBadRequest)
} }
if len(ad.Code) == 0 || len(ad.Code) > 128 { if ad.Code == "" || len(ad.Code) > 128 {
return NewAppError("AuthData.IsValid", "model.authorize.is_valid.auth_code.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest) return NewAppError("AuthData.IsValid", "model.authorize.is_valid.auth_code.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest)
} }
@@ -82,11 +82,11 @@ func (ar *AuthorizeRequest) IsValid() *AppError {
return NewAppError("AuthData.IsValid", "model.authorize.is_valid.client_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("AuthData.IsValid", "model.authorize.is_valid.client_id.app_error", nil, "", http.StatusBadRequest)
} }
if len(ar.ResponseType) == 0 { if ar.ResponseType == "" {
return NewAppError("AuthData.IsValid", "model.authorize.is_valid.response_type.app_error", nil, "", http.StatusBadRequest) return NewAppError("AuthData.IsValid", "model.authorize.is_valid.response_type.app_error", nil, "", http.StatusBadRequest)
} }
if len(ar.RedirectUri) == 0 || len(ar.RedirectUri) > 256 || !IsValidHttpUrl(ar.RedirectUri) { if ar.RedirectUri == "" || len(ar.RedirectUri) > 256 || !IsValidHttpUrl(ar.RedirectUri) {
return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ar.ClientId, http.StatusBadRequest) return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ar.ClientId, http.StatusBadRequest)
} }
@@ -110,7 +110,7 @@ func (ad *AuthData) PreSave() {
ad.CreateAt = GetMillis() ad.CreateAt = GetMillis()
} }
if len(ad.Scope) == 0 { if ad.Scope == "" {
ad.Scope = DEFAULT_SCOPE ad.Scope = DEFAULT_SCOPE
} }
} }

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

@@ -82,7 +82,7 @@ func (b *Bot) IsValid() *AppError {
return NewAppError("Bot.IsValid", "model.bot.is_valid.description.app_error", b.Trace(), "", http.StatusBadRequest) return NewAppError("Bot.IsValid", "model.bot.is_valid.description.app_error", b.Trace(), "", http.StatusBadRequest)
} }
if len(b.OwnerId) == 0 || utf8.RuneCountInString(b.OwnerId) > BOT_CREATOR_ID_MAX_RUNES { if b.OwnerId == "" || utf8.RuneCountInString(b.OwnerId) > BOT_CREATOR_ID_MAX_RUNES {
return NewAppError("Bot.IsValid", "model.bot.is_valid.creator_id.app_error", b.Trace(), "", http.StatusBadRequest) return NewAppError("Bot.IsValid", "model.bot.is_valid.creator_id.app_error", b.Trace(), "", http.StatusBadRequest)
} }

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

@@ -584,11 +584,11 @@ func (c *Client4) doApiRequestReader(method, url string, data io.Reader, etag st
return nil, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest) return nil, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)
} }
if len(etag) > 0 { if etag != "" {
rq.Header.Set(HEADER_ETAG_CLIENT, etag) rq.Header.Set(HEADER_ETAG_CLIENT, etag)
} }
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -629,7 +629,7 @@ func (c *Client4) doUploadFile(url string, body io.Reader, contentType string, c
} }
rq.Header.Set("Content-Type", contentType) rq.Header.Set("Content-Type", contentType)
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -653,7 +653,7 @@ func (c *Client4) DoEmojiUploadFile(url string, data []byte, contentType string)
} }
rq.Header.Set("Content-Type", contentType) rq.Header.Set("Content-Type", contentType)
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -677,7 +677,7 @@ func (c *Client4) DoUploadImportTeam(url string, data []byte, contentType string
} }
rq.Header.Set("Content-Type", contentType) rq.Header.Set("Content-Type", contentType)
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -1490,7 +1490,7 @@ func (c *Client4) SetProfileImage(userId string, data []byte) (bool, *Response)
} }
rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Header.Set("Content-Type", writer.FormDataContentType())
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -1739,7 +1739,7 @@ func (c *Client4) SetBotIconImage(botUserId string, data []byte) (bool, *Respons
} }
rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Header.Set("Content-Type", writer.FormDataContentType())
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -2273,7 +2273,7 @@ func (c *Client4) SetTeamIcon(teamId string, data []byte) (bool, *Response) {
} }
rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Header.Set("Content-Type", writer.FormDataContentType())
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -3471,7 +3471,7 @@ func (c *Client4) UploadLicenseFile(data []byte) (bool, *Response) {
} }
rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Header.Set("Content-Type", writer.FormDataContentType())
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -3878,7 +3878,7 @@ func (c *Client4) DownloadComplianceReport(reportId string) ([]byte, *Response)
return nil, &Response{Error: NewAppError("DownloadComplianceReport", "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)} return nil, &Response{Error: NewAppError("DownloadComplianceReport", "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)}
} }
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken)
} }
@@ -4248,7 +4248,7 @@ func (c *Client4) UploadBrandImage(data []byte) (bool, *Response) {
} }
rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Header.Set("Content-Type", writer.FormDataContentType())
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -4403,7 +4403,7 @@ func (c *Client4) GetOAuthAccessToken(data url.Values) (*AccessResponse, *Respon
} }
rq.Header.Set("Content-Type", "application/x-www-form-urlencoded") rq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }
@@ -5042,7 +5042,7 @@ func (c *Client4) uploadPlugin(file io.Reader, force bool) (*Manifest, *Response
} }
rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Header.Set("Content-Type", writer.FormDataContentType())
if len(c.AuthToken) > 0 { if c.AuthToken != "" {
rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken)
} }

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

@@ -39,7 +39,7 @@ func (o *ClusterDiscovery) PreSave() {
func (o *ClusterDiscovery) AutoFillHostname() { func (o *ClusterDiscovery) AutoFillHostname() {
// attempt to set the hostname from the OS // attempt to set the hostname from the OS
if len(o.Hostname) == 0 { if o.Hostname == "" {
if hn, err := os.Hostname(); err == nil { if hn, err := os.Hostname(); err == nil {
o.Hostname = hn o.Hostname = hn
} }
@@ -48,8 +48,8 @@ func (o *ClusterDiscovery) AutoFillHostname() {
func (o *ClusterDiscovery) AutoFillIpAddress(iface string, ipAddress string) { func (o *ClusterDiscovery) AutoFillIpAddress(iface string, ipAddress string) {
// attempt to set the hostname to the first non-local IP address // attempt to set the hostname to the first non-local IP address
if len(o.Hostname) == 0 { if o.Hostname == "" {
if len(ipAddress) > 0 { if ipAddress != "" {
o.Hostname = ipAddress o.Hostname = ipAddress
} else { } else {
o.Hostname = GetServerIpAddress(iface) o.Hostname = GetServerIpAddress(iface)
@@ -93,15 +93,15 @@ func (o *ClusterDiscovery) IsValid() *AppError {
return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.id.app_error", nil, "", http.StatusBadRequest) return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.id.app_error", nil, "", http.StatusBadRequest)
} }
if len(o.ClusterName) == 0 { if o.ClusterName == "" {
return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.name.app_error", nil, "", http.StatusBadRequest) return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.name.app_error", nil, "", http.StatusBadRequest)
} }
if len(o.Type) == 0 { if o.Type == "" {
return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.type.app_error", nil, "", http.StatusBadRequest) return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.type.app_error", nil, "", http.StatusBadRequest)
} }
if len(o.Hostname) == 0 { if o.Hostname == "" {
return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.hostname.app_error", nil, "", http.StatusBadRequest) return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.hostname.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -105,7 +105,7 @@ func (o *Command) IsValid() *AppError {
return NewAppError("Command.IsValid", "model.command.is_valid.trigger.app_error", nil, "", http.StatusBadRequest) return NewAppError("Command.IsValid", "model.command.is_valid.trigger.app_error", nil, "", http.StatusBadRequest)
} }
if len(o.URL) == 0 || len(o.URL) > 1024 { if o.URL == "" || len(o.URL) > 1024 {
return NewAppError("Command.IsValid", "model.command.is_valid.url.app_error", nil, "", http.StatusBadRequest) return NewAppError("Command.IsValid", "model.command.is_valid.url.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -84,7 +84,7 @@ func (c *Compliance) IsValid() *AppError {
return NewAppError("Compliance.IsValid", "model.compliance.is_valid.create_at.app_error", nil, "", http.StatusBadRequest) return NewAppError("Compliance.IsValid", "model.compliance.is_valid.create_at.app_error", nil, "", http.StatusBadRequest)
} }
if len(c.Desc) > 512 || len(c.Desc) == 0 { if len(c.Desc) > 512 || c.Desc == "" {
return NewAppError("Compliance.IsValid", "model.compliance.is_valid.desc.app_error", nil, "", http.StatusBadRequest) return NewAppError("Compliance.IsValid", "model.compliance.is_valid.desc.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -1117,7 +1117,7 @@ func (s *SqlSettings) SetDefaults(isUpdate bool) {
if isUpdate { if isUpdate {
// When updating an existing configuration, ensure an encryption key has been specified. // When updating an existing configuration, ensure an encryption key has been specified.
if s.AtRestEncryptKey == nil || len(*s.AtRestEncryptKey) == 0 { if s.AtRestEncryptKey == nil || *s.AtRestEncryptKey == "" {
s.AtRestEncryptKey = NewString(NewRandomString(32)) s.AtRestEncryptKey = NewString(NewRandomString(32))
} }
} else { } else {
@@ -1383,7 +1383,7 @@ func (s *FileSettings) SetDefaults(isUpdate bool) {
if isUpdate { if isUpdate {
// When updating an existing configuration, ensure link salt has been specified. // When updating an existing configuration, ensure link salt has been specified.
if s.PublicLinkSalt == nil || len(*s.PublicLinkSalt) == 0 { if s.PublicLinkSalt == nil || *s.PublicLinkSalt == "" {
s.PublicLinkSalt = NewString(NewRandomString(32)) s.PublicLinkSalt = NewString(NewRandomString(32))
} }
} else { } else {
@@ -1416,7 +1416,7 @@ func (s *FileSettings) SetDefaults(isUpdate bool) {
s.AmazonS3Region = NewString("") s.AmazonS3Region = NewString("")
} }
if s.AmazonS3Endpoint == nil || len(*s.AmazonS3Endpoint) == 0 { if s.AmazonS3Endpoint == nil || *s.AmazonS3Endpoint == "" {
// Defaults to "s3.amazonaws.com" // Defaults to "s3.amazonaws.com"
s.AmazonS3Endpoint = NewString("s3.amazonaws.com") s.AmazonS3Endpoint = NewString("s3.amazonaws.com")
} }
@@ -1529,11 +1529,11 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) {
s.SMTPPassword = NewString("") s.SMTPPassword = NewString("")
} }
if s.SMTPServer == nil || len(*s.SMTPServer) == 0 { if s.SMTPServer == nil || *s.SMTPServer == "" {
s.SMTPServer = NewString("localhost") s.SMTPServer = NewString("localhost")
} }
if s.SMTPPort == nil || len(*s.SMTPPort) == 0 { if s.SMTPPort == nil || *s.SMTPPort == "" {
s.SMTPPort = NewString("10025") s.SMTPPort = NewString("10025")
} }
@@ -3114,7 +3114,7 @@ func (o *Config) SetDefaults() {
} }
func (o *Config) IsValid() *AppError { func (o *Config) IsValid() *AppError {
if len(*o.ServiceSettings.SiteURL) == 0 && *o.EmailSettings.EnableEmailBatching { if *o.ServiceSettings.SiteURL == "" && *o.EmailSettings.EnableEmailBatching {
return NewAppError("Config.IsValid", "model.config.is_valid.site_url_email_batching.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.site_url_email_batching.app_error", nil, "", http.StatusBadRequest)
} }
@@ -3122,7 +3122,7 @@ func (o *Config) IsValid() *AppError {
return NewAppError("Config.IsValid", "model.config.is_valid.cluster_email_batching.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.cluster_email_batching.app_error", nil, "", http.StatusBadRequest)
} }
if len(*o.ServiceSettings.SiteURL) == 0 && *o.ServiceSettings.AllowCookiesForSubdomains { if *o.ServiceSettings.SiteURL == "" && *o.ServiceSettings.AllowCookiesForSubdomains {
return NewAppError("Config.IsValid", "model.config.is_valid.allow_cookies_for_subdomains.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.allow_cookies_for_subdomains.app_error", nil, "", http.StatusBadRequest)
} }
@@ -3245,7 +3245,7 @@ func (s *SqlSettings) isValid() *AppError {
return NewAppError("Config.IsValid", "model.config.is_valid.sql_query_timeout.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.sql_query_timeout.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.DataSource) == 0 { if *s.DataSource == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.sql_data_src.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.sql_data_src.app_error", nil, "", http.StatusBadRequest)
} }
@@ -3374,47 +3374,47 @@ func (s *LdapSettings) isValid() *AppError {
func (s *SamlSettings) isValid() *AppError { func (s *SamlSettings) isValid() *AppError {
if *s.Enable { if *s.Enable {
if len(*s.IdpUrl) == 0 || !IsValidHttpUrl(*s.IdpUrl) { if *s.IdpUrl == "" || !IsValidHttpUrl(*s.IdpUrl) {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_url.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_url.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.IdpDescriptorUrl) == 0 || !IsValidHttpUrl(*s.IdpDescriptorUrl) { if *s.IdpDescriptorUrl == "" || !IsValidHttpUrl(*s.IdpDescriptorUrl) {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_descriptor_url.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_descriptor_url.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.IdpCertificateFile) == 0 { if *s.IdpCertificateFile == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_cert.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_cert.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.EmailAttribute) == 0 { if *s.EmailAttribute == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.UsernameAttribute) == 0 { if *s.UsernameAttribute == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_username_attribute.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_username_attribute.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.ServiceProviderIdentifier) == 0 { if *s.ServiceProviderIdentifier == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_spidentifier_attribute.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_spidentifier_attribute.app_error", nil, "", http.StatusBadRequest)
} }
if *s.Verify { if *s.Verify {
if len(*s.AssertionConsumerServiceURL) == 0 || !IsValidHttpUrl(*s.AssertionConsumerServiceURL) { if *s.AssertionConsumerServiceURL == "" || !IsValidHttpUrl(*s.AssertionConsumerServiceURL) {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_assertion_consumer_service_url.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_assertion_consumer_service_url.app_error", nil, "", http.StatusBadRequest)
} }
} }
if *s.Encrypt { if *s.Encrypt {
if len(*s.PrivateKeyFile) == 0 { if *s.PrivateKeyFile == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_private_key.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_private_key.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.PublicCertificateFile) == 0 { if *s.PublicCertificateFile == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_public_cert.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_public_cert.app_error", nil, "", http.StatusBadRequest)
} }
} }
if len(*s.EmailAttribute) == 0 { if *s.EmailAttribute == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest)
} }
@@ -3425,7 +3425,7 @@ func (s *SamlSettings) isValid() *AppError {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_canonical_algorithm.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_canonical_algorithm.app_error", nil, "", http.StatusBadRequest)
} }
if len(*s.GuestAttribute) > 0 { if *s.GuestAttribute != "" {
if !(strings.Contains(*s.GuestAttribute, "=")) { if !(strings.Contains(*s.GuestAttribute, "=")) {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_guest_attribute.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_guest_attribute.app_error", nil, "", http.StatusBadRequest)
} }
@@ -3434,7 +3434,7 @@ func (s *SamlSettings) isValid() *AppError {
} }
} }
if len(*s.AdminAttribute) > 0 { if *s.AdminAttribute != "" {
if !(strings.Contains(*s.AdminAttribute, "=")) { if !(strings.Contains(*s.AdminAttribute, "=")) {
return NewAppError("Config.IsValid", "model.config.is_valid.saml_admin_attribute.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.saml_admin_attribute.app_error", nil, "", http.StatusBadRequest)
} }
@@ -3535,7 +3535,7 @@ func (s *ServiceSettings) isValid() *AppError {
func (s *ElasticsearchSettings) isValid() *AppError { func (s *ElasticsearchSettings) isValid() *AppError {
if *s.EnableIndexing { if *s.EnableIndexing {
if len(*s.ConnectionUrl) == 0 { if *s.ConnectionUrl == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.connection_url.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.connection_url.app_error", nil, "", http.StatusBadRequest)
} }
} }
@@ -3573,7 +3573,7 @@ func (s *ElasticsearchSettings) isValid() *AppError {
func (bs *BleveSettings) isValid() *AppError { func (bs *BleveSettings) isValid() *AppError {
if *bs.EnableIndexing { if *bs.EnableIndexing {
if len(*bs.IndexDir) == 0 { if *bs.IndexDir == "" {
return NewAppError("Config.IsValid", "model.config.is_valid.bleve_search.filename.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.bleve_search.filename.app_error", nil, "", http.StatusBadRequest)
} }
} else { } else {
@@ -3608,7 +3608,7 @@ func (s *DataRetentionSettings) isValid() *AppError {
} }
func (s *LocalizationSettings) isValid() *AppError { func (s *LocalizationSettings) isValid() *AppError {
if len(*s.AvailableLocales) > 0 { if *s.AvailableLocales != "" {
if !strings.Contains(*s.AvailableLocales, *s.DefaultClientLocale) { if !strings.Contains(*s.AvailableLocales, *s.DefaultClientLocale) {
return NewAppError("Config.IsValid", "model.config.is_valid.localization.available_locales.app_error", nil, "", http.StatusBadRequest) return NewAppError("Config.IsValid", "model.config.is_valid.localization.available_locales.app_error", nil, "", http.StatusBadRequest)
} }
@@ -3703,33 +3703,33 @@ func (o *Config) GetSanitizeOptions() map[string]bool {
} }
func (o *Config) Sanitize() { func (o *Config) Sanitize() {
if o.LdapSettings.BindPassword != nil && len(*o.LdapSettings.BindPassword) > 0 { if o.LdapSettings.BindPassword != nil && *o.LdapSettings.BindPassword != "" {
*o.LdapSettings.BindPassword = FAKE_SETTING *o.LdapSettings.BindPassword = FAKE_SETTING
} }
*o.FileSettings.PublicLinkSalt = FAKE_SETTING *o.FileSettings.PublicLinkSalt = FAKE_SETTING
if len(*o.FileSettings.AmazonS3SecretAccessKey) > 0 { if *o.FileSettings.AmazonS3SecretAccessKey != "" {
*o.FileSettings.AmazonS3SecretAccessKey = FAKE_SETTING *o.FileSettings.AmazonS3SecretAccessKey = FAKE_SETTING
} }
if o.EmailSettings.SMTPPassword != nil && len(*o.EmailSettings.SMTPPassword) > 0 { if o.EmailSettings.SMTPPassword != nil && *o.EmailSettings.SMTPPassword != "" {
*o.EmailSettings.SMTPPassword = FAKE_SETTING *o.EmailSettings.SMTPPassword = FAKE_SETTING
} }
if len(*o.GitLabSettings.Secret) > 0 { if *o.GitLabSettings.Secret != "" {
*o.GitLabSettings.Secret = FAKE_SETTING *o.GitLabSettings.Secret = FAKE_SETTING
} }
if o.GoogleSettings.Secret != nil && len(*o.GoogleSettings.Secret) > 0 { if o.GoogleSettings.Secret != nil && *o.GoogleSettings.Secret != "" {
*o.GoogleSettings.Secret = FAKE_SETTING *o.GoogleSettings.Secret = FAKE_SETTING
} }
if o.Office365Settings.Secret != nil && len(*o.Office365Settings.Secret) > 0 { if o.Office365Settings.Secret != nil && *o.Office365Settings.Secret != "" {
*o.Office365Settings.Secret = FAKE_SETTING *o.Office365Settings.Secret = FAKE_SETTING
} }
if o.OpenIdSettings.Secret != nil && len(*o.OpenIdSettings.Secret) > 0 { if o.OpenIdSettings.Secret != nil && *o.OpenIdSettings.Secret != "" {
*o.OpenIdSettings.Secret = FAKE_SETTING *o.OpenIdSettings.Secret = FAKE_SETTING
} }
@@ -3746,11 +3746,11 @@ func (o *Config) Sanitize() {
o.SqlSettings.DataSourceSearchReplicas[i] = FAKE_SETTING o.SqlSettings.DataSourceSearchReplicas[i] = FAKE_SETTING
} }
if o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != nil && len(*o.MessageExportSettings.GlobalRelaySettings.SmtpPassword) > 0 { if o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != nil && *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != "" {
*o.MessageExportSettings.GlobalRelaySettings.SmtpPassword = FAKE_SETTING *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword = FAKE_SETTING
} }
if o.ServiceSettings.GfycatApiSecret != nil && len(*o.ServiceSettings.GfycatApiSecret) > 0 { if o.ServiceSettings.GfycatApiSecret != nil && *o.ServiceSettings.GfycatApiSecret != "" {
*o.ServiceSettings.GfycatApiSecret = FAKE_SETTING *o.ServiceSettings.GfycatApiSecret = FAKE_SETTING
} }

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

@@ -57,7 +57,7 @@ func (emoji *Emoji) IsValid() *AppError {
} }
func IsValidEmojiName(name string) *AppError { func IsValidEmojiName(name string) *AppError {
if len(name) == 0 || len(name) > EMOJI_NAME_MAX_LENGTH || !IsValidAlphaNumHyphenUnderscore(name, false) || inSystemEmoji(name) { if name == "" || len(name) > EMOJI_NAME_MAX_LENGTH || !IsValidAlphaNumHyphenUnderscore(name, false) || inSystemEmoji(name) {
return NewAppError("Emoji.IsValid", "model.emoji.name.app_error", nil, "", http.StatusBadRequest) return NewAppError("Emoji.IsValid", "model.emoji.name.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -139,7 +139,7 @@ func (group *Group) IsValidForCreate() *AppError {
return NewAppError("Group.IsValidForCreate", "model.group.source.app_error", nil, "", http.StatusBadRequest) return NewAppError("Group.IsValidForCreate", "model.group.source.app_error", nil, "", http.StatusBadRequest)
} }
if len(group.RemoteId) > GroupRemoteIDMaxLength || (len(group.RemoteId) == 0 && group.requiresRemoteId()) { if len(group.RemoteId) > GroupRemoteIDMaxLength || (group.RemoteId == "" && group.requiresRemoteId()) {
return NewAppError("Group.IsValidForCreate", "model.group.remote_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("Group.IsValidForCreate", "model.group.remote_id.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -23,7 +23,7 @@ func (i *GuestsInvite) IsValid() *AppError {
} }
for _, email := range i.Emails { for _, email := range i.Emails {
if len(email) > USER_EMAIL_MAX_LENGTH || len(email) == 0 || !IsValidEmail(email) { if len(email) > USER_EMAIL_MAX_LENGTH || email == "" || !IsValidEmail(email) {
return NewAppError("GuestsInvite.IsValid", "model.guest.is_valid.email.app_error", nil, "email="+email, http.StatusBadRequest) return NewAppError("GuestsInvite.IsValid", "model.guest.is_valid.email.app_error", nil, "email="+email, http.StatusBadRequest)
} }
} }

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

@@ -296,7 +296,7 @@ func (lr *LicenseRecord) IsValid() *AppError {
return NewAppError("LicenseRecord.IsValid", "model.license_record.is_valid.create_at.app_error", nil, "", http.StatusBadRequest) return NewAppError("LicenseRecord.IsValid", "model.license_record.is_valid.create_at.app_error", nil, "", http.StatusBadRequest)
} }
if len(lr.Bytes) == 0 || len(lr.Bytes) > 10000 { if lr.Bytes == "" || len(lr.Bytes) > 10000 {
return NewAppError("LicenseRecord.IsValid", "model.license_record.is_valid.create_at.app_error", nil, "", http.StatusBadRequest) return NewAppError("LicenseRecord.IsValid", "model.license_record.is_valid.create_at.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -53,11 +53,11 @@ func (a *OAuthApp) IsValid() *AppError {
return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.creator_id.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.creator_id.app_error", nil, "app_id="+a.Id, http.StatusBadRequest)
} }
if len(a.ClientSecret) == 0 || len(a.ClientSecret) > 128 { if a.ClientSecret == "" || len(a.ClientSecret) > 128 {
return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.client_secret.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.client_secret.app_error", nil, "app_id="+a.Id, http.StatusBadRequest)
} }
if len(a.Name) == 0 || len(a.Name) > 64 { if a.Name == "" || len(a.Name) > 64 {
return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.name.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.name.app_error", nil, "app_id="+a.Id, http.StatusBadRequest)
} }
@@ -71,7 +71,7 @@ func (a *OAuthApp) IsValid() *AppError {
} }
} }
if len(a.Homepage) == 0 || len(a.Homepage) > 256 || !IsValidHttpUrl(a.Homepage) { if a.Homepage == "" || len(a.Homepage) > 256 || !IsValidHttpUrl(a.Homepage) {
return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.homepage.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.homepage.app_error", nil, "app_id="+a.Id, http.StatusBadRequest)
} }
@@ -79,7 +79,7 @@ func (a *OAuthApp) IsValid() *AppError {
return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.description.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.description.app_error", nil, "app_id="+a.Id, http.StatusBadRequest)
} }
if len(a.IconURL) > 0 { if a.IconURL != "" {
if len(a.IconURL) > 512 || !IsValidHttpUrl(a.IconURL) { if len(a.IconURL) > 512 || !IsValidHttpUrl(a.IconURL) {
return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.icon_url.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.icon_url.app_error", nil, "app_id="+a.Id, http.StatusBadRequest)
} }

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

@@ -154,7 +154,7 @@ func (o *OutgoingWebhook) IsValid() *AppError {
if len(o.TriggerWords) != 0 { if len(o.TriggerWords) != 0 {
for _, triggerWord := range o.TriggerWords { for _, triggerWord := range o.TriggerWords {
if len(triggerWord) == 0 { if triggerWord == "" {
return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.trigger_words.app_error", nil, "", http.StatusBadRequest) return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.trigger_words.app_error", nil, "", http.StatusBadRequest)
} }
} }
@@ -215,7 +215,7 @@ func (o *OutgoingWebhook) PreUpdate() {
} }
func (o *OutgoingWebhook) TriggerWordExactMatch(word string) bool { func (o *OutgoingWebhook) TriggerWordExactMatch(word string) bool {
if len(word) == 0 { if word == "" {
return false return false
} }
@@ -229,7 +229,7 @@ func (o *OutgoingWebhook) TriggerWordExactMatch(word string) bool {
} }
func (o *OutgoingWebhook) TriggerWordStartsWith(word string) bool { func (o *OutgoingWebhook) TriggerWordStartsWith(word string) bool {
if len(word) == 0 { if word == "" {
return false return false
} }
@@ -243,7 +243,7 @@ func (o *OutgoingWebhook) TriggerWordStartsWith(word string) bool {
} }
func (o *OutgoingWebhook) GetTriggerWord(word string, isExactMatch bool) (triggerWord string) { func (o *OutgoingWebhook) GetTriggerWord(word string, isExactMatch bool) (triggerWord string) {
if len(word) == 0 { if word == "" {
return return
} }

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

@@ -21,11 +21,11 @@ type PluginKeyValue struct {
} }
func (kv *PluginKeyValue) IsValid() *AppError { func (kv *PluginKeyValue) IsValid() *AppError {
if len(kv.PluginId) == 0 || utf8.RuneCountInString(kv.PluginId) > KEY_VALUE_PLUGIN_ID_MAX_RUNES { if kv.PluginId == "" || utf8.RuneCountInString(kv.PluginId) > KEY_VALUE_PLUGIN_ID_MAX_RUNES {
return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.plugin_id.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.plugin_id.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest)
} }
if len(kv.Key) == 0 || utf8.RuneCountInString(kv.Key) > KEY_VALUE_KEY_MAX_RUNES { if kv.Key == "" || utf8.RuneCountInString(kv.Key) > KEY_VALUE_KEY_MAX_RUNES {
return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.key.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.key.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest)
} }

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

@@ -277,19 +277,19 @@ func (o *Post) IsValid(maxPostSize int) *AppError {
return NewAppError("Post.IsValid", "model.post.is_valid.channel_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("Post.IsValid", "model.post.is_valid.channel_id.app_error", nil, "", http.StatusBadRequest)
} }
if !(IsValidId(o.RootId) || len(o.RootId) == 0) { if !(IsValidId(o.RootId) || o.RootId == "") {
return NewAppError("Post.IsValid", "model.post.is_valid.root_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("Post.IsValid", "model.post.is_valid.root_id.app_error", nil, "", http.StatusBadRequest)
} }
if !(IsValidId(o.ParentId) || len(o.ParentId) == 0) { if !(IsValidId(o.ParentId) || o.ParentId == "") {
return NewAppError("Post.IsValid", "model.post.is_valid.parent_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("Post.IsValid", "model.post.is_valid.parent_id.app_error", nil, "", http.StatusBadRequest)
} }
if len(o.ParentId) == 26 && len(o.RootId) == 0 { if len(o.ParentId) == 26 && o.RootId == "" {
return NewAppError("Post.IsValid", "model.post.is_valid.root_parent.app_error", nil, "", http.StatusBadRequest) return NewAppError("Post.IsValid", "model.post.is_valid.root_parent.app_error", nil, "", http.StatusBadRequest)
} }
if !(len(o.OriginalId) == 26 || len(o.OriginalId) == 0) { if !(len(o.OriginalId) == 26 || o.OriginalId == "") {
return NewAppError("Post.IsValid", "model.post.is_valid.original_id.app_error", nil, "", http.StatusBadRequest) return NewAppError("Post.IsValid", "model.post.is_valid.original_id.app_error", nil, "", http.StatusBadRequest)
} }

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

@@ -75,7 +75,7 @@ func (o *Preference) IsValid() *AppError {
return NewAppError("Preference.IsValid", "model.preference.is_valid.id.app_error", nil, "user_id="+o.UserId, http.StatusBadRequest) return NewAppError("Preference.IsValid", "model.preference.is_valid.id.app_error", nil, "user_id="+o.UserId, http.StatusBadRequest)
} }
if len(o.Category) == 0 || len(o.Category) > 32 { if o.Category == "" || len(o.Category) > 32 {
return NewAppError("Preference.IsValid", "model.preference.is_valid.category.app_error", nil, "category="+o.Category, http.StatusBadRequest) return NewAppError("Preference.IsValid", "model.preference.is_valid.category.app_error", nil, "category="+o.Category, http.StatusBadRequest)
} }

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

@@ -73,7 +73,7 @@ func (o *Reaction) IsValid() *AppError {
validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`) validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`)
if len(o.EmojiName) == 0 || len(o.EmojiName) > EMOJI_NAME_MAX_LENGTH || !validName.MatchString(o.EmojiName) { if o.EmojiName == "" || len(o.EmojiName) > EMOJI_NAME_MAX_LENGTH || !validName.MatchString(o.EmojiName) {
return NewAppError("Reaction.IsValid", "model.reaction.is_valid.emoji_name.app_error", nil, "emoji_name="+o.EmojiName, http.StatusBadRequest) return NewAppError("Reaction.IsValid", "model.reaction.is_valid.emoji_name.app_error", nil, "emoji_name="+o.EmojiName, http.StatusBadRequest)
} }

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

@@ -482,7 +482,7 @@ func (r *Role) IsValidWithoutId() bool {
return false return false
} }
if len(r.DisplayName) == 0 || len(r.DisplayName) > ROLE_DISPLAY_NAME_MAX_LENGTH { if r.DisplayName == "" || len(r.DisplayName) > ROLE_DISPLAY_NAME_MAX_LENGTH {
return false return false
} }
@@ -526,7 +526,7 @@ func CleanRoleNames(roleNames []string) ([]string, bool) {
} }
func IsValidRoleName(roleName string) bool { func IsValidRoleName(roleName string) bool {
if len(roleName) <= 0 || len(roleName) > ROLE_NAME_MAX_LENGTH { if roleName == "" || len(roleName) > ROLE_NAME_MAX_LENGTH {
return false return false
} }

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

@@ -114,7 +114,7 @@ func (scheme *Scheme) IsValid() bool {
} }
func (scheme *Scheme) IsValidForCreate() bool { func (scheme *Scheme) IsValidForCreate() bool {
if len(scheme.DisplayName) == 0 || len(scheme.DisplayName) > SCHEME_DISPLAY_NAME_MAX_LENGTH { if scheme.DisplayName == "" || len(scheme.DisplayName) > SCHEME_DISPLAY_NAME_MAX_LENGTH {
return false return false
} }

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

@@ -312,7 +312,7 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams {
paramsList := []*SearchParams{} paramsList := []*SearchParams{}
if len(plainTerms) > 0 || len(excludedPlainTerms) > 0 { if plainTerms != "" || excludedPlainTerms != "" {
paramsList = append(paramsList, &SearchParams{ paramsList = append(paramsList, &SearchParams{
Terms: plainTerms, Terms: plainTerms,
ExcludedTerms: excludedPlainTerms, ExcludedTerms: excludedPlainTerms,
@@ -333,7 +333,7 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams {
}) })
} }
if len(hashtagTerms) > 0 || len(excludedHashtagTerms) > 0 { if hashtagTerms != "" || excludedHashtagTerms != "" {
paramsList = append(paramsList, &SearchParams{ paramsList = append(paramsList, &SearchParams{
Terms: hashtagTerms, Terms: hashtagTerms,
ExcludedTerms: excludedHashtagTerms, ExcludedTerms: excludedHashtagTerms,
@@ -355,8 +355,8 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams {
} }
// special case for when no terms are specified but we still have a filter // special case for when no terms are specified but we still have a filter
if len(plainTerms) == 0 && len(hashtagTerms) == 0 && if plainTerms == "" && hashtagTerms == "" &&
len(excludedPlainTerms) == 0 && len(excludedHashtagTerms) == 0 && excludedPlainTerms == "" && excludedHashtagTerms == "" &&
(len(inChannels) != 0 || len(fromUsers) != 0 || (len(inChannels) != 0 || len(fromUsers) != 0 ||
len(excludedChannels) != 0 || len(excludedUsers) != 0 || len(excludedChannels) != 0 || len(excludedUsers) != 0 ||
len(extensions) != 0 || len(excludedExtensions) != 0 || len(extensions) != 0 || len(excludedExtensions) != 0 ||

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

@@ -155,7 +155,7 @@ func (s *Session) GetTeamByTeamId(teamId string) *TeamMember {
} }
func (s *Session) IsMobileApp() bool { func (s *Session) IsMobileApp() bool {
return len(s.DeviceId) > 0 || s.IsMobile() return s.DeviceId != "" || s.IsMobile()
} }
func (s *Session) IsMobile() bool { func (s *Session) IsMobile() bool {

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

@@ -152,7 +152,7 @@ func (o *Team) IsValid() *AppError {
return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest) return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest)
} }
if len(o.Email) > 0 && !IsValidEmail(o.Email) { if o.Email != "" && !IsValidEmail(o.Email) {
return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest) return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest)
} }
@@ -168,7 +168,7 @@ func (o *Team) IsValid() *AppError {
return NewAppError("Team.IsValid", "model.team.is_valid.description.app_error", nil, "id="+o.Id, http.StatusBadRequest) return NewAppError("Team.IsValid", "model.team.is_valid.description.app_error", nil, "id="+o.Id, http.StatusBadRequest)
} }
if len(o.InviteId) == 0 { if o.InviteId == "" {
return NewAppError("Team.IsValid", "model.team.is_valid.invite_id.app_error", nil, "id="+o.Id, http.StatusBadRequest) return NewAppError("Team.IsValid", "model.team.is_valid.invite_id.app_error", nil, "id="+o.Id, http.StatusBadRequest)
} }
@@ -208,7 +208,7 @@ func (o *Team) PreSave() {
o.Description = SanitizeUnicode(o.Description) o.Description = SanitizeUnicode(o.Description)
o.CompanyName = SanitizeUnicode(o.CompanyName) o.CompanyName = SanitizeUnicode(o.CompanyName)
if len(o.InviteId) == 0 { if o.InviteId == "" {
o.InviteId = NewId() o.InviteId = NewId()
} }
} }

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

@@ -274,7 +274,7 @@ func (u *User) IsValid() *AppError {
return InvalidUserError("username", u.Id) return InvalidUserError("username", u.Id)
} }
if len(u.Email) > USER_EMAIL_MAX_LENGTH || len(u.Email) == 0 || !IsValidEmail(u.Email) { if len(u.Email) > USER_EMAIL_MAX_LENGTH || u.Email == "" || !IsValidEmail(u.Email) {
return InvalidUserError("email", u.Id) return InvalidUserError("email", u.Id)
} }
@@ -298,11 +298,11 @@ func (u *User) IsValid() *AppError {
return InvalidUserError("auth_data", u.Id) return InvalidUserError("auth_data", u.Id)
} }
if u.AuthData != nil && len(*u.AuthData) > 0 && len(u.AuthService) == 0 { if u.AuthData != nil && *u.AuthData != "" && u.AuthService == "" {
return InvalidUserError("auth_data_type", u.Id) return InvalidUserError("auth_data_type", u.Id)
} }
if len(u.Password) > 0 && u.AuthData != nil && len(*u.AuthData) > 0 { if u.Password != "" && u.AuthData != nil && *u.AuthData != "" {
return InvalidUserError("auth_data_pwd", u.Id) return InvalidUserError("auth_data_pwd", u.Id)
} }
@@ -381,7 +381,7 @@ func (u *User) PreSave() {
u.Timezone = timezones.DefaultUserTimezone() u.Timezone = timezones.DefaultUserTimezone()
} }
if len(u.Password) > 0 { if u.Password != "" {
u.Password = HashPassword(u.Password) u.Password = HashPassword(u.Password)
} }
} }
@@ -414,7 +414,7 @@ func (u *User) PreUpdate() {
splitKeys := strings.Split(u.NotifyProps[MENTION_KEYS_NOTIFY_PROP], ",") splitKeys := strings.Split(u.NotifyProps[MENTION_KEYS_NOTIFY_PROP], ",")
goodKeys := []string{} goodKeys := []string{}
for _, key := range splitKeys { for _, key := range splitKeys {
if len(key) > 0 { if key != "" {
goodKeys = append(goodKeys, strings.ToLower(key)) goodKeys = append(goodKeys, strings.ToLower(key))
} }
} }
@@ -597,11 +597,11 @@ func (u *User) AddNotifyProp(key string, value string) {
} }
func (u *User) GetFullName() string { func (u *User) GetFullName() string {
if len(u.FirstName) > 0 && len(u.LastName) > 0 { if u.FirstName != "" && u.LastName != "" {
return u.FirstName + " " + u.LastName return u.FirstName + " " + u.LastName
} else if len(u.FirstName) > 0 { } else if u.FirstName != "" {
return u.FirstName return u.FirstName
} else if len(u.LastName) > 0 { } else if u.LastName != "" {
return u.LastName return u.LastName
} else { } else {
return "" return ""
@@ -612,13 +612,13 @@ func (u *User) getDisplayName(baseName, nameFormat string) string {
displayName := baseName displayName := baseName
if nameFormat == SHOW_NICKNAME_FULLNAME { if nameFormat == SHOW_NICKNAME_FULLNAME {
if len(u.Nickname) > 0 { if u.Nickname != "" {
displayName = u.Nickname displayName = u.Nickname
} else if fullName := u.GetFullName(); len(fullName) > 0 { } else if fullName := u.GetFullName(); fullName != "" {
displayName = fullName displayName = fullName
} }
} else if nameFormat == SHOW_FULLNAME { } else if nameFormat == SHOW_FULLNAME {
if fullName := u.GetFullName(); len(fullName) > 0 { if fullName := u.GetFullName(); fullName != "" {
displayName = fullName displayName = fullName
} }
} }
@@ -768,7 +768,7 @@ func HashPassword(password string) string {
// ComparePassword compares the hash // ComparePassword compares the hash
func ComparePassword(hash string, password string) bool { func ComparePassword(hash string, password string) bool {
if len(password) == 0 || len(hash) == 0 { if password == "" || hash == "" {
return false return false
} }
@@ -881,7 +881,7 @@ func (u *UserWithGroups) GetGroupIDs() []string {
return nil return nil
} }
trimmed := strings.TrimSpace(*u.GroupIDs) trimmed := strings.TrimSpace(*u.GroupIDs)
if len(trimmed) == 0 { if trimmed == "" {
return nil return nil
} }
return strings.Split(trimmed, ",") return strings.Split(trimmed, ",")

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

@@ -335,7 +335,7 @@ func StringFromJson(data io.Reader) string {
func GetServerIpAddress(iface string) string { func GetServerIpAddress(iface string) string {
var addrs []net.Addr var addrs []net.Addr
if len(iface) == 0 { if iface == "" {
var err error var err error
addrs, err = net.InterfaceAddrs() addrs, err = net.InterfaceAddrs()
if err != nil { if err != nil {
@@ -495,7 +495,7 @@ func IsFileExtImage(ext string) bool {
func GetImageMimeType(ext string) string { func GetImageMimeType(ext string) string {
ext = strings.ToLower(ext) ext = strings.ToLower(ext)
if len(IMAGE_MIME_TYPES[ext]) == 0 { if IMAGE_MIME_TYPES[ext] == "" {
return "image" return "image"
} }
return IMAGE_MIME_TYPES[ext] return IMAGE_MIME_TYPES[ext]

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

@@ -59,11 +59,11 @@ func (p *HelpersImpl) ensureServerVersion(required string) error {
// GetPluginAssetURL implements GetPluginAssetURL. // GetPluginAssetURL implements GetPluginAssetURL.
func (p *HelpersImpl) GetPluginAssetURL(pluginID, asset string) (string, error) { func (p *HelpersImpl) GetPluginAssetURL(pluginID, asset string) (string, error) {
if len(pluginID) == 0 { if pluginID == "" {
return "", errors.New("empty pluginID provided") return "", errors.New("empty pluginID provided")
} }
if len(asset) == 0 { if asset == "" {
return "", errors.New("empty asset name provided") return "", errors.New("empty asset name provided")
} }

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

@@ -352,7 +352,7 @@ func getPathsFromObjectInfos(in <-chan s3.ObjectInfo) <-chan s3.ObjectInfo {
func (b *S3FileBackend) ListDirectory(path string) ([]string, error) { func (b *S3FileBackend) ListDirectory(path string) ([]string, error) {
path = filepath.Join(b.pathPrefix, path) path = filepath.Join(b.pathPrefix, path)
if !strings.HasSuffix(path, "/") && len(path) > 0 { if !strings.HasSuffix(path, "/") && path != "" {
// s3Clnt returns only the path itself when "/" is not present // s3Clnt returns only the path itself when "/" is not present
// appending "/" to make it consistent across all filesstores // appending "/" to make it consistent across all filesstores
path = path + "/" path = path + "/"
@@ -408,12 +408,12 @@ func s3PutOptions(encrypted bool, contentType string) s3.PutObjectOptions {
} }
func CheckMandatoryS3Fields(settings *model.FileSettings) error { func CheckMandatoryS3Fields(settings *model.FileSettings) error {
if settings.AmazonS3Bucket == nil || len(*settings.AmazonS3Bucket) == 0 { if settings.AmazonS3Bucket == nil || *settings.AmazonS3Bucket == "" {
return errors.New("missing s3 bucket settings") return errors.New("missing s3 bucket settings")
} }
// if S3 endpoint is not set call the set defaults to set that // if S3 endpoint is not set call the set defaults to set that
if settings.AmazonS3Endpoint == nil || len(*settings.AmazonS3Endpoint) == 0 { if settings.AmazonS3Endpoint == nil || *settings.AmazonS3Endpoint == "" {
settings.SetDefaults(true) settings.SetDefaults(true)
} }

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

@@ -273,7 +273,7 @@ func SendMailUsingConfig(to, subject, htmlBody string, config *model.Config, ena
// allows for sending an email with attachments and differing MIME/SMTP recipients // allows for sending an email with attachments and differing MIME/SMTP recipients
func sendMailUsingConfigAdvanced(mail mailData, config *model.Config, enableComplianceFeatures bool) *model.AppError { func sendMailUsingConfigAdvanced(mail mailData, config *model.Config, enableComplianceFeatures bool) *model.AppError {
if len(*config.EmailSettings.SMTPServer) == 0 { if *config.EmailSettings.SMTPServer == "" {
return nil return nil
} }
@@ -324,11 +324,11 @@ func SendMail(c smtpClient, mail mailData, fileBackend filesstore.FileBackend, d
"Precedence": {"bulk"}, "Precedence": {"bulk"},
} }
if len(mail.replyTo.Address) > 0 { if mail.replyTo.Address != "" {
headers["Reply-To"] = []string{mail.replyTo.String()} headers["Reply-To"] = []string{mail.replyTo.String()}
} }
if len(mail.cc) > 0 { if mail.cc != "" {
headers["CC"] = []string{mail.cc} headers["CC"] = []string{mail.cc}
} }

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

@@ -424,10 +424,10 @@ func TestSendMail(t *testing.T) {
mail := mailData{"", "", mail.Address{}, "", tc.replyTo, "", "", nil, nil, nil} mail := mailData{"", "", mail.Address{}, "", tc.replyTo, "", "", nil, nil, nil}
appErr = SendMail(mocm, mail, mockBackend, time.Now()) appErr = SendMail(mocm, mail, mockBackend, time.Now())
require.Nil(t, appErr) require.Nil(t, appErr)
if len(tc.contains) > 0 { if tc.contains != "" {
require.Contains(t, string(mocm.data), tc.contains) require.Contains(t, string(mocm.data), tc.contains)
} }
if len(tc.notContains) > 0 { if tc.notContains != "" {
require.NotContains(t, string(mocm.data), tc.notContains) require.NotContains(t, string(mocm.data), tc.notContains)
} }
mocm.data = []byte{} mocm.data = []byte{}

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

@@ -43,7 +43,7 @@ func getIssuerFromUrl(uri string) string {
issuer := "Mattermost" issuer := "Mattermost"
siteUrl := strings.TrimSpace(uri) siteUrl := strings.TrimSpace(uri)
if len(siteUrl) > 0 { if siteUrl != "" {
siteUrl = strings.TrimPrefix(siteUrl, "https://") siteUrl = strings.TrimPrefix(siteUrl, "https://")
siteUrl = strings.TrimPrefix(siteUrl, "http://") siteUrl = strings.TrimPrefix(siteUrl, "http://")
issuer = strings.TrimPrefix(siteUrl, "www.") issuer = strings.TrimPrefix(siteUrl, "www.")

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

@@ -159,7 +159,7 @@ func (b *BleveEngine) SearchPosts(channels *model.ChannelList, searchParams []*m
notTermQueries = append(notTermQueries, hashtagQ) notTermQueries = append(notTermQueries, hashtagQ)
} }
} else { } else {
if len(params.Terms) > 0 { if params.Terms != "" {
terms := []string{} terms := []string{}
for _, term := range strings.Split(params.Terms, " ") { for _, term := range strings.Split(params.Terms, " ") {
if strings.HasSuffix(term, "*") { if strings.HasSuffix(term, "*") {
@@ -179,7 +179,7 @@ func (b *BleveEngine) SearchPosts(channels *model.ChannelList, searchParams []*m
} }
} }
if len(params.ExcludedTerms) > 0 { if params.ExcludedTerms != "" {
messageQ := bleve.NewMatchQuery(params.ExcludedTerms) messageQ := bleve.NewMatchQuery(params.ExcludedTerms)
messageQ.SetField("Message") messageQ.SetField("Message")
messageQ.SetOperator(termOperator) messageQ.SetOperator(termOperator)
@@ -654,7 +654,7 @@ func (b *BleveEngine) SearchFiles(channels *model.ChannelList, searchParams []*m
} }
} }
if len(params.Terms) > 0 { if params.Terms != "" {
terms := []string{} terms := []string{}
for _, term := range strings.Split(params.Terms, " ") { for _, term := range strings.Split(params.Terms, " ") {
if strings.HasSuffix(term, "*") { if strings.HasSuffix(term, "*") {
@@ -679,7 +679,7 @@ func (b *BleveEngine) SearchFiles(channels *model.ChannelList, searchParams []*m
} }
} }
if len(params.ExcludedTerms) > 0 { if params.ExcludedTerms != "" {
nameQ := bleve.NewMatchQuery(params.ExcludedTerms) nameQ := bleve.NewMatchQuery(params.ExcludedTerms)
nameQ.SetField("Name") nameQ.SetField("Name")
nameQ.SetOperator(termOperator) nameQ.SetOperator(termOperator)

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

@@ -126,7 +126,7 @@ func (ts *TelemetryService) ensureTelemetryID() {
} }
id := props[model.SYSTEM_TELEMETRY_ID] id := props[model.SYSTEM_TELEMETRY_ID]
if len(id) == 0 { if id == "" {
id = model.NewId() id = model.NewId()
systemID := &model.System{Name: model.SYSTEM_TELEMETRY_ID, Value: id} systemID := &model.System{Name: model.SYSTEM_TELEMETRY_ID, Value: id}
ts.dbStore.System().Save(systemID) ts.dbStore.System().Save(systemID)

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

@@ -623,7 +623,7 @@ func (s SqlChannelStore) SaveDirectChannel(directchannel *model.Channel, member1
} }
func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *model.Channel, maxChannelsPerTeam int64) (*model.Channel, error) { func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *model.Channel, maxChannelsPerTeam int64) (*model.Channel, error) {
if len(channel.Id) > 0 { if channel.Id != "" {
return nil, store.NewErrInvalidInput("Channel", "Id", channel.Id) return nil, store.NewErrInvalidInput("Channel", "Id", channel.Id)
} }
@@ -1031,7 +1031,7 @@ func (s SqlChannelStore) getAllChannelsQuery(opts store.ChannelSearchOpts, forCo
query = query.Where(sq.Eq{"c.DeleteAt": int(0)}) query = query.Where(sq.Eq{"c.DeleteAt": int(0)})
} }
if len(opts.NotAssociatedToGroup) > 0 { if opts.NotAssociatedToGroup != "" {
query = query.Where("c.Id NOT IN (SELECT ChannelId FROM GroupChannels WHERE GroupChannels.GroupId = ? AND GroupChannels.DeleteAt = 0)", opts.NotAssociatedToGroup) query = query.Where("c.Id NOT IN (SELECT ChannelId FROM GroupChannels WHERE GroupChannels.GroupId = ? AND GroupChannels.DeleteAt = 0)", opts.NotAssociatedToGroup)
} }
@@ -1142,7 +1142,7 @@ func (s SqlChannelStore) GetPublicChannelsByIdsForTeam(teamId string, channelIds
idQuery := "" idQuery := ""
for index, channelId := range channelIds { for index, channelId := range channelIds {
if len(idQuery) > 0 { if idQuery != "" {
idQuery += ", " idQuery += ", "
} }
@@ -2335,7 +2335,7 @@ func (s SqlChannelStore) GetForPost(postId string) (*model.Channel, error) {
func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) (int64, error) { func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) (int64, error) {
query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType" query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType"
if len(teamId) > 0 { if teamId != "" {
query += " AND TeamId = :TeamId" query += " AND TeamId = :TeamId"
} }
@@ -2349,7 +2349,7 @@ func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) (
func (s SqlChannelStore) AnalyticsDeletedTypeCount(teamId string, channelType string) (int64, error) { func (s SqlChannelStore) AnalyticsDeletedTypeCount(teamId string, channelType string) (int64, error) {
query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType AND DeleteAt > 0" query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType AND DeleteAt > 0"
if len(teamId) > 0 { if teamId != "" {
query += " AND TeamId = :TeamId" query += " AND TeamId = :TeamId"
} }
@@ -2681,7 +2681,7 @@ func (s SqlChannelStore) channelSearchQuery(term string, opts store.ChannelSearc
query = query.Where(sq.NotEq{"c.Name": opts.ExcludeChannelNames}) query = query.Where(sq.NotEq{"c.Name": opts.ExcludeChannelNames})
} }
if len(opts.NotAssociatedToGroup) > 0 { if opts.NotAssociatedToGroup != "" {
query = query.Where("c.Id NOT IN (SELECT ChannelId FROM GroupChannels WHERE GroupChannels.GroupId = ? AND GroupChannels.DeleteAt = 0)", opts.NotAssociatedToGroup) query = query.Where("c.Id NOT IN (SELECT ChannelId FROM GroupChannels WHERE GroupChannels.GroupId = ? AND GroupChannels.DeleteAt = 0)", opts.NotAssociatedToGroup)
} }

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

@@ -54,7 +54,7 @@ func (s SqlCommandStore) createIndexesIfNotExists() {
} }
func (s SqlCommandStore) Save(command *model.Command) (*model.Command, error) { func (s SqlCommandStore) Save(command *model.Command) (*model.Command, error) {
if len(command.Id) > 0 { if command.Id != "" {
return nil, store.NewErrInvalidInput("Command", "CommandId", command.Id) return nil, store.NewErrInvalidInput("Command", "CommandId", command.Id)
} }
@@ -193,7 +193,7 @@ func (s SqlCommandStore) AnalyticsCommandCount(teamId string) (int64, error) {
From("Commands"). From("Commands").
Where(sq.Eq{"DeleteAt": 0}) Where(sq.Eq{"DeleteAt": 0})
if len(teamId) > 0 { if teamId != "" {
query = query.Where(sq.Eq{"TeamId": teamId}) query = query.Where(sq.Eq{"TeamId": teamId})
} }

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

@@ -39,7 +39,7 @@ func (s SqlCommandWebhookStore) createIndexesIfNotExists() {
} }
func (s SqlCommandWebhookStore) Save(webhook *model.CommandWebhook) (*model.CommandWebhook, error) { func (s SqlCommandWebhookStore) Save(webhook *model.CommandWebhook) (*model.CommandWebhook, error) {
if len(webhook.Id) > 0 { if webhook.Id != "" {
return nil, store.NewErrInvalidInput("CommandWebhook", "id", webhook.Id) return nil, store.NewErrInvalidInput("CommandWebhook", "id", webhook.Id)
} }

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

@@ -476,31 +476,31 @@ func (fs SqlFileInfoStore) Search(paramsList []*model.SearchParams, userId, team
} }
// handle after: before: on: filters // handle after: before: on: filters
if len(params.OnDate) > 0 { if params.OnDate != "" {
onDateStart, onDateEnd := params.GetOnDateMillis() onDateStart, onDateEnd := params.GetOnDateMillis()
query = query.Where(sq.Expr("FI.CreateAt BETWEEN ? AND ?", strconv.FormatInt(onDateStart, 10), strconv.FormatInt(onDateEnd, 10))) query = query.Where(sq.Expr("FI.CreateAt BETWEEN ? AND ?", strconv.FormatInt(onDateStart, 10), strconv.FormatInt(onDateEnd, 10)))
} else { } else {
if len(params.ExcludedDate) > 0 { if params.ExcludedDate != "" {
excludedDateStart, excludedDateEnd := params.GetExcludedDateMillis() excludedDateStart, excludedDateEnd := params.GetExcludedDateMillis()
query = query.Where(sq.Expr("FI.CreateAt NOT BETWEEN ? AND ?", strconv.FormatInt(excludedDateStart, 10), strconv.FormatInt(excludedDateEnd, 10))) query = query.Where(sq.Expr("FI.CreateAt NOT BETWEEN ? AND ?", strconv.FormatInt(excludedDateStart, 10), strconv.FormatInt(excludedDateEnd, 10)))
} }
if len(params.AfterDate) > 0 { if params.AfterDate != "" {
afterDate := params.GetAfterDateMillis() afterDate := params.GetAfterDateMillis()
query = query.Where(sq.GtOrEq{"FI.CreateAt": strconv.FormatInt(afterDate, 10)}) query = query.Where(sq.GtOrEq{"FI.CreateAt": strconv.FormatInt(afterDate, 10)})
} }
if len(params.BeforeDate) > 0 { if params.BeforeDate != "" {
beforeDate := params.GetBeforeDateMillis() beforeDate := params.GetBeforeDateMillis()
query = query.Where(sq.LtOrEq{"FI.CreateAt": strconv.FormatInt(beforeDate, 10)}) query = query.Where(sq.LtOrEq{"FI.CreateAt": strconv.FormatInt(beforeDate, 10)})
} }
if len(params.ExcludedAfterDate) > 0 { if params.ExcludedAfterDate != "" {
afterDate := params.GetExcludedAfterDateMillis() afterDate := params.GetExcludedAfterDateMillis()
query = query.Where(sq.Lt{"FI.CreateAt": strconv.FormatInt(afterDate, 10)}) query = query.Where(sq.Lt{"FI.CreateAt": strconv.FormatInt(afterDate, 10)})
} }
if len(params.ExcludedBeforeDate) > 0 { if params.ExcludedBeforeDate != "" {
beforeDate := params.GetExcludedBeforeDateMillis() beforeDate := params.GetExcludedBeforeDateMillis()
query = query.Where(sq.Gt{"FI.CreateAt": strconv.FormatInt(beforeDate, 10)}) query = query.Where(sq.Gt{"FI.CreateAt": strconv.FormatInt(beforeDate, 10)})
} }

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

@@ -986,7 +986,7 @@ func (s *SqlGroupStore) groupsBySyncableBaseQuery(st model.GroupSyncableType, t
query = query.Where("ug.AllowReference = true") query = query.Where("ug.AllowReference = true")
} }
if len(opts.Q) > 0 { if opts.Q != "" {
pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\"))
operatorKeyword := "ILIKE" operatorKeyword := "ILIKE"
if s.DriverName() == model.DATABASE_DRIVER_MYSQL { if s.DriverName() == model.DATABASE_DRIVER_MYSQL {
@@ -1051,7 +1051,7 @@ func (s *SqlGroupStore) getGroupsAssociatedToChannelsByTeam(st model.GroupSyncab
query = query.Where("ug.AllowReference = true") query = query.Where("ug.AllowReference = true")
} }
if len(opts.Q) > 0 { if opts.Q != "" {
pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\"))
operatorKeyword := "ILIKE" operatorKeyword := "ILIKE"
if s.DriverName() == model.DATABASE_DRIVER_MYSQL { if s.DriverName() == model.DATABASE_DRIVER_MYSQL {
@@ -1171,7 +1171,7 @@ func (s *SqlGroupStore) GetGroups(page, perPage int, opts model.GroupSearchOpts)
groupsQuery = groupsQuery.Where("g.AllowReference = true") groupsQuery = groupsQuery.Where("g.AllowReference = true")
} }
if len(opts.Q) > 0 { if opts.Q != "" {
pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\"))
operatorKeyword := "ILIKE" operatorKeyword := "ILIKE"
if s.DriverName() == model.DATABASE_DRIVER_MYSQL { if s.DriverName() == model.DATABASE_DRIVER_MYSQL {

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

@@ -62,7 +62,7 @@ func (as SqlOAuthStore) createIndexesIfNotExists() {
} }
func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) (*model.OAuthApp, error) { func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) (*model.OAuthApp, error) {
if len(app.Id) > 0 { if app.Id != "" {
return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id) return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id)
} }

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

@@ -114,7 +114,7 @@ func (s *SqlPostStore) SaveMultiple(posts []*model.Post) ([]*model.Post, int, er
rootIds := make(map[string]int) rootIds := make(map[string]int)
maxDateRootIds := make(map[string]int64) maxDateRootIds := make(map[string]int64)
for idx, post := range posts { for idx, post := range posts {
if len(post.Id) > 0 { if post.Id != "" {
return nil, idx, store.NewErrInvalidInput("Post", "id", post.Id) return nil, idx, store.NewErrInvalidInput("Post", "id", post.Id)
} }
post.PreSave() post.PreSave()
@@ -140,7 +140,7 @@ func (s *SqlPostStore) SaveMultiple(posts []*model.Post) ([]*model.Post, int, er
} }
} }
if len(post.RootId) == 0 { if post.RootId == "" {
continue continue
} }
@@ -199,7 +199,7 @@ func (s *SqlPostStore) SaveMultiple(posts []*model.Post) ([]*model.Post, int, er
unknownRepliesPosts := []*model.Post{} unknownRepliesPosts := []*model.Post{}
for _, post := range posts { for _, post := range posts {
if len(post.RootId) == 0 { if post.RootId == "" {
count, ok := rootIds[post.Id] count, ok := rootIds[post.Id]
if ok { if ok {
post.ReplyCount += int64(count) post.ReplyCount += int64(count)
@@ -285,7 +285,7 @@ func (s *SqlPostStore) Update(newPost *model.Post, oldPost *model.Post) (*model.
time := model.GetMillis() time := model.GetMillis()
s.GetMaster().Exec("UPDATE Channels SET LastPostAt = :LastPostAt WHERE Id = :ChannelId AND LastPostAt < :LastPostAt", map[string]interface{}{"LastPostAt": time, "ChannelId": newPost.ChannelId}) s.GetMaster().Exec("UPDATE Channels SET LastPostAt = :LastPostAt WHERE Id = :ChannelId AND LastPostAt < :LastPostAt", map[string]interface{}{"LastPostAt": time, "ChannelId": newPost.ChannelId})
if len(newPost.RootId) > 0 { if newPost.RootId != "" {
s.GetMaster().Exec("UPDATE Posts SET UpdateAt = :UpdateAt WHERE Id = :RootId AND UpdateAt < :UpdateAt", map[string]interface{}{"UpdateAt": time, "RootId": newPost.RootId}) s.GetMaster().Exec("UPDATE Posts SET UpdateAt = :UpdateAt WHERE Id = :RootId AND UpdateAt < :UpdateAt", map[string]interface{}{"UpdateAt": time, "RootId": newPost.RootId})
s.GetMaster().Exec("UPDATE Threads SET LastReplyAt = :UpdateAt WHERE PostId = :RootId", map[string]interface{}{"UpdateAt": time, "RootId": newPost.RootId}) s.GetMaster().Exec("UPDATE Threads SET LastReplyAt = :UpdateAt WHERE PostId = :RootId", map[string]interface{}{"UpdateAt": time, "RootId": newPost.RootId})
} }
@@ -319,7 +319,7 @@ func (s *SqlPostStore) OverwriteMultiple(posts []*model.Post) ([]*model.Post, in
return nil, idx, errors.Wrap(err, "failed to update Post") return nil, idx, errors.Wrap(err, "failed to update Post")
} }
if len(post.RootId) > 0 { if post.RootId != "" {
tx.Exec("UPDATE Threads SET LastReplyAt = :UpdateAt WHERE PostId = :RootId", map[string]interface{}{"UpdateAt": updateAt, "RootId": post.Id}) tx.Exec("UPDATE Threads SET LastReplyAt = :UpdateAt WHERE PostId = :RootId", map[string]interface{}{"UpdateAt": updateAt, "RootId": post.Id})
} }
} }
@@ -425,7 +425,7 @@ func (s *SqlPostStore) GetFlaggedPostsForChannel(userId, channelId string, offse
return pl, nil return pl, nil
} }
func (s *SqlPostStore) getPostWithCollapsedThreads(id string, extended bool) (*model.PostList, error) { func (s *SqlPostStore) getPostWithCollapsedThreads(id string, extended bool) (*model.PostList, error) {
if len(id) == 0 { if id == "" {
return nil, store.NewErrInvalidInput("Post", "id", id) return nil, store.NewErrInvalidInput("Post", "id", id)
} }
@@ -460,7 +460,7 @@ func (s *SqlPostStore) Get(id string, skipFetchThreads, collapsedThreads, collap
} }
pl := model.NewPostList() pl := model.NewPostList()
if len(id) == 0 { if id == "" {
return nil, store.NewErrInvalidInput("Post", "id", id) return nil, store.NewErrInvalidInput("Post", "id", id)
} }
@@ -483,7 +483,7 @@ func (s *SqlPostStore) Get(id string, skipFetchThreads, collapsedThreads, collap
rootId = post.Id rootId = post.Id
} }
if len(rootId) == 0 { if rootId == "" {
return nil, errors.Wrapf(err, "invalid rootId with value=%s", rootId) return nil, errors.Wrapf(err, "invalid rootId with value=%s", rootId)
} }
@@ -1247,7 +1247,7 @@ var specialSearchChar = []string{
func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, queryParams map[string]interface{}) (string, map[string]interface{}) { func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, queryParams map[string]interface{}) (string, map[string]interface{}) {
searchQuery := "" searchQuery := ""
// handle after: before: on: filters // handle after: before: on: filters
if len(params.OnDate) > 0 { if params.OnDate != "" {
onDateStart, onDateEnd := params.GetOnDateMillis() onDateStart, onDateEnd := params.GetOnDateMillis()
queryParams["OnDateStart"] = strconv.FormatInt(onDateStart, 10) queryParams["OnDateStart"] = strconv.FormatInt(onDateStart, 10)
queryParams["OnDateEnd"] = strconv.FormatInt(onDateEnd, 10) queryParams["OnDateEnd"] = strconv.FormatInt(onDateEnd, 10)
@@ -1256,7 +1256,7 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q
searchQuery += "AND CreateAt BETWEEN :OnDateStart AND :OnDateEnd " searchQuery += "AND CreateAt BETWEEN :OnDateStart AND :OnDateEnd "
} else { } else {
if len(params.ExcludedDate) > 0 { if params.ExcludedDate != "" {
excludedDateStart, excludedDateEnd := params.GetExcludedDateMillis() excludedDateStart, excludedDateEnd := params.GetExcludedDateMillis()
queryParams["ExcludedDateStart"] = strconv.FormatInt(excludedDateStart, 10) queryParams["ExcludedDateStart"] = strconv.FormatInt(excludedDateStart, 10)
queryParams["ExcludedDateEnd"] = strconv.FormatInt(excludedDateEnd, 10) queryParams["ExcludedDateEnd"] = strconv.FormatInt(excludedDateEnd, 10)
@@ -1264,7 +1264,7 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q
searchQuery += "AND CreateAt NOT BETWEEN :ExcludedDateStart AND :ExcludedDateEnd " searchQuery += "AND CreateAt NOT BETWEEN :ExcludedDateStart AND :ExcludedDateEnd "
} }
if len(params.AfterDate) > 0 { if params.AfterDate != "" {
afterDate := params.GetAfterDateMillis() afterDate := params.GetAfterDateMillis()
queryParams["AfterDate"] = strconv.FormatInt(afterDate, 10) queryParams["AfterDate"] = strconv.FormatInt(afterDate, 10)
@@ -1272,7 +1272,7 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q
searchQuery += "AND CreateAt >= :AfterDate " searchQuery += "AND CreateAt >= :AfterDate "
} }
if len(params.BeforeDate) > 0 { if params.BeforeDate != "" {
beforeDate := params.GetBeforeDateMillis() beforeDate := params.GetBeforeDateMillis()
queryParams["BeforeDate"] = strconv.FormatInt(beforeDate, 10) queryParams["BeforeDate"] = strconv.FormatInt(beforeDate, 10)
@@ -1280,14 +1280,14 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q
searchQuery += "AND CreateAt <= :BeforeDate " searchQuery += "AND CreateAt <= :BeforeDate "
} }
if len(params.ExcludedAfterDate) > 0 { if params.ExcludedAfterDate != "" {
afterDate := params.GetExcludedAfterDateMillis() afterDate := params.GetExcludedAfterDateMillis()
queryParams["ExcludedAfterDate"] = strconv.FormatInt(afterDate, 10) queryParams["ExcludedAfterDate"] = strconv.FormatInt(afterDate, 10)
searchQuery += "AND CreateAt < :ExcludedAfterDate " searchQuery += "AND CreateAt < :ExcludedAfterDate "
} }
if len(params.ExcludedBeforeDate) > 0 { if params.ExcludedBeforeDate != "" {
beforeDate := params.GetExcludedBeforeDateMillis() beforeDate := params.GetExcludedBeforeDateMillis()
queryParams["ExcludedBeforeDate"] = strconv.FormatInt(beforeDate, 10) queryParams["ExcludedBeforeDate"] = strconv.FormatInt(beforeDate, 10)
@@ -1387,7 +1387,7 @@ func (s *SqlPostStore) search(teamId string, userId string, params *model.Search
if params.Terms == "" && params.ExcludedTerms == "" && if params.Terms == "" && params.ExcludedTerms == "" &&
len(params.InChannels) == 0 && len(params.ExcludedChannels) == 0 && len(params.InChannels) == 0 && len(params.ExcludedChannels) == 0 &&
len(params.FromUsers) == 0 && len(params.ExcludedUsers) == 0 && len(params.FromUsers) == 0 && len(params.ExcludedUsers) == 0 &&
len(params.OnDate) == 0 && len(params.AfterDate) == 0 && len(params.BeforeDate) == 0 { params.OnDate == "" && params.AfterDate == "" && params.BeforeDate == "" {
return list, nil return list, nil
} }
@@ -1576,7 +1576,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A
COUNT(DISTINCT Posts.UserId) AS Value COUNT(DISTINCT Posts.UserId) AS Value
FROM Posts` FROM Posts`
if len(teamId) > 0 { if teamId != "" {
query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND"
} else { } else {
query += " WHERE" query += " WHERE"
@@ -1593,7 +1593,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A
TO_CHAR(DATE(TO_TIMESTAMP(Posts.CreateAt / 1000)), 'YYYY-MM-DD') AS Name, COUNT(DISTINCT Posts.UserId) AS Value TO_CHAR(DATE(TO_TIMESTAMP(Posts.CreateAt / 1000)), 'YYYY-MM-DD') AS Name, COUNT(DISTINCT Posts.UserId) AS Value
FROM Posts` FROM Posts`
if len(teamId) > 0 { if teamId != "" {
query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND"
} else { } else {
query += " WHERE" query += " WHERE"
@@ -1631,7 +1631,7 @@ func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCoun
query += " INNER JOIN Bots ON Posts.UserId = Bots.Userid" query += " INNER JOIN Bots ON Posts.UserId = Bots.Userid"
} }
if len(options.TeamId) > 0 { if options.TeamId != "" {
query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND"
} else { } else {
query += " WHERE" query += " WHERE"
@@ -1653,7 +1653,7 @@ func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCoun
query += " INNER JOIN Bots ON Posts.UserId = Bots.Userid" query += " INNER JOIN Bots ON Posts.UserId = Bots.Userid"
} }
if len(options.TeamId) > 0 { if options.TeamId != "" {
query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND"
} else { } else {
query += " WHERE" query += " WHERE"
@@ -1688,7 +1688,7 @@ func (s *SqlPostStore) AnalyticsPostCount(teamId string, mustHaveFile bool, must
Select("COUNT(p.Id) AS Value"). Select("COUNT(p.Id) AS Value").
From("Posts p") From("Posts p")
if len(teamId) > 0 { if teamId != "" {
query = query. query = query.
Join("Channels c ON (c.Id = p.ChannelId)"). Join("Channels c ON (c.Id = p.ChannelId)").
Where(sq.Eq{"c.TeamId": teamId}) Where(sq.Eq{"c.TeamId": teamId})
@@ -2103,7 +2103,7 @@ func (s *SqlPostStore) cleanupThreads(postId, rootId, userId string, permanent b
} }
return nil return nil
} }
if len(rootId) > 0 { if rootId != "" {
thread, err := s.Thread().Get(rootId) thread, err := s.Thread().Get(rootId)
if err != nil { if err != nil {
if err != sql.ErrNoRows { if err != sql.ErrNoRows {
@@ -2125,7 +2125,7 @@ func (s *SqlPostStore) updateThreadsFromPosts(transaction *gorp.Transaction, pos
var rootIds []string var rootIds []string
for _, post := range posts { for _, post := range posts {
// skip if post is not a part of a thread // skip if post is not a part of a thread
if len(post.RootId) == 0 { if post.RootId == "" {
continue continue
} }
rootIds = append(rootIds, post.RootId) rootIds = append(rootIds, post.RootId)

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

@@ -102,7 +102,7 @@ func (s *SqlRoleStore) Save(role *model.Role) (*model.Role, error) {
return nil, store.NewErrInvalidInput("Role", "<any>", fmt.Sprintf("%v", role)) return nil, store.NewErrInvalidInput("Role", "<any>", fmt.Sprintf("%v", role))
} }
if len(role.Id) == 0 { if role.Id == "" {
transaction, err := s.GetMaster().Begin() transaction, err := s.GetMaster().Begin()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "begin_transaction") return nil, errors.Wrap(err, "begin_transaction")

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

@@ -47,7 +47,7 @@ func (s SqlSchemeStore) createIndexesIfNotExists() {
} }
func (s *SqlSchemeStore) Save(scheme *model.Scheme) (*model.Scheme, error) { func (s *SqlSchemeStore) Save(scheme *model.Scheme) (*model.Scheme, error) {
if len(scheme.Id) == 0 { if scheme.Id == "" {
transaction, err := s.GetMaster().Begin() transaction, err := s.GetMaster().Begin()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "begin_transaction") return nil, errors.Wrap(err, "begin_transaction")
@@ -213,7 +213,7 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr
} }
scheme.Id = model.NewId() scheme.Id = model.NewId()
if len(scheme.Name) == 0 { if scheme.Name == "" {
scheme.Name = model.NewId() scheme.Name = model.NewId()
} }
scheme.CreateAt = model.GetMillis() scheme.CreateAt = model.GetMillis()
@@ -332,7 +332,7 @@ func (s *SqlSchemeStore) GetAllPage(scope string, offset int, limit int) ([]*mod
var schemes []*model.Scheme var schemes []*model.Scheme
scopeClause := "" scopeClause := ""
if len(scope) > 0 { if scope != "" {
scopeClause = " AND Scope=:Scope " scopeClause = " AND Scope=:Scope "
} }

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

@@ -49,7 +49,7 @@ func (me SqlSessionStore) createIndexesIfNotExists() {
} }
func (me SqlSessionStore) Save(session *model.Session) (*model.Session, error) { func (me SqlSessionStore) Save(session *model.Session) (*model.Session, error) {
if len(session.Id) > 0 { if session.Id != "" {
return nil, store.NewErrInvalidInput("Session", "id", session.Id) return nil, store.NewErrInvalidInput("Session", "id", session.Id)
} }
session.PreSave() session.PreSave()

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

@@ -424,7 +424,7 @@ func (ss *SqlStore) MarkSystemRanUnitTests() {
} }
unitTests := props[model.SYSTEM_RAN_UNIT_TESTS] unitTests := props[model.SYSTEM_RAN_UNIT_TESTS]
if len(unitTests) == 0 { if unitTests == "" {
systemTests := &model.System{Name: model.SYSTEM_RAN_UNIT_TESTS, Value: "1"} systemTests := &model.System{Name: model.SYSTEM_RAN_UNIT_TESTS, Value: "1"}
ss.System().Save(systemTests) ss.System().Save(systemTests)
} }

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

@@ -250,7 +250,7 @@ func (s SqlTeamStore) createIndexesIfNotExists() {
// Save adds the team to the database if a team with the same name does not already // Save adds the team to the database if a team with the same name does not already
// exist in the database. It returns the team added if the operation is successful. // exist in the database. It returns the team added if the operation is successful.
func (s SqlTeamStore) Save(team *model.Team) (*model.Team, error) { func (s SqlTeamStore) Save(team *model.Team) (*model.Team, error) {
if len(team.Id) > 0 { if team.Id != "" {
return nil, store.NewErrInvalidInput("Team", "id", team.Id) return nil, store.NewErrInvalidInput("Team", "id", team.Id)
} }
@@ -335,7 +335,7 @@ func (s SqlTeamStore) GetByInviteId(inviteId string) (*model.Team, error) {
return nil, store.NewErrNotFound("Team", fmt.Sprintf("inviteId=%s", inviteId)) return nil, store.NewErrNotFound("Team", fmt.Sprintf("inviteId=%s", inviteId))
} }
if len(inviteId) == 0 || team.InviteId != inviteId { if inviteId == "" || team.InviteId != inviteId {
return nil, store.NewErrNotFound("Team", fmt.Sprintf("inviteId=%s", inviteId)) return nil, store.NewErrNotFound("Team", fmt.Sprintf("inviteId=%s", inviteId))
} }
return &team, nil return &team, nil
@@ -405,7 +405,7 @@ func (s SqlTeamStore) teamSearchQuery(term string, opts *model.TeamSearch, count
} }
} }
if len(term) > 0 { if term != "" {
term = sanitizeSearchTerm(term, "\\") term = sanitizeSearchTerm(term, "\\")
term = wildcardSearchTerm(term) term = wildcardSearchTerm(term)

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

@@ -35,7 +35,7 @@ func (s SqlTermsOfServiceStore) createIndexesIfNotExists() {
} }
func (s SqlTermsOfServiceStore) Save(termsOfService *model.TermsOfService) (*model.TermsOfService, error) { func (s SqlTermsOfServiceStore) Save(termsOfService *model.TermsOfService) (*model.TermsOfService, error) {
if len(termsOfService.Id) > 0 { if termsOfService.Id != "" {
return nil, store.NewErrInvalidInput("TermsOfService", "Id", termsOfService.Id) return nil, store.NewErrInvalidInput("TermsOfService", "Id", termsOfService.Id)
} }

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

@@ -99,7 +99,7 @@ func (us SqlUserStore) createIndexesIfNotExists() {
} }
func (us SqlUserStore) Save(user *model.User) (*model.User, error) { func (us SqlUserStore) Save(user *model.User) (*model.User, error) {
if len(user.Id) > 0 { if user.Id != "" {
return nil, store.NewErrInvalidInput("User", "id", user.Id) return nil, store.NewErrInvalidInput("User", "id", user.Id)
} }

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