You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

397 lines
13 KiB

4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. from flask.helpers import send_from_directory
  2. import ldap as l
  3. from ldap3 import Server, Connection
  4. from ldap3.core.exceptions import LDAPBindError
  5. from flask import Flask, g, request, redirect, url_for, render_template, flash
  6. from flask_sqlalchemy import SQLAlchemy
  7. from flask_login import LoginManager, login_manager, current_user, login_user, \
  8. logout_user, login_required
  9. from flask_wtf import FlaskForm
  10. from flask_cache_buster import CacheBuster
  11. from wtforms import StringField, PasswordField, BooleanField, SubmitField
  12. from wtforms.validators import DataRequired
  13. from werkzeug.utils import secure_filename
  14. from flask_bootstrap import Bootstrap
  15. import short_url
  16. import os
  17. import sqlite3
  18. app = Flask(__name__)
  19. Bootstrap(app)
  20. app.secret_key = 'asdf'
  21. app.debug = True
  22. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
  23. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  24. app.config['WTF_CSRF_SECRET_KEY'] = 'asdf'
  25. # Base
  26. app.config['LDAP_REALM_NAME'] = 'OpenLDAP Authentication'
  27. app.config['LDAP_HOST'] = os.environ.get('LDAP_HOST')
  28. app.config['LDAP_BASE_DN'] = os.environ.get('LDAP_BASE_DN')
  29. app.config['LDAP_USERNAME'] = os.environ.get('LDAP_USERNAME')
  30. app.config['LDAP_PASSWORD'] = os.environ.get('LDAP_PASSWORD')
  31. # Uploads
  32. app.config['UPLOAD_FOLDER'] = 'links/images'
  33. # OpenLDAP
  34. app.config['LDAP_OBJECTS_DN'] = 'dn'
  35. app.config['LDAP_OPENLDAP'] = True
  36. app.config['LDAP_USER_OBJECT_FILTER'] = '(&(objectclass=posixAccount)(uid=%s))'
  37. # Login cookies
  38. #app.config['SESSION_COOKIE_DOMAIN'] = os.environ.get('COOKIE_DOMAIN')
  39. #app.config['REMEMBER_COOKIE_DOMAIN'] = os.environ.get('COOKIE_DOMAIN')
  40. short_domain = os.environ.get('SHORT_DOMAIN')
  41. ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
  42. db = SQLAlchemy(app)
  43. login_manager = LoginManager(app)
  44. login_manager.init_app(app)
  45. login_manager.login_view = 'login'
  46. db.create_all()
  47. config = {
  48. 'extensions': ['.js', '.css', '.csv'],
  49. 'hash_size': 10
  50. }
  51. cache_buster = CacheBuster(config=config)
  52. cache_buster.register_cache_buster(app)
  53. server = Server(app.config['LDAP_HOST'])
  54. conn = Connection(server, app.config['LDAP_USERNAME'], app.config['LDAP_PASSWORD'], auto_bind=True)
  55. class User(db.Model):
  56. __tablename__ = 'user'
  57. id = db.Column(db.Integer, primary_key=True)
  58. username = db.Column(db.String(100))
  59. authenticated = db.Column(db.Boolean, default=False)
  60. def __init__(self, username):
  61. self.username = username
  62. @staticmethod
  63. def try_login(username, password):
  64. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % username, attributes=['*'])
  65. if len(conn.entries) > 0:
  66. Connection(app.config['LDAP_HOST'], conn.entries[0].entry_dn, password, auto_bind=True)
  67. return
  68. raise LDAPBindError
  69. def is_authenticated(self):
  70. return self.authenticated
  71. def is_active(self):
  72. return True
  73. def is_anonymous(self):
  74. return False
  75. def get_id(self):
  76. return self.id
  77. def get_user_dict(self):
  78. user = {'dn': '',
  79. 'firstName': '',
  80. 'lastName': '',
  81. 'email': '',
  82. 'userName': self.username,
  83. }
  84. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % self.username, attributes=['*'])
  85. user['dn'] = conn.entries[0].entry_dn
  86. user['firstName'] = conn.entries[0].givenName.value
  87. user['lastName'] = conn.entries[0].sn.value
  88. user['email'] = conn.entries[0].mail.value
  89. return user
  90. class LoginForm(FlaskForm):
  91. username = StringField('Username', validators=[DataRequired()])
  92. password = PasswordField('Password', validators=[DataRequired()])
  93. remember_me = BooleanField('Remember Me')
  94. submit = SubmitField('Sign In')
  95. @login_manager.user_loader
  96. def load_user(id):
  97. return User.query.get(int(id))
  98. @app.before_request
  99. def get_current_user():
  100. g.user = current_user
  101. @app.route('/')
  102. @login_required
  103. def index():
  104. pastes = get_pastes_for_user()
  105. links = get_links_for_user()
  106. images = get_images_for_user()
  107. return render_template('profile.j2', user = current_user.get_user_dict(), short_domain = short_domain, links = links, pastes = pastes, images = images)
  108. @app.route('/link')
  109. @login_required
  110. def link():
  111. return render_template('link.j2', user = current_user.get_user_dict(), short_domain = short_domain)
  112. @app.route('/paste')
  113. @login_required
  114. def text():
  115. return render_template('paste.j2', user = current_user.get_user_dict())
  116. @app.route('/image', methods=['GET', 'POST'])
  117. @login_required
  118. def image():
  119. if request.method == 'POST':
  120. print(request.files)
  121. # check if the post request has the file part
  122. if 'file' not in request.files:
  123. return render_template('image.j2', user = current_user.get_user_dict(), short_domain = short_domain, error_msg = "No file part.")
  124. file = request.files['file']
  125. # if user does not select file, browser also
  126. # submit an empty part without filename
  127. if file.filename == '':
  128. return render_template('image.j2', user = current_user.get_user_dict(), short_domain = short_domain, error_msg = "No selected file.")
  129. if file and allowed_file(file.filename):
  130. conn = sqlite3.connect('links/links.db')
  131. c = conn.cursor()
  132. filename = secure_filename(file.filename)
  133. file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  134. c.execute("INSERT INTO images (filename, user_id) VALUES (?, ?)", (filename, current_user.get_user_dict()['dn']))
  135. c.execute("SELECT * FROM images WHERE filename=?", (filename,))
  136. row = c.fetchone()
  137. print(row[0])
  138. conn.commit()
  139. conn.close()
  140. url_fragment = short_url.encode_url(row[0])
  141. return render_template('image.j2', user = current_user.get_user_dict(), short_domain = short_domain, success_msg = "Your image link is <a target='_blank' href='{}/i/{}'>{}/i/{}</a>".format(short_domain, url_fragment, short_domain, url_fragment))
  142. return render_template('image.j2', user = current_user.get_user_dict(), short_domain = short_domain)
  143. @app.route('/login', methods=['GET', 'POST'])
  144. def login():
  145. if current_user.is_authenticated:
  146. flash('You are already logged in.')
  147. return redirect(url_for('index'))
  148. form = LoginForm(request.form)
  149. print(form)
  150. print(request.method)
  151. if request.method == 'POST' and form.validate():
  152. username = request.form.get('username')
  153. password = request.form.get('password')
  154. print(username)
  155. print(password)
  156. try:
  157. User.try_login(username, password)
  158. except LDAPBindError:
  159. flash(
  160. 'Invalid username or password. Please try again.',
  161. 'danger')
  162. return render_template('login.j2', form=form)
  163. user = User.query.filter(User.username == username).first()
  164. print(user)
  165. if user is None:
  166. user = User(username, password)
  167. db.session.add(user)
  168. user.authenticated = True
  169. db.session.commit()
  170. login_user(user, remember=form.remember_me.data)
  171. print('You have successfully logged in.')
  172. return redirect(url_for('index'))
  173. if form.errors:
  174. flash(form.errors, 'danger')
  175. return render_template('login.j2', form=form)
  176. @app.route('/shorten', methods=['POST'])
  177. @login_required
  178. def shorten_url():
  179. if request.method == 'POST':
  180. url = request.form['url']
  181. conn = sqlite3.connect('links/links.db')
  182. c = conn.cursor()
  183. if url is not None and len(url) > 0:
  184. c.execute("INSERT INTO links (url, user_id) VALUES (?, ?)", (url, current_user.get_user_dict()['dn']))
  185. c.execute("SELECT * FROM links WHERE url=?", (url,))
  186. row = c.fetchone()
  187. print(row[0])
  188. conn.commit()
  189. conn.close()
  190. url_fragment = short_url.encode_url(row[0])
  191. return "Your shortened link is <a target='_blank' href='{}/l/{}'>{}/l/{}</a>".format(short_domain, url_fragment, short_domain, url_fragment)
  192. conn.commit()
  193. conn.close()
  194. return 'Error'
  195. @app.route('/save', methods=['POST'])
  196. @login_required
  197. def save_paste():
  198. if request.method == 'POST':
  199. paste = request.data
  200. conn = sqlite3.connect('links/links.db')
  201. c = conn.cursor()
  202. if paste is not None and len(paste) > 0:
  203. c.execute("INSERT INTO pastes (paste, user_id) VALUES (?, ?)", (paste, current_user.get_user_dict()['dn']))
  204. c.execute("SELECT * FROM pastes WHERE paste=?", (paste,))
  205. row = c.fetchone()
  206. print(row[0])
  207. conn.commit()
  208. conn.close()
  209. url_fragment = short_url.encode_url(row[0])
  210. return {"success": True, "msg": "Your paste link is <a target='_blank' href='{}/p/{}'>{}/p/{}</a>".format(short_domain, url_fragment, short_domain, url_fragment)}
  211. conn.commit()
  212. conn.close()
  213. return {'success': False}
  214. @app.route('/delete', methods=['POST'])
  215. @login_required
  216. def delete():
  217. if request.method == 'POST':
  218. data = request.json
  219. table = data['table']
  220. conn = sqlite3.connect('links/links.db')
  221. c = conn.cursor()
  222. if table == 'links':
  223. c.execute("DELETE FROM links WHERE id=? AND user_id=?", (data['id'], current_user.get_user_dict()['dn']))
  224. elif table == 'pastes':
  225. c.execute("DELETE FROM pastes WHERE id=? AND user_id=?", (data['id'], current_user.get_user_dict()['dn']))
  226. elif table == 'images':
  227. c.execute("DELETE FROM images WHERE id=? AND user_id=?", (data['id'], current_user.get_user_dict()['dn']))
  228. else:
  229. return {'success': False, 'msg': 'This table doesn\'t exist!'}
  230. conn.commit()
  231. conn.close()
  232. return {'success': True, 'msg': 'Deleted successfully!'}
  233. return {'success': False, 'msg': 'An error occurred.'}
  234. @app.route('/l/<url>')
  235. def expand_url(url):
  236. idx = short_url.decode_url(url)
  237. conn = sqlite3.connect('links/links.db')
  238. c = conn.cursor()
  239. c.execute("SELECT * FROM links WHERE id=?", (idx,))
  240. out = c.fetchone()
  241. if out != None:
  242. out_link = out[1]
  243. return redirect(out_link)
  244. return render_template('404.j2')
  245. @app.route('/p/<url>')
  246. def show_paste(url):
  247. idx = short_url.decode_url(url)
  248. conn = sqlite3.connect('links/links.db')
  249. c = conn.cursor()
  250. c.execute("SELECT * FROM pastes WHERE id=?", (idx,))
  251. out = c.fetchone()
  252. if out != None:
  253. out_paste = str(out[1], 'utf-8')
  254. return render_template('public_paste.j2', paste = out_paste)
  255. return render_template('404.j2')
  256. @app.route('/i/<url>')
  257. def show_image(url):
  258. idx = short_url.decode_url(url)
  259. conn = sqlite3.connect('links/links.db')
  260. c = conn.cursor()
  261. c.execute("SELECT * FROM images WHERE id=?", (idx,))
  262. out = c.fetchone()
  263. if out != None:
  264. filename = out[1]
  265. return send_from_directory(app.config['UPLOAD_FOLDER'], filename=filename, as_attachment=False)
  266. return render_template('404.j2')
  267. def get_pastes_for_user():
  268. conn = sqlite3.connect('links/links.db')
  269. c = conn.cursor()
  270. c.execute("SELECT * FROM pastes WHERE user_id=?", (current_user.get_user_dict()["dn"],))
  271. out = []
  272. for row in c.fetchall():
  273. a = "{}/p/{}<span class='faded'> - {}</span>".format(short_domain, short_url.encode_url(row[0]), str(row[1], 'utf-8')[:80])
  274. b = "{}/p/{}".format(short_domain, short_url.encode_url(row[0]))
  275. out.append((row[0], a, b))
  276. return out
  277. def get_links_for_user():
  278. conn = sqlite3.connect('links/links.db')
  279. c = conn.cursor()
  280. c.execute("SELECT * FROM links WHERE user_id=?", (current_user.get_user_dict()["dn"],))
  281. out = []
  282. for row in c.fetchall():
  283. a = "{}/l/{}<span class='faded'> - {}</span>".format(short_domain, short_url.encode_url(row[0]), row[1])
  284. b = "{}/l/{}".format(short_domain, short_url.encode_url(row[0]))
  285. out.append((row[0], a, b))
  286. return out
  287. def get_images_for_user():
  288. conn = sqlite3.connect('links/links.db')
  289. c = conn.cursor()
  290. c.execute("SELECT * FROM images WHERE user_id=?", (current_user.get_user_dict()["dn"],))
  291. out = []
  292. for row in c.fetchall():
  293. a = "{}/i/{}".format(short_domain, short_url.encode_url(row[0]))
  294. out.append((row[0], a, a))
  295. return out
  296. def allowed_file(filename):
  297. return '.' in filename and \
  298. filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  299. @app.route('/logout')
  300. @login_required
  301. def logout():
  302. user = current_user
  303. user.authenticated = False
  304. db.session.add(user)
  305. db.session.commit()
  306. logout_user()
  307. return redirect(url_for('game'))
  308. if __name__ == '__main__':
  309. app.run()