Guest User

Untitled

a guest
Feb 24th, 2015
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.02 KB | None | 0 0
  1. #! /usr/bin/env python
  2. # coding=utf8
  3.  
  4. import sqlite3
  5. import markdown2
  6. from passlib.hash import des_crypt
  7. from flask import \
  8.     Flask, \
  9.     render_template, \
  10.     json, \
  11.     redirect, \
  12.     abort, \
  13.     url_for, \
  14.     request, \
  15.     session, \
  16.     flash, \
  17.     g
  18.  
  19.  
  20. app = Flask(__name__, static_folder='assets', template_folder='tmpl')
  21. app.secret_key = open('secret').read()
  22. user_db_path = 'user.db'
  23. market_db_path = 'market.db'
  24.  
  25.  
  26. class User(object):
  27.     def __init__(self, name, surname, username, passwd_hash, is_admin):
  28.         self.name = name
  29.         self.surname = surname
  30.         self.username = username
  31.         self.passwd_hash = passwd_hash
  32.         self.is_admin = is_admin
  33.         self.is_valid = False
  34.  
  35.  
  36. class Item(object):
  37.     def __init__(self, id, author, title, desc):
  38.         self.id = id
  39.         self.author = author
  40.         self.title = title
  41.         self.desc = desc
  42.  
  43.  
  44. def get_user(u):
  45.     db = getattr(g, '_user_db', None)
  46.     if not db:
  47.         db = g._user_db = sqlite3.connect(user_db_path)
  48.  
  49.     cur = db.cursor()
  50.     q = "SELECT name, surname, username, passwd, is_admin FROM users WHERE username='{0}';".format(u)
  51.     cur.execute(q)
  52.     rv = cur.fetchall()
  53.     cur.close()
  54.  
  55.     if not rv:
  56.         return None
  57.     return User(rv[0][0], rv[0][1], rv[0][2], rv[0][3], rv[0][4])
  58.  
  59.  
  60. def auth_user(u, p):
  61.     db = getattr(g, '_user_db', None)
  62.     if not db:
  63.         db = g._user_db = sqlite3.connect(user_db_path)
  64.  
  65.     cur = db.cursor()
  66.     q = "SELECT name, surname, username, passwd, is_admin FROM users WHERE username='{0}';".format(u)
  67.     cur.execute(q)
  68.     rv = cur.fetchall()
  69.     cur.close()
  70.  
  71.     if not rv:
  72.         return None
  73.  
  74.     u = User(rv[0][0], rv[0][1], rv[0][2], rv[0][3], rv[0][4])
  75.     try:
  76.         # We need DES for backwards compatibility with the mainframe.
  77.         # But, at least we enforce a reasonable policy!  Just for
  78.         # future reference, here's the regex: \?[A-Z]{2}[a-z]{2}[0-9]{2}!
  79.         if des_crypt.verify(p, u.passwd_hash):
  80.             u.is_valid = True
  81.     except Exception, e:
  82.         print e
  83.     return u
  84.  
  85.  
  86. def get_selling():
  87.     db = getattr(g, '_market_db', None)
  88.     if not db:
  89.         db = g._market_db = sqlite3.connect(market_db_path)
  90.  
  91.     cur = db.cursor()
  92.     q = 'SELECT id, seller, title, description FROM selling ORDER BY id DESC;'
  93.     cur.execute(q)
  94.     rv = cur.fetchall()
  95.     cur.close()
  96.  
  97.     return [Item(r[0], r[1], r[2], r[3]) for r in rv]
  98.  
  99.  
  100. def get_buying():
  101.     db = getattr(g, '_market_db', None)
  102.     if not db:
  103.         db = g._market_db = sqlite3.connect(market_db_path)
  104.  
  105.     cur = db.cursor()
  106.     q = 'SELECT id, buyer, title, description FROM buying ORDER BY id DESC;'
  107.     cur.execute(q)
  108.     rv = cur.fetchall()
  109.     cur.close()
  110.  
  111.     return [Item(r[0], r[1], r[2], r[3]) for r in rv]
  112.  
  113.  
  114. def submit_post(u, t, d, a):
  115.     db = getattr(g, '_market_db', None)
  116.     if not db:
  117.         db = g._market_db = sqlite3.connect(market_db_path)
  118.  
  119.     table = 'buying'
  120.     author_col = 'buyer'
  121.     if a == 'sell':
  122.         table = 'selling'
  123.         author_col = 'seller'
  124.  
  125.     cur = db.cursor()
  126.     q = "INSERT INTO {0}({1}, title, description) VALUES(?, ?, ?);".format(table, author_col)
  127.     cur.execute(q, (u.username, t, d))
  128.     cur.close()
  129.     db.commit()
  130.  
  131.  
  132. @app.route('/')
  133. def index():
  134.     if 'username' not in session:
  135.         return render_template('login.html')
  136.     selling = get_selling()
  137.     buying = get_buying()
  138.     return render_template('index.html', selling=selling, buying=buying)
  139.  
  140.  
  141. @app.route('/login', methods=['POST'])
  142. def login():
  143.     username = request.form['username']
  144.     password = request.form['password']
  145.     u = auth_user(username, password)
  146.     if u:
  147.         if u.is_valid:
  148.             session['username'] = u.username
  149.         else:
  150.             flash('Invalid credentials, {0}, try again'.format(u.username), 'error')
  151.     else:
  152.         flash('No such user {0}'.format(username), 'error')
  153.     return redirect(url_for('index'))
  154.  
  155.  
  156. @app.route('/logout')
  157. def logout():
  158.     session.pop('username')
  159.     return redirect(url_for('index'))
  160.  
  161.  
  162. @app.route('/post')
  163. def post():
  164.     if 'username' not in session:
  165.         return redirect(url_for('index'))
  166.  
  167.     u = get_user(session['username'])
  168.     if not u:
  169.         return redirect(url_for('index'))
  170.  
  171.     return render_template('post.html', user=u)
  172.  
  173.  
  174. @app.route('/submit', methods=['POST'])
  175. def submit():
  176.     if 'username' not in session:
  177.         return redirect(url_for('index'))
  178.  
  179.     u = get_user(session['username'])
  180.     if not u:
  181.         return redirect(url_for('index'))
  182.  
  183.     title = request.form['title']
  184.     desc = request.form['description']
  185.     action = request.form['buy-or-sell']
  186.  
  187.     if not title or not desc or (action != 'buy' and action != 'sell'):
  188.         flash('Invalid post, try again', 'error')
  189.         return redirect(url_for('post'))
  190.  
  191.     submit_post(u, title, desc, action)
  192.     return redirect(url_for('index'))
  193.  
  194.  
  195. if __name__ == '__main__':
  196.     app.run(debug=False, host='0.0.0.0', port=3000)
Advertisement
Add Comment
Please, Sign In to add comment