summaryrefslogtreecommitdiffstats
path: root/app/session.go
blob: 6d46f3d3a9401ff700a2414fd36aa75d55c570fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package app

import (
	"fmt"
	"net/http"

	"github.com/mattermost/mattermost-server/mlog"
	"github.com/mattermost/mattermost-server/model"
)

func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppError) {
	session.Token = ""

	result := <-a.Srv.Store.Session().Save(session)
	if result.Err != nil {
		return nil, result.Err
	}
	session = result.Data.(*model.Session)

	a.AddSessionToCache(session)

	return session, nil
}

func (a *App) GetSession(token string) (*model.Session, *model.AppError) {
	metrics := a.Metrics

	var session *model.Session
	if ts, ok := a.sessionCache.Get(token); ok {
		session = ts.(*model.Session)
		if metrics != nil {
			metrics.IncrementMemCacheHitCounterSession()
		}
	} else {
		if metrics != nil {
			metrics.IncrementMemCacheMissCounterSession()
		}
	}

	if session == nil {
		if sessionResult := <-a.Srv.Store.Session().Get(token); sessionResult.Err == nil {
			session = sessionResult.Data.(*model.Session)

			if session != nil {
				if session.Token != token {
					return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "", http.StatusUnauthorized)
				}

				if !session.IsExpired() {
					a.AddSessionToCache(session)
				}
			}
		} else if sessionResult.Err.StatusCode == http.StatusInternalServerError {
			return nil, sessionResult.Err
		}
	}

	if session == nil {
		var err *model.AppError
		session, err = a.createSessionForUserAccessToken(token)
		if err != nil {
			detailedError := ""
			statusCode := http.StatusUnauthorized
			if err.Id != "app.user_access_token.invalid_or_missing" {
				detailedError = err.Error()
				statusCode = err.StatusCode
			}
			return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token}, detailedError, statusCode)
		}
	}

	if session == nil || session.IsExpired() {
		return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token}, "", http.StatusUnauthorized)
	}

	license := a.License()
	if *a.Config().ServiceSettings.SessionIdleTimeoutInMinutes > 0 &&
		license != nil && *license.Features.Compliance &&
		session != nil && !session.IsOAuth && !session.IsMobileApp() &&
		session.Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_USER_ACCESS_TOKEN {

		timeout := int64(*a.Config().ServiceSettings.SessionIdleTimeoutInMinutes) * 1000 * 60
		if model.GetMillis()-session.LastActivityAt > timeout {
			a.RevokeSessionById(session.Id)
			return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token}, "idle timeout", http.StatusUnauthorized)
		}
	}

	return session, nil
}

func (a *App) GetSessions(userId string) ([]*model.Session, *model.AppError) {
	result := <-a.Srv.Store.Session().GetSessions(userId)
	if result.Err != nil {
		return nil, result.Err
	}
	return result.Data.([]*model.Session), nil

}

func (a *App) RevokeAllSessions(userId string) *model.AppError {
	result := <-a.Srv.Store.Session().GetSessions(userId)
	if result.Err != nil {
		return result.Err
	}
	sessions := result.Data.([]*model.Session)

	for _, session := range sessions {
		if session.IsOAuth {
			a.RevokeAccessToken(session.Token)
		} else {
			if result := <-a.Srv.Store.Session().Remove(session.Id); result.Err != nil {
				return result.Err
			}
		}
	}

	a.ClearSessionCacheForUser(userId)

	return nil
}

func (a *App) ClearSessionCacheForUser(userId string) {
	a.ClearSessionCacheForUserSkipClusterSend(userId)

	if a.Cluster != nil {
		msg := &model.ClusterMessage{
			Event:    model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER,
			SendType: model.CLUSTER_SEND_RELIABLE,
			Data:     userId,
		}
		a.Cluster.SendClusterMessage(msg)
	}
}

func (a *App) ClearSessionCacheForUserSkipClusterSend(userId string) {
	keys := a.sessionCache.Keys()

	for _, key := range keys {
		if ts, ok := a.sessionCache.Get(key); ok {
			session := ts.(*model.Session)
			if session.UserId == userId {
				a.sessionCache.Remove(key)
				if a.Metrics != nil {
					a.Metrics.IncrementMemCacheInvalidationCounterSession()
				}
			}
		}
	}

	a.InvalidateWebConnSessionCacheForUser(userId)
}

