Files
mattermost/server/channels/app/bot.go

612 lines
19 KiB
Go
Raw Normal View History

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
package app
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
2023-08-15 14:56:05 +03:00
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/store"
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
)
const (
internalKeyPrefix = "mmi_"
botUserKey = internalKeyPrefix + "botid"
)
// EnsureBot provides similar functionality with the plugin-api BotService. It doesn't accept
// any ensureBotOptions hence it is not required for now.
func (a *App) EnsureBot(rctx request.CTX, pluginID string, bot *model.Bot) (string, error) {
if bot == nil {
return "", errors.New("passed a nil bot")
}
if bot.Username == "" {
return "", errors.New("passed a bot with no username")
}
botIDBytes, err := a.GetPluginKey(pluginID, botUserKey)
if err != nil {
return "", err
}
// If the bot has already been created, use it
if botIDBytes != nil {
botID := string(botIDBytes)
// ensure existing bot is synced with what is being created
botPatch := &model.BotPatch{
Username: &bot.Username,
DisplayName: &bot.DisplayName,
Description: &bot.Description,
}
if _, err = a.PatchBot(rctx, botID, botPatch); err != nil {
return "", fmt.Errorf("failed to patch bot: %w", err)
}
return botID, nil
}
// Check for an existing bot user with that username. If one exists, then use that.
if user, appErr := a.GetUserByUsername(bot.Username); appErr == nil && user != nil {
if user.IsBot {
if appErr := a.SetPluginKey(pluginID, botUserKey, []byte(user.Id)); appErr != nil {
return "", fmt.Errorf("failed to set plugin key: %w", err)
}
} else {
rctx.Logger().Error("Plugin attempted to use an account that already exists. Convert user to a bot "+
"account in the CLI by running 'mattermost user convert <username> --bot'. If the user is an "+
"existing user account you want to preserve, change its username and restart the Mattermost server, "+
"after which the plugin will create a bot account with that name. For more information about bot "+
"accounts, see https://mattermost.com/pl/default-bot-accounts", mlog.String("username",
bot.Username),
mlog.String("user_id",
user.Id),
)
}
return user.Id, nil
}
createdBot, err := a.CreateBot(rctx, bot)
if err != nil {
return "", fmt.Errorf("failed to create bot: %w", err)
}
if appErr := a.SetPluginKey(pluginID, botUserKey, []byte(createdBot.UserId)); appErr != nil {
return "", fmt.Errorf("failed to set plugin key: %w", err)
}
return createdBot.UserId, nil
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
// CreateBot creates the given bot and corresponding user.
func (a *App) CreateBot(c request.CTX, bot *model.Bot) (*model.Bot, *model.AppError) {
vErr := bot.IsValidCreate()
if vErr != nil {
return nil, vErr
}
user, nErr := a.Srv().Store().User().Save(c, model.UserFromBot(bot))
if nErr != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput
switch {
case errors.As(nErr, &appErr):
return nil, appErr
case errors.As(nErr, &invErr):
code := ""
switch invErr.Field {
case "email":
code = "app.user.save.email_exists.app_error"
case "username":
code = "app.user.save.username_exists.app_error"
default:
code = "app.user.save.existing.app_error"
}
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("CreateBot", code, nil, "", http.StatusBadRequest).Wrap(nErr)
default:
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("CreateBot", "app.user.save.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
bot.UserId = user.Id
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
savedBot, nErr := a.Srv().Store().Bot().Save(bot)
if nErr != nil {
a.Srv().Store().User().PermanentDelete(bot.UserId)
var appErr *model.AppError
switch {
case errors.As(nErr, &appErr): // in case we haven't converted to plain error.
return nil, appErr
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("CreateBot", "app.bot.createbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
// Get the owner of the bot, if one exists. If not, don't send a message
ownerUser, err := a.Srv().Store().User().Get(context.Background(), bot.OwnerId)
var nfErr *store.ErrNotFound
if err != nil && !errors.As(err, &nfErr) {
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("CreateBot", "app.user.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
} else if ownerUser != nil {
// Send a message to the bot's creator to inform them that the bot needs to be added
// to a team and channel after it's created
2023-08-15 14:56:05 +03:00
channel, err := a.getOrCreateDirectChannelWithUser(c, user, ownerUser)
if err != nil {
return nil, err
}
T := i18n.GetUserTranslations(ownerUser.Locale)
botAddPost := &model.Post{
2021-07-12 20:05:36 +02:00
Type: model.PostTypeAddBotTeamsChannels,
UserId: savedBot.UserId,
ChannelId: channel.Id,
Message: T("api.bot.teams_channels.add_message_mobile"),
}
if _, err := a.CreatePostAsUser(c, botAddPost, c.Session().Id, true); err != nil {
return nil, err
}
}
return savedBot, nil
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
func (a *App) GetSystemBot(rctx request.CTX) (*model.Bot, *model.AppError) {
perPage := 1
userOptions := &model.UserGetOptions{
Page: 0,
PerPage: perPage,
2021-07-12 20:05:36 +02:00
Role: model.SystemAdminRoleId,
Inactive: false,
}
sysAdminList, err := a.GetUsersFromProfiles(userOptions)
if err != nil {
return nil, err
}
if len(sysAdminList) == 0 {
return nil, model.NewAppError("GetSystemBot", "app.bot.get_system_bot.empty_admin_list.app_error", nil, "", http.StatusInternalServerError)
}
T := i18n.GetUserTranslations(sysAdminList[0].Locale)
systemBot := &model.Bot{
2021-07-12 20:05:36 +02:00
Username: model.BotSystemBotUsername,
DisplayName: T("app.system.system_bot.bot_displayname"),
Description: "",
OwnerId: sysAdminList[0].Id,
}
return a.getOrCreateBot(rctx, systemBot)
}
func (a *App) getOrCreateBot(rctx request.CTX, botDef *model.Bot) (*model.Bot, *model.AppError) {
botUser, appErr := a.GetUserByUsername(botDef.Username)
if appErr != nil {
if appErr.StatusCode != http.StatusNotFound {
return nil, appErr
}
// cannot find this bot user, save the user
user, nErr := a.Srv().Store().User().Save(rctx, model.UserFromBot(botDef))
if nErr != nil {
var appError *model.AppError
var invErr *store.ErrInvalidInput
switch {
case errors.As(nErr, &appError):
return nil, appError
case errors.As(nErr, &invErr):
code := ""
switch invErr.Field {
case "email":
code = "app.user.save.email_exists.app_error"
case "username":
code = "app.user.save.username_exists.app_error"
default:
code = "app.user.save.existing.app_error"
}
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("getOrCreateBot", code, nil, "", http.StatusBadRequest).Wrap(nErr)
default:
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("getOrCreateBot", "app.user.save.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
}
botDef.UserId = user.Id
//save the bot
savedBot, nErr := a.Srv().Store().Bot().Save(botDef)
if nErr != nil {
a.Srv().Store().User().PermanentDelete(savedBot.UserId)
var nAppErr *model.AppError
switch {
case errors.As(nErr, &nAppErr): // in case we haven't converted to plain error.
return nil, nAppErr
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("getOrCreateBot", "app.bot.createbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
}
return savedBot, nil
}
if botUser == nil {
return nil, model.NewAppError("getOrCreateBot", "app.bot.createbot.internal_error", nil, "", http.StatusInternalServerError)
}
//return the bot for this user
savedBot, appErr := a.GetBot(botUser.Id, false)
if appErr != nil {
return nil, appErr
}
return savedBot, nil
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
// PatchBot applies the given patch to the bot and corresponding user.
func (a *App) PatchBot(rctx request.CTX, botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
bot, err := a.GetBot(botUserId, true)
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
if err != nil {
return nil, err
}
2021-06-17 09:22:16 +02:00
if !bot.WouldPatch(botPatch) {
return bot, nil
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
bot.Patch(botPatch)
user, nErr := a.Srv().Store().User().Get(context.Background(), botUserId)
if nErr != nil {
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", MissingAccountError, nil, "", http.StatusNotFound).Wrap(nErr)
default:
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.user.get.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
patchedUser := model.UserFromBot(bot)
user.Id = patchedUser.Id
user.Username = patchedUser.Username
user.Email = patchedUser.Email
user.FirstName = patchedUser.FirstName
userUpdate, nErr := a.Srv().Store().User().Update(rctx, user, true)
if nErr != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput
var conErr *store.ErrConflict
switch {
case errors.As(nErr, &appErr):
return nil, appErr
case errors.As(nErr, &invErr):
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.user.update.find.app_error", nil, "", http.StatusBadRequest).Wrap(nErr)
case errors.As(nErr, &conErr):
2022-08-18 11:01:37 +02:00
if conErr.Resource == "Username" {
return nil, model.NewAppError("PatchBot", "app.user.save.username_exists.app_error", nil, "", http.StatusBadRequest).Wrap(nErr)
}
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.user.save.email_exists.app_error", nil, "", http.StatusBadRequest).Wrap(nErr)
default:
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.user.update.finding.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
a.InvalidateCacheForUser(user.Id)
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
ruser := userUpdate.New
a.sendUpdatedUserEvent(*ruser)
bot, nErr = a.Srv().Store().Bot().Update(bot)
if nErr != nil {
var nfErr *store.ErrNotFound
var appErr *model.AppError
switch {
case errors.As(nErr, &nfErr):
return nil, model.MakeBotNotFoundError("SqlBotStore.Get", nfErr.ID).Wrap(nErr)
case errors.As(nErr, &appErr): // in case we haven't converted to plain error.
return nil, appErr
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.bot.patchbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
}
return bot, nil
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
// GetBot returns the given bot.
func (a *App) GetBot(botUserId string, includeDeleted bool) (*model.Bot, *model.AppError) {
bot, err := a.Srv().Store().Bot().Get(botUserId, includeDeleted)
if err != nil {
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &nfErr):
return nil, model.MakeBotNotFoundError("SqlBotStore.Get", nfErr.ID).Wrap(err)
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("GetBot", "app.bot.getbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
}
return bot, nil
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
// GetBots returns the requested page of bots.
func (a *App) GetBots(options *model.BotGetOptions) (model.BotList, *model.AppError) {
bots, err := a.Srv().Store().Bot().GetAll(options)
if err != nil {
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("GetBots", "app.bot.getbots.internal_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
return bots, nil
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
// UpdateBotActive marks a bot as active or inactive, along with its corresponding user.
func (a *App) UpdateBotActive(c request.CTX, botUserId string, active bool) (*model.Bot, *model.AppError) {
user, nErr := a.Srv().Store().User().Get(context.Background(), botUserId)
if nErr != nil {
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", MissingAccountError, nil, "", http.StatusNotFound).Wrap(nErr)
default:
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.user.get.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
if _, err := a.UpdateActive(c, user, active); err != nil {
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
return nil, err
}
bot, nErr := a.Srv().Store().Bot().Get(botUserId, true)
if nErr != nil {
var nfErr *store.ErrNotFound
switch {
case errors.As(nErr, &nfErr):
return nil, model.MakeBotNotFoundError("SqlBotStore.Get", nfErr.ID).Wrap(nErr)
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("UpdateBotActive", "app.bot.getbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
changed := true
if active && bot.DeleteAt != 0 {
bot.DeleteAt = 0
} else if !active && bot.DeleteAt == 0 {
bot.DeleteAt = model.GetMillis()
} else {
changed = false
}
if changed {
bot, nErr = a.Srv().Store().Bot().Update(bot)
if nErr != nil {
var nfErr *store.ErrNotFound
var appErr *model.AppError
switch {
case errors.As(nErr, &nfErr):
return nil, model.MakeBotNotFoundError("SqlBotStore.Get", nfErr.ID).Wrap(nErr)
case errors.As(nErr, &appErr): // in case we haven't converted to plain error.
return nil, appErr
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.bot.patchbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
}
return bot, nil
}
// PermanentDeleteBot permanently deletes a bot and its corresponding user.
func (a *App) PermanentDeleteBot(botUserId string) *model.AppError {
if err := a.Srv().Store().Bot().PermanentDelete(botUserId); err != nil {
var invErr *store.ErrInvalidInput
switch {
case errors.As(err, &invErr):
2022-08-18 11:01:37 +02:00
return model.NewAppError("PermanentDeleteBot", "app.bot.permenent_delete.bad_id", map[string]any{"user_id": invErr.Value}, "", http.StatusBadRequest).Wrap(err)
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return model.NewAppError("PatchBot", "app.bot.permanent_delete.internal_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
if err := a.Srv().Store().User().PermanentDelete(botUserId); err != nil {
2022-08-18 11:01:37 +02:00
return model.NewAppError("PermanentDeleteBot", "app.user.permanent_delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
return nil
}
// UpdateBotOwner changes a bot's owner to the given value.
func (a *App) UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError) {
bot, err := a.Srv().Store().Bot().Get(botUserId, true)
if err != nil {
var nfErr *store.ErrNotFound
switch {
case errors.As(err, &nfErr):
return nil, model.MakeBotNotFoundError("SqlBotStore.Get", nfErr.ID).Wrap(err)
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("UpdateBotOwner", "app.bot.getbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
bot.OwnerId = newOwnerId
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
bot, err = a.Srv().Store().Bot().Update(bot)
if err != nil {
var nfErr *store.ErrNotFound
var appErr *model.AppError
switch {
case errors.As(err, &nfErr):
return nil, model.MakeBotNotFoundError("SqlBotStore.Get", nfErr.ID).Wrap(err)
case errors.As(err, &appErr): // in case we haven't converted to plain error.
return nil, appErr
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("PatchBot", "app.bot.patchbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
return bot, nil
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
// disableUserBots disables all bots owned by the given user.
func (a *App) disableUserBots(c request.CTX, userID string) *model.AppError {
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
perPage := 20
for {
options := &model.BotGetOptions{
OwnerId: userID,
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
IncludeDeleted: false,
OnlyOrphaned: false,
Page: 0,
PerPage: perPage,
}
userBots, err := a.GetBots(options)
if err != nil {
return err
}
for _, bot := range userBots {
_, err := a.UpdateBotActive(c, bot.UserId, false)
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
if err != nil {
c.Logger().Warn("Unable to deactivate bot.", mlog.String("bot_user_id", bot.UserId), mlog.Err(err))
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 3fcecd521a5c6ccfdb52fb4c3fb1f8c6ea528a4e. * 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
2019-03-05 07:06:45 -08:00
}
}
// Get next set of bots if we got the max number of bots
if len(userBots) == perPage {
options.Page += 1
continue
}
break
}
return nil
}
func (a *App) notifySysadminsBotOwnerDeactivated(c request.CTX, userID string) *model.AppError {
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
perPage := 25
botOptions := &model.BotGetOptions{
OwnerId: userID,
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
IncludeDeleted: false,
OnlyOrphaned: false,
Page: 0,
PerPage: perPage,
}
// get owner bots
var userBots []*model.Bot
for {
bots, err := a.GetBots(botOptions)
if err != nil {
return err
}
userBots = append(userBots, bots...)
if len(bots) < perPage {
break
}
botOptions.Page += 1
}
// user does not own bots
if len(userBots) == 0 {
return nil
}
userOptions := &model.UserGetOptions{
Page: 0,
PerPage: perPage,
2021-07-12 20:05:36 +02:00
Role: model.SystemAdminRoleId,
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
Inactive: false,
}
// get sysadmins
var sysAdmins []*model.User
for {
sysAdminsList, err := a.GetUsersFromProfiles(userOptions)
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
if err != nil {
return err
}
sysAdmins = append(sysAdmins, sysAdminsList...)
if len(sysAdminsList) < perPage {
break
}
userOptions.Page += 1
}
// user being disabled
user, err := a.GetUser(userID)
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
if err != nil {
return err
}
// for each sysadmin, notify user that owns bots was disabled
for _, sysAdmin := range sysAdmins {
channel, appErr := a.GetOrCreateDirectChannel(c, sysAdmin.Id, sysAdmin.Id)
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
if appErr != nil {
return appErr
}
post := &model.Post{
UserId: sysAdmin.Id,
ChannelId: channel.Id,
Message: a.getDisableBotSysadminMessage(user, userBots),
2021-07-12 20:05:36 +02:00
Type: model.PostTypeSystemGeneric,
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
}
_, appErr = a.CreatePost(c, post, channel, false, true)
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
if appErr != nil {
return appErr
}
}
return nil
}
func (a *App) getDisableBotSysadminMessage(user *model.User, userBots model.BotList) string {
disableBotsSetting := *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated
var printAllBots = true
numBotsToPrint := len(userBots)
if numBotsToPrint > 10 {
numBotsToPrint = 10
printAllBots = false
}
var message, botList string
for _, bot := range userBots[:numBotsToPrint] {
botList += fmt.Sprintf("* %v\n", bot.Username)
}
T := i18n.GetUserTranslations(user.Locale)
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
message = T("app.bot.get_disable_bot_sysadmin_message",
map[string]any{
[MM-14725] Inform System Admins when a user who managed bot ac… (#11669) * Add notification, to sysadmins, when a user is disabled and the user owns bots. * If the user doesn't have any bots, there is no need to send a notifcation to sysadmins * Remove comment * Update documention link * Send as System * Query teams for each sysadmin and add first response to hardcoded link. * Remove fmt.print debug statements * remove link with hard-coded team. Will add this as future enhancement Expose GetDisableBotSysadminMessage function so it can be tested Add test new function for testing new notification feature * Fix shadow error * Swap sentences in the message when System Console > Bot Accounts > Disable bot accounts when owner is deactivated: is set to false * Another message correction * Rename Custom Integrations to Integrations * rename botsDisabled variable to disableBotsSetting * - increase the number of bots and sysadmins queried to 1000. - limit the number of bots printed in the post to 10, but mention the total bots owned by the user * Enable translations for sysadmin messages * - Rename function. The actual purpose for the function is to notify sysadmins that a user, that owned bots, was disabled. - convert GetDisableBotSysadminMessage from a function to a method. This allows getting *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated in the method and avoids having to pass the value as an input to a function * fix "make i18n-extract" error. Reorganize .json file * Correct the upper range value to be the minimum of number of elements in the userBots array, or the upper limit (10) * replace t.fatal with require statements fix golangci-lint errors * Create separate message when user managed less than or fewer than 10 bots Test cases for both message types * fix i18n sorting * Using pagination to get the bots and sysadmins instead of setting arbitrary value for PerPage and only retrieving first page * only use one translation ID for the message. push all logic into the template so translators can view the logic add disableBotsSetting and printAllBots variables to the translation map * Break the for loop once len(bots) < perPage value, instead of breaking once there are no bots. This saves one additional call
2019-12-06 20:00:47 -06:00
"UserName": user.Username,
"NumBots": len(userBots),
"BotNames": botList,
"disableBotsSetting": disableBotsSetting,
"printAllBots": printAllBots,
})
return message
}
// ConvertUserToBot converts a user to bot.
func (a *App) ConvertUserToBot(user *model.User) (*model.Bot, *model.AppError) {
bot, err := a.Srv().Store().Bot().Save(model.BotFromUser(user))
if err != nil {
var appErr *model.AppError
switch {
case errors.As(err, &appErr): // in case we haven't converted to plain error.
return nil, appErr
default: // last fallback in case it doesn't map to an existing app error.
2022-08-18 11:01:37 +02:00
return nil, model.NewAppError("CreateBot", "app.bot.createbot.internal_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
}
return bot, nil
}