Files
mattermost/app/login.go
Christopher Speller 06b579d18a MM-12393 Server side of bot accounts. (#10378)
* bots model, store and api (#9903)

* bots model, store and api

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

* uncomment tests incorrectly commented, and fix merge issues

* add etags support

* add missing licenses

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

* rejig permissions

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

* conform to general rest api pattern

* eliminate redundant http.StatusOK

* Update api4/bot.go

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

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

* Update model/bot.go

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

* Update model/client4.go

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

* move sessionHasPermissionToManageBot to app/authorization.go

* use api.ApiSessionRequired for createBot

* introduce BOT_DESCRIPTION_MAX_RUNES constant

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

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

* Add additional config settings to tests

* upgrade db to 5.7 (#10019)

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

* Fix typos (#10024)

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

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

This reverts commit 3fcecd521a.

* s/DisableBot/UpdateBotActive

* add permissions on upgrade

* Update NOTICE.txt (#10054)

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

* avoid leaking bot knowledge without permission

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

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

* 6798 added the permsission check before getting the reactions

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

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

* 6798 connected the app function with the new store function

* 6798 fixed the review comments

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

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

* Trigger Login Hooks with OAuth (#10061)

* make BotStore.GetAll deterministic even on duplicate CreateAt

* fix spurious TestMuteCommandSpecificChannel test failure

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

* fix race in TestExportUserChannels

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

* MM-13117: bot tokens (#10111)

* eliminate redundant Client/AdminClient declarations

* harden TestUpdateChannelScheme to API failures

* eliminate unnecessary config restoration

* minor cleanup

* make TestGenerateMfaSecret config dependency explicit

* TestCreateUserAccessToken for bots

* TestGetUserAccessToken* for bots

* leverage SessionHasPermissionToUserOrBot for user token APIs

* Test(Revoke|Disable|Enable)UserAccessToken

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

* uncomment TestResetPassword, but still skip

* mark assert(Invalid)Token as helper

* fix whitespace issues

* fix mangled comments

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

* MM-13117: expose bot API to plugins

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

* gofmt issues

* expunge use of BotList in plugin/client API

* introduce model.BotGetOptions

* use botUserId term for clarity

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

* Add way to list orphaned bots.

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

* Apply suggestions from code review

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

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

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

* MM-13104: disallow bot login

* fix shadowing

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

* Disable user bots when user is disabled.

* Grammer.

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

* Fixing bot branch for test changes.

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

* Rename bot CreatorId to OwnerId

* Adding ability to re-enable bots

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

* Adding diagnostics and licencing counting for bot accounts.

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

* Removing unnessisary nil values from UserCountOptions.

* Changing comment to GoDoc format

* Improving user count SQL

* Some improvments from feedback.

* Omit empty on User.IsBot
2019-03-05 07:06:45 -08:00

222 lines
6.3 KiB
Go

// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/avct/uasurfer"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
"github.com/mattermost/mattermost-server/store"
)
func (a *App) CheckForClientSideCert(r *http.Request) (string, string, string) {
pem := r.Header.Get("X-SSL-Client-Cert") // mapped to $ssl_client_cert from nginx
subject := r.Header.Get("X-SSL-Client-Cert-Subject-DN") // mapped to $ssl_client_s_dn from nginx
email := ""
if len(subject) > 0 {
for _, v := range strings.Split(subject, "/") {
kv := strings.Split(v, "=")
if len(kv) == 2 && kv[0] == "emailAddress" {
email = kv[1]
}
}
}
return pem, subject, email
}
func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken string, ldapOnly bool) (user *model.User, err *model.AppError) {
// Do statistics
defer func() {
if a.Metrics != nil {
if user == nil || err != nil {
a.Metrics.IncrementLoginFail()
} else {
a.Metrics.IncrementLogin()
}
}
}()
if len(password) == 0 {
return nil, model.NewAppError("AuthenticateUserForLogin", "api.user.login.blank_pwd.app_error", nil, "", http.StatusBadRequest)
}
// Get the MM user we are trying to login
if user, err = a.GetUserForLogin(id, loginId); err != nil {
return nil, err
}
// If client side cert is enable and it's checking as a primary source
// then trust the proxy and cert that the correct user is supplied and allow
// them access
if *a.Config().ExperimentalSettings.ClientSideCertEnable && *a.Config().ExperimentalSettings.ClientSideCertCheck == model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH {
// Unless the user is a bot.
if err = checkUserNotBot(user); err != nil {
return nil, err
}
return user, nil
}
// and then authenticate them
if user, err = a.authenticateUser(user, password, mfaToken); err != nil {
return nil, err
}
return user, nil
}
func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) {
enableUsername := *a.Config().EmailSettings.EnableSignInWithUsername
enableEmail := *a.Config().EmailSettings.EnableSignInWithEmail
// If we are given a userID then fail if we can't find a user with that ID
if len(id) != 0 {
user, err := a.GetUser(id)
if err != nil {
if err.Id != store.MISSING_ACCOUNT_ERROR {
err.StatusCode = http.StatusInternalServerError
return nil, err
}
err.StatusCode = http.StatusBadRequest
return nil, err
}
return user, nil
}
// Try to get the user by username/email
if result := <-a.Srv.Store.User().GetForLogin(loginId, enableUsername, enableEmail); result.Err == nil {
return result.Data.(*model.User), nil
}
// Try to get the user with LDAP if enabled
if *a.Config().LdapSettings.Enable && a.Ldap != nil {
if ldapUser, err := a.Ldap.GetUser(loginId); err == nil {
if user, err := a.GetUserByAuth(ldapUser.AuthData, model.USER_AUTH_SERVICE_LDAP); err == nil {
return user, nil
}
return ldapUser, nil
}
}
return nil, model.NewAppError("GetUserForLogin", "store.sql_user.get_for_login.app_error", nil, "", http.StatusBadRequest)
}
func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) (*model.Session, *model.AppError) {
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
var rejectionReason string
pluginContext := a.PluginContext()
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
rejectionReason = hooks.UserWillLogIn(pluginContext, user)
return rejectionReason == ""
}, plugin.UserWillLogInId)
if rejectionReason != "" {
return nil, model.NewAppError("DoLogin", "Login rejected by plugin: "+rejectionReason, nil, "", http.StatusBadRequest)
}
}
session := &model.Session{UserId: user.Id, Roles: user.GetRawRoles(), DeviceId: deviceId, IsOAuth: false}
session.GenerateCSRF()
maxAge := *a.Config().ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24
if len(deviceId) > 0 {
session.SetExpireInDays(*a.Config().ServiceSettings.SessionLengthMobileInDays)
// A special case where we logout of all other sessions with the same Id
if err := a.RevokeSessionsForDeviceId(user.Id, deviceId, ""); err != nil {
err.StatusCode = http.StatusInternalServerError
return nil, err
}
} else {
session.SetExpireInDays(*a.Config().ServiceSettings.SessionLengthWebInDays)
}
ua := uasurfer.Parse(r.UserAgent())
plat := getPlatformName(ua)
os := getOSName(ua)
bname := getBrowserName(ua, r.UserAgent())
bversion := getBrowserVersion(ua, r.UserAgent())
session.AddProp(model.SESSION_PROP_PLATFORM, plat)
session.AddProp(model.SESSION_PROP_OS, os)
session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion))
var err *model.AppError
if session, err = a.CreateSession(session); err != nil {
err.StatusCode = http.StatusInternalServerError
return nil, err
}
w.Header().Set(model.HEADER_TOKEN, session.Token)
secure := false
if GetProtocol(r) == "https" {
secure = true
}
domain := a.GetCookieDomain()
expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0)
sessionCookie := &http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Value: session.Token,
Path: "/",
MaxAge: maxAge,
Expires: expiresAt,
HttpOnly: true,
Domain: domain,
Secure: secure,
}
userCookie := &http.Cookie{
Name: model.SESSION_COOKIE_USER,
Value: user.Id,
Path: "/",
MaxAge: maxAge,
Expires: expiresAt,
Domain: domain,
Secure: secure,
}
csrfCookie := &http.Cookie{
Name: model.SESSION_COOKIE_CSRF,
Value: session.GetCSRF(),
Path: "/",
MaxAge: maxAge,
Expires: expiresAt,
Domain: domain,
Secure: secure,
}
http.SetCookie(w, sessionCookie)
http.SetCookie(w, userCookie)
http.SetCookie(w, csrfCookie)
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
a.Srv.Go(func() {
pluginContext := a.PluginContext()
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
hooks.UserHasLoggedIn(pluginContext, user)
return true
}, plugin.UserHasLoggedInId)
})
}
return session, nil
}
func GetProtocol(r *http.Request) string {
if r.Header.Get(model.HEADER_FORWARDED_PROTO) == "https" || r.TLS != nil {
return "https"
}
return "http"
}