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.

216 lines
6.2 KiB

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. import ldap as l
  2. from ldap3 import Server, Connection
  3. from ldap3.core.exceptions import LDAPBindError
  4. from flask import Flask, g, request, redirect, url_for, render_template, flash
  5. from flask_sqlalchemy import SQLAlchemy
  6. from flask_login import LoginManager, login_manager, current_user, login_user, \
  7. logout_user, login_required
  8. from flask_wtf import FlaskForm
  9. from wtforms import StringField, PasswordField, BooleanField, SubmitField
  10. from wtforms.validators import DataRequired
  11. from flask_bootstrap import Bootstrap
  12. import short_url
  13. import os
  14. import sqlite3
  15. app = Flask(__name__)
  16. Bootstrap(app)
  17. app.secret_key = 'asdf'
  18. app.debug = True
  19. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
  20. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  21. app.config['WTF_CSRF_SECRET_KEY'] = 'asdf'
  22. # Base
  23. app.config['LDAP_REALM_NAME'] = 'OpenLDAP Authentication'
  24. app.config['LDAP_HOST'] = os.environ.get('LDAP_HOST')
  25. app.config['LDAP_BASE_DN'] = os.environ.get('LDAP_BASE_DN')
  26. app.config['LDAP_USERNAME'] = os.environ.get('LDAP_USERNAME')
  27. app.config['LDAP_PASSWORD'] = os.environ.get('LDAP_PASSWORD')
  28. # OpenLDAP
  29. app.config['LDAP_OBJECTS_DN'] = 'dn'
  30. app.config['LDAP_OPENLDAP'] = True
  31. app.config['LDAP_USER_OBJECT_FILTER'] = '(&(objectclass=posixAccount)(uid=%s))'
  32. # Login cookies
  33. app.config['SESSION_COOKIE_DOMAIN'] = os.environ.get('COOKIE_DOMAIN')
  34. app.config['REMEMBER_COOKIE_DOMAIN'] = os.environ.get('COOKIE_DOMAIN')
  35. short_domain = os.environ.get('SHORT_DOMAIN')
  36. db = SQLAlchemy(app)
  37. login_manager = LoginManager(app)
  38. login_manager.init_app(app)
  39. login_manager.login_view = 'login'
  40. db.create_all()
  41. server = Server(app.config['LDAP_HOST'])
  42. conn = Connection(server, app.config['LDAP_USERNAME'], app.config['LDAP_PASSWORD'], auto_bind=True)
  43. class User(db.Model):
  44. __tablename__ = 'user'
  45. id = db.Column(db.Integer, primary_key=True)
  46. username = db.Column(db.String(100))
  47. password = db.Column(db.String(128))
  48. authenticated = db.Column(db.Boolean, default=False)
  49. def __init__(self, username, password):
  50. self.username = username
  51. self.password = password
  52. @staticmethod
  53. def try_login(username, password):
  54. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % username, attributes=['*'])
  55. if len(conn.entries) > 0:
  56. Connection(app.config['LDAP_HOST'], conn.entries[0].entry_dn, password, auto_bind=True)
  57. return
  58. raise LDAPBindError
  59. def is_authenticated(self):
  60. return self.authenticated
  61. def is_active(self):
  62. return True
  63. def is_anonymous(self):
  64. return False
  65. def get_id(self):
  66. return self.id
  67. def get_user_dict(self):
  68. user = {'dn': '',
  69. 'firstName': '',
  70. 'lastName': '',
  71. 'email': '',
  72. 'userName': self.username,
  73. }
  74. conn.search(app.config['LDAP_BASE_DN'], app.config['LDAP_USER_OBJECT_FILTER'] % self.username, attributes=['*'])
  75. user['dn'] = conn.entries[0].entry_dn
  76. user['firstName'] = conn.entries[0].givenName.value
  77. user['lastName'] = conn.entries[0].sn.value
  78. user['email'] = conn.entries[0].mail.value
  79. return user
  80. class LoginForm(FlaskForm):
  81. username = StringField('Username', validators=[DataRequired()])
  82. password = PasswordField('Password', validators=[DataRequired()])
  83. remember_me = BooleanField('Remember Me')
  84. submit = SubmitField('Sign In')
  85. @login_manager.user_loader
  86. def load_user(id):
  87. return User.query.get(int(id))
  88. @app.before_request
  89. def get_current_user():
  90. g.user = current_user
  91. @app.route('/')
  92. @login_required
  93. def index():
  94. return render_template('profile.j2', user = current_user.get_user_dict(), short_domain = short_domain)
  95. @app.route('/login', methods=['GET', 'POST'])
  96. def login():
  97. if current_user.is_authenticated:
  98. flash('You are already logged in.')
  99. return redirect(url_for('index'))
  100. form = LoginForm(request.form)
  101. print(form)
  102. print(request.method)
  103. if request.method == 'POST' and form.validate():
  104. username = request.form.get('username')
  105. password = request.form.get('password')
  106. print(username)
  107. print(password)
  108. try:
  109. User.try_login(username, password)
  110. except LDAPBindError:
  111. flash(
  112. 'Invalid username or password. Please try again.',
  113. 'danger')
  114. return render_template('login.j2', form=form)
  115. user = User.query.filter(User.username == username).first()
  116. print(user)
  117. if user is None:
  118. user = User(username, password)
  119. db.session.add(user)
  120. user.authenticated = True
  121. db.session.commit()
  122. login_user(user, remember=form.remember_me.data)
  123. print('You have successfully logged in.')
  124. return redirect(url_for('index'))
  125. if form.errors:
  126. flash(form.errors, 'danger')
  127. return render_template('login.j2', form=form)
  128. @app.route('/shorten', methods=['POST'])
  129. @login_required
  130. def shorten_url():
  131. if request.method == 'POST':
  132. url = request.form['url']
  133. conn = sqlite3.connect('links/links.db')
  134. c = conn.cursor()
  135. if url is not None and len(url) > 0:
  136. c.execute("INSERT INTO links (url) VALUES (?)", (url,))
  137. c.execute("SELECT * FROM links WHERE url=?", (url,))
  138. row = c.fetchone()
  139. print(row[0])
  140. conn.commit()
  141. conn.close()
  142. url_fragment = short_url.encode_url(row[0])
  143. return "Your shortened link is <a href='{}/{}'>{}/{}</a>".format(short_domain, url_fragment, short_domain, url_fragment)
  144. conn.commit()
  145. conn.close()
  146. return 'Error'
  147. @app.route('/l/<url>')
  148. def expand_url(url):
  149. idx = short_url.decode_url(url)
  150. conn = sqlite3.connect('links/links.db')
  151. c = conn.cursor()
  152. c.execute("SELECT * FROM links WHERE id=?", (idx,))
  153. out_link = c.fetchone()[1]
  154. return redirect(out_link)
  155. @app.route('/logout')
  156. @login_required
  157. def logout():
  158. user = current_user
  159. user.authenticated = False
  160. db.session.add(user)
  161. db.session.commit()
  162. logout_user()
  163. return redirect(url_for('game'))
  164. if __name__ == '__main__':
  165. app.run()