func (a *App) AddSessionToCache(session *model.Session) {
	a.sessionCache.AddWithExpiresInSecs(session.Token, session, int64(*a.Config().ServiceSettings.SessionCacheInMinutes*60))
}

func (a *App) SessionCacheLength() int {
	return a.sessionCache.Len()
}

func (a *App) RevokeSessionsForDeviceId(userId string, deviceId string, currentSessionId string) *model.AppError {
	result := <-a.Srv.Store.Session().GetSessions(userId)
	if result.Err != nil {
		return result.Err
	}
	sessions := result.Data.([]*model.Session)
	for _, session := range sessions {
		if session.DeviceId == deviceId && session.Id != currentSessionId {
			mlog.Debug(fmt.Sprintf("Revoking sessionId=%v for userId=%v re-login with same device Id", session.Id, userId), mlog.String("user_id", userId))
			if err := a.RevokeSession(session); err != nil {
				// Soft error so we still remove the other sessions
				mlog.Error(err.Error())
			}
		}
	}

	return nil
}

func (a *App) GetSessionById(sessionId string) (*model.Session, *model.AppError) {
	result := <-a.Srv.Store.Session().Get(sessionId)
	if result.Err != nil {
		result.Err.StatusCode = http.StatusBadRequest
		return nil, result.Err
	}
	return result.Data.(*model.Session), nil
}

func (a *App) RevokeSessionById(sessionId string) *model.AppError {
	result := <-a.Srv.Store.Session().Get(sessionId)
	if result.Err != nil {
		result.Err.StatusCode = http.StatusBadRequest
		return result.Err
	}
	return a.RevokeSession(result.Data.(*model.Session))

}

func (a *App) RevokeSession(session *model.Session) *model.AppError {
	if session.IsOAuth {
		if err := a.RevokeAccessToken(session.Token); err != nil {
			return err
		}
	} else {
		if result := <-a.Srv.Store.Session().Remove(session.Id); result.Err != nil {
			return result.Err
		}
	}

	a.ClearSessionCacheForUser(session.UserId)

	return nil
}

func (a *App) AttachDeviceId(sessionId string, deviceId string, expiresAt int64) *model.AppError {
	if result := <-a.Srv.Store.Session().UpdateDeviceId(sessionId, deviceId, expiresAt); result.Err != nil {
		return result.Err
	}

	return nil
}

func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) {
	now := model.GetMillis()

	a.UpdateWebConnUserActivity(session, now)

	if now-session.LastActivityAt < model.SESSION_ACTIVITY_TIMEOUT {
		return
	}

	if result := <-a.Srv.Store.Session().UpdateLastActivityAt(session.Id, now); result.Err != nil {
		mlog.Error(fmt.Sprintf("Failed to update LastActivityAt for user_id=%v and session_id=%v, err=%v", session.UserId, session.Id, result.Err), mlog.String("user_id", session.UserId))
	}

	session.LastActivityAt = now
	a.AddSessionToCache(&session)
}

func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) {
	if !*a.Config().ServiceSettings.EnableUserAccessTokens {
		return nil, model.NewAppError("CreateUserAccessToken", "app.user_access_token.disabled", nil, "", http.StatusNotImplemented)
	}

	token.Token = model.NewId()

	uchan := a.Srv.Store.User().Get(token.UserId)

	result := <-a.Srv.Store.UserAccessToken().Save(token)
	if result.Err != nil {
		return nil, result.Err
	}
	token = result.Data.(*model.UserAccessToken)

	if result := <-uchan; result.Err != nil {
		mlog.Error(result.Err.Error())
	} else {
		user := result.Data.(*model.User)
		if err := a.SendUserAccessTokenAddedEmail(user.Email, user.Locale, a.GetSiteURL()); err != nil {
			mlog.Error(err.Error())
		}
	}

	return token, nil

}

