flaskr.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """
  2. Simple flask thing
  3. """
  4. import random
  5. import string
  6. from datetime import datetime
  7. from flask import render_template, request, redirect, \
  8. flash, url_for, abort, json
  9. from flask_breadcrumbs import Breadcrumbs, register_breadcrumb
  10. from flask_menu import Menu, register_menu
  11. from flask_login import login_required, login_user, logout_user
  12. from app import app, db, rrclient, alt_rrclient
  13. from app.models import User, Log, Key
  14. Menu(app=app)
  15. Breadcrumbs(app=app)
  16. @register_breadcrumb(app, '.login', 'Login')
  17. @app.route("/login", methods=["GET", "POST"])
  18. def login():
  19. """Handle login page and data"""
  20. if request.method == 'POST':
  21. email = request.form['email']
  22. password = request.form['password']
  23. user = User.query.filter(User.email == email).first()
  24. if user:
  25. if user.check_password(password):
  26. login_user(user, remember=True)
  27. flash('Successfully loggend in.', 'success')
  28. if request.args.get("next"):
  29. return redirect(request.args.get('next'))
  30. return redirect(url_for('index'))
  31. flash('Password Incorrect.', 'warning')
  32. return render_template('site/login.html', login_email=email)
  33. flash('Email not found.', 'warning')
  34. return render_template('site/login.html')
  35. @app.route("/register", methods=["POST"])
  36. def register():
  37. """Register a new user"""
  38. name = request.form['name'] if 'name' in request.form else None
  39. email = request.form['email'] if 'email' in request.form else None
  40. password = request.form['password'] if 'email' in request.form else None
  41. if name is None:
  42. flash('Fill in the name.', 'warning')
  43. return render_template('login.j2')
  44. if email is None:
  45. flash('Fill in the email.', 'warning')
  46. return render_template(
  47. 'login.j2',
  48. name=name
  49. )
  50. if password is None:
  51. flash('Fill in the password.', 'warning')
  52. return render_template(
  53. 'login.j2',
  54. name=name,
  55. email=email
  56. )
  57. user = User.query.filter(User.email == email).first()
  58. if user is not None:
  59. flash('Email already taken.', 'warning')
  60. return render_template(
  61. 'login.j2',
  62. name=name,
  63. )
  64. user = User()
  65. user.name = name
  66. user.email = email
  67. user.password = password
  68. db.session.add(user)
  69. db.session.commit()
  70. login_user(user)
  71. flash('Successfully registered account "%s".' % (user.name), 'success')
  72. if request.args.get("next") is not None:
  73. return redirect(request.args.get("next"))
  74. return redirect(url_for('index'))
  75. @app.route("/logout")
  76. @login_required
  77. def logout():
  78. """Logout function for users"""
  79. logout_user()
  80. flash('succesfully logged out', 'success')
  81. return redirect(url_for('login'))
  82. @app.route('/')
  83. @register_menu(app, '.', 'Home')
  84. @register_breadcrumb(app, '.', 'Home')
  85. def index():
  86. """Show homepage"""
  87. # users = User.query.count()
  88. return render_template('site/index.html')
  89. # return render_template('site/index.html', users=users)
  90. @app.route('/users')
  91. @register_menu(app, 'users', 'Users')
  92. @register_breadcrumb(app, '.users', 'Users')
  93. @login_required
  94. def user_index():
  95. """Show users"""
  96. users = User.query.all()
  97. return render_template('user/index.html', users=users)
  98. def user_overview_dlc(*args, **kwargs):
  99. """Generate dynamic_list for user"""
  100. id = request.view_args['id']
  101. user = User.query.get(id)
  102. return [{'text': user.email, 'url': user.name}]
  103. @app.route('/user/<int:id>')
  104. @register_breadcrumb(app, '.users.id', '',
  105. dynamic_list_constructor=user_overview_dlc)
  106. @login_required
  107. def user_overview(id):
  108. """Show user overview"""
  109. id = int(id)
  110. user = User.query.get(id)
  111. return render_template('user/overview.html', user=user)
  112. @app.route('/user/<int:id>/generate_key')
  113. @login_required
  114. def user_generate_key(id):
  115. """Generate new key for user"""
  116. user = User.query.get(id)
  117. key = Key()
  118. key.key = ''.join(random.sample(
  119. string.ascii_letters + string.digits, 32
  120. ))
  121. key.user_id = user.id
  122. db.session.add(key)
  123. db.session.commit()
  124. flash('Succesfully generated key', 'success')
  125. return redirect(url_for('user_overview', id=user.id))
  126. @app.route('/user/<int:user_id>/key/<int:key_id>/activate')
  127. @login_required
  128. def user_toogle_key(user_id, key_id):
  129. """Activate key"""
  130. user = User.query.get(user_id)
  131. key = Key.query.get(key_id)
  132. key.active = not key.active
  133. db.session.add(key)
  134. db.session.commit()
  135. if key.active:
  136. flash('Activated key', 'success')
  137. else:
  138. flash('Deactivated key', 'success')
  139. return redirect(url_for('user_overview', id=user.id))
  140. @app.route('/api/authenticated', methods=["POST"])
  141. def api_authenticated():
  142. """Check key"""
  143. if 'Authorization' not in request.headers:
  144. return abort(403)
  145. authorization = request.headers['authorization']
  146. key = Key.query.filter(Key.key == authorization).count()
  147. if key:
  148. return json.dumps(True)
  149. return json.dumps(False)
  150. @app.route('/api/request/<path:url_path>', methods=["GET"])
  151. def api_get(url_path):
  152. """Check key"""
  153. if 'Authorization' not in request.headers:
  154. return abort(403)
  155. authorization = request.headers['authorization']
  156. key = Key.query.filter(Key.key == authorization).first()
  157. if not key or not key.active:
  158. return abort(403)
  159. log = Log()
  160. log.date_time = datetime.now()
  161. log.key_id = key.id
  162. log.request_type = 'GET'
  163. log.request_url = url_path
  164. db.session.add(log)
  165. db.session.commit()
  166. alt = request.args.get('alt')
  167. if alt:
  168. result = alt_rrclient.get(url_path)
  169. else:
  170. result = rrclient.get(url_path)
  171. log.succes = True
  172. db.session.commit()
  173. return result
  174. @app.route('/api/request/send_chat/<string:language>', methods=["POST"])
  175. def api_send_chat(language):
  176. """Check key"""
  177. if 'Authorization' not in request.headers:
  178. return abort(403)
  179. authorization = request.headers['authorization']
  180. key = Key.query.filter(Key.key == authorization).first()
  181. if not key or not key.active:
  182. return abort(403)
  183. if 'message' not in request.form:
  184. return abort(400)
  185. message = request.form['message']
  186. log = Log()
  187. log.date_time = datetime.now()
  188. log.key_id = key.id
  189. log.request_type = 'CHAT'
  190. log.request_url = language
  191. db.session.add(log)
  192. db.session.commit()
  193. alt = request.args.get('alt')
  194. if alt:
  195. alt_rrclient.send_chat(language, message)
  196. else:
  197. rrclient.send_chat(language, message)
  198. log.succes = True
  199. db.session.commit()
  200. return json.dumps(True)
  201. @app.route('/api/request/<path:url_path>', methods=["POST"])
  202. def api_post(url_path):
  203. """Check key"""
  204. if 'Authorization' not in request.headers:
  205. return abort(403)
  206. authorization = request.headers['authorization']
  207. key = Key.query.filter(Key.key == authorization).first()
  208. if not key or not key.active:
  209. return abort(403)
  210. log = Log()
  211. log.date_time = datetime.now()
  212. log.key_id = key.id
  213. log.request_type = 'POST'
  214. log.request_url = url_path
  215. db.session.add(log)
  216. db.session.commit()
  217. data = request.get_json()
  218. if not data:
  219. data = {}
  220. alt = request.args.get('alt')
  221. if alt:
  222. result = alt_rrclient.post(url_path, data=data)
  223. else:
  224. result = rrclient.post(url_path, data=data)
  225. log.succes = True
  226. db.session.commit()
  227. return result