Newer
Older
Digital_Repository / Old / pysocks / auth.py
nstanger on 12 Nov 2005 9 KB - Second attempt at importing!
  1. #! /usr/bin/python
  2.  
  3. #------------------------------------------------------------------------
  4. # name:
  5. # author: J Skinner
  6. # Date Written:
  7. # Purpose:
  8. # Notes
  9. #------------------------------------------------------------------------
  10.  
  11.  
  12.  
  13. #------------------------ GLOBALS ------------------------------------
  14.  
  15. DEBUG_MAIN = 0
  16. DEBUG = 0
  17. IS_CGI = 1
  18. IS_DB = 1
  19.  
  20. #------------------------ IMPORTS ------------------------------------
  21.  
  22. import string
  23. import os
  24. import sys
  25.  
  26. import cgi
  27. import traceback
  28.  
  29. import MySQLdb
  30. import access
  31. import Cookie
  32.  
  33. from the_form import The_Form
  34.  
  35.  
  36. TEMPLATE_DIR = '/home/joe/Work/pysocks/'
  37.  
  38. def get_file_as_string(fname):
  39. return '\n'.join(open(fname, 'r').readlines())
  40.  
  41.  
  42. class Auth:
  43. auth_exception = 'authentication exception'
  44. # error pages start at id 10000
  45. ERROR_PAGE = 10001
  46. __logout_link = '<a href="./index.cgi?action=logout">logout</a>'
  47. __login_link = '<a href="./index.cgi?action=login">login</a>'
  48.  
  49. def test(self):
  50. print 'visted', self.__visted, '<br>'
  51. print 'auth_level', self.auth_level, '<br>'
  52. print 'user_id', self.__user_id, '<br>'
  53. print 'cookie', self.__cookie, '<br>'
  54. print 'auth_id', self.__auth_id, '<br>'
  55. print 'set_cookie', self.__set_cookie, '<br>'
  56. print
  57. print 'logged_in', self.__logged_in, '<br>'
  58. #print 'cookie', self.__cookie['pysocks_id'].value, '<br>'
  59. #print 'env cookie', os.environ['HTTP_COOKIE'], '<br>'
  60. #print 'form_data', `self.__form_data`
  61.  
  62. def __init__(self, db, form_data=None):
  63. self.__visted = []
  64. self.__form_data = form_data
  65. self.__db = db
  66. self.auth_level = 0
  67. self.__user_id = None
  68. self.__cookie = None
  69. self.__auth_id = None
  70. self.__set_cookie = None
  71. self.do_login = None
  72. self.do_logout = None
  73. self.do_download = None
  74. self.__logged_in = None
  75.  
  76. self.__setup()
  77.  
  78. if self.__form_data.action == 'login':
  79. self.do_login = 1
  80. elif self.__form_data.action == 'login_check':
  81. self.login_check()
  82. elif self.__form_data.action == 'logout':
  83. self.do_logout = 1
  84. self.logout()
  85. elif self.__form_data.action == 'download':
  86. self.do_download = 1
  87.  
  88. def __setup(self):
  89. if os.environ.has_key('HTTP_COOKIE'):
  90. self.__visted.append('setup: environ check')
  91. self.__cookie = Cookie.SmartCookie(os.environ['HTTP_COOKIE'])
  92. else:
  93. self.__cookie = Cookie.SmartCookie()
  94.  
  95. if self.__cookie.has_key('pysocks_id'):
  96. self.__visted.append('setup: cookie key')
  97. self.__user_id = self.__cookie['pysocks_id'].value
  98. try:
  99. self.__auth_id, self.__status = self.__db.get('auth',
  100. ['auth_id', 'status'],
  101. where='auth_id="%s"'%self.__user_id)[0]
  102. self.__visted.append('setup: %s'%self.__auth_id)
  103. if self.__status not in [-1, 0]:
  104. self.__logged_in = 1
  105. except self.__db.NO_DATA:
  106. # something wrong - maybe the cookie has been expired.
  107. # set the cookie to the active but not logged in status
  108. # 0 and give the person a new auth record.
  109.  
  110. self.__auth_id = self.__db.put('auth', {'status':'0'} )
  111.  
  112. self.__cookie['pysocks_id'] = self.__auth_id
  113. self.__visted.append('setup: except clause')
  114.  
  115. else:
  116. # we have no cookie set it up
  117. # check to see that the login isn't expired
  118. self.__auth_id = self.__db.put('auth', {'status':'0'} )
  119.  
  120. self.__cookie['pysocks_id'] = self.__auth_id
  121.  
  122. # if expired send them to a login screen or an error screen
  123. # not sure which.
  124.  
  125. # get further details.
  126.  
  127. # user_info = self.__db.get_dict('user', [...],
  128. # where='auth_id="%s"'%self.__auth_id)[0]
  129.  
  130. def show_login(self):
  131. # this is a temp hack.
  132. self.__set_cookie = 1
  133. print get_file_as_string(Template_DIR+'login.html')
  134.  
  135. def login_check(self):
  136. # this is broken fix.
  137. self.__visted.append('login_check')
  138.  
  139. if self.__form_data.username and \
  140. self.__form_data.passwd:
  141. pass
  142. else:
  143. # we have a bad password bail out.
  144. return -1, 1000
  145.  
  146. try:
  147. results = self.__db.get_dict('users',
  148. ['username', 'passwd', 'user_id', 'auth_level'],
  149. where='username="%s" and passwd="%s"'%(
  150. self.__form_data.username, self.__form_data.passwd))[0]
  151. self.__db.set('auth', {'status':1},
  152. where='auth_id="%s"'%self.__auth_id)
  153. self.auth_level = results['auth_level']
  154. self.__logged_in = 1
  155. except self.__db.NO_DATA:
  156. return -1, 1000
  157.  
  158. return 1, 1
  159. def logout(self):
  160. '''\
  161. expire the cookie to logout the person and
  162. update the status in the db'''
  163.  
  164. try:
  165. self.__db.set('auth', {'status':0},
  166. where='auth_id=%s'%self.__cookie['pysocks_id'].value)
  167. except:
  168. self.__visted.append('logout: Error in auth.logout()')
  169.  
  170. self.__cookie['pysocks_id'] = 0
  171. self.__logged_in = 0
  172. self.__visted.append('logout: %s'%self.__logged_in)
  173. self.__visted.append('logout: %s'%str(self.__cookie))
  174.  
  175.  
  176. def is_logged_in(self):
  177. return self.__logged_in
  178. def __get_cookie(self):
  179. if os.environ.has_key('HTTP_COOKIE'):
  180. self.__cookie.load(os.environ['HTTP_COOKIE'])
  181. self.__user_id = self.__cookie['pysocks_id']
  182.  
  183. # query the database to check if this is still valid.
  184.  
  185. try:
  186. self.__user_id, self.auth_level = \
  187. self.__db.get_dict('auth', ['logged_in'],
  188. where='id=%s'%self.__cockie['user_id', 'auth_level'])[0]
  189. except self.__db.NO_DATA:
  190. # no one home.
  191. # generate an error
  192. raise self.auth_exception
  193.  
  194.  
  195. def error_page(self):
  196. return Page(self.__ERROR_PAGE)
  197. pass
  198.  
  199. def show(self):
  200. return self.__cookie
  201.  
  202. def login_status(self):
  203. self.__visted.append('login status %s'%self.__logged_in)
  204. if self.__logged_in:
  205. return 'Currently Logged in | %s'%self.__logout_link
  206. else:
  207. return 'Not logged in | %s'%self.__login_link
  208.  
  209. def get_cookie_header(self):
  210. #self.__cookie['pysocks_id'] = self.__auth_id
  211. return str(self.__cookie)
  212.  
  213. #------------------------ CODE ------------------------------------
  214.  
  215.  
  216. #class The_Form:
  217. # __attributes = {'username':None, 'passwd':None, 'function':'default',
  218. # 'action':None}
  219. # __keys = __attributes.keys()
  220. #
  221. # def __init__(self, vals=None, extra_attrs=None):
  222. # '''\
  223. # init object
  224. # has two optional parameters both dictionaries
  225. # vals is a set of vals to put into the object and
  226. # extra_attrs is a list of attributes with defaults that can be
  227. # added
  228. # '''
  229. #
  230. # if extra_attrs:
  231. # for i in extra_attrs.keys():
  232. # self.__attributes[i] = extra_attrs[i]
  233. # self.__keys = self.__attributes.keys()
  234. #
  235. # if vals:
  236. # for i in vals.keys():
  237. # if i in self.__keys:
  238. # self.__attributes[i] = vals[i]
  239. # else:
  240. # self.__invalid_item = 1
  241. #
  242. # def error(self):
  243. # if self.__invalid_item:
  244. # return 1
  245. # else:
  246. # return 0
  247. #
  248. #
  249. # def get_values_from_form(self, form):
  250. # for i in self.__keys:
  251. # if form.has_key(i):
  252. # self.__attributes[i] = form[i].value
  253. #
  254. # def __setattr__(self, attr, val):
  255. # if attr in self.__keys:
  256. # self.__attributes[attr] = val
  257. #
  258. #
  259. # def __getattr__(self, attr):
  260. # if attr in self.__keys:
  261. # return self.__attributes[attr]
  262.  
  263. class Page:
  264. __attributes = {'login':None}
  265. __keys = __attributes.keys()
  266.  
  267. def __init__(self, auth):
  268. self.__auth = auth
  269. pass
  270.  
  271. def __set_cookie(self):
  272. pass
  273.  
  274. def __show_header(self):
  275. print 'Content-type: text/html'
  276. print self.__auth.get_cookie_header()
  277. print
  278.  
  279. def __show_body(self):
  280. self.__attributes['login'] = self.__auth.login_status()
  281. print self.__template%self.__attributes
  282.  
  283. def load_template(self, template):
  284. self.__template = get_file_as_string(template)
  285.  
  286. def show(self):
  287. self.__show_header()
  288. self.__show_header()
  289. self.__show_body()
  290.  
  291. def main():
  292.  
  293. form = cgi.FieldStorage()
  294. form_data = The_Form()
  295. form_data.get_values_from_form(form)
  296. db = access.Access(dbname='pysocks', user='crypt')
  297. auth = Auth(db, form_data)
  298. page = Page(auth)
  299.  
  300. # print 'Content-type: text/html'
  301. # print
  302. page.load_template('/home/crypt/Work/pysocks/simple.html')
  303.  
  304.  
  305. page.show()
  306.  
  307. auth.test()
  308.  
  309. # print os.environ['cookie']
  310. # print cgi.print_environ()
  311.  
  312.  
  313.  
  314. #------------------------------------------------------------------------
  315.  
  316. if __name__ == '__main__':
  317. main()
  318.  
  319. #------------------------ END ------------------------------------