def get_id_from_cookie(self, role=False, for_site='', sites=False, name=False, email=False, altid=False, data=False):
# If for_site and site name does not appear in cookie.sites, None will be returned for role
# Null string will be returned for role, if site name is present
cookieStr = self.get_user_cookie()
if not cookieStr:
return None
try:
comps = [urllib.unquote(x) for x in cookieStr.split(':')]
##if Options['debug']:
##print >> sys.stderr, "DEBUG: sdserver.UserIdMixin.get_id_from_cookie", comps
userId, userRole, userSites, token, data_json = comps[:5]
userData = json.loads(base64.b64decode(data_json))
if role:
if not userRole and for_site:
if not userSites:
return None
return sdproxy.getSiteRole(for_site, userSites)
return userRole
if sites:
return userSites
if name:
return userData.get('name', '')
if email:
return userData.get('email', '')
if altid:
return userData.get('altid', '')
if data:
return userData
return userId
except Exception, err:
print >> sys.stderr, 'sdserver: COOKIE ERROR - '+str(err)
self.clear_user_cookie()
return None
python类debug()的实例源码
def get(self, subpath, inner=None):
userId = self.get_current_user()
if Options['debug'] and not self.get_argument('reload', ''):
print >> sys.stderr, 'DEBUG: ActionHandler.get', userId, Options['site_number'], subpath
if subpath == '_logout':
self.clear_user_cookie()
self.render('logout.html')
return
root = str(self.get_argument("root", ""))
token = str(self.get_argument("token", ""))
if not self.check_admin_access(token=token, root=root):
if self.previewActive() and subpath.startswith('_preview/') and not self.get_user_cookie():
next_url = '/' + subpath
if Options['site_name']:
next_url = '/'+Options['site_name']+next_url
self.redirect(Global.login_url+'?next='+urllib.quote_plus(next_url))
return
raise tornado.web.HTTPError(403, log_message='CUSTOM:<a href="/">Login</a> as admin to proceed %s' % self.previewActive())
try:
return self.getAction(subpath)
except Exception, excp:
msg = str(excp)
if msg.startswith('CUSTOM:') and not Options['debug']:
print >> sys.stderr, 'sdserver: '+msg
self.custom_error(500, '<html><body><h3>%s</h3></body></html>' % msg[len('CUSTOM:'):])
return
else:
raise
def post(self, subpath, inner=None):
userId = self.get_current_user()
if Options['debug']:
print >> sys.stderr, 'DEBUG: postAction', userId, Options['site_number'], subpath
if not self.check_admin_access():
raise tornado.web.HTTPError(403)
return self.postAction(subpath)
def put(self, subpath):
if Options['debug']:
print >> sys.stderr, 'DEBUG: putAction', Options['site_number'], subpath, len(self.request.body), self.request.arguments, self.request.headers.get('Content-Type')
action, sep, subsubpath = subpath.partition('/')
if action == '_remoteupload':
token = sliauth.gen_hmac_token(Options['auth_key'], 'upload:'+sliauth.digest_hex(self.request.body))
if self.get_argument('token') != token:
raise tornado.web.HTTPError(404, log_message='CUSTOM:Invalid remote upload token')
fname, fext = os.path.splitext(subsubpath)
uploadType, sessionNumber, src_path, web_path, web_images = self.getUploadType(fname)
errMsg = ''
if fext == '.zip':
fname1, fbody1, fname2, fbody2 = '', '', subsubpath, self.request.body
else:
fname1, fbody1, fname2, fbody2 = subsubpath, self.request.body, '', ''
if fbody1 and fext == '.md':
fbody1 = sliauth.normalize_newlines(fbody1)
try:
errMsg = self.uploadSession(uploadType, sessionNumber, fname1, fbody1, fname2, fbody2, modimages='clear')
except Exception, excp:
if Options['debug']:
import traceback
traceback.print_exc()
errMsg = str(excp)
if errMsg:
raise tornado.web.HTTPError(404, log_message='CUSTOM:Error in remote uploading session: '+errMsg)
self.set_status(200)
self.finish()
return
raise tornado.web.HTTPError(403, log_message='CUSTOM:Invalid PUT action '+action)
def reloadPreview(self, slideNumber=0):
previewingSession = self.previewActive()
if not previewingSession:
return
previewPath = '_preview/index.html'
if Options['site_name']:
previewPath = Options['site_name'] + '/' + previewPath
sessionConnections = WSHandler.get_connections('index')
userId = self.get_id_from_cookie()
userRole = self.get_id_from_cookie(role=True, for_site=Options['site_name'])
userConnections = sessionConnections.get(userId, [])
if Options['debug']:
print >> sys.stderr, 'sdserver.reloadPreview: slide=%s, conn=%s' % (slideNumber, len(userConnections))
for connection in userConnections:
connection.sendEvent(previewPath, '', userRole, ['', 1, 'ReloadPage', [slideNumber]])
def rebuild(self, uploadType='', indexOnly=False, make='', log_dict=False):
if uploadType:
utypes = [uploadType] if uploadType != TOP_LEVEL else []
else:
utypes = self.get_session_names()
if not indexOnly:
WSHandler.lockAllConnections('Site rebuilt. Reload page', reload=True)
msg_dict = {}
msg_list = []
if Options['debug'] :
print >> sys.stderr, 'sdserver.rebuild:', make, utypes
for utype in utypes:
retval = self.compile(utype, dest_dir=self.site_web_dir+privatePrefix(utype)+'/'+utype, indexOnly=indexOnly, make=make)
msgs = retval.get('messages',[])
msg_dict[utype] = msgs
if msgs:
msg_list += msgs + ['']
retval = self.compile(TOP_LEVEL, dest_dir=self.site_web_dir, indexOnly=False, make='')
msgs = retval.get('messages',[])
msg_dict[TOP_LEVEL] = msgs
if msgs:
msg_list += msgs
return msg_dict if log_dict else msg_list
def truncateSession(self, truncateParams, prevSessionName='', prevMsgs=[], rollingOver=False):
# Truncate session (possibly after rollover)
sessionName = truncateParams['sessionName']
sessionPath = getSessionPath(sessionName, site_prefix=True)
try:
errMsg = self.uploadSession(truncateParams['uploadType'], truncateParams['sessionNumber'], truncateParams['sessionName']+'.md', truncateParams['sessionText'], truncateParams['fname2'], truncateParams['fbody2'], modify='truncate', rollingOver=rollingOver)
except Exception, excp:
if Options['debug']:
import traceback
traceback.print_exc()
raise tornado.web.HTTPError(404, log_message='CUSTOM:Error in truncating rolled over session %s: %s' % (sessionName, excp))
if errMsg:
if self.previewState:
self.discardPreview()
if prevSessionName:
self.displayMessage('Error in truncating rolled over session '+sessionName+': '+errMsg, back_url=sessionPath)
else:
self.set_header('Content-Type', 'application/json')
retval = {'result': 'error', 'error': errMsg}
self.write( json.dumps(retval) )
return
self.previewState['modimages'] = 'clear'
previewPath = '/_preview/index.html'
if Options['site_name']:
previewPath = '/'+Options['site_name']+previewPath
if prevSessionName:
html_prefix = 'Rolled over %s slides from session %s to session %s. Proceed to preview of truncated session <a href="%s">%s</a>' % (truncateParams['slidesRolled'], sessionName, prevSessionName, previewPath, sessionName)
self.displayMessage(prevMsgs, html_prefix=html_prefix)
else:
self.set_header('Content-Type', 'application/json')
retval = {'result': 'success'}
self.write( json.dumps(retval) )
def extract_slides(self, src_path, web_path):
try:
return slidoc.extract_slides(src_path, web_path)
except Exception, excp:
if Options['debug']:
import traceback
traceback.print_exc()
raise tornado.web.HTTPError(404, log_message='CUSTOM:'+str(excp))
def setupInteractive(cls, connection, path, action, slideId='', questionAttrs=None, rollbackOption=None):
if Options['debug']:
print >> sys.stderr, 'sdserver.setupInteractive:', path, action, cls._interactiveSession
interactiveSession = UserIdMixin.get_path_base(cls._interactiveSession[1]) if cls._interactiveSession[1] else ''
basePath = UserIdMixin.get_path_base(path) if path else ''
if action == 'start':
if interactiveSession and interactiveSession != basePath:
raise Exception('There is already an interactive session: '+interactiveSession)
if not basePath:
return
cls._interactiveSession = (connection, path, slideId, questionAttrs)
cls._interactiveErrors = {}
if rollbackOption:
sdproxy.startTransactSession(basePath)
elif action in ('rollback', 'end'):
if not interactiveSession:
return
cls._interactiveSession = (None, '', '', None)
cls._interactiveErrors = {}
if sdproxy.transactionalSession(interactiveSession):
if action == 'rollback':
sdproxy.rollbackTransactSession(interactiveSession)
else:
sdproxy.endTransactSession(interactiveSession)
def closeConnections(cls, path, userIdList, excludeId=None):
# Note: closed connections may be automatically re-opened; use lockConnection to force reloads
sessionConnections = cls._connections.get(path,{})
for userId in userIdList:
if excludeId and userId == excludeId:
continue
if Options['debug']:
print >> sys.stderr, "DEBUG: sdserver.closeConnections", 'Closing connections for user:', userId
for connection in sessionConnections.get(userId,[])[:]: # connection list may be altered by close
connection.close()
def lockSessionConnections(cls, sessionName, lock_msg, reload=False):
# Lock all socket connections for specified session (for uploads/modifications)
# (Null string value for lock_msg unlocks)
if Options['debug']:
print >> sys.stderr, 'DEBUG: lockSessionConnections', sessionName, lock_msg, reload
for userId, connections in cls.get_connections(sessionName).items():
for connection in connections:
connection.locked = lock_msg
connection.write_message_safe(json.dumps([0, 'lock', [connection.locked, reload]] ))
if Options['debug']:
print >> sys.stderr, 'DEBUG: lockSessionConnections', 'DONE'
def open(self, path=''):
self.clientVersion = self.get_argument('version','')
self.msgTime = time.time()
self.locked = ''
self.timeout = None
self.userId = self.get_id_from_cookie()
self.pathUser = (path, self.userId)
self.sessionVersion = self.getSessionVersion(self.get_path_base(path))
self.userRole = self.get_id_from_cookie(role=True, for_site=Options['site_name'])
connectionList = self._connections[self.pathUser[0]][self.pathUser[1]]
if not connectionList:
connectionList.sd_role = self.userRole
connectionList.append(self)
self.pluginInstances = {}
self.awaitBinary = None
if Options['debug']:
print >> sys.stderr, "DEBUG: WSopen", sliauth.iso_date(nosubsec=True), self.pathUser, self.clientVersion
if not self.userId:
self.close()
self.eventBuffer = []
self.eventFlusher = PeriodicCallback(self.flushEventBuffer, EVENT_BUFFER_SEC*1000)
self.eventFlusher.start()
self.write_message_safe(json.dumps([0, 'session_setup', [self.sessionVersion] ]))
def write_message_safe(self, msg):
try:
self.write_message(msg)
except Exception, excp:
if Options['debug']:
print >> sys.stderr, 'DEBUG: write_message_safe: Error in write_message', self.pathUser, self.locked, str(excp)
def get_absolute_path(self, *args, **kwargs):
abs_path = super(AuthStaticFileHandler, self).get_absolute_path(*args, **kwargs)
if '?' in abs_path:
# Treat ? in path as the query delimiter (but not in get_current_user)
abs_path, _, self.abs_query = abs_path.partition('?')
if Options['debug']:
print >>sys.stderr, "AuthStaticFileHandler.get_absolute_path", abs_path, self.abs_query
return abs_path
def get(self):
if self.get_argument("oauth_token", None):
user = yield self.get_authenticated_user()
# Save the user using e.g. set_secure_cookie()
if Options['debug']:
print >> sys.stderr, "TwitterAuth: step 2 access_token =", user.get('access_token')
username = user['username']
if username.startswith('_') or username in (sdproxy.ADMINUSER_ID, sdproxy.TESTUSER_ID):
self.custom_error(500, 'Disallowed username: '+username, clear_cookies=True)
displayName = user['name']
role, sites = Global.userRoles.id_role_sites(username)
self.set_id(username, displayName=displayName, role=role, sites=sites)
self.redirect(self.get_argument("next", "/"))
else:
yield self.authorize_redirect()
def sendPrivateRequest(relay_address, path='/', proto='http'):
if Options['debug']:
print >> sys.stderr, 'DEBUG: sdserver.sendPrivateRequest:', relay_address, path
if isinstance(relay_address, tuple):
http_client = tornado.httpclient.HTTPClient()
url = proto+('://%s:%d' % relay_address)
return http_client.fetch(url+path, request_timeout=300)
else:
import multiproxy
sock = multiproxy.create_unix_client_socket(relay_address)
retval = sock.sendall('''GET %s HTTP/1.1\r\nHost: localhost\r\n\r\n''' % path)
sock.close()
return retval
def shutdown_server():
if Global.http_server:
Global.http_server.stop()
Global.http_server = None
if Global.server_socket:
try:
Global.server_socket.close()
except Exception, excp:
print >> sys.stderr, 'sdserver.shutdown_server: ERROR', sexcp
if Options['debug']:
print >> sys.stderr, 'sdserver.shutdown_server:'
def initialize(self, debug):
if debug:
self.write_error = self.write_debugger_error
def create_application(debug=False):
handlers = [
('/error/', BadHandler, {'debug': debug}),
]
if debug:
return DebugApplication(handlers, debug=True)
return Application(handlers, debug=debug)