github.com/qichengzx/mattermost-server@v4.5.1-0.20180604164826-2c75247c97d0+incompatible/store/sqlstore/session_store.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package sqlstore 5 6 import ( 7 "fmt" 8 "net/http" 9 "time" 10 11 "github.com/mattermost/mattermost-server/mlog" 12 "github.com/mattermost/mattermost-server/model" 13 "github.com/mattermost/mattermost-server/store" 14 ) 15 16 const ( 17 SESSIONS_CLEANUP_DELAY_MILLISECONDS = 100 18 ) 19 20 type SqlSessionStore struct { 21 SqlStore 22 } 23 24 func NewSqlSessionStore(sqlStore SqlStore) store.SessionStore { 25 us := &SqlSessionStore{sqlStore} 26 27 for _, db := range sqlStore.GetAllConns() { 28 table := db.AddTableWithName(model.Session{}, "Sessions").SetKeys(false, "Id") 29 table.ColMap("Id").SetMaxSize(26) 30 table.ColMap("Token").SetMaxSize(26) 31 table.ColMap("UserId").SetMaxSize(26) 32 table.ColMap("DeviceId").SetMaxSize(512) 33 table.ColMap("Roles").SetMaxSize(64) 34 table.ColMap("Props").SetMaxSize(1000) 35 } 36 37 return us 38 } 39 40 func (me SqlSessionStore) CreateIndexesIfNotExists() { 41 me.CreateIndexIfNotExists("idx_sessions_user_id", "Sessions", "UserId") 42 me.CreateIndexIfNotExists("idx_sessions_token", "Sessions", "Token") 43 me.CreateIndexIfNotExists("idx_sessions_expires_at", "Sessions", "ExpiresAt") 44 me.CreateIndexIfNotExists("idx_sessions_create_at", "Sessions", "CreateAt") 45 me.CreateIndexIfNotExists("idx_sessions_last_activity_at", "Sessions", "LastActivityAt") 46 } 47 48 func (me SqlSessionStore) Save(session *model.Session) store.StoreChannel { 49 return store.Do(func(result *store.StoreResult) { 50 if len(session.Id) > 0 { 51 result.Err = model.NewAppError("SqlSessionStore.Save", "store.sql_session.save.existing.app_error", nil, "id="+session.Id, http.StatusBadRequest) 52 return 53 } 54 55 session.PreSave() 56 57 tcs := me.Team().GetTeamsForUser(session.UserId) 58 59 if err := me.GetMaster().Insert(session); err != nil { 60 result.Err = model.NewAppError("SqlSessionStore.Save", "store.sql_session.save.app_error", nil, "id="+session.Id+", "+err.Error(), http.StatusInternalServerError) 61 return 62 } else { 63 result.Data = session 64 } 65 66 if rtcs := <-tcs; rtcs.Err != nil { 67 result.Err = model.NewAppError("SqlSessionStore.Save", "store.sql_session.save.app_error", nil, "id="+session.Id+", "+rtcs.Err.Error(), http.StatusInternalServerError) 68 return 69 } else { 70 tempMembers := rtcs.Data.([]*model.TeamMember) 71 session.TeamMembers = make([]*model.TeamMember, 0, len(tempMembers)) 72 for _, tm := range tempMembers { 73 if tm.DeleteAt == 0 { 74 session.TeamMembers = append(session.TeamMembers, tm) 75 } 76 } 77 } 78 }) 79 } 80 81 func (me SqlSessionStore) Get(sessionIdOrToken string) store.StoreChannel { 82 return store.Do(func(result *store.StoreResult) { 83 var sessions []*model.Session 84 85 if _, err := me.GetReplica().Select(&sessions, "SELECT * FROM Sessions WHERE Token = :Token OR Id = :Id LIMIT 1", map[string]interface{}{"Token": sessionIdOrToken, "Id": sessionIdOrToken}); err != nil { 86 result.Err = model.NewAppError("SqlSessionStore.Get", "store.sql_session.get.app_error", nil, "sessionIdOrToken="+sessionIdOrToken+", "+err.Error(), http.StatusInternalServerError) 87 } else if len(sessions) == 0 { 88 result.Err = model.NewAppError("SqlSessionStore.Get", "store.sql_session.get.app_error", nil, "sessionIdOrToken="+sessionIdOrToken, http.StatusNotFound) 89 } else { 90 result.Data = sessions[0] 91 92 tcs := me.Team().GetTeamsForUser(sessions[0].UserId) 93 if rtcs := <-tcs; rtcs.Err != nil { 94 result.Err = model.NewAppError("SqlSessionStore.Get", "store.sql_session.get.app_error", nil, "sessionIdOrToken="+sessionIdOrToken+", "+rtcs.Err.Error(), http.StatusInternalServerError) 95 return 96 } else { 97 tempMembers := rtcs.Data.([]*model.TeamMember) 98 sessions[0].TeamMembers = make([]*model.TeamMember, 0, len(tempMembers)) 99 for _, tm := range tempMembers { 100 if tm.DeleteAt == 0 { 101 sessions[0].TeamMembers = append(sessions[0].TeamMembers, tm) 102 } 103 } 104 } 105 } 106 }) 107 } 108 109 func (me SqlSessionStore) GetSessions(userId string) store.StoreChannel { 110 return store.Do(func(result *store.StoreResult) { 111 var sessions []*model.Session 112 113 tcs := me.Team().GetTeamsForUser(userId) 114 115 if _, err := me.GetReplica().Select(&sessions, "SELECT * FROM Sessions WHERE UserId = :UserId ORDER BY LastActivityAt DESC", map[string]interface{}{"UserId": userId}); err != nil { 116 result.Err = model.NewAppError("SqlSessionStore.GetSessions", "store.sql_session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError) 117 } else { 118 119 result.Data = sessions 120 } 121 122 if rtcs := <-tcs; rtcs.Err != nil { 123 result.Err = model.NewAppError("SqlSessionStore.GetSessions", "store.sql_session.get_sessions.app_error", nil, rtcs.Err.Error(), http.StatusInternalServerError) 124 return 125 } else { 126 for _, session := range sessions { 127 tempMembers := rtcs.Data.([]*model.TeamMember) 128 session.TeamMembers = make([]*model.TeamMember, 0, len(tempMembers)) 129 for _, tm := range tempMembers { 130 if tm.DeleteAt == 0 { 131 session.TeamMembers = append(session.TeamMembers, tm) 132 } 133 } 134 } 135 } 136 }) 137 } 138 139 func (me SqlSessionStore) GetSessionsWithActiveDeviceIds(userId string) store.StoreChannel { 140 return store.Do(func(result *store.StoreResult) { 141 var sessions []*model.Session 142 143 if _, err := me.GetReplica().Select(&sessions, "SELECT * FROM Sessions WHERE UserId = :UserId AND ExpiresAt != 0 AND :ExpiresAt <= ExpiresAt AND DeviceId != ''", map[string]interface{}{"UserId": userId, "ExpiresAt": model.GetMillis()}); err != nil { 144 result.Err = model.NewAppError("SqlSessionStore.GetActiveSessionsWithDeviceIds", "store.sql_session.get_sessions.app_error", nil, err.Error(), http.StatusInternalServerError) 145 } else { 146 147 result.Data = sessions 148 } 149 }) 150 } 151 152 func (me SqlSessionStore) Remove(sessionIdOrToken string) store.StoreChannel { 153 return store.Do(func(result *store.StoreResult) { 154 _, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE Id = :Id Or Token = :Token", map[string]interface{}{"Id": sessionIdOrToken, "Token": sessionIdOrToken}) 155 if err != nil { 156 result.Err = model.NewAppError("SqlSessionStore.RemoveSession", "store.sql_session.remove.app_error", nil, "id="+sessionIdOrToken+", err="+err.Error(), http.StatusInternalServerError) 157 } 158 }) 159 } 160 161 func (me SqlSessionStore) RemoveAllSessions() store.StoreChannel { 162 return store.Do(func(result *store.StoreResult) { 163 _, err := me.GetMaster().Exec("DELETE FROM Sessions") 164 if err != nil { 165 result.Err = model.NewAppError("SqlSessionStore.RemoveAllSessions", "store.sql_session.remove_all_sessions_for_team.app_error", nil, err.Error(), http.StatusInternalServerError) 166 } 167 }) 168 } 169 170 func (me SqlSessionStore) PermanentDeleteSessionsByUser(userId string) store.StoreChannel { 171 return store.Do(func(result *store.StoreResult) { 172 _, err := me.GetMaster().Exec("DELETE FROM Sessions WHERE UserId = :UserId", map[string]interface{}{"UserId": userId}) 173 if err != nil { 174 result.Err = model.NewAppError("SqlSessionStore.RemoveAllSessionsForUser", "store.sql_session.permanent_delete_sessions_by_user.app_error", nil, "id="+userId+", err="+err.Error(), http.StatusInternalServerError) 175 } 176 }) 177 } 178 179 func (me SqlSessionStore) UpdateLastActivityAt(sessionId string, time int64) store.StoreChannel { 180 return store.Do(func(result *store.StoreResult) { 181 if _, err := me.GetMaster().Exec("UPDATE Sessions SET LastActivityAt = :LastActivityAt WHERE Id = :Id", map[string]interface{}{"LastActivityAt": time, "Id": sessionId}); err != nil { 182 result.Err = model.NewAppError("SqlSessionStore.UpdateLastActivityAt", "store.sql_session.update_last_activity.app_error", nil, "sessionId="+sessionId, http.StatusInternalServerError) 183 } else { 184 result.Data = sessionId 185 } 186 }) 187 } 188 189 func (me SqlSessionStore) UpdateRoles(userId, roles string) store.StoreChannel { 190 return store.Do(func(result *store.StoreResult) { 191 if _, err := me.GetMaster().Exec("UPDATE Sessions SET Roles = :Roles WHERE UserId = :UserId", map[string]interface{}{"Roles": roles, "UserId": userId}); err != nil { 192 result.Err = model.NewAppError("SqlSessionStore.UpdateRoles", "store.sql_session.update_roles.app_error", nil, "userId="+userId, http.StatusInternalServerError) 193 } else { 194 result.Data = userId 195 } 196 }) 197 } 198 199 func (me SqlSessionStore) UpdateDeviceId(id string, deviceId string, expiresAt int64) store.StoreChannel { 200 return store.Do(func(result *store.StoreResult) { 201 if _, err := me.GetMaster().Exec("UPDATE Sessions SET DeviceId = :DeviceId, ExpiresAt = :ExpiresAt WHERE Id = :Id", map[string]interface{}{"DeviceId": deviceId, "Id": id, "ExpiresAt": expiresAt}); err != nil { 202 result.Err = model.NewAppError("SqlSessionStore.UpdateDeviceId", "store.sql_session.update_device_id.app_error", nil, err.Error(), http.StatusInternalServerError) 203 } else { 204 result.Data = deviceId 205 } 206 }) 207 } 208 209 func (me SqlSessionStore) AnalyticsSessionCount() store.StoreChannel { 210 return store.Do(func(result *store.StoreResult) { 211 query := 212 `SELECT 213 COUNT(*) 214 FROM 215 Sessions 216 WHERE ExpiresAt > :Time` 217 218 if c, err := me.GetReplica().SelectInt(query, map[string]interface{}{"Time": model.GetMillis()}); err != nil { 219 result.Err = model.NewAppError("SqlSessionStore.AnalyticsSessionCount", "store.sql_session.analytics_session_count.app_error", nil, err.Error(), http.StatusInternalServerError) 220 } else { 221 result.Data = c 222 } 223 }) 224 } 225 226 func (me SqlSessionStore) Cleanup(expiryTime int64, batchSize int64) { 227 mlog.Debug("Cleaning up session store.") 228 229 var query string 230 if me.DriverName() == model.DATABASE_DRIVER_POSTGRES { 231 query = "DELETE FROM Sessions WHERE Id = any (array (SELECT Id FROM Sessions WHERE ExpiresAt != 0 AND :ExpiresAt > ExpiresAt LIMIT :Limit))" 232 } else { 233 query = "DELETE FROM Sessions WHERE ExpiresAt != 0 AND :ExpiresAt > ExpiresAt LIMIT :Limit" 234 } 235 236 var rowsAffected int64 = 1 237 238 for rowsAffected > 0 { 239 if sqlResult, err := me.GetMaster().Exec(query, map[string]interface{}{"ExpiresAt": expiryTime, "Limit": batchSize}); err != nil { 240 mlog.Error(fmt.Sprintf("Unable to cleanup session store. err=%v", err.Error())) 241 return 242 } else { 243 var rowErr error 244 rowsAffected, rowErr = sqlResult.RowsAffected() 245 if rowErr != nil { 246 mlog.Error(fmt.Sprintf("Unable to cleanup session store. err=%v", err.Error())) 247 return 248 } 249 } 250 251 time.Sleep(SESSIONS_CLEANUP_DELAY_MILLISECONDS * time.Millisecond) 252 } 253 }