Untitled

mail@pastecode.io avatar
unknown
plain_text
20 days ago
2.5 kB
3
Indexable
Never
@app.route('/register', methods=['GET','POST'])
def register():
    if request.method == 'POST':
        username = request.form.get("username")
        password = request.form.get("password")
        repeat_password = request.form.get("passwordRepeat")

        existing_user = users_collection.find_one({"$or": [{"username": username}]})

        if not username or not password or not repeat_password:
            flash('Fields cannot be empty', 'error')
            return redirect(url_for('register'))
        
        if existing_user:
            flash('Username already exists', 'error')
            return redirect(url_for('register'))
        
        if password != repeat_password:
            flash("Passwords don't match", 'error')
            return redirect(url_for('register'))
        
        hasher = hashlib.shake_256()
        hasher.update(password.encode("utf-8"))
        hashed_password = hasher.digest(32)
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        data = {
            "created": timestamp,
            "username": username,
            "password": hashed_password,
            "admin": 0,
            "tasks": 0
        }
        users_collection.insert_one(data)

        flash('You have registered successfully', 'success')
        return redirect(url_for('login'))

    return render_template(register_template)

@app.route('/login', methods=['POST','GET'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        user = users_collection.find_one({"username": username})

        if not username or not password:
            flash('Fields cannot be empty', 'error')
            return redirect(url_for('login'))

        if user:
            stored_password = user.get("password")
            hasher = hashlib.shake_256()
            hasher.update(password.encode('utf-8'))
            hashed_password = hasher.digest(32)

            if hashed_password == stored_password:
                session["username"] = user["username"]
                session["admin"] = user.get("admin", 0)
                return redirect(url_for('main'))
            else:
                flash('Incorrect password', 'error')
                return redirect(url_for('login'))
        else:
            flash("User doesn't exist", 'error')
            return redirect(url_for('login'))

    return render_template(login_template)
Leave a Comment