Unverified Commit 06b579d1 authored by Christopher Speller's avatar Christopher Speller Committed by GitHub

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: default avatarlieut-data <jesse.hallam@gmail.com>

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

* Update model/bot.go
Co-Authored-By: default avatarlieut-data <jesse.hallam@gmail.com>

* Update model/client4.go
Co-Authored-By: default avatarlieut-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 3fcecd52.

* 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: default avatarcrspeller <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: default avatarcrspeller <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
parent 80e0d01f
......@@ -443,12 +443,12 @@
revision = "60711f1a8329503b04e1c88535f419d0bb440bff"
[[projects]]
branch = "master"
digest = "1:f44dea49cf8d9389516c537b7ef61bfb5836a9bf485e213673917258413f24c3"
branch = "mm-14140"
digest = "1:697ef923111e6b1a9fc09d4e799cb071469dbaccb371eb707832407cbde07413"
name = "github.com/mattermost/gorp"
packages = ["."]
pruneopts = "UT"
revision = "520a119fe3536337cf8feeaf76afae0f5ae193f1"
revision = "a13faa4e058457a4e0e0c02268cd6561b55c9702"
[[projects]]
branch = "master"
......
......@@ -24,6 +24,9 @@ type Routes struct {
UserByUsername *mux.Router // 'api/v4/users/username/{username:[A-Za-z0-9_-\.]+}'
UserByEmail *mux.Router // 'api/v4/users/email/{email}'
Bots *mux.Router // 'api/v4/bots'
Bot *mux.Router // 'api/v4/bots/{bot_user_id:[A-Za-z0-9]+}'
Teams *mux.Router // 'api/v4/teams'
TeamsForUser *mux.Router // 'api/v4/users/{user_id:[A-Za-z0-9]+}/teams'
Team *mux.Router // 'api/v4/teams/{team_id:[A-Za-z0-9]+}'
......@@ -132,6 +135,9 @@ func Init(configservice configservice.ConfigService, globalOptionsFunc app.AppOp
api.BaseRoutes.UserByUsername = api.BaseRoutes.Users.PathPrefix("/username/{username:[A-Za-z0-9\\_\\-\\.]+}").Subrouter()
api.BaseRoutes.UserByEmail = api.BaseRoutes.Users.PathPrefix("/email/{email}").Subrouter()
api.BaseRoutes.Bots = api.BaseRoutes.ApiRoot.PathPrefix("/bots").Subrouter()
api.BaseRoutes.Bot = api.BaseRoutes.ApiRoot.PathPrefix("/bots/{bot_user_id:[A-Za-z0-9]+}").Subrouter()
api.BaseRoutes.Teams = api.BaseRoutes.ApiRoot.PathPrefix("/teams").Subrouter()
api.BaseRoutes.TeamsForUser = api.BaseRoutes.User.PathPrefix("/teams").Subrouter()
api.BaseRoutes.Team = api.BaseRoutes.Teams.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter()
......@@ -209,6 +215,7 @@ func Init(configservice configservice.ConfigService, globalOptionsFunc app.AppOp
api.BaseRoutes.Groups = api.BaseRoutes.ApiRoot.PathPrefix("/groups").Subrouter()
api.InitUser()
api.InitBot()
api.InitTeam()
api.InitChannel()
api.InitPost()
......
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api4
import (
"net/http"
"github.com/mattermost/mattermost-server/model"
)
func (api *API) InitBot() {
api.BaseRoutes.Bots.Handle("", api.ApiSessionRequired(createBot)).Methods("POST")
api.BaseRoutes.Bot.Handle("", api.ApiSessionRequired(patchBot)).Methods("PUT")
api.BaseRoutes.Bot.Handle("", api.ApiSessionRequired(getBot)).Methods("GET")
api.BaseRoutes.Bots.Handle("", api.ApiSessionRequired(getBots)).Methods("GET")
api.BaseRoutes.Bot.Handle("/disable", api.ApiSessionRequired(disableBot)).Methods("POST")
api.BaseRoutes.Bot.Handle("/enable", api.ApiSessionRequired(enableBot)).Methods("POST")
api.BaseRoutes.Bot.Handle("/assign/{user_id:[A-Za-z0-9]+}", api.ApiSessionRequired(assignBot)).Methods("POST")
}
func createBot(c *Context, w http.ResponseWriter, r *http.Request) {
botPatch := model.BotPatchFromJson(r.Body)
if botPatch == nil {
c.SetInvalidParam("bot")
return
}
bot := &model.Bot{
OwnerId: c.App.Session.UserId,
}
bot.Patch(botPatch)
if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_BOT) {
c.SetPermissionError(model.PERMISSION_CREATE_BOT)
return
}
createdBot, err := c.App.CreateBot(bot)
if err != nil {
c.Err = err
return
}
w.WriteHeader(http.StatusCreated)
w.Write(createdBot.ToJson())
}
func patchBot(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireBotUserId()
if c.Err != nil {
return
}
botUserId := c.Params.BotUserId
botPatch := model.BotPatchFromJson(r.Body)
if botPatch == nil {
c.SetInvalidParam("bot")
return
}
if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil {
c.Err = err
return
}
updatedBot, err := c.App.PatchBot(botUserId, botPatch)
if err != nil {
c.Err = err
return
}
w.Write(updatedBot.ToJson())
}
func getBot(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireBotUserId()
if c.Err != nil {
return
}
botUserId := c.Params.BotUserId
includeDeleted := r.URL.Query().Get("include_deleted") == "true"
bot, err := c.App.GetBot(botUserId, includeDeleted)
if err != nil {
c.Err = err
return
}
if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_OTHERS_BOTS) {
// Allow access to any bot.
} else if bot.OwnerId == c.App.Session.UserId {
if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_BOTS) {
// Pretend like the bot doesn't exist at all to avoid revealing that the
// user is a bot. It's kind of silly in this case, sine we created the bot,
// but we don't have read bot permissions.
c.Err = model.MakeBotNotFoundError(botUserId)
return
}
} else {
// Pretend like the bot doesn't exist at all, to avoid revealing that the
// user is a bot.
c.Err = model.MakeBotNotFoundError(botUserId)
return
}
if c.HandleEtag(bot.Etag(), "Get Bot", w, r) {
return
}
w.Write(bot.ToJson())
}
func getBots(c *Context, w http.ResponseWriter, r *http.Request) {
includeDeleted := r.URL.Query().Get("include_deleted") == "true"
onlyOrphaned := r.URL.Query().Get("only_orphaned") == "true"
var OwnerId string
if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_OTHERS_BOTS) {
// Get bots created by any user.
OwnerId = ""
} else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_BOTS) {
// Only get bots created by this user.
OwnerId = c.App.Session.UserId
} else {
c.SetPermissionError(model.PERMISSION_READ_BOTS)
return
}
bots, err := c.App.GetBots(&model.BotGetOptions{
Page: c.Params.Page,
PerPage: c.Params.PerPage,
OwnerId: OwnerId,
IncludeDeleted: includeDeleted,
OnlyOrphaned: onlyOrphaned,
})
if err != nil {
c.Err = err
return
}
if c.HandleEtag(bots.Etag(), "Get Bots", w, r) {
return
}
w.Write(bots.ToJson())
}
func disableBot(c *Context, w http.ResponseWriter, r *http.Request) {
updateBotActive(c, w, r, false)
}
func enableBot(c *Context, w http.ResponseWriter, r *http.Request) {
updateBotActive(c, w, r, true)
}
func updateBotActive(c *Context, w http.ResponseWriter, r *http.Request, active bool) {
c.RequireBotUserId()
if c.Err != nil {
return
}
botUserId := c.Params.BotUserId
if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil {
c.Err = err
return
}
bot, err := c.App.UpdateBotActive(botUserId, active)
if err != nil {
c.Err = err
return
}
w.Write(bot.ToJson())
}
func assignBot(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireUserId()
c.RequireBotUserId()
if c.Err != nil {
return
}
botUserId := c.Params.BotUserId
userId := c.Params.UserId
if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil {
c.Err = err
return
}
bot, err := c.App.UpdateBotOwner(botUserId, userId)
if err != nil {
c.Err = err
return
}
w.Write(bot.ToJson())
}
This diff is collapsed.
......@@ -1446,7 +1446,7 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) {
if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, c.Params.UserId) {
c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS)
return
}
......@@ -1515,7 +1515,7 @@ func getUserAccessTokensForUser(c *Context, w http.ResponseWriter, r *http.Reque
return
}
if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) {
if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, c.Params.UserId) {
c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS)
return
}
......@@ -1546,7 +1546,7 @@ func getUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if !c.App.SessionHasPermissionToUser(c.App.Session, accessToken.UserId) {
if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) {
c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS)
return
}
......@@ -1575,7 +1575,7 @@ func revokeUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if !c.App.SessionHasPermissionToUser(c.App.Session, accessToken.UserId) {
if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) {
c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS)
return
}
......@@ -1611,7 +1611,7 @@ func disableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request)
return
}
if !c.App.SessionHasPermissionToUser(c.App.Session, accessToken.UserId) {
if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) {
c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS)
return
}
......@@ -1647,7 +1647,7 @@ func enableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if !c.App.SessionHasPermissionToUser(c.App.Session, accessToken.UserId) {
if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) {
c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS)
return
}
......
This diff is collapsed.
......@@ -19,7 +19,7 @@ const (
func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppError) {
skipIntensiveQueries := false
var systemUserCount int64
r := <-a.Srv.Store.User().AnalyticsUniqueUserCount("")
r := <-a.Srv.Store.User().Count(model.UserCountOptions{})
if r.Err != nil {
return nil, r.Err
}
......@@ -53,7 +53,9 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo
if teamId == "" {
userInactiveChan = a.Srv.Store.User().AnalyticsGetInactiveUsersCount()
} else {
userChan = a.Srv.Store.User().AnalyticsUniqueUserCount(teamId)
userChan = a.Srv.Store.User().Count(model.UserCountOptions{
TeamId: teamId,
})
}
var postChan store.StoreChannel
......
......@@ -163,6 +163,11 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) {
model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_READ_USER_ACCESS_TOKEN.Id,
model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_CREATE_BOT.Id,
model.PERMISSION_READ_BOTS.Id,
model.PERMISSION_READ_OTHERS_BOTS.Id,
model.PERMISSION_MANAGE_BOTS.Id,
model.PERMISSION_MANAGE_OTHERS_BOTS.Id,
model.PERMISSION_REMOVE_OTHERS_REACTIONS.Id,
model.PERMISSION_LIST_TEAM_CHANNELS.Id,
model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id,
......@@ -331,6 +336,11 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) {
model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_READ_USER_ACCESS_TOKEN.Id,
model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_CREATE_BOT.Id,
model.PERMISSION_READ_BOTS.Id,
model.PERMISSION_READ_OTHERS_BOTS.Id,
model.PERMISSION_MANAGE_BOTS.Id,
model.PERMISSION_MANAGE_OTHERS_BOTS.Id,
model.PERMISSION_REMOVE_OTHERS_REACTIONS.Id,
model.PERMISSION_LIST_TEAM_CHANNELS.Id,
model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id,
......@@ -465,6 +475,11 @@ func TestDoEmojisPermissionsMigration(t *testing.T) {
model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_READ_USER_ACCESS_TOKEN.Id,
model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_CREATE_BOT.Id,
model.PERMISSION_READ_BOTS.Id,
model.PERMISSION_READ_OTHERS_BOTS.Id,
model.PERMISSION_MANAGE_BOTS.Id,
model.PERMISSION_MANAGE_OTHERS_BOTS.Id,
model.PERMISSION_REMOVE_OTHERS_REACTIONS.Id,
model.PERMISSION_LIST_TEAM_CHANNELS.Id,
model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id,
......
......@@ -143,6 +143,10 @@ func (a *App) CheckUserPreflightAuthenticationCriteria(user *model.User, mfaToke
return err
}
if err := checkUserNotBot(user); err != nil {
return err
}
if err := checkUserLoginAttempts(user, *a.Config().ServiceSettings.MaximumLoginAttempts); err != nil {
return err
}
......@@ -191,6 +195,13 @@ func checkUserNotDisabled(user *model.User) *model.AppError {
return nil
}
func checkUserNotBot(user *model.User) *model.AppError {
if user.IsBot {
return model.NewAppError("Login", "api.user.login.bot_login_forbidden.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized)
}
return nil
}
func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) {
license := a.License()
ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap != nil && license != nil && *license.Features.LDAP
......
......@@ -12,6 +12,10 @@ import (
"github.com/mattermost/mattermost-server/model"
)
func (a *App) MakePermissionError(permission *model.Permission) *model.AppError {
return model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "userId="+a.Session.UserId+", "+"permission="+permission.Id, http.StatusForbidden)
}
func (a *App) SessionHasPermissionTo(session model.Session, permission *model.Permission) bool {
return a.RolesGrantPermission(session.GetUserRoles(), permission.Id)
}
......@@ -98,6 +102,18 @@ func (a *App) SessionHasPermissionToUser(session model.Session, userId string) b
return false
}
func (a *App) SessionHasPermissionToUserOrBot(session model.Session, userId string) bool {
if a.SessionHasPermissionToUser(session, userId) {
return true
}
if err := a.SessionHasPermissionToManageBot(session, userId); err == nil {
return true
}
return false
}
func (a *App) HasPermissionTo(askingUserId string, permission *model.Permission) bool {
user, err := a.GetUser(askingUserId)
if err != nil {
......@@ -205,3 +221,35 @@ func (a *App) RolesGrantPermission(roleNames []string, permissionId string) bool
return false
}
// SessionHasPermissionToManageBot returns nil if the session has access to manage the given bot.
// This function deviates from other authorization checks in returning an error instead of just
// a boolean, allowing the permission failure to be exposed with more granularity.
func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId string) *model.AppError {
existingBot, err := a.GetBot(botUserId, true)
if err != nil {
return err
}
if existingBot.OwnerId == session.UserId {
if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_BOTS) {
if !a.SessionHasPermissionTo(session, model.PERMISSION_READ_BOTS) {
// If the user doesn't have permission to read bots, pretend as if
// the bot doesn't exist at all.
return model.MakeBotNotFoundError(botUserId)
}
return a.MakePermissionError(model.PERMISSION_MANAGE_BOTS)
}
} else {
if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_OTHERS_BOTS) {
if !a.SessionHasPermissionTo(session, model.PERMISSION_READ_OTHERS_BOTS) {
// If the user doesn't have permission to read others' bots,
// pretend as if the bot doesn't exist at all.
return model.MakeBotNotFoundError(botUserId)
}
return a.MakePermissionError(model.PERMISSION_MANAGE_OTHERS_BOTS)
}
}
return nil
}
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
)
// CreateBot creates the given bot and corresponding user.
func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) {
result := <-a.Srv.Store.User().Save(model.UserFromBot(bot))
if result.Err != nil {
return nil, result.Err
}
bot.UserId = result.Data.(*model.User).Id
result = <-a.Srv.Store.Bot().Save(bot)
if result.Err != nil {
<-a.Srv.Store.User().PermanentDelete(bot.UserId)
return nil, result.Err
}
return result.Data.(*model.Bot), nil
}
// PatchBot applies the given patch to the bot and corresponding user.
func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
bot, err := a.GetBot(botUserId, true)
if err != nil {
return nil, err
}
bot.Patch(botPatch)
result := <-a.Srv.Store.User().Get(botUserId)
if result.Err != nil {
return nil, result.Err
}
user := result.Data.(*model.User)
patchedUser := model.UserFromBot(bot)
user.Id = patchedUser.Id
user.Username = patchedUser.Username
user.Email = patchedUser.Email
user.FirstName = patchedUser.FirstName
if result = <-a.Srv.Store.User().Update(user, true); result.Err != nil {
return nil, result.Err
}
result = <-a.Srv.Store.Bot().Update(bot)
if result.Err != nil {
return nil, result.Err
}
return result.Data.(*model.Bot), nil
}
// GetBot returns the given bot.
func (a *App) GetBot(botUserId string, includeDeleted bool) (*model.Bot, *model.AppError) {
result := <-a.Srv.Store.Bot().Get(botUserId, includeDeleted)
if result.Err != nil {
return nil, result.Err
}
return result.Data.(*model.Bot), nil
}
// GetBots returns the requested page of bots.
func (a *App) GetBots(options *model.BotGetOptions) (model.BotList, *model.AppError) {
result := <-a.Srv.Store.Bot().GetAll(options)
if result.Err != nil {
return nil, result.Err
}
return result.Data.([]*model.Bot), nil
}
// UpdateBotActive marks a bot as active or inactive, along with its corresponding user.
func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model.AppError) {
result := <-a.Srv.Store.User().Get(botUserId)
if result.Err != nil {
return nil, result.Err
}
user := result.Data.(*model.User)
if _, err := a.UpdateActive(user, active); err != nil {
return nil, err
}
result = <-a.Srv.Store.Bot().Get(botUserId, true)
if result.Err != nil {
return nil, result.Err
}
bot := result.Data.(*model.Bot)
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 {
result := <-a.Srv.Store.Bot().Update(bot)
if result.Err != nil {
return nil, result.Err
}
bot = result.Data.(*model.Bot)
}
return bot, nil
}
// PermanentDeleteBot permanently deletes a bot and its corresponding user.
func (a *App) PermanentDeleteBot(botUserId string) *model.AppError {
if result := <-a.Srv.Store.Bot().PermanentDelete(botUserId); result.Err != nil {
return result.Err
}
if result := <-a.Srv.Store.User().PermanentDelete(botUserId); result.Err != nil {
return result.Err
}
return nil
}
// UpdateBotOwner changes a bot's owner to the given value
func (a *App) UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError) {
result := <-a.Srv.Store.Bot().Get(botUserId, true)
if result.Err != nil {
return nil, result.Err
}
bot := result.Data.(*model.Bot)
bot.OwnerId = newOwnerId
if result = <-a.Srv.Store.Bot().Update(bot); result.Err != nil {
return nil, result.Err
}
return result.Data.(*model.Bot), nil
}
// disableUserBots disables all bots owned by the given user
func (a *App) disableUserBots(userId string) *model.AppError {
perPage := 20
for {
options := &model.BotGetOptions{
OwnerId: userId,
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(bot.UserId, false)
if err != nil {
mlog.Error("Unable to deactivate bot.", mlog.String("bot_user_id", bot.UserId), mlog.Err(err))
}
}
// Get next set of bots if we got the max number of bots
if len(userBots) == perPage {
options.Page += 1
continue
}
break
}
return nil
}
This diff is collapsed.
......@@ -122,6 +122,7 @@ func pluginActivated(pluginStates map[string]*model.PluginState, pluginId string
func (a *App) trackActivity() {
var userCount int64
var botAccountsCount int64
var activeUsersDailyCount int64
var activeUsersMonthlyCount int64
var inactiveUserCount int64
......@@ -147,10 +148,19 @@ func (a *App) trackActivity() {
activeUsersMonthlyCount = r.Data.(int64)
}
if ucr := <-a.Srv.Store.User().GetTotalUsersCount(); ucr.Err == nil {
if ucr := <-a.Srv.Store.User().Count(model.UserCountOptions{
IncludeDeleted: true,
}); ucr.Err == nil {
userCount = ucr.Data.(int64)
}
if bc := <-a.Srv.Store.User().Count(model.UserCountOptions{
IncludeBotAccounts: true,
ExcludeRegularUsers: true,
}); bc.Err == nil {
botAccountsCount = bc.Data.(int64)
}
if iucr := <-a.Srv.Store.User().AnalyticsGetInactiveUsersCount(); iucr.Err == nil {
inactiveUserCount = iucr.Data.(int64)
}
......@@ -197,6 +207,7 @@ func (a *App) trackActivity() {