MM-12393 Server side of bot accounts. (#10378)

* bots model, store and api (#9903)

* bots model, store and api

Fixes: MM-13100, MM-13101, MM-13103, MM-13105, MMM-13119

* uncomment tests incorrectly commented, and fix merge issues

* add etags support

* add missing licenses

* remove unused sqlbuilder.go (for now...)

* rejig permissions

* split out READ_BOTS into READ_BOTS and READ_OTHERS_BOTS, the latter
implicitly allowing the former
* make MANAGE_OTHERS_BOTS imply MANAGE_BOTS

* conform to general rest api pattern

* eliminate redundant http.StatusOK

* Update api4/bot.go

Co-Authored-By: lieut-data <jesse.hallam@gmail.com>

* s/model.UserFromBotModel/model.UserFromBot/g

* Update model/bot.go

Co-Authored-By: lieut-data <jesse.hallam@gmail.com>

* Update model/client4.go

Co-Authored-By: lieut-data <jesse.hallam@gmail.com>

* move sessionHasPermissionToManageBot to app/authorization.go

* use api.ApiSessionRequired for createBot

* introduce BOT_DESCRIPTION_MAX_RUNES constant

* MM-13512 Prevent getting a user by email based on privacy settings (#10021)

* MM-13512 Prevent getting a user by email based on privacy settings

* Add additional config settings to tests

* upgrade db to 5.7 (#10019)

* MM-13526 Add validation when setting a user's Locale field (#10022)

* Fix typos (#10024)

* Fixing first user being created with system admin privilages without being explicity specified. (#10014)

* Revert "Support for Embeded chat (#9129)" (#10017)

This reverts commit 3fcecd521a.

* s/DisableBot/UpdateBotActive

* add permissions on upgrade

* Update NOTICE.txt (#10054)

- add new dependency (text)
- handle switch to forked dependency (go-gomail -> go-mail)
- misc copyright owner updates

* avoid leaking bot knowledge without permission

* [GH-6798] added a new api endpoint to get the bulk reactions for posts (#10049)

* 6798 added a new api to get the bulk reactions for posts

* 6798 added the permsission check before getting the reactions

* GH-6798 added a new app function for the new endpoint

* 6798 added a store method to get reactions for multiple posts

* 6798 connected the app function with the new store function

* 6798 fixed the review comments

* MM-13559 Update model.post.is_valid.file_ids.app_error text per report (#10055)

Ticket: https://mattermost.atlassian.net/browse/MM-13559
Report: https://github.com/mattermost/mattermost-server/issues/10023

* Trigger Login Hooks with OAuth (#10061)

* make BotStore.GetAll deterministic even on duplicate CreateAt

* fix spurious TestMuteCommandSpecificChannel test failure

See
https://community-daily.mattermost.com/core/pl/px9p8s3dzbg1pf3ddrm5cr36uw

* fix race in TestExportUserChannels

* TestExportUserChannels: remove SaveMember call, as it is redundant and used to be silently failing anyway

* MM-13117: bot tokens (#10111)

* eliminate redundant Client/AdminClient declarations

* harden TestUpdateChannelScheme to API failures

* eliminate unnecessary config restoration

* minor cleanup

* make TestGenerateMfaSecret config dependency explicit

* TestCreateUserAccessToken for bots

* TestGetUserAccessToken* for bots

* leverage SessionHasPermissionToUserOrBot for user token APIs

* Test(Revoke|Disable|Enable)UserAccessToken

* make EnableUserAccessTokens explicit, so as to not rely on local config.json

* uncomment TestResetPassword, but still skip

* mark assert(Invalid)Token as helper

* fix whitespace issues

* fix mangled comments

* MM-13116: bot plugin api (#10113)

* MM-13117: expose bot API to plugins

This also changes the `CreatorId` column definition to allow for plugin
ids, as the default unless the plugin overrides is to use the plugin id
here. This branch hasn't hit master yet, so no migration needed.

* gofmt issues

* expunge use of BotList in plugin/client API

* introduce model.BotGetOptions

* use botUserId term for clarity

* MM-13129 Adding functionality to deal with orphaned bots (#10238)

* Add way to list orphaned bots.

* Add /assign route to modify ownership of bot accounts.

* Apply suggestions from code review

Co-Authored-By: crspeller <crspeller@gmail.com>

* MM-13120: add IsBot field to returned user objects (#10103)

* MM-13104: forbid bot login (#10251)

* MM-13104: disallow bot login

* fix shadowing

* MM-13136 Disable user bots when user is disabled. (#10293)

* Disable user bots when user is disabled.

* Grammer.

Co-Authored-By: crspeller <crspeller@gmail.com>

* Fixing bot branch for test changes.

* Don't use external dependancies in bot plugin tests.

* Rename bot CreatorId to OwnerId

* Adding ability to re-enable bots

* Fixing IsBot to not attempt to be saved to DB.

* Adding diagnostics and licencing counting for bot accounts.

* Modifying gorp to allow reading of '-' fields.

* Removing unnessisary nil values from UserCountOptions.

* Changing comment to GoDoc format

* Improving user count SQL

* Some improvments from feedback.

* Omit empty on User.IsBot
Этот коммит содержится в:
Christopher Speller
2019-03-05 07:06:45 -08:00
коммит произвёл GitHub
родитель 80e0d01fe5
Коммит 06b579d18a
53 изменённых файлов: 5951 добавлений и 403 удалений

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

@@ -87,6 +87,10 @@ func (s *LayeredStore) User() UserStore {
return s.DatabaseLayer.User()
}
func (s *LayeredStore) Bot() BotStore {
return s.DatabaseLayer.Bot()
}
func (s *LayeredStore) Audit() AuditStore {
return s.DatabaseLayer.Audit()
}

253
store/sqlstore/bot_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,253 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
import (
"database/sql"
"net/http"
"strings"
"github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
// bot is a subset of the model.Bot type, omitting the model.User fields.
type bot struct {
UserId string `json:"user_id"`
Description string `json:"description"`
OwnerId string `json:"owner_id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt int64 `json:"delete_at"`
}
func botFromModel(b *model.Bot) *bot {
return &bot{
UserId: b.UserId,
Description: b.Description,
OwnerId: b.OwnerId,
CreateAt: b.CreateAt,
UpdateAt: b.UpdateAt,
DeleteAt: b.DeleteAt,
}
}
// SqlBotStore is a store for managing bots in the database.
// Bots are otherwise normal users with extra metadata record in the Bots table. The primary key
// for a bot matches the primary key value for corresponding User record.
type SqlBotStore struct {
SqlStore
metrics einterfaces.MetricsInterface
}
// NewSqlBotStore creates an instance of SqlBotStore, registering the table schema in question.
func NewSqlBotStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) store.BotStore {
us := &SqlBotStore{
SqlStore: sqlStore,
metrics: metrics,
}
for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(bot{}, "Bots").SetKeys(false, "UserId")
table.ColMap("UserId").SetMaxSize(26)
table.ColMap("Description").SetMaxSize(1024)
table.ColMap("OwnerId").SetMaxSize(model.BOT_CREATOR_ID_MAX_RUNES)
}
return us
}
func (us SqlBotStore) CreateIndexesIfNotExists() {
}
// traceBot is a helper function for adding to a bot trace when logging.
func traceBot(bot *model.Bot, extra map[string]interface{}) map[string]interface{} {
trace := make(map[string]interface{})
for key, value := range bot.Trace() {
trace[key] = value
}
for key, value := range extra {
trace[key] = value
}
return trace
}
// Get fetches the given bot in the database.
func (us SqlBotStore) Get(botUserId string, includeDeleted bool) store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
var excludeDeletedSql = "AND b.DeleteAt = 0"
if includeDeleted {
excludeDeletedSql = ""
}
var bot *model.Bot
if err := us.GetReplica().SelectOne(&bot, `
SELECT
b.UserId,
u.Username,
u.FirstName AS DisplayName,
b.Description,
b.OwnerId,
b.CreateAt,
b.UpdateAt,
b.DeleteAt
FROM
Bots b
JOIN
Users u ON (u.Id = b.UserId)
WHERE
b.UserId = :user_id
`+excludeDeletedSql+`
`, map[string]interface{}{
"user_id": botUserId,
}); err == sql.ErrNoRows {
result.Err = model.MakeBotNotFoundError(botUserId)
} else if err != nil {
result.Err = model.NewAppError("SqlBotStore.Get", "store.sql_bot.get.app_error", map[string]interface{}{"user_id": botUserId}, err.Error(), http.StatusInternalServerError)
} else {
result.Data = bot
}
})
}
// GetAll fetches from all bots in the database.
func (us SqlBotStore) GetAll(options *model.BotGetOptions) store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
params := map[string]interface{}{
"offset": options.Page * options.PerPage,
"limit": options.PerPage,
}
var conditions []string
var conditionsSql string
var additionalJoin string
if !options.IncludeDeleted {
conditions = append(conditions, "b.DeleteAt = 0")
}
if options.OwnerId != "" {
conditions = append(conditions, "b.OwnerId = :creator_id")
params["creator_id"] = options.OwnerId
}
if options.OnlyOrphaned {
additionalJoin = "JOIN Users o ON (o.Id = b.OwnerId)"
conditions = append(conditions, "o.DeleteAt != 0")
}
if len(conditions) > 0 {
conditionsSql = "WHERE " + strings.Join(conditions, " AND ")
}
sql := `
SELECT
b.UserId,
u.Username,
u.FirstName AS DisplayName,
b.Description,
b.OwnerId,
b.CreateAt,
b.UpdateAt,
b.DeleteAt
FROM
Bots b
JOIN
Users u ON (u.Id = b.UserId)
` + additionalJoin + `
` + conditionsSql + `
ORDER BY
b.CreateAt ASC,
u.Username ASC
LIMIT
:limit
OFFSET
:offset
`
var data []*model.Bot
if _, err := us.GetReplica().Select(&data, sql, params); err != nil {
result.Err = model.NewAppError("SqlBotStore.GetAll", "store.sql_bot.get_all.app_error", nil, err.Error(), http.StatusInternalServerError)
}
result.Data = data
})
}
// Save persists a new bot to the database.
// It assumes the corresponding user was saved via the user store.
func (us SqlBotStore) Save(bot *model.Bot) store.StoreChannel {
bot = bot.Clone()
return store.Do(func(result *store.StoreResult) {
bot.PreSave()
if result.Err = bot.IsValid(); result.Err != nil {
return
}
if err := us.GetMaster().Insert(botFromModel(bot)); err != nil {
result.Err = model.NewAppError("SqlBotStore.Save", "store.sql_bot.save.app_error", bot.Trace(), err.Error(), http.StatusInternalServerError)
return
}
result.Data = bot
})
}
// Update persists an updated bot to the database.
// It assumes the corresponding user was updated via the user store.
func (us SqlBotStore) Update(bot *model.Bot) store.StoreChannel {
bot = bot.Clone()
return store.Do(func(result *store.StoreResult) {
bot.PreUpdate()
if result.Err = bot.IsValid(); result.Err != nil {
return
}
oldBotResult := <-us.Get(bot.UserId, true)
if oldBotResult.Err != nil {
result.Err = oldBotResult.Err
return
}
oldBot := oldBotResult.Data.(*model.Bot)
oldBot.Description = bot.Description
oldBot.OwnerId = bot.OwnerId
oldBot.UpdateAt = bot.UpdateAt
oldBot.DeleteAt = bot.DeleteAt
bot = oldBot
if count, err := us.GetMaster().Update(botFromModel(bot)); err != nil {
result.Err = model.NewAppError("SqlBotStore.Update", "store.sql_bot.update.updating.app_error", bot.Trace(), err.Error(), http.StatusInternalServerError)
} else if count != 1 {
result.Err = model.NewAppError("SqlBotStore.Update", "store.sql_bot.update.app_error", traceBot(bot, map[string]interface{}{"count": count}), "", http.StatusInternalServerError)
}
result.Data = bot
})
}
// PermanentDelete removes the bot from the database altogether.
// If the corresponding user is to be deleted, it must be done via the user store.
func (us SqlBotStore) PermanentDelete(botUserId string) store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
userResult := <-us.User().PermanentDelete(botUserId)
if userResult.Err != nil {
result.Err = userResult.Err
return
}
if _, err := us.GetMaster().Exec(`
DELETE FROM
Bots
WHERE
UserId = :user_id
`, map[string]interface{}{
"user_id": botUserId,
}); err != nil {
result.Err = model.NewAppError("SqlBotStore.Update", "store.sql_bot.delete.app_error", map[string]interface{}{"user_id": botUserId}, err.Error(), http.StatusBadRequest)
}
})
}

14
store/sqlstore/bot_store_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,14 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestBotStore(t *testing.T) {
StoreTest(t, storetest.TestBotStore)
}

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

@@ -73,6 +73,7 @@ type SqlStore interface {
Channel() store.ChannelStore
Post() store.PostStore
User() store.UserStore
Bot() store.BotStore
Audit() store.AuditStore
ClusterDiscovery() store.ClusterDiscoveryStore
Compliance() store.ComplianceStore

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

@@ -71,6 +71,7 @@ type SqlSupplierOldStores struct {
channel store.ChannelStore
post store.PostStore
user store.UserStore
bot store.BotStore
audit store.AuditStore
cluster store.ClusterDiscoveryStore
compliance store.ComplianceStore
@@ -126,6 +127,7 @@ func NewSqlSupplier(settings model.SqlSettings, metrics einterfaces.MetricsInter
supplier.oldStores.channel = NewSqlChannelStore(supplier, metrics)
supplier.oldStores.post = NewSqlPostStore(supplier, metrics)
supplier.oldStores.user = NewSqlUserStore(supplier, metrics)
supplier.oldStores.bot = NewSqlBotStore(supplier, metrics)
supplier.oldStores.audit = NewSqlAuditStore(supplier)
supplier.oldStores.cluster = NewSqlClusterDiscoveryStore(supplier)
supplier.oldStores.compliance = NewSqlComplianceStore(supplier)
@@ -167,6 +169,7 @@ func NewSqlSupplier(settings model.SqlSettings, metrics einterfaces.MetricsInter
supplier.oldStores.channel.(*SqlChannelStore).CreateIndexesIfNotExists()
supplier.oldStores.post.(*SqlPostStore).CreateIndexesIfNotExists()
supplier.oldStores.user.(*SqlUserStore).CreateIndexesIfNotExists()
supplier.oldStores.bot.(*SqlBotStore).CreateIndexesIfNotExists()
supplier.oldStores.audit.(*SqlAuditStore).CreateIndexesIfNotExists()
supplier.oldStores.compliance.(*SqlComplianceStore).CreateIndexesIfNotExists()
supplier.oldStores.session.(*SqlSessionStore).CreateIndexesIfNotExists()
@@ -936,6 +939,10 @@ func (ss *SqlSupplier) User() store.UserStore {
return ss.oldStores.user
}
func (ss *SqlSupplier) Bot() store.BotStore {
return ss.oldStores.bot
}
func (ss *SqlSupplier) Session() store.SessionStore {
return ss.oldStores.session
}

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

@@ -4,12 +4,15 @@
package sqlstore
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/pkg/errors"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/services/timezones"
@@ -55,10 +58,11 @@ const (
)
const (
EXIT_VERSION_SAVE_MISSING = 1001
EXIT_TOO_OLD = 1002
EXIT_VERSION_SAVE = 1003
EXIT_THEME_MIGRATION = 1004
EXIT_VERSION_SAVE_MISSING = 1001
EXIT_TOO_OLD = 1002
EXIT_VERSION_SAVE = 1003
EXIT_THEME_MIGRATION = 1004
EXIT_ROLE_MIGRATION_FAILED = 1005
)
func UpgradeDatabase(sqlStore SqlStore) {
@@ -554,6 +558,33 @@ func UpgradeDatabaseToVersion57(sqlStore SqlStore) {
}
}
func getRole(sqlStore SqlStore, name string) (*model.Role, error) {
var dbRole Role
if err := sqlStore.GetReplica().SelectOne(&dbRole, "SELECT * from Roles WHERE Name = :Name", map[string]interface{}{"Name": name}); err != nil {
if err == sql.ErrNoRows {
return nil, errors.Wrapf(err, "failed to find role %s", name)
} else {
return nil, errors.Wrapf(err, "failed to query role %s", name)
}
}
return dbRole.ToModel(), nil
}
func saveRole(sqlStore SqlStore, role *model.Role) error {
dbRole := NewRoleFromModel(role)
dbRole.UpdateAt = model.GetMillis()
if rowsChanged, err := sqlStore.GetMaster().Update(dbRole); err != nil {
return errors.Wrap(err, "failed to update role")
} else if rowsChanged != 1 {
return errors.New("found no role to update")
}
return nil
}
func UpgradeDatabaseToVersion58(sqlStore SqlStore) {
if shouldPerformUpgrade(sqlStore, VERSION_5_7_0, VERSION_5_8_0) {
// idx_channels_txt was removed in `UpgradeDatabaseToVersion50`, but merged as part of
@@ -583,6 +614,26 @@ func UpgradeDatabaseToVersion59(sqlStore SqlStore) {
func UpgradeDatabaseToVersion510(sqlStore SqlStore) {
// if shouldPerformUpgrade(sqlStore, VERSION_5_9_0, VERSION_5_10_0) {
// Grant new bot permissions to the system admin. Ideally we'd use the RoleStore directly,
// but it uses the new supplier model, which isn't initialized in the UpgradeDatabase code
// path. Also, the role won't exist for new servers, so don't fail on fetch, and don't
// bother inserting since it will be created with the new permissions anyway.
if role, err := getRole(sqlStore, model.SYSTEM_ADMIN_ROLE_ID); err != nil {
mlog.Warn("Failed to find role " + model.SYSTEM_ADMIN_ROLE_ID + " for upgrade: " + err.Error())
} else {
role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_BOT.Id)
role.Permissions = append(role.Permissions, model.PERMISSION_READ_BOTS.Id)
role.Permissions = append(role.Permissions, model.PERMISSION_READ_OTHERS_BOTS.Id)
role.Permissions = append(role.Permissions, model.PERMISSION_MANAGE_BOTS.Id)
role.Permissions = append(role.Permissions, model.PERMISSION_MANAGE_OTHERS_BOTS.Id)
if err := saveRole(sqlStore, role); err != nil {
mlog.Critical(err.Error())
time.Sleep(time.Second)
os.Exit(EXIT_ROLE_MIGRATION_FAILED)
}
}
// saveSchemaVersion(sqlStore, VERSION_5_10_0)
// }
}

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

@@ -68,8 +68,9 @@ func NewSqlUserStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) st
}
us.usersQuery = sq.
Select("u.*").
From("Users u")
Select("u.*", "b.UserId IS NOT NULL AS IsBot").
From("Users u").
LeftJoin("Bots b ON ( b.UserId = u.Id )")
if us.DriverName() == model.DATABASE_DRIVER_POSTGRES {
us.usersQuery = us.usersQuery.PlaceholderFormat(sq.Dollar)
@@ -1036,16 +1037,6 @@ func (us SqlUserStore) VerifyEmail(userId, email string) store.StoreChannel {
})
}
func (us SqlUserStore) GetTotalUsersCount() store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
if count, err := us.GetReplica().SelectInt("SELECT COUNT(Id) FROM Users"); err != nil {
result.Err = model.NewAppError("SqlUserStore.GetTotalUsersCount", "store.sql_user.get_total_users_count.app_error", nil, err.Error(), http.StatusInternalServerError)
} else {
result.Data = count
}
})
}
func (us SqlUserStore) PermanentDelete(userId string) store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
if _, err := us.GetMaster().Exec("DELETE FROM Users WHERE Id = :UserId", map[string]interface{}{"UserId": userId}); err != nil {
@@ -1054,20 +1045,45 @@ func (us SqlUserStore) PermanentDelete(userId string) store.StoreChannel {
})
}
func (us SqlUserStore) AnalyticsUniqueUserCount(teamId string) store.StoreChannel {
func (us SqlUserStore) Count(options model.UserCountOptions) store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
query := ""
if len(teamId) > 0 {
query = "SELECT COUNT(DISTINCT Users.Email) From Users, TeamMembers WHERE TeamMembers.TeamId = :TeamId AND Users.Id = TeamMembers.UserId AND TeamMembers.DeleteAt = 0 AND Users.DeleteAt = 0"
} else {
query = "SELECT COUNT(DISTINCT Email) FROM Users WHERE DeleteAt = 0"
query := sq.Select("COUNT(Users.Id)").From("Users")
if !options.IncludeDeleted {
query = query.Where("Users.DeleteAt = 0")
}
v, err := us.GetReplica().SelectInt(query, map[string]interface{}{"TeamId": teamId})
if err != nil {
result.Err = model.NewAppError("SqlUserStore.AnalyticsUniqueUserCount", "store.sql_user.analytics_unique_user_count.app_error", nil, err.Error(), http.StatusInternalServerError)
if options.IncludeBotAccounts {
if options.ExcludeRegularUsers {
query = query.Join("Bots ON Users.Id = Bots.UserId")
}
} else {
result.Data = v
query = query.LeftJoin("Bots ON Users.Id = Bots.UserId").Where("Bots.UserId IS NULL")
if options.ExcludeRegularUsers {
// Currenty this doesn't make sense because it will always return 0
result.Err = model.NewAppError("SqlUserStore.Count", "UserCountOptions don't make sense", nil, "", http.StatusInternalServerError)
return
}
}
if options.TeamId != "" {
query = query.LeftJoin("TeamMembers ON Users.Id = TeamMembers.UserId").Where("TeamMembers.TeamId = ? AND TeamMembers.DeleteAt = 0", options.TeamId)
}
if us.DriverName() == model.DATABASE_DRIVER_POSTGRES {
query = query.PlaceholderFormat(sq.Dollar)
}
queryString, args, err := query.ToSql()
if err != nil {
result.Err = model.NewAppError("SqlUserStore.Get", "store.sql_user.app_error", nil, err.Error(), http.StatusInternalServerError)
return
}
if count, err := us.GetReplica().SelectInt(queryString, args...); err != nil {
result.Err = model.NewAppError("SqlUserStore.Count", "store.sql_user.get_total_users_count.app_error", nil, err.Error(), http.StatusInternalServerError)
} else {
result.Data = count
}
})
}

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

@@ -43,6 +43,7 @@ type Store interface {
Channel() ChannelStore
Post() PostStore
User() UserStore
Bot() BotStore
Audit() AuditStore
ClusterDiscovery() ClusterDiscoveryStore
Compliance() ComplianceStore
@@ -264,10 +265,8 @@ type UserStore interface {
GetEtagForAllProfiles() StoreChannel
GetEtagForProfiles(teamId string) StoreChannel
UpdateFailedPasswordAttempts(userId string, attempts int) StoreChannel
GetTotalUsersCount() StoreChannel
GetSystemAdminProfiles() StoreChannel
PermanentDelete(userId string) StoreChannel
AnalyticsUniqueUserCount(teamId string) StoreChannel
AnalyticsActiveCount(time int64) StoreChannel
GetUnreadCount(userId string) StoreChannel
GetUnreadCountForChannel(userId string, channelId string) StoreChannel
@@ -286,6 +285,15 @@ type UserStore interface {
ClearAllCustomRoleAssignments() StoreChannel
InferSystemInstallDate() StoreChannel
GetAllAfter(limit int, afterId string) StoreChannel
Count(options model.UserCountOptions) StoreChannel
}
type BotStore interface {
Get(userId string, includeDeleted bool) StoreChannel
GetAll(options *model.BotGetOptions) StoreChannel
Save(bot *model.Bot) StoreChannel
Update(bot *model.Bot) StoreChannel
PermanentDelete(userId string) StoreChannel
}
type SessionStore interface {

441
store/storetest/bot_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,441 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"net/http"
"testing"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func makeBotWithUser(ss store.Store, bot *model.Bot) (*model.Bot, *model.User) {
user := store.Must(ss.User().Save(model.UserFromBot(bot))).(*model.User)
bot.UserId = user.Id
bot = store.Must(ss.Bot().Save(bot)).(*model.Bot)
return bot, user
}
func TestBotStore(t *testing.T, ss store.Store) {
t.Run("Get", func(t *testing.T) { testBotStoreGet(t, ss) })
t.Run("GetAll", func(t *testing.T) { testBotStoreGetAll(t, ss) })
t.Run("Save", func(t *testing.T) { testBotStoreSave(t, ss) })
t.Run("Update", func(t *testing.T) { testBotStoreUpdate(t, ss) })
t.Run("PermanentDelete", func(t *testing.T) { testBotStorePermanentDelete(t, ss) })
}
func testBotStoreGet(t *testing.T, ss store.Store) {
deletedBot, _ := makeBotWithUser(ss, &model.Bot{
Username: "deleted_bot",
Description: "A deleted bot",
OwnerId: model.NewId(),
})
deletedBot.DeleteAt = 1
deletedBot = store.Must(ss.Bot().Update(deletedBot)).(*model.Bot)
defer func() { store.Must(ss.Bot().PermanentDelete(deletedBot.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(deletedBot.UserId)) }()
permanentlyDeletedBot, _ := makeBotWithUser(ss, &model.Bot{
Username: "permanently_deleted_bot",
Description: "A permanently deleted bot",
OwnerId: model.NewId(),
DeleteAt: 0,
})
store.Must(ss.Bot().PermanentDelete(permanentlyDeletedBot.UserId))
b1, _ := makeBotWithUser(ss, &model.Bot{
Username: "b1",
Description: "The first bot",
OwnerId: model.NewId(),
})
defer func() { store.Must(ss.Bot().PermanentDelete(b1.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b1.UserId)) }()
b2, _ := makeBotWithUser(ss, &model.Bot{
Username: "b2",
Description: "The second bot",
OwnerId: model.NewId(),
})
defer func() { store.Must(ss.Bot().PermanentDelete(b2.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b2.UserId)) }()
t.Run("get non-existent bot", func(t *testing.T) {
result := <-ss.Bot().Get("unknown", false)
require.NotNil(t, result.Err)
require.Equal(t, http.StatusNotFound, result.Err.StatusCode)
})
t.Run("get deleted bot", func(t *testing.T) {
result := <-ss.Bot().Get(deletedBot.UserId, false)
require.NotNil(t, result.Err)
require.Equal(t, http.StatusNotFound, result.Err.StatusCode)
})
t.Run("get deleted bot, include deleted", func(t *testing.T) {
result := <-ss.Bot().Get(deletedBot.UserId, true)
require.Nil(t, result.Err)
require.Equal(t, deletedBot, result.Data.(*model.Bot))
})
t.Run("get permanently deleted bot", func(t *testing.T) {
result := <-ss.Bot().Get(permanentlyDeletedBot.UserId, false)
require.NotNil(t, result.Err)
require.Equal(t, http.StatusNotFound, result.Err.StatusCode)
})
t.Run("get bot 1", func(t *testing.T) {
result := <-ss.Bot().Get(b1.UserId, false)
require.Nil(t, result.Err)
require.Equal(t, b1, result.Data.(*model.Bot))
})
t.Run("get bot 2", func(t *testing.T) {
result := <-ss.Bot().Get(b2.UserId, false)
require.Nil(t, result.Err)
require.Equal(t, b2, result.Data.(*model.Bot))
})
}
func testBotStoreGetAll(t *testing.T, ss store.Store) {
OwnerId1 := model.NewId()
OwnerId2 := model.NewId()
deletedBot, _ := makeBotWithUser(ss, &model.Bot{
Username: "deleted_bot",
Description: "A deleted bot",
OwnerId: OwnerId1,
})
deletedBot.DeleteAt = 1
deletedBot = store.Must(ss.Bot().Update(deletedBot)).(*model.Bot)
defer func() { store.Must(ss.Bot().PermanentDelete(deletedBot.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(deletedBot.UserId)) }()
permanentlyDeletedBot, _ := makeBotWithUser(ss, &model.Bot{
Username: "permanently_deleted_bot",
Description: "A permanently deleted bot",
OwnerId: OwnerId1,
DeleteAt: 0,
})
store.Must(ss.Bot().PermanentDelete(permanentlyDeletedBot.UserId))
b1, _ := makeBotWithUser(ss, &model.Bot{
Username: "b1",
Description: "The first bot",
OwnerId: OwnerId1,
})
defer func() { store.Must(ss.Bot().PermanentDelete(b1.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b1.UserId)) }()
b2, _ := makeBotWithUser(ss, &model.Bot{
Username: "b2",
Description: "The second bot",
OwnerId: OwnerId1,
})
defer func() { store.Must(ss.Bot().PermanentDelete(b2.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b2.UserId)) }()
t.Run("get original bots", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 10})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b1,
b2,
}, result.Data.([]*model.Bot))
})
b3, _ := makeBotWithUser(ss, &model.Bot{
Username: "b3",
Description: "The third bot",
OwnerId: OwnerId1,
})
defer func() { store.Must(ss.Bot().PermanentDelete(b3.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b3.UserId)) }()
b4, _ := makeBotWithUser(ss, &model.Bot{
Username: "b4",
Description: "The fourth bot",
OwnerId: OwnerId2,
})
defer func() { store.Must(ss.Bot().PermanentDelete(b4.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b4.UserId)) }()
deletedUser := model.User{
Email: MakeEmail(),
Username: model.NewId(),
}
if err := (<-ss.User().Save(&deletedUser)).Err; err != nil {
t.Fatal("couldn't save user", err)
}
deletedUser.DeleteAt = model.GetMillis()
if err := (<-ss.User().Update(&deletedUser, true)).Err; err != nil {
t.Fatal("couldn't delete user", err)
}
defer func() { store.Must(ss.User().PermanentDelete(deletedUser.Id)) }()
ob5, _ := makeBotWithUser(ss, &model.Bot{
Username: "ob5",
Description: "Orphaned bot 5",
OwnerId: deletedUser.Id,
})
defer func() { store.Must(ss.Bot().PermanentDelete(b4.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b4.UserId)) }()
t.Run("get newly created bot stoo", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 10})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b1,
b2,
b3,
b4,
ob5,
}, result.Data.([]*model.Bot))
})
t.Run("get orphaned", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 10, OnlyOrphaned: true})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
ob5,
}, result.Data.([]*model.Bot))
})
t.Run("get page=0, per_page=2", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 2})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b1,
b2,
}, result.Data.([]*model.Bot))
})
t.Run("get page=1, limit=2", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 1, PerPage: 2})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b3,
b4,
}, result.Data.([]*model.Bot))
})
t.Run("get page=5, perpage=1000", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 5, PerPage: 1000})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{}, result.Data.([]*model.Bot))
})
t.Run("get offset=0, limit=2, include deleted", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 2, IncludeDeleted: true})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
deletedBot,
b1,
}, result.Data.([]*model.Bot))
})
t.Run("get offset=2, limit=2, include deleted", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 1, PerPage: 2, IncludeDeleted: true})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b2,
b3,
}, result.Data.([]*model.Bot))
})
t.Run("get offset=0, limit=10, creator id 1", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 10, OwnerId: OwnerId1})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b1,
b2,
b3,
}, result.Data.([]*model.Bot))
})
t.Run("get offset=0, limit=10, creator id 2", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 10, OwnerId: OwnerId2})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b4,
}, result.Data.([]*model.Bot))
})
t.Run("get offset=0, limit=10, include deleted, creator id 1", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 10, IncludeDeleted: true, OwnerId: OwnerId1})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
deletedBot,
b1,
b2,
b3,
}, result.Data.([]*model.Bot))
})
t.Run("get offset=0, limit=10, include deleted, creator id 2", func(t *testing.T) {
result := <-ss.Bot().GetAll(&model.BotGetOptions{Page: 0, PerPage: 10, IncludeDeleted: true, OwnerId: OwnerId2})
require.Nil(t, result.Err)
require.Equal(t, []*model.Bot{
b4,
}, result.Data.([]*model.Bot))
})
}
func testBotStoreSave(t *testing.T, ss store.Store) {
t.Run("invalid bot", func(t *testing.T) {
bot := &model.Bot{
UserId: model.NewId(),
Username: "invalid bot",
Description: "description",
}
result := <-ss.Bot().Save(bot)
require.NotNil(t, result.Err)
require.Equal(t, "model.bot.is_valid.username.app_error", result.Err.Id)
})
t.Run("normal bot", func(t *testing.T) {
bot := &model.Bot{
Username: "normal_bot",
Description: "description",
OwnerId: model.NewId(),
}
user := store.Must(ss.User().Save(model.UserFromBot(bot))).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(user.Id)) }()
bot.UserId = user.Id
result := <-ss.Bot().Save(bot)
require.Nil(t, result.Err)
defer func() { store.Must(ss.Bot().PermanentDelete(bot.UserId)) }()
// Verify the returned bot matches the saved bot, modulo expected changes
returnedNewBot := result.Data.(*model.Bot)
require.NotEqual(t, 0, returnedNewBot.CreateAt)
require.NotEqual(t, 0, returnedNewBot.UpdateAt)
require.Equal(t, returnedNewBot.CreateAt, returnedNewBot.UpdateAt)
bot.UserId = returnedNewBot.UserId
bot.CreateAt = returnedNewBot.CreateAt
bot.UpdateAt = returnedNewBot.UpdateAt
bot.DeleteAt = 0
require.Equal(t, bot, returnedNewBot)
// Verify the actual bot in the database matches the saved bot.
result = <-ss.Bot().Get(bot.UserId, false)
require.Nil(t, result.Err)
actualNewBot := result.Data.(*model.Bot)
require.Equal(t, bot, actualNewBot)
})
}
func testBotStoreUpdate(t *testing.T, ss store.Store) {
t.Run("invalid bot should fail to update", func(t *testing.T) {
existingBot, _ := makeBotWithUser(ss, &model.Bot{
Username: "existing_bot",
OwnerId: model.NewId(),
})
defer func() { store.Must(ss.Bot().PermanentDelete(existingBot.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(existingBot.UserId)) }()
bot := existingBot.Clone()
bot.Username = "invalid username"
result := <-ss.Bot().Update(bot)
require.NotNil(t, result.Err)
require.Equal(t, "model.bot.is_valid.username.app_error", result.Err.Id)
})
t.Run("existing bot should update", func(t *testing.T) {
existingBot, _ := makeBotWithUser(ss, &model.Bot{
Username: "existing_bot",
OwnerId: model.NewId(),
})
defer func() { store.Must(ss.Bot().PermanentDelete(existingBot.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(existingBot.UserId)) }()
bot := existingBot.Clone()
bot.OwnerId = model.NewId()
bot.Description = "updated description"
bot.CreateAt = 999999 // Ignored
bot.UpdateAt = 999999 // Ignored
bot.DeleteAt = 100000 // Allowed
result := <-ss.Bot().Update(bot)
require.Nil(t, result.Err)
// Verify the returned bot matches the updated bot, modulo expected timestamp changes
returnedBot := result.Data.(*model.Bot)
require.Equal(t, existingBot.CreateAt, returnedBot.CreateAt)
require.NotEqual(t, bot.UpdateAt, returnedBot.UpdateAt, "update should have advanced UpdateAt")
require.True(t, returnedBot.UpdateAt > bot.UpdateAt, "update should have advanced UpdateAt")
require.NotEqual(t, 99999, returnedBot.UpdateAt, "should have ignored user-provided UpdateAt")
bot.CreateAt = returnedBot.CreateAt
bot.UpdateAt = returnedBot.UpdateAt
// Verify the actual (now deleted) bot in the database
result = <-ss.Bot().Get(bot.UserId, true)
require.Nil(t, result.Err)
require.Equal(t, bot, result.Data.(*model.Bot))
})
t.Run("deleted bot should update, restoring", func(t *testing.T) {
existingBot, _ := makeBotWithUser(ss, &model.Bot{
Username: "existing_bot",
OwnerId: model.NewId(),
})
defer func() { store.Must(ss.Bot().PermanentDelete(existingBot.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(existingBot.UserId)) }()
existingBot.DeleteAt = 100000
existingBot = store.Must(ss.Bot().Update(existingBot)).(*model.Bot)
bot := existingBot.Clone()
bot.DeleteAt = 0
result := <-ss.Bot().Update(bot)
require.Nil(t, result.Err)
// Verify the returned bot matches the updated bot, modulo expected timestamp changes
returnedBot := result.Data.(*model.Bot)
require.EqualValues(t, 0, returnedBot.DeleteAt)
bot.UpdateAt = returnedBot.UpdateAt
// Verify the actual bot in the database
result = <-ss.Bot().Get(bot.UserId, false)
require.Nil(t, result.Err)
require.Equal(t, bot, result.Data.(*model.Bot))
})
}
func testBotStorePermanentDelete(t *testing.T, ss store.Store) {
b1, _ := makeBotWithUser(ss, &model.Bot{
Username: "b1",
OwnerId: model.NewId(),
})
defer func() { store.Must(ss.Bot().PermanentDelete(b1.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b1.UserId)) }()
b2, _ := makeBotWithUser(ss, &model.Bot{
Username: "b2",
OwnerId: model.NewId(),
})
defer func() { store.Must(ss.Bot().PermanentDelete(b2.UserId)) }()
defer func() { store.Must(ss.User().PermanentDelete(b2.UserId)) }()
t.Run("permanently delete a non-existent bot", func(t *testing.T) {
result := <-ss.Bot().PermanentDelete("unknown")
require.Nil(t, result.Err)
})
t.Run("permanently delete bot", func(t *testing.T) {
result := <-ss.Bot().PermanentDelete(b1.UserId)
require.Nil(t, result.Err)
result = <-ss.Bot().Get(b1.UserId, false)
require.NotNil(t, result.Err)
require.Equal(t, http.StatusNotFound, result.Err.StatusCode)
})
}

94
store/storetest/mocks/BotStore.go Обычный файл
Просмотреть файл

@@ -0,0 +1,94 @@
// Code generated by mockery v1.0.0. DO NOT EDIT.
// Regenerate this file using `make store-mocks`.
package mocks
import mock "github.com/stretchr/testify/mock"
import model "github.com/mattermost/mattermost-server/model"
import store "github.com/mattermost/mattermost-server/store"
// BotStore is an autogenerated mock type for the BotStore type
type BotStore struct {
mock.Mock
}
// Get provides a mock function with given fields: userId, includeDeleted
func (_m *BotStore) Get(userId string, includeDeleted bool) store.StoreChannel {
ret := _m.Called(userId, includeDeleted)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(string, bool) store.StoreChannel); ok {
r0 = rf(userId, includeDeleted)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// GetAll provides a mock function with given fields: options
func (_m *BotStore) GetAll(options *model.BotGetOptions) store.StoreChannel {
ret := _m.Called(options)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(*model.BotGetOptions) store.StoreChannel); ok {
r0 = rf(options)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// PermanentDelete provides a mock function with given fields: userId
func (_m *BotStore) PermanentDelete(userId string) store.StoreChannel {
ret := _m.Called(userId)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(string) store.StoreChannel); ok {
r0 = rf(userId)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// Save provides a mock function with given fields: bot
func (_m *BotStore) Save(bot *model.Bot) store.StoreChannel {
ret := _m.Called(bot)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(*model.Bot) store.StoreChannel); ok {
r0 = rf(bot)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// Update provides a mock function with given fields: bot
func (_m *BotStore) Update(bot *model.Bot) store.StoreChannel {
ret := _m.Called(bot)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(*model.Bot) store.StoreChannel); ok {
r0 = rf(bot)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}

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

@@ -30,6 +30,22 @@ func (_m *LayeredStoreDatabaseLayer) Audit() store.AuditStore {
return r0
}
// Bot provides a mock function with given fields:
func (_m *LayeredStoreDatabaseLayer) Bot() store.BotStore {
ret := _m.Called()
var r0 store.BotStore
if rf, ok := ret.Get(0).(func() store.BotStore); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.BotStore)
}
}
return r0
}
// Channel provides a mock function with given fields:
func (_m *LayeredStoreDatabaseLayer) Channel() store.ChannelStore {
ret := _m.Called()

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

@@ -58,6 +58,22 @@ func (_m *SqlStore) Audit() store.AuditStore {
return r0
}
// Bot provides a mock function with given fields:
func (_m *SqlStore) Bot() store.BotStore {
ret := _m.Called()
var r0 store.BotStore
if rf, ok := ret.Get(0).(func() store.BotStore); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.BotStore)
}
}
return r0
}
// Channel provides a mock function with given fields:
func (_m *SqlStore) Channel() store.ChannelStore {
ret := _m.Called()

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

@@ -28,6 +28,22 @@ func (_m *Store) Audit() store.AuditStore {
return r0
}
// Bot provides a mock function with given fields:
func (_m *Store) Bot() store.BotStore {
ret := _m.Called()
var r0 store.BotStore
if rf, ok := ret.Get(0).(func() store.BotStore); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.BotStore)
}
}
return r0
}
// Channel provides a mock function with given fields:
func (_m *Store) Channel() store.ChannelStore {
ret := _m.Called()

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

@@ -61,22 +61,6 @@ func (_m *UserStore) AnalyticsGetSystemAdminCount() store.StoreChannel {
return r0
}
// AnalyticsUniqueUserCount provides a mock function with given fields: teamId
func (_m *UserStore) AnalyticsUniqueUserCount(teamId string) store.StoreChannel {
ret := _m.Called(teamId)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(string) store.StoreChannel); ok {
r0 = rf(teamId)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// ClearAllCustomRoleAssignments provides a mock function with given fields:
func (_m *UserStore) ClearAllCustomRoleAssignments() store.StoreChannel {
ret := _m.Called()
@@ -98,6 +82,22 @@ func (_m *UserStore) ClearCaches() {
_m.Called()
}
// Count provides a mock function with given fields: options
func (_m *UserStore) Count(options model.UserCountOptions) store.StoreChannel {
ret := _m.Called(options)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(model.UserCountOptions) store.StoreChannel); ok {
r0 = rf(options)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// Get provides a mock function with given fields: id
func (_m *UserStore) Get(id string) store.StoreChannel {
ret := _m.Called(id)
@@ -498,22 +498,6 @@ func (_m *UserStore) GetSystemAdminProfiles() store.StoreChannel {
return r0
}
// GetTotalUsersCount provides a mock function with given fields:
func (_m *UserStore) GetTotalUsersCount() store.StoreChannel {
ret := _m.Called()
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func() store.StoreChannel); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// GetUnreadCount provides a mock function with given fields: userId
func (_m *UserStore) GetUnreadCount(userId string) store.StoreChannel {
ret := _m.Called(userId)

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

@@ -23,6 +23,7 @@ type Store struct {
ChannelStore mocks.ChannelStore
PostStore mocks.PostStore
UserStore mocks.UserStore
BotStore mocks.BotStore
AuditStore mocks.AuditStore
ClusterDiscoveryStore mocks.ClusterDiscoveryStore
ComplianceStore mocks.ComplianceStore
@@ -55,6 +56,7 @@ func (s *Store) Team() store.TeamStore { return &s.T
func (s *Store) Channel() store.ChannelStore { return &s.ChannelStore }
func (s *Store) Post() store.PostStore { return &s.PostStore }
func (s *Store) User() store.UserStore { return &s.UserStore }
func (s *Store) Bot() store.BotStore { return &s.BotStore }
func (s *Store) Audit() store.AuditStore { return &s.AuditStore }
func (s *Store) ClusterDiscovery() store.ClusterDiscoveryStore { return &s.ClusterDiscoveryStore }
func (s *Store) Compliance() store.ComplianceStore { return &s.ComplianceStore }
@@ -98,6 +100,7 @@ func (s *Store) AssertExpectations(t mock.TestingT) bool {
&s.ChannelStore,
&s.PostStore,
&s.UserStore,
&s.BotStore,
&s.AuditStore,
&s.ClusterDiscoveryStore,
&s.ComplianceStore,

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

@@ -25,12 +25,14 @@ func TestUserStore(t *testing.T, ss store.Store) {
require.Nil(t, result.Err, "failed cleaning up test user %s", u.Username)
}
t.Run("Count", func(t *testing.T) { testCount(t, ss) })
t.Run("AnalyticsGetInactiveUsersCount", func(t *testing.T) { testUserStoreAnalyticsGetInactiveUsersCount(t, ss) })
t.Run("AnalyticsGetSystemAdminCount", func(t *testing.T) { testUserStoreAnalyticsGetSystemAdminCount(t, ss) })
t.Run("Save", func(t *testing.T) { testUserStoreSave(t, ss) })
t.Run("Update", func(t *testing.T) { testUserStoreUpdate(t, ss) })
t.Run("UpdateUpdateAt", func(t *testing.T) { testUserStoreUpdateUpdateAt(t, ss) })
t.Run("UpdateFailedPasswordAttempts", func(t *testing.T) { testUserStoreUpdateFailedPasswordAttempts(t, ss) })
t.Run("Get", func(t *testing.T) { testUserStoreGet(t, ss) })
t.Run("UserCount", func(t *testing.T) { testUserCount(t, ss) })
t.Run("GetAllUsingAuthService", func(t *testing.T) { testGetAllUsingAuthService(t, ss) })
t.Run("GetAllProfiles", func(t *testing.T) { testUserStoreGetAllProfiles(t, ss) })
t.Run("GetProfiles", func(t *testing.T) { testUserStoreGetProfiles(t, ss) })
@@ -59,8 +61,6 @@ func TestUserStore(t *testing.T, ss store.Store) {
t.Run("SearchInChannel", func(t *testing.T) { testUserStoreSearchInChannel(t, ss) })
t.Run("SearchNotInTeam", func(t *testing.T) { testUserStoreSearchNotInTeam(t, ss) })
t.Run("SearchWithoutTeam", func(t *testing.T) { testUserStoreSearchWithoutTeam(t, ss) })
t.Run("AnalyticsGetInactiveUsersCount", func(t *testing.T) { testUserStoreAnalyticsGetInactiveUsersCount(t, ss) })
t.Run("AnalyticsGetSystemAdminCount", func(t *testing.T) { testUserStoreAnalyticsGetSystemAdminCount(t, ss) })
t.Run("GetProfilesNotInTeam", func(t *testing.T) { testUserStoreGetProfilesNotInTeam(t, ss) })
t.Run("ClearAllCustomRoleAssignments", func(t *testing.T) { testUserStoreClearAllCustomRoleAssignments(t, ss) })
t.Run("GetAllAfter", func(t *testing.T) { testUserStoreGetAllAfter(t, ss) })
@@ -259,6 +259,13 @@ func testUserStoreGet(t *testing.T, ss store.Store) {
Email: MakeEmail(),
Username: model.NewId(),
})).(*model.User)
store.Must(ss.Bot().Save(&model.Bot{
UserId: u2.Id,
Username: u2.Username,
OwnerId: u1.Id,
}))
u2.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u2.Id)) }()
defer func() { store.Must(ss.User().PermanentDelete(u2.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1))
@@ -273,32 +280,19 @@ func testUserStoreGet(t *testing.T, ss store.Store) {
actual := result.Data.(*model.User)
require.Equal(t, u1, actual)
require.False(t, actual.IsBot)
})
t.Run("fetch user 2", func(t *testing.T) {
t.Run("fetch user 2, also a bot", func(t *testing.T) {
result := <-ss.User().Get(u2.Id)
require.Nil(t, result.Err)
actual := result.Data.(*model.User)
require.Equal(t, u2, actual)
require.True(t, actual.IsBot)
})
}
func testUserCount(t *testing.T, ss store.Store) {
u1 := &model.User{}
u1.Email = MakeEmail()
store.Must(ss.User().Save(u1))
defer func() { store.Must(ss.User().PermanentDelete(u1.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: model.NewId(), UserId: u1.Id}, -1))
if result := <-ss.User().GetTotalUsersCount(); result.Err != nil {
t.Fatal(result.Err)
} else {
count := result.Data.(int64)
require.False(t, count <= 0, "expected count > 0, got %d", count)
}
}
func testGetAllUsingAuthService(t *testing.T, ss store.Store) {
teamId := model.NewId()
@@ -325,6 +319,13 @@ func testGetAllUsingAuthService(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
t.Run("get by unknown auth service", func(t *testing.T) {
@@ -372,6 +373,13 @@ func testUserStoreGetAllProfiles(t *testing.T, ss store.Store) {
Email: MakeEmail(),
Username: "u3" + model.NewId(),
})).(*model.User)
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
u4 := store.Must(ss.User().Save(&model.User{
@@ -529,6 +537,13 @@ func testUserStoreGetProfiles(t *testing.T, ss store.Store) {
Email: MakeEmail(),
Username: "u3" + model.NewId(),
})).(*model.User)
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
@@ -660,6 +675,13 @@ func testUserStoreGetProfilesInChannel(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
c1 := store.Must(ss.Channel().Save(&model.Channel{
TeamId: teamId,
@@ -741,6 +763,13 @@ func testUserStoreGetProfilesInChannelByStatus(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
c1 := store.Must(ss.Channel().Save(&model.Channel{
TeamId: teamId,
@@ -827,6 +856,13 @@ func testUserStoreGetProfilesWithoutTeam(t *testing.T, ss store.Store) {
Username: "u3" + model.NewId(),
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("get, offset 0, limit 100", func(t *testing.T) {
result := <-ss.User().GetProfilesWithoutTeam(0, 100)
@@ -870,6 +906,13 @@ func testUserStoreGetAllProfilesInChannel(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
c1 := store.Must(ss.Channel().Save(&model.Channel{
TeamId: teamId,
@@ -970,6 +1013,13 @@ func testUserStoreGetProfilesNotInChannel(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
c1 := store.Must(ss.Channel().Save(&model.Channel{
TeamId: teamId,
@@ -1068,6 +1118,13 @@ func testUserStoreGetProfilesByIds(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("get u1 by id, no caching", func(t *testing.T) {
result := <-ss.User().GetProfileByIds([]string{u1.Id}, false)
@@ -1124,6 +1181,13 @@ func testUserStoreGetProfilesByUsernames(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: team2Id, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("get by u1 and u2 usernames, team id 1", func(t *testing.T) {
result := <-ss.User().GetProfilesByUsernames([]string{u1.Username, u2.Username}, teamId)
@@ -1181,6 +1245,13 @@ func testUserStoreGetSystemAdminProfiles(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("all system admin profiles", func(t *testing.T) {
result := <-ss.User().GetSystemAdminProfiles()
@@ -1215,6 +1286,13 @@ func testUserStoreGetByEmail(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("get u1 by email", func(t *testing.T) {
result := <-ss.User().GetByEmail(u1.Email)
@@ -1276,6 +1354,13 @@ func testUserStoreGetByAuthData(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("get by u1 auth", func(t *testing.T) {
result := <-ss.User().GetByAuth(u1.AuthData, u1.AuthService)
@@ -1333,6 +1418,13 @@ func testUserStoreGetByUsername(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("get u1 by username", func(t *testing.T) {
result := <-ss.User().GetByUsername(u1.Username)
@@ -1397,6 +1489,13 @@ func testUserStoreGetForLogin(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
t.Run("get u1 by username, allow both", func(t *testing.T) {
result := <-ss.User().GetForLogin(u1.Username, true, true)
@@ -1666,6 +1765,13 @@ func testUserStoreGetRecentlyActiveUsersForTeam(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
millis := model.GetMillis()
u3.LastActivityAt = millis
@@ -1727,6 +1833,13 @@ func testUserStoreGetNewUsersForTeam(t *testing.T, ss store.Store) {
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u3.Id}, -1))
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
u4 := store.Must(ss.User().Save(&model.User{
Email: MakeEmail(),
@@ -1830,6 +1943,13 @@ func testUserStoreSearch(t *testing.T, ss store.Store) {
}
store.Must(ss.User().Save(u3))
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
u5 := &model.User{
Username: "yu" + model.NewId(),
@@ -2160,6 +2280,13 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) {
}
store.Must(ss.User().Save(u3))
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
tid := model.NewId()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: tid, UserId: u1.Id}, -1))
@@ -2367,6 +2494,13 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) {
}
store.Must(ss.User().Save(u3))
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
tid := model.NewId()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: tid, UserId: u1.Id}, -1))
@@ -2513,6 +2647,13 @@ func testUserStoreSearchNotInTeam(t *testing.T, ss store.Store) {
}
store.Must(ss.User().Save(u3))
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
u4 := &model.User{
Username: "simon" + model.NewId(),
@@ -2685,6 +2826,13 @@ func testUserStoreSearchWithoutTeam(t *testing.T, ss store.Store) {
}
store.Must(ss.User().Save(u3))
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
tid := model.NewId()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: tid, UserId: u3.Id}, -1))
@@ -2753,6 +2901,94 @@ func testUserStoreSearchWithoutTeam(t *testing.T, ss store.Store) {
}
}
func testCount(t *testing.T, ss store.Store) {
// Regular
teamId := model.NewId()
u1 := &model.User{}
u1.Email = MakeEmail()
store.Must(ss.User().Save(u1))
defer func() { store.Must(ss.User().PermanentDelete(u1.Id)) }()
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: teamId, UserId: u1.Id}, -1))
// Deleted
u2 := &model.User{}
u2.Email = MakeEmail()
u2.DeleteAt = model.GetMillis()
store.Must(ss.User().Save(u2))
defer func() { store.Must(ss.User().PermanentDelete(u2.Id)) }()
// Bot
u3 := store.Must(ss.User().Save(&model.User{
Email: MakeEmail(),
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
result := <-ss.User().Count(model.UserCountOptions{
IncludeBotAccounts: false,
IncludeDeleted: false,
TeamId: "",
})
require.Nil(t, result.Err)
require.Equal(t, int64(1), result.Data.(int64))
result = <-ss.User().Count(model.UserCountOptions{
IncludeBotAccounts: true,
IncludeDeleted: false,
TeamId: "",
})
require.Nil(t, result.Err)
require.Equal(t, int64(2), result.Data.(int64))
result = <-ss.User().Count(model.UserCountOptions{
IncludeBotAccounts: false,
IncludeDeleted: true,
TeamId: "",
})
require.Nil(t, result.Err)
require.Equal(t, int64(2), result.Data.(int64))
result = <-ss.User().Count(model.UserCountOptions{
IncludeBotAccounts: true,
IncludeDeleted: true,
TeamId: "",
})
require.Nil(t, result.Err)
require.Equal(t, int64(3), result.Data.(int64))
result = <-ss.User().Count(model.UserCountOptions{
IncludeBotAccounts: true,
IncludeDeleted: true,
ExcludeRegularUsers: true,
TeamId: "",
})
require.Nil(t, result.Err)
require.Equal(t, int64(1), result.Data.(int64))
result = <-ss.User().Count(model.UserCountOptions{
IncludeBotAccounts: true,
IncludeDeleted: true,
TeamId: teamId,
})
require.Nil(t, result.Err)
require.Equal(t, int64(1), result.Data.(int64))
result = <-ss.User().Count(model.UserCountOptions{
IncludeBotAccounts: true,
IncludeDeleted: true,
TeamId: model.NewId(),
})
require.Nil(t, result.Err)
require.Equal(t, int64(0), result.Data.(int64))
}
func testUserStoreAnalyticsGetInactiveUsersCount(t *testing.T, ss store.Store) {
u1 := &model.User{}
u1.Email = MakeEmail()
@@ -2849,6 +3085,13 @@ func testUserStoreGetProfilesNotInTeam(t *testing.T, ss store.Store) {
Username: "u3" + model.NewId(),
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u3.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u3.Id,
Username: u3.Username,
OwnerId: u1.Id,
}))
u3.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u3.Id)) }()
var etag1, etag2, etag3 string
@@ -3030,6 +3273,13 @@ func testUserStoreGetAllAfter(t *testing.T, ss store.Store) {
Username: "u2" + model.NewId(),
})).(*model.User)
defer func() { store.Must(ss.User().PermanentDelete(u2.Id)) }()
store.Must(ss.Bot().Save(&model.Bot{
UserId: u2.Id,
Username: u2.Username,
OwnerId: u1.Id,
}))
u2.IsBot = true
defer func() { store.Must(ss.Bot().PermanentDelete(u2.Id)) }()
expected := []*model.User{u1, u2}
if strings.Compare(u2.Id, u1.Id) < 0 {