Guest User

Untitled

a guest
Jan 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.98 KB | None | 0 0
  1. #!./flaskvenv/bin/python
  2. # -*- coding: utf-8 -*-
  3. # python libs
  4. import os
  5. from uuid import uuid4
  6. # flask
  7. from config import app
  8. from flask import render_template, flash, request, url_for, redirect, session, send_from_directory, abort, send_file
  9. # hashing password
  10. from passlib.hash import sha256_crypt
  11. # forms
  12. from forms import RegistrationForm, AddEmployees, AddPost, UploadFile
  13. from werkzeug.utils import secure_filename
  14. # mysql
  15. from MySQLdb import escape_string as thwart # sql injection
  16. from dbconnect import connection
  17. # python
  18. import gc
  19. # user decorators
  20. from decorator import login_required, role_control
  21. from datetime import datetime
  22. # content
  23. from content import get_count_file, file_types, get_content, get_bday_employees
  24.  
  25.  
  26. ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','docx', 'doc'])
  27.  
  28. def allowed_file(filename):
  29. return '.' in filename and \
  30. filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  31.  
  32.  
  33. @app.route('/')
  34. def index():
  35. title = "Главная"
  36. c,conn = connection()
  37. c.execute("SELECT * FROM posts ORDER BY uid DESC LIMIT 0,10")
  38. return render_template('index.html', title=title, data=c, get_count_file=get_count_file, bday=get_bday_employees())
  39.  
  40. @app.route('/personal/')
  41. @login_required
  42. def personal():
  43. title = "Профиль"
  44. c,conn = connection()
  45. c.execute("SELECT username, email, name, lastname, role FROM users WHERE username = %s", [thwart(session['username'])])
  46. data = c.fetchone()
  47. return render_template("user_info.html", title=title, data=data)
  48.  
  49. @app.route('/emplist/')
  50. @login_required
  51. def emplist():
  52. title = "Список сотрудников"
  53. c,conn = connection()
  54. c.execute("SELECT * FROM employees")
  55. data = c
  56. return render_template("emplist.html", title=title, data=data)
  57.  
  58.  
  59. @app.route('/list/')
  60. def list():
  61. title = 'Файлы'
  62. return render_template("filelist.html", get_count_file=get_count_file, type=file_types, get_content=get_content, title=title)
  63.  
  64. @app.route('/posts/')
  65. def posts():
  66. title = "Новости"
  67. data = ''
  68. c,conn = connection()
  69. c.execute("SELECT * FROM posts WHERE post_type = 'new' ORDER BY uid DESC LIMIT 0,10")
  70. news = c
  71. c.close()
  72. conn.close()
  73. b,a = connection()
  74. b.execute("SELECT * FROM posts WHERE post_type = 'not' ORDER BY uid DESC LIMIT 0,10")
  75. notify = b
  76. b.close()
  77. a.close()
  78. return render_template('posts.html', title=title, news=news, notify=notify)
  79.  
  80. @app.route('/post/<hash>')
  81. def view_post(hash):
  82. c,conn = connection()
  83. c.execute("SELECT * FROM posts WHERE url = %s", [hash])
  84. data = c.fetchone()
  85. title = data[2]
  86. return render_template("view_post.html", data=data, title=title)
  87.  
  88. @app.route('/file/<fileid>', methods=['POST','GET'])
  89. def get_file(fileid):
  90. c,conn = connection()
  91. c.execute("SELECT name FROM files WHERE hash = %s", [thwart(fileid)])
  92. name = c.fetchone()[0]
  93. c.close()
  94. conn.close()
  95. uploads = os.path.join(app.root_path, 'static/upload/', name)
  96. return send_file(uploads, attachment_filename=name)
  97.  
  98. @app.route('/login/', methods=['GET', 'POST'])
  99. def login():
  100. title="Login"
  101. error=""
  102. try:
  103. c,conn = connection()
  104. if request.method == 'POST':
  105. data = c.execute("SELECT * FROM users WHERE username = (%s)",
  106. [thwart(request.form['username'])])
  107. data = c.fetchone()[2]
  108. if 'logged_in' in session:
  109. flash("You already auth")
  110. return redirect(url_for('index'))
  111. elif sha256_crypt.verify(request.form['password'], data) :
  112. session['logged_in'] = True
  113. session['username'] = request.form['username']
  114. flash("Вы вошли в систему")
  115. return redirect(url_for('index'))
  116. else:
  117. error = "Недопустимые учетные данные, повторите попытку"
  118. gc.collect()
  119. return render_template('login.html', title=title, error=error)
  120. except Exception as e:
  121. error = 'Недопустимые учетные данные, повторите попытку'
  122. return render_template('login.html', title=title, error=error)
  123.  
  124. @app.route('/logout/')
  125. def logout():
  126. session.clear()
  127. flash("Вы вышли из системы")
  128. gc.collect()
  129. return redirect(url_for('index'))
  130.  
  131. @app.route('/register/', methods=['GET','POST'])
  132. @login_required
  133. @role_control
  134. def register():
  135. try:
  136. error = ''
  137. title = "Register"
  138. form = RegistrationForm(request.form)
  139. if request.method == 'POST' and form.validate():
  140. username = form.username.data
  141. email = form.email.data
  142. password = sha256_crypt.encrypt((str(form.password.data)))
  143. name = form.name.data
  144. lastname = form.lastname.data
  145. role = form.role.data
  146.  
  147. c,conn = connection()
  148. x = c.execute("SELECT * FROM users WHERE username = (%s)",
  149. [thwart(username)])
  150. if int(x) > 0:
  151. flash("The user already registered")
  152. return redirect(url_for("register"))
  153. else:
  154. c.execute("INSERT INTO users (username, password, email, name, lastname, role) VALUES (%s, %s, %s, %s, %s, %s)",
  155. [thwart(username), thwart(password), thwart(email), thwart(name), thwart(lastname), thwart(role)])
  156. conn.commit()
  157. flash("Пользователь добавлен!")
  158. c.close()
  159. conn.close()
  160. gc.collect()
  161. return redirect(url_for('index'))
  162. return render_template('register.html', title=title, form=form, error=error)
  163. except Exception as e:
  164. return(str(e))
  165.  
  166. @app.route('/employees/', methods=['GET','POST'])
  167. @login_required
  168. def add_employees():
  169. try:
  170. title = "Добавить сотрудников"
  171. form = AddEmployees(request.form)
  172. if request.method == 'POST':
  173. name = form.name.data
  174. lastname = form.lastname.data
  175. dep = form.dep.data
  176. bday = form.bday.data
  177.  
  178. c, conn = connection()
  179. c.execute("INSERT INTO employees (name, lastname,dep, bday) VALUES (%s, %s, %s, %s)",
  180. [thwart(name), thwart(lastname), thwart(dep), thwart(bday)])
  181. conn.commit()
  182. flash("Добавлен сотрудник")
  183. c.close()
  184. conn.close()
  185.  
  186. return redirect(url_for('index'))
  187. return render_template('add_employees.html', title=title, form=form)
  188. except Exception as e:
  189. return(str(e))
  190.  
  191. @app.route('/post/', methods=['GET', 'POST'])
  192. @login_required
  193. def add_post():
  194. try:
  195. title = "Добавить новости"
  196. form = AddPost(request.form)
  197. if request.method == 'POST':
  198. post_type = form.post_type.data.encode('utf-8').decode()
  199. subject = form.subject.data.encode('utf-8').decode()
  200. full_text = form.full_text.data.encode('utf-8').decode()
  201.  
  202. c,conn = connection()
  203. c.execute("INSERT INTO posts (post_type, subject, full_text, url) VALUES (%s, %s, %s, %s)",
  204. [thwart(post_type), thwart(subject), thwart(full_text), thwart(str(uuid4()))])
  205. conn.commit()
  206. flash("Добвален пост")
  207. c.close()
  208. conn.close()
  209.  
  210. return redirect(url_for('index'))
  211. return render_template('add_post.html', title=title, form=form)
  212. except Exception as e:
  213. return(str(e))
  214.  
  215. @app.route('/upload/', methods=['GET', 'POST'])
  216. @login_required
  217. def upload():
  218. title = "Добавить файлы"
  219. form = UploadFile(request.form)
  220. if request.method == 'POST':
  221. if 'file' not in request.files:
  222. flash("No file part")
  223. return redirect(request.url)
  224. file = request.files['file']
  225. if file.filename == '':
  226. flash("No selected file")
  227. return redirect(request.url)
  228. if file and allowed_file(file.filename):
  229. file_type = form.file_parent.data
  230. # filename = secure_filename(file.filename)
  231. filename = file.filename
  232. print(filename)
  233. file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  234. c,conn = connection()
  235. c.execute("INSERT INTO files (name, url, hash, file_type) VALUES (%s, %s, %s, %s)",
  236. [thwart(filename),thwart(app.config['UPLOAD_FOLDER'] + '/' + filename),thwart(str(uuid4())),thwart(file_type)])
  237. conn.commit()
  238. c.close()
  239. conn.close()
  240. flash("Файл добавлен")
  241. return redirect(url_for('upload'))
  242. return render_template('add_file.html',title=title)
  243.  
  244.  
  245.  
  246. @app.route('/check/')
  247. def check():
  248. return '''Check page
  249. '''
  250. # error handlers
  251. @app.errorhandler(404)
  252. def page_not_found(e):
  253. error = "404: Страница не найдена"
  254. return render_template("fail.html", error=error)
  255.  
  256. if __name__ == "__main__":
  257. app.run(debug=True, host='0.0.0.0')
Add Comment
Please, Sign In to add comment