Attachment 'xenforo.py'

Download

   1 # -*- coding: iso-8859-1 -*-
   2 """
   3     MoinMoin - Authentication against xenforo
   4 
   5     if we have a cookie in the format: xf_session=bxxxx27f98162681a2b45150fe36065b
   6     then we look in the xf_session table for session_id = <cookie>.
   7     if the row doesn't exist, deny
   8     if that row exists, it will be like:
   9 	session_id = bxxxx27f98162681a2b45150fe36065b
  10 	session_data = a:7:{s:12:"sessionStart";i:1342373577;s:2:"ip";b:0;s:7:"user_id";i:1;s:16:"previousActivity";i:1342373565;s:16:"dismissedNotices";a:0:{}s:12:"reportCounts";a:3:{s:5:"total";i:0;s:8:"assigned";i:0;s:13:"lastBuildDate";i:1342373577;}s:16:"moderationCounts";a:2:{s:5:"total";i:0;s:13:"lastBuildDate";i:1342373577;}}
  11 	expiry_date = 1342378332
  12     if now() > expiry_date then deny
  13     else we then parse out the user_id;i;1;s;16 bit.
  14     The user_id == 1 from above, we look for in xf_user table:
  15 	user_id == 1
  16 	username == donbowman
  17 
  18     @copyright: 2012 Don Bowman (don.waterloo@gmail.com)
  19     @license: GNU GPL, see COPYING for details.
  20 """
  21 
  22 from MoinMoin import log
  23 logging = log.getLogger(__name__)
  24 
  25 import MySQLdb
  26 import urllib, sys, re, time
  27 import traceback
  28 from MoinMoin import user
  29 from MoinMoin.auth import BaseAuth
  30 
  31 class XenforoAuth(BaseAuth):
  32     """ authenticate to Xenforo database from the xf_session cookie
  33     """
  34     name = 'xenforo_session'
  35 
  36     def __init__(self, autocreate=True):
  37         """ @param autocreate: if true then create the user on first run
  38         """
  39         BaseAuth.__init__(self)
  40         self.autocreate = autocreate
  41 
  42     def request(self, request, user_obj, **kw):
  43 	username = kw.get('name')
  44 	password = kw.get('password')
  45 	login = kw.get('login')
  46 	user_obj = kw.get('user_obj')
  47 	cfg = request.cfg
  48 
  49         cookie = kw.get('cookie')
  50         if cookie is None:
  51 	    logging.error("xenforo: no cookies")
  52 	    return user_obj, True
  53 	try:
  54 	    session_id = cookie['xf_session']
  55 	except:
  56 	    info = sys.exc_info()
  57 	    logging.error("xenforo: no xf_session cookie")
  58 	    return user_obj, True
  59 
  60 	# To avoid hammering the mysql, store in a session variable
  61 	if (request.session.new == False):
  62 	    if 'xf_username' in request.session:
  63 		logging.info("use %s for username from session" % request.session['xf_username'])
  64 		u = user.User(request,
  65 		              name=request.session['xf_username'],
  66 			      auth_username=request.session['xf_username'],
  67 			      auth_method=self.name)
  68 		if u and self.autocreate:
  69 		    u.create_or_update(False)
  70 		if u and u.valid:
  71 		    return u, True # True to get other methods called, too
  72 
  73 	try:
  74 	    connection = MySQLdb.connect(host=cfg.auth_xenforo_mysql_host,
  75 					 user=cfg.auth_xenforo_mysql_user,
  76 					 passwd=cfg.auth_xenforo_mysql_pass,
  77 					 db=cfg.auth_xenforo_mysql_db)
  78 	    cursor = connection.cursor()
  79 	    cursor.execute("SELECT session_id, session_data, expiry_date " +
  80 	                   "FROM xf_session " +
  81 			   "WHERE session_id = '" + session_id + "'")
  82 	    data = cursor.fetchall()
  83 	    if (len(data) != 0):
  84 		# now check expiry as data[0][2]
  85 		if (time.time() > data[0][2]):
  86 		    logging.error("session has expired for %s" % session_id)
  87 		else:
  88 		    # OK, now we know the user is valid, has a valid session, lets
  89 		    # get their name from xf_user after parsing the user_id from the string
  90 		    # <i'm not really sure what the encoding is of this string>
  91 		    partial = re.sub('.*"user_id";i:','',data[0][1],1)
  92 		    user_id = re.sub(';.*','',partial)
  93 		    cursor.execute("SELECT username " +
  94 				   "FROM xf_user " +
  95 				   "WHERE user_id = '" + user_id + "'")
  96 		    data = cursor.fetchall()
  97 		    if (len(data) != 1):
  98 			logging.error("invalid user_id %s, got %d rows" % (user_id, len(data)))
  99 		    else:
 100 			username = data[0][0]
 101 			request.session['xf_username'] = username
 102 			logging.info("Username %s has logged in" % username)
 103 			u = user.User(request, name=username, auth_username=username, auth_method=self.name)
 104 			if u and self.autocreate:
 105 			    u.create_or_update(False)
 106 			if u and u.valid:
 107 			    return u, True # True to get other methods called, too
 108 	    else:
 109 		logging.error("session %s doesn't exist in db" % session_id)
 110 	except:
 111 	    info = sys.exc_info()
 112 	    logging.error("xenforo: caught an exception, traceback follows...")
 113 	    logging.error(''.join(traceback.format_exception(*info)))
 114 
 115         return user_obj, True # continue with next method in auth list

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2012-07-15 20:57:57, 4.2 KB) [[attachment:xenforo.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.