focalboard/server/services/store/sqlstore/session.go

112 lines
2.5 KiB
Go
Raw Normal View History

2020-12-02 21:12:14 +01:00
package sqlstore
import (
"encoding/json"
"time"
sq "github.com/Masterminds/squirrel"
2021-01-26 23:13:46 +01:00
"github.com/mattermost/focalboard/server/model"
2020-12-02 21:12:14 +01:00
)
2021-01-27 19:01:24 +01:00
// GetActiveUserCount returns the number of users with active sessions within N seconds ago
func (s *SQLStore) GetActiveUserCount(updatedSecondsAgo int64) (int, error) {
query := s.getQueryBuilder().
Select("count(distinct user_id)").
From("sessions").
Where(sq.Gt{"update_at": time.Now().Unix() - updatedSecondsAgo})
row := query.QueryRow()
var count int
err := row.Scan(&count)
if err != nil {
return 0, err
}
return count, nil
}
2020-12-07 17:04:35 +01:00
func (s *SQLStore) GetSession(token string, expireTime int64) (*model.Session, error) {
2020-12-02 21:12:14 +01:00
query := s.getQueryBuilder().
Select("id", "token", "user_id", "props").
From("sessions").
2020-12-07 17:04:35 +01:00
Where(sq.Eq{"token": token}).
Where(sq.Gt{"update_at": time.Now().Unix() - expireTime})
2020-12-02 21:12:14 +01:00
row := query.QueryRow()
session := model.Session{}
var propsBytes []byte
err := row.Scan(&session.ID, &session.Token, &session.UserID, &propsBytes)
if err != nil {
return nil, err
}
err = json.Unmarshal(propsBytes, &session.Props)
if err != nil {
return nil, err
}
return &session, nil
}
func (s *SQLStore) CreateSession(session *model.Session) error {
now := time.Now().Unix()
propsBytes, err := json.Marshal(session.Props)
if err != nil {
return err
}
query := s.getQueryBuilder().Insert("sessions").
Columns("id", "token", "user_id", "props", "create_at", "update_at").
Values(session.ID, session.Token, session.UserID, propsBytes, now, now)
_, err = query.Exec()
return err
}
func (s *SQLStore) RefreshSession(session *model.Session) error {
now := time.Now().Unix()
query := s.getQueryBuilder().Update("sessions").
2021-01-27 19:01:24 +01:00
Where(sq.Eq{"token": session.Token}).
2020-12-02 21:12:14 +01:00
Set("update_at", now)
_, err := query.Exec()
return err
}
func (s *SQLStore) UpdateSession(session *model.Session) error {
now := time.Now().Unix()
propsBytes, err := json.Marshal(session.Props)
if err != nil {
return err
}
query := s.getQueryBuilder().Update("sessions").
2021-01-27 19:24:19 +01:00
Where(sq.Eq{"token": session.Token}).
2020-12-02 21:12:14 +01:00
Set("update_at", now).
Set("props", propsBytes)
_, err = query.Exec()
return err
}
func (s *SQLStore) DeleteSession(sessionId string) error {
query := s.getQueryBuilder().Delete("sessions").
Where("id", sessionId)
_, err := query.Exec()
return err
}
2020-12-07 17:04:35 +01:00
func (s *SQLStore) CleanUpSessions(expireTime int64) error {
query := s.getQueryBuilder().Delete("sessions").
Where(sq.Lt{"update_at": time.Now().Unix() - expireTime})
_, err := query.Exec()
return err
}