瀏覽代碼

first attempt at secure file upload

control 3 年之前
父節點
當前提交
1ec26ed50c
共有 3 個文件被更改,包括 33 次插入2 次删除
  1. 6 0
      app/alphagen.py
  2. 25 0
      app/dashboards.py
  3. 2 2
      app/templates/create_art.html

+ 6 - 0
app/alphagen.py

@@ -0,0 +1,6 @@
+import string, secrets
+
+def gen_alphanum():
+    alphanumeric = string.ascii_letters + string.digits
+    ralphanum = ''.join(secrets.choice(alphanumeric) for i in range(16))
+    return ralphanum

+ 25 - 0
app/dashboards.py

@@ -1,9 +1,14 @@
+import os
+
 from flask import Blueprint, render_template, request, flash, redirect, url_for
 from flask_login import login_required, current_user
 from werkzeug.security import generate_password_hash, check_password_hash
+from werkzeug.utils import secure_filename
 from .models import User
 from . import db
 
+from . import alphagen as ag
+
 dashboards = Blueprint('dashboards', __name__)
 
 # Main Pages
@@ -35,6 +40,26 @@ def profile():
 @dashboards.route('/create_art', methods=['GET', 'POST'])
 #login_required
 def create():
+    UPLOAD_FOLDER = 'app/static/incoming'
+    ALLOWED_EXT = {'png', 'jpg', 'jpeg'}
+
+    # Checks file for allowed extension
+    def allowed_file(filename):
+        return '.' in filename and \
+                filename.rsplit('.', 1)[1].lower() in ALLOWED_EXT
+
+    # check POST req
+    if request.method == "POST":
+        new_art = request.files.get('art_img')
+
+        if new_art and new_art.filename != '' and allowed_file(new_art.filename):
+            sfn = secure_filename(new_art.filename) # strips any slashes
+            ssfn, fx = os.path.splitext(sfn) # ensures that internal filenames are not
+            rsfn = ag.gen_alphanum() # known to users.
+            ffn = f'{rsfn}{fx}'
+            new_art.save(f'{UPLOAD_FOLDER}/{ffn}')
+
+
     return render_template('create_art.html', user=current_user)
 	
 # Pop Ups

+ 2 - 2
app/templates/create_art.html

@@ -48,7 +48,7 @@
                     <label for="buyout_price"></label>
                 </div>
                 <!--Upload Art or choose what they bought before-->     
-                <input type="file" id="art_img" name="art_img">
+                <input type="file" id="art_img" name="art_img" accept="image/jpg, image/png">
                 <select name="web_group" style="height:47px" required aria-invalid="false"> 
                     <option value="cng-555">Select your own Art in our platform</option>
                     <option name="web_group" value="bought_art">bought_Art</option>
@@ -67,4 +67,4 @@
                 <button type="submit">Create</button>
 
 </form>
-{% endblock %}
+{% endblock %}