func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Session, *model.AppError) {
	if !*a.Config().ServiceSettings.EnableUserAccessTokens {
		return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "EnableUserAccessTokens=false", http.StatusUnauthorized)
	}

	var token *model.UserAccessToken
	result := <-a.Srv.Store.UserAccessToken().GetByToken(tokenString)
	if result.Err != nil {
		return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, result.Err.Error(), http.StatusUnauthorized)
	}
	token = result.Data.(*model.UserAccessToken)

	if !token.IsActive {
		return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "inactive_token", http.StatusUnauthorized)
	}

	var user *model.User
	result = <-a.Srv.Store.User().Get(token.UserId)
	if result.Err != nil {
		return nil, result.Err
	}
	user = result.Data.(*model.User)

	if user.DeleteAt != 0 {
		return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "inactive_user_id="+user.Id, http.StatusUnauthorized)
	}

	session := &model.Session{
		Token:   token.Token,
		UserId:  user.Id,
		Roles:   user.GetRawRoles(),
		IsOAuth: false,
	}

	session.AddProp(model.SESSION_PROP_USER_ACCESS_TOKEN_ID, token.Id)
	session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_USER_ACCESS_TOKEN)
	session.SetExpireInDays(model.SESSION_USER_ACCESS_TOKEN_EXPIRY)

	result = <-a.Srv.Store.Session().Save(session)
	if result.Err != nil {
		return nil, result.Err
	}
	session = result.Data.(*model.Session)

	a.AddSessionToCache(session)

	return session, nil

}

func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError {
	var session *model.Session
	if result := <-a.Srv.Store.Session().Get(token.Token); result.Err == nil {
		session = result.Data.(*model.Session)
	}

	if result := <-a.Srv.Store.UserAccessToken().Delete(token.Id); result.Err != nil {
		return result.Err
	}

	if session == nil {
		return nil
	}

	return a.RevokeSession(session)
}

func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppError {
	var session *model.Session
	if result := <-a.Srv.Store.Session().Get(token.Token); result.Err == nil {
		session = result.Data.(*model.Session)
	}

	if result := <-a.Srv.Store.UserAccessToken().UpdateTokenDisable(token.Id); result.Err != nil {
		return result.Err
	}

	if session == nil {
		return nil
	}

	return a.RevokeSession(session)
}

func (a *App) EnableUserAccessToken(token *model.UserAccessToken) *model.AppError {
	var session *model.Session
	if result := <-a.Srv.Store.Session().Get(token.Token); result.Err == nil {
		session = result.Data.(*model.Session)
	}

	if result := <-a.Srv.Store.UserAccessToken().UpdateTokenEnable(token.Id); result.Err != nil {
		return result.Err
	}

	if session == nil {
		return nil
	}

	return nil
}

func (a *App) GetUserAccessTokens(page, perPage int) ([]*model.UserAccessToken, *model.AppError) {
	result := <-a.Srv.Store.UserAccessToken().GetAll(page*perPage, perPage)
	if result.Err != nil {
		return nil, result.Err
	}
	tokens := result.Data.([]*model.UserAccessToken)
	for _, token := range tokens {
		token.Token = ""
	}

	return tokens, nil

}

func (a *App) GetUserAccessTokensForUser(userId string, page, perPage int) ([]*model.UserAccessToken, *model.AppError) {
	result := <-a.Srv.Store.UserAccessToken().GetByUser(userId, page*perPage, perPage)
	if result.Err != nil {
		return nil, result.Err
	}
	tokens := result.Data.([]*model.UserAccessToken)
	for _, token := range tokens {
		token.Token = ""
	}

	return tokens, nil

}

func (a *App) GetUserAccessToken(tokenId string, sanitize bool) (*model.UserAccessToken, *model.AppError) {
	result := <-a.Srv.Store.UserAccessToken().Get(tokenId)
	if result.Err != nil {
		return nil, result.Err
	}
	token := result.Data.(*model.UserAccessToken)
	if sanitize {
		token.Token = ""
	}
	return token, nil

}

func (a *App) SearchUserAccessTokens(term string) ([]*model.UserAccessToken, *model.AppError) {
	result := <-a.Srv.Store.UserAccessToken().Search(term)
	if result.Err != nil {
		return nil, result.Err
	}
	tokens := result.Data.([]*model.UserAccessToken)
	for _, token := range tokens {
		token.Token = ""
	}
	return tokens, nil

}