Skip to content

Commit 0a9a484

Browse files
zeripath6543techknowlogicklunny
authored
Create DB session provider(based on xorm) (#13031)
* Create Xorm session provider This PR creates a Xorm session provider which creates the appropriate Session table for macaron/session. Fix #7137 Signed-off-by: Andrew Thornton <[email protected]> * extraneous l Signed-off-by: Andrew Thornton <[email protected]> * fix lint Signed-off-by: Andrew Thornton <[email protected]> * use key instead of ID to be compatible with go-macaron/session Signed-off-by: Andrew Thornton <[email protected]> * And change the migration too. Signed-off-by: Andrew Thornton <[email protected]> * Update spacing of imports Co-authored-by: 6543 <[email protected]> * Update modules/session/xorm.go Co-authored-by: techknowlogick <[email protected]> * add xorm provider to the virtual provider Signed-off-by: Andrew Thornton <[email protected]> * prep for master merge * prep for merge master * As per @lunny * move migration out of the way * Move to call this db session as per @lunny Signed-off-by: Andrew Thornton <[email protected]> Co-authored-by: 6543 <[email protected]> Co-authored-by: techknowlogick <[email protected]> Co-authored-by: Lunny Xiao <[email protected]>
1 parent fc4a8c2 commit 0a9a484

File tree

8 files changed

+321
-2
lines changed

8 files changed

+321
-2
lines changed

docs/content/doc/advanced/config-cheat-sheet.en-us.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ Define allowed algorithms and their minimum key length (use -1 to disable a type
551551

552552
## Session (`session`)
553553

554-
- `PROVIDER`: **memory**: Session engine provider \[memory, file, redis, mysql, couchbase, memcache, postgres\].
554+
- `PROVIDER`: **memory**: Session engine provider \[memory, file, redis, db, mysql, couchbase, memcache, postgres\].
555555
- `PROVIDER_CONFIG`: **data/sessions**: For file, the root path; for others, the connection string.
556556
- `COOKIE_SECURE`: **false**: Enable this to force using HTTPS for all session access.
557557
- `COOKIE_NAME`: **i\_like\_gitea**: The name of the cookie used for the session ID.

models/migrations/migrations.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,8 @@ var migrations = []Migration{
290290
NewMigration("Add Dismissed to Review table", addDismissedReviewColumn),
291291
// v171 -> v172
292292
NewMigration("Add Sorting to ProjectBoard table", addSortingColToProjectBoard),
293+
// v172 -> v173
294+
NewMigration("Add sessions table for go-chi/session", addSessionTable),
293295
}
294296

295297
// GetCurrentDBVersion returns the current db version

models/migrations/v172.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Copyright 2020 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package migrations
6+
7+
import (
8+
"code.gitea.io/gitea/modules/timeutil"
9+
10+
"xorm.io/xorm"
11+
)
12+
13+
func addSessionTable(x *xorm.Engine) error {
14+
type Session struct {
15+
Key string `xorm:"pk CHAR(16)"`
16+
Data []byte `xorm:"BLOB"`
17+
CreatedUnix timeutil.TimeStamp
18+
}
19+
return x.Sync2(new(Session))
20+
}

models/models.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ func init() {
132132
new(Project),
133133
new(ProjectBoard),
134134
new(ProjectIssue),
135+
new(Session),
135136
)
136137

137138
gonicNames := []string{"SSL", "UID"}

models/session.go

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
// Copyright 2020 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package models
6+
7+
import (
8+
"fmt"
9+
10+
"code.gitea.io/gitea/modules/timeutil"
11+
)
12+
13+
// Session represents a session compatible for go-chi session
14+
type Session struct {
15+
Key string `xorm:"pk CHAR(16)"` // has to be Key to match with go-chi/session
16+
Data []byte `xorm:"BLOB"`
17+
Expiry timeutil.TimeStamp // has to be Expiry to match with go-chi/session
18+
}
19+
20+
// UpdateSession updates the session with provided id
21+
func UpdateSession(key string, data []byte) error {
22+
_, err := x.ID(key).Update(&Session{
23+
Data: data,
24+
Expiry: timeutil.TimeStampNow(),
25+
})
26+
return err
27+
}
28+
29+
// ReadSession reads the data for the provided session
30+
func ReadSession(key string) (*Session, error) {
31+
session := Session{
32+
Key: key,
33+
}
34+
sess := x.NewSession()
35+
defer sess.Close()
36+
if err := sess.Begin(); err != nil {
37+
return nil, err
38+
}
39+
40+
if has, err := sess.Get(&session); err != nil {
41+
return nil, err
42+
} else if !has {
43+
session.Expiry = timeutil.TimeStampNow()
44+
_, err := sess.Insert(&session)
45+
if err != nil {
46+
return nil, err
47+
}
48+
}
49+
50+
return &session, sess.Commit()
51+
}
52+
53+
// ExistSession checks if a session exists
54+
func ExistSession(key string) (bool, error) {
55+
session := Session{
56+
Key: key,
57+
}
58+
return x.Get(&session)
59+
}
60+
61+
// DestroySession destroys a session
62+
func DestroySession(key string) error {
63+
_, err := x.Delete(&Session{
64+
Key: key,
65+
})
66+
return err
67+
}
68+
69+
// RegenerateSession regenerates a session from the old id
70+
func RegenerateSession(oldKey, newKey string) (*Session, error) {
71+
sess := x.NewSession()
72+
defer sess.Close()
73+
if err := sess.Begin(); err != nil {
74+
return nil, err
75+
}
76+
77+
if has, err := sess.Get(&Session{
78+
Key: newKey,
79+
}); err != nil {
80+
return nil, err
81+
} else if has {
82+
return nil, fmt.Errorf("session Key: %s already exists", newKey)
83+
}
84+
85+
if has, err := sess.Get(&Session{
86+
Key: oldKey,
87+
}); err != nil {
88+
return nil, err
89+
} else if !has {
90+
_, err := sess.Insert(&Session{
91+
Key: oldKey,
92+
Expiry: timeutil.TimeStampNow(),
93+
})
94+
if err != nil {
95+
return nil, err
96+
}
97+
}
98+
99+
if _, err := sess.Exec("UPDATE "+sess.Engine().TableName(&Session{})+" SET `key` = ? WHERE `key`=?", newKey, oldKey); err != nil {
100+
return nil, err
101+
}
102+
103+
s := Session{
104+
Key: newKey,
105+
}
106+
if _, err := sess.Get(&s); err != nil {
107+
return nil, err
108+
}
109+
110+
return &s, sess.Commit()
111+
}
112+
113+
// CountSessions returns the number of sessions
114+
func CountSessions() (int64, error) {
115+
return x.Count(&Session{})
116+
}
117+
118+
// CleanupSessions cleans up expired sessions
119+
func CleanupSessions(maxLifetime int64) error {
120+
_, err := x.Where("created_unix <= ?", timeutil.TimeStampNow().Add(-maxLifetime)).Delete(&Session{})
121+
return err
122+
}

modules/session/db.go

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
// Copyright 2020 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package session
6+
7+
import (
8+
"log"
9+
"sync"
10+
11+
"code.gitea.io/gitea/models"
12+
"code.gitea.io/gitea/modules/timeutil"
13+
14+
"gitea.com/go-chi/session"
15+
)
16+
17+
// DBStore represents a session store implementation based on the DB.
18+
type DBStore struct {
19+
sid string
20+
lock sync.RWMutex
21+
data map[interface{}]interface{}
22+
}
23+
24+
// NewDBStore creates and returns a DB session store.
25+
func NewDBStore(sid string, kv map[interface{}]interface{}) *DBStore {
26+
return &DBStore{
27+
sid: sid,
28+
data: kv,
29+
}
30+
}
31+
32+
// Set sets value to given key in session.
33+
func (s *DBStore) Set(key, val interface{}) error {
34+
s.lock.Lock()
35+
defer s.lock.Unlock()
36+
37+
s.data[key] = val
38+
return nil
39+
}
40+
41+
// Get gets value by given key in session.
42+
func (s *DBStore) Get(key interface{}) interface{} {
43+
s.lock.RLock()
44+
defer s.lock.RUnlock()
45+
46+
return s.data[key]
47+
}
48+
49+
// Delete delete a key from session.
50+
func (s *DBStore) Delete(key interface{}) error {
51+
s.lock.Lock()
52+
defer s.lock.Unlock()
53+
54+
delete(s.data, key)
55+
return nil
56+
}
57+
58+
// ID returns current session ID.
59+
func (s *DBStore) ID() string {
60+
return s.sid
61+
}
62+
63+
// Release releases resource and save data to provider.
64+
func (s *DBStore) Release() error {
65+
// Skip encoding if the data is empty
66+
if len(s.data) == 0 {
67+
return nil
68+
}
69+
70+
data, err := session.EncodeGob(s.data)
71+
if err != nil {
72+
return err
73+
}
74+
75+
return models.UpdateSession(s.sid, data)
76+
}
77+
78+
// Flush deletes all session data.
79+
func (s *DBStore) Flush() error {
80+
s.lock.Lock()
81+
defer s.lock.Unlock()
82+
83+
s.data = make(map[interface{}]interface{})
84+
return nil
85+
}
86+
87+
// DBProvider represents a DB session provider implementation.
88+
type DBProvider struct {
89+
maxLifetime int64
90+
}
91+
92+
// Init initializes DB session provider.
93+
// connStr: username:password@protocol(address)/dbname?param=value
94+
func (p *DBProvider) Init(maxLifetime int64, connStr string) error {
95+
p.maxLifetime = maxLifetime
96+
return nil
97+
}
98+
99+
// Read returns raw session store by session ID.
100+
func (p *DBProvider) Read(sid string) (session.RawStore, error) {
101+
s, err := models.ReadSession(sid)
102+
if err != nil {
103+
return nil, err
104+
}
105+
106+
var kv map[interface{}]interface{}
107+
if len(s.Data) == 0 || s.Expiry.Add(p.maxLifetime) <= timeutil.TimeStampNow() {
108+
kv = make(map[interface{}]interface{})
109+
} else {
110+
kv, err = session.DecodeGob(s.Data)
111+
if err != nil {
112+
return nil, err
113+
}
114+
}
115+
116+
return NewDBStore(sid, kv), nil
117+
}
118+
119+
// Exist returns true if session with given ID exists.
120+
func (p *DBProvider) Exist(sid string) bool {
121+
has, err := models.ExistSession(sid)
122+
if err != nil {
123+
panic("session/DB: error checking existence: " + err.Error())
124+
}
125+
return has
126+
}
127+
128+
// Destroy deletes a session by session ID.
129+
func (p *DBProvider) Destroy(sid string) error {
130+
return models.DestroySession(sid)
131+
}
132+
133+
// Regenerate regenerates a session store from old session ID to new one.
134+
func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
135+
s, err := models.RegenerateSession(oldsid, sid)
136+
if err != nil {
137+
return nil, err
138+
139+
}
140+
141+
var kv map[interface{}]interface{}
142+
if len(s.Data) == 0 || s.Expiry.Add(p.maxLifetime) <= timeutil.TimeStampNow() {
143+
kv = make(map[interface{}]interface{})
144+
} else {
145+
kv, err = session.DecodeGob(s.Data)
146+
if err != nil {
147+
return nil, err
148+
}
149+
}
150+
151+
return NewDBStore(sid, kv), nil
152+
}
153+
154+
// Count counts and returns number of sessions.
155+
func (p *DBProvider) Count() int {
156+
total, err := models.CountSessions()
157+
if err != nil {
158+
panic("session/DB: error counting records: " + err.Error())
159+
}
160+
return int(total)
161+
}
162+
163+
// GC calls GC to clean expired sessions.
164+
func (p *DBProvider) GC() {
165+
if err := models.CleanupSessions(p.maxLifetime); err != nil {
166+
log.Printf("session/DB: error garbage collecting: %v", err)
167+
}
168+
}
169+
170+
func init() {
171+
session.Register("db", &DBProvider{})
172+
}

modules/session/virtual.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ func (o *VirtualSessionProvider) Init(gclifetime int64, config string) error {
3939
o.provider = &session.FileProvider{}
4040
case "redis":
4141
o.provider = &RedisProvider{}
42+
case "db":
43+
o.provider = &DBProvider{}
4244
case "mysql":
4345
o.provider = &mysql.MysqlProvider{}
4446
case "postgres":

modules/setting/session.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ var (
4141
func newSessionService() {
4242
sec := Cfg.Section("session")
4343
SessionConfig.Provider = sec.Key("PROVIDER").In("memory",
44-
[]string{"memory", "file", "redis", "mysql", "postgres", "couchbase", "memcache"})
44+
[]string{"memory", "file", "redis", "mysql", "postgres", "couchbase", "memcache", "db"})
4545
SessionConfig.ProviderConfig = strings.Trim(sec.Key("PROVIDER_CONFIG").MustString(path.Join(AppDataPath, "sessions")), "\" ")
4646
if SessionConfig.Provider == "file" && !filepath.IsAbs(SessionConfig.ProviderConfig) {
4747
SessionConfig.ProviderConfig = path.Join(AppWorkPath, SessionConfig.ProviderConfig)

0 commit comments

Comments
 (0)