MM-25394 session expired push notifications (#14732)

* new job type created that checks for expired mobile sessions and pushes notifications.

* only send session expired notifications if ExtendSessionLengthWithActivity is enabled.

* includes schema change:  field added to Sessions table
Этот коммит содержится в:
Doug Lauder
2020-06-17 14:47:54 -04:00
коммит произвёл GitHub
родитель 2bb6071f73
Коммит b317ee5cf2
29 изменённых файлов: 694 добавлений и 4 удалений

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

@@ -136,6 +136,10 @@ func (a *App) initJobs() {
if jobsPluginsInterface != nil {
a.srv.Jobs.Plugins = jobsPluginsInterface(a)
}
if jobsExpiryNotifyInterface != nil {
a.srv.Jobs.ExpiryNotify = jobsExpiryNotifyInterface(a)
}
a.srv.Jobs.Workers = a.srv.Jobs.InitWorkers()
a.srv.Jobs.Schedulers = a.srv.Jobs.InitSchedulers()
}

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

@@ -226,6 +226,8 @@ type AppIface interface {
NewWebConn(ws *websocket.Conn, session model.Session, t goi18n.TranslateFunc, locale string) *WebConn
// NewWebHub creates a new Hub.
NewWebHub() *Hub
// NotifySessionsExpired is called periodically from the job server to notify any mobile sessions that have expired.
NotifySessionsExpired() *model.AppError
// OverrideIconURLIfEmoji changes the post icon override URL prop, if it has an emoji icon,
// so that it points to the URL (relative) of the emoji - static if emoji is default, /api if custom.
OverrideIconURLIfEmoji(post *model.Post)

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

@@ -90,6 +90,12 @@ func RegisterJobsBleveIndexerInterface(f func(*Server) tjobs.IndexerJobInterface
jobsBleveIndexerInterface = f
}
var jobsExpiryNotifyInterface func(*App) tjobs.ExpiryNotifyJobInterface
func RegisterJobsExpiryNotifyJobInterface(f func(*App) tjobs.ExpiryNotifyJobInterface) {
jobsExpiryNotifyInterface = f
}
var ldapInterface func(*App) einterfaces.LdapInterface
func RegisterLdapInterface(f func(*App) einterfaces.LdapInterface) {

87
app/expirynotify.go Обычный файл
Просмотреть файл

@@ -0,0 +1,87 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"github.com/mattermost/mattermost-server/v5/mlog"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/utils"
)
const (
OneHourMillis = 60 * 60 * 1000
)
// NotifySessionsExpired is called periodically from the job server to notify any mobile sessions that have expired.
func (a *App) NotifySessionsExpired() *model.AppError {
if *a.Config().EmailSettings.SendPushNotifications {
pushServer := *a.Config().EmailSettings.PushNotificationServer
if license := a.srv.License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) {
mlog.Warn("Push notifications are disabled. Go to System Console > Notifications > Mobile Push to enable them.")
return nil
}
}
// Get all mobile sessions that expired within the last hour.
sessions, err := a.srv.Store.Session().GetSessionsExpired(OneHourMillis, true, true)
if err != nil {
return err
}
msg := &model.PushNotification{
Version: model.PUSH_MESSAGE_V2,
Type: model.PUSH_TYPE_SESSION,
}
for _, session := range sessions {
tmpMessage := msg.DeepCopy()
tmpMessage.SetDeviceIdAndPlatform(session.DeviceId)
tmpMessage.AckId = model.NewId()
tmpMessage.Message = a.getSessionExpiredPushMessage(session)
errPush := a.sendToPushProxy(tmpMessage, session)
if errPush != nil {
a.NotificationsLog().Error("Notification error",
mlog.String("ackId", tmpMessage.AckId),
mlog.String("type", tmpMessage.Type),
mlog.String("userId", session.UserId),
mlog.String("deviceId", tmpMessage.DeviceId),
mlog.String("status", errPush.Error()),
)
continue
}
a.NotificationsLog().Info("Notification sent",
mlog.String("ackId", tmpMessage.AckId),
mlog.String("type", tmpMessage.Type),
mlog.String("userId", session.UserId),
mlog.String("deviceId", tmpMessage.DeviceId),
mlog.String("status", model.PUSH_SEND_SUCCESS),
)
if a.Metrics() != nil {
a.Metrics().IncrementPostSentPush()
}
err = a.srv.Store.Session().UpdateExpiredNotify(session.Id, true)
if err != nil {
mlog.Error("Failed to update ExpiredNotify flag", mlog.String("sessionid", session.Id), mlog.Err(err))
}
}
return nil
}
func (a *App) getSessionExpiredPushMessage(session *model.Session) string {
locale := model.DEFAULT_LOCALE
user, err := a.GetUser(session.UserId)
if err == nil {
locale = user.Locale
}
T := utils.GetUserTranslations(locale)
siteName := *a.Config().TeamSettings.SiteName
props := map[string]interface{}{"siteName": siteName, "daysCount": *a.Config().ServiceSettings.SessionLengthMobileInDays}
return T("api.push_notifications.session.expired", props)
}

80
app/expirynotify_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,80 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/stretchr/testify/require"
)
func TestNotifySessionsExpired(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
handler := &testPushNotificationHandler{t: t}
pushServer := httptest.NewServer(
http.HandlerFunc(handler.handleReq),
)
defer pushServer.Close()
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.PushNotificationServer = pushServer.URL
})
t.Run("push notifications disabled", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.SendPushNotifications = false
})
err := th.App.NotifySessionsExpired()
// no error, but also no requests sent
require.Nil(t, err)
require.Equal(t, 0, handler.numReqs())
})
t.Run("two sessions expired", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.SendPushNotifications = true
})
data := []struct {
deviceId string
expiresAt int64
notified bool
}{
{deviceId: "android:11111", expiresAt: model.GetMillis() + 100000, notified: false},
{deviceId: "android:22222", expiresAt: model.GetMillis() - 1000, notified: false},
{deviceId: "android:33333", expiresAt: model.GetMillis() - 2000, notified: false},
{deviceId: "android:44444", expiresAt: model.GetMillis() - 3000, notified: true},
}
for _, d := range data {
_, err := th.App.CreateSession(&model.Session{
UserId: th.BasicUser.Id,
DeviceId: d.deviceId,
ExpiresAt: d.expiresAt,
ExpiredNotify: d.notified,
})
require.Nil(t, err)
}
err := th.App.NotifySessionsExpired()
require.Nil(t, err)
require.Equal(t, 2, handler.numReqs())
expected := []string{"22222", "33333"}
require.Equal(t, model.PUSH_TYPE_SESSION, handler.notifications()[0].Type)
require.Contains(t, expected, handler.notifications()[0].DeviceId)
require.Contains(t, handler.notifications()[0].Message, "Session Expired")
require.Equal(t, model.PUSH_TYPE_SESSION, handler.notifications()[1].Type)
require.Contains(t, expected, handler.notifications()[1].DeviceId)
require.Contains(t, handler.notifications()[1].Message, "Session Expired")
})
}

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

@@ -10078,6 +10078,28 @@ func (a *OpenTracingAppLayer) NewWebHub() *Hub {
return resultVar0
}
func (a *OpenTracingAppLayer) NotifySessionsExpired() *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NotifySessionsExpired")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.NotifySessionsExpired()
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
ext.Error.Set(span, true)
}
return resultVar0
}
func (a *OpenTracingAppLayer) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.OpenInteractiveDialog")