-
Notifications
You must be signed in to change notification settings - Fork 3
/
Session.py
246 lines (207 loc) · 7.72 KB
/
Session.py
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
from Config import *
from UserInfo import UserInfo
from Util import Util
import Utmp
import modes
import User
import UCache
import time
import os
import json
import sqlite3
import datetime
import UserManager
from Log import Log
from errors import *
class Session:
def GetID(self):
return self.sessionid
def GetUserName(self):
return self.username
def GetUser(self):
return self.user
@staticmethod
def IsTimeout(created):
return (datetime.datetime.now() - created > SESSION_TIMEOUT)
def Timeout(self):
return Session.IsTimeout(self.created)
@staticmethod
def GET(svc, session, params, action):
if (action == 'verify'):
SessionManager.VerifySession(svc, session, params)
else:
raise WrongArgs("unknown action")
@staticmethod
def POST(svc, session, params, action):
raise WrongArgs("unknown action")
def __init__(self, user, fromip, _sessionid = None, _created = None, scopes = ['auth']):
self.username = user.name
self.uid = UCache.UCache.SearchUser(self.username)
if (_sessionid is None):
self.sessionid = Util.RandomStr(SESSIONID_LEN)
self.created = datetime.datetime.now()
else:
self.sessionid = _sessionid
self.created = _created
self.user = UserManager.UserManager.LoadUser(user.name)
self._userinfo = None
self.utmpent = -1
self._fromip = fromip
self.scopes = scopes
SessionManager.Insert(self)
if (_sessionid is None):
SessionManager.Record(self)
else:
SessionManager.Update(self)
def InitNewUserInfo(self):
userinfo = UserInfo()
userinfo.active = 1
userinfo.pid = os.getpid()
if ((self.user.HasPerm(User.PERM_CHATCLOAK) or self.user.HasPerm(User.PERM_CLOAK)) and (self.user.HasFlag(User.CLOAK_FLAG))):
userinfo.invisible = 1
userinfo.mode = modes.XMPP
userinfo.pager = 0
if (self.user.Defined(User.DEF_FRIENDCALL)):
userinfo.pager |= User.FRIEND_PAGER
if (self.user.HasFlag(User.PAGER_FLAG)):
userinfo.pager |= User.ALL_PAGER
userinfo.pager |= User.FRIEND_PAGER
if (self.user.Defined(User.DEF_FRIENDMSG)):
userinfo.pager |= User.FRIENDMSG_PAGER
if (self.user.Defined(User.DEF_ALLMSG)):
userinfo.pager |= User.ALLMSG_PAGER
userinfo.pager |= User.FRIENDMSG_PAGER
userinfo.uid = self.uid
setattr(userinfo, 'from', self._fromip)
userinfo.freshtime = int(time.time())
userinfo.userid = self.username
userinfo.realname = 'ANONYMOUS' # XXX: fix later
userinfo.username = self.user.userec.username
return userinfo
def Register(self):
# register this session (so TERM users can see me)
userinfo = self.InitNewUserInfo()
self.utmpent = Utmp.Utmp.GetNewUtmpEntry(userinfo)
if (self.utmpent == -1):
return None
Log.debug("assigned utmp %d to new user" % self.utmpent)
self.user.GetFriends(userinfo)
userinfo.save()
self._userinfo = userinfo
return userinfo
def Unregister(self):
if (self.utmpent < 0):
Log.error("Unregister() without Register() or failed!")
return False
Utmp.Utmp.Clear(self.utmpent, self.uid, self._userinfo.pid)
return True
def RecordLogin(self, count = False):
self.user.RecordLogin(self._fromip, self._userinfo, count)
def GetMirror(self, port = 0):
server = Config.GetString("BBS_WEBDOMAIN", "")
if (not server):
server = Config.GetString("BBSDOMAIN", "")
if (not server):
raise ServerError("can't get server domain")
return server
def CheckScope(self, scope):
return scope in self.scopes
def GetScopesStr(self):
return ','.join(self.scopes)
def GetUserInfo(self):
return self._userinfo
class SessionManager:
sessions = {}
@staticmethod
def Insert(session):
SessionManager.sessions[session.sessionid] = session
@staticmethod
def Record(session):
conn = SessionManager.ConnectDB()
try:
now = datetime.datetime.now()
conn.execute("insert into sessions values (?, ?, ?, ?, ?, ?, ?)", (session.sessionid, session.username, now, now, session._fromip, session._fromip, session.GetScopesStr()))
conn.commit()
finally:
conn.close()
@staticmethod
def Update(session):
conn = SessionManager.ConnectDB()
try:
now = datetime.datetime.now()
conn.execute("update sessions set last_seen = ?, last_ip = ? where id = ?", (now, session._fromip, session.sessionid))
conn.commit()
finally:
conn.close()
@staticmethod
def ConnectDB():
conn = sqlite3.connect(BBS_ROOT + "auth.db", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
conn.row_factory = sqlite3.Row
try:
conn.execute("select * from sessions")
except sqlite3.OperationalError:
SessionManager.InitDB(conn);
return conn
@staticmethod
def InitDB(conn):
conn.execute("create table sessions(id text, username text, created timestamp, last_seen timestamp, login_ip text, last_ip text, scopes text)")
conn.execute("create index if not exists idx_id_sessions on sessions ( id )")
conn.commit()
@staticmethod
def CheckSession(id):
if id not in SessionManager.sessions:
conn = SessionManager.ConnectDB()
try:
for row in conn.execute("select * from sessions where id = ?", (id, )):
created = row['created']
if not Session.IsTimeout(created):
return row['username']
else:
return None
return None
finally:
conn.close()
session = SessionManager.sessions[id]
if session.Timeout():
return None
return session.username
@staticmethod
def GetSession(id, fromip):
now = datetime.datetime.now()
if (id not in SessionManager.sessions):
conn = SessionManager.ConnectDB()
try:
for row in conn.execute("select * from sessions where id = ?", (id, )):
username = row['username']
user = UserManager.UserManager.LoadUser(username)
if (user is None):
continue
created = row['created']
scopes = row['scopes'].split(',')
session = Session(user, fromip, id, created, scopes)
if (session.Timeout()):
return None
session.RecordLogin()
return session
return None
finally:
conn.close()
session = SessionManager.sessions[id]
if (session.Timeout()):
return None
session._fromip = fromip
SessionManager.Update(session)
session.RecordLogin()
return session
@staticmethod
def VerifySession(svc, session, params):
if (session == None):
svc.return_error(404, "session not found or session timed out")
else:
if not session.CheckScope('bbs') and not session.CheckScope('auth'): raise NoPerm("out of scope")
result = {}
result['status'] = "ok"
svc.writedata(json.dumps(result))
class BasicSession(object):
def __init__(self, fromip):
self._fromip = fromip