Skip to content

Commit

Permalink
modificações
Browse files Browse the repository at this point in the history
  • Loading branch information
thisiscleverson committed Jan 30, 2024
1 parent 837ecd8 commit 338589d
Show file tree
Hide file tree
Showing 10 changed files with 300 additions and 208 deletions.
10 changes: 1 addition & 9 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
<<<<<<< HEAD
__pycache__/

instance/
migrations/
flask_session/
.venv/
=======
__pycache__

instance
migrations
flask_session
>>>>>>> 78d4ede (create auth)
.venv/
17 changes: 0 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,17 @@

## como rodar esse projeto

<<<<<<< HEAD
<<<<<<< HEAD
=======
=======
>>>>>>> 78d4ede (create auth)
* Antes de mais nada, é indicado criar um ambiente virtual.
```sh
python3 -m venv .venv
```

<<<<<<< HEAD
>>>>>>> 78d4ede (create auth)
=======
>>>>>>> 78d4ede (create auth)
```sh
export FLASK_app=app
export FLASK_ENV=Development
export FLASK_DEBUG=True

<<<<<<< HEAD
<<<<<<< HEAD
flask run
=======
python3 -m flask run -h localhost
>>>>>>> 78d4ede (create auth)
=======
python3 -m flask run -h localhost
>>>>>>> 78d4ede (create auth)
```

## migrate
Expand Down
9 changes: 0 additions & 9 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from flask import Flask
from flask import Flask, render_template
from flask_migrate import Migrate
from flask_session import Session
Expand All @@ -8,14 +7,6 @@

def create_register_blueprint(app):
from .auth import auth
from .blog import blog

app.register_blueprint(auth)
app.register_blueprint(blog)


def create_app():
app = Flask(__name__, template_folder='../templates')
from .admin import admin
from .blog import blog

Expand Down
162 changes: 162 additions & 0 deletions app/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import re
from unidecode import unidecode
from uuid import uuid4
from flask import Blueprint, request, redirect, session, render_template, flash, jsonify
from app.models import Contents, db

admin = Blueprint('admin', __name__)

@admin.route('/admin', methods=['GET'])
def home():
if not session.get("token"):
return redirect('/login')

draft_list = Contents.query.filter(Contents.status == "draft").all()
contents_list = Contents.query.filter(Contents.status == "published").all()

return render_template('admin/home.html', draft_list=draft_list, contents_list=contents_list)


@admin.route('/publish', methods=['GET', 'POST'])
def publish():
if not session.get("token"):
return redirect('/login')

if request.method == "POST":
title, content, description = get_title_content_description()

if data_valid(title, content):
insert_content(
title=title,
body=content,
status='published',
accessType='public',
description=description
)
return redirect('/')

flash("O titulo ou texto não está preenchido adequadamente! Por favor, verifique se você preencheu os campo corretamente!")

return render_template('admin/editor.html', is_draft_mode=True)


@admin.route('/update/<id>', methods=['GET', 'POST', 'PUT'])
def update(id):
if not session.get("token"):
return redirect('/login')

if request.method == "POST":
data = request.get_json()

title = data['title']
body = data['body']
description = data['description']

if data_valid(title, body):
update_content(id=id, title=title,body=body, description=description)
return jsonify({"status_code": 200, 'success': True}), 200

return jsonify({"status_code":200, "success":True, "message":"O titulo ou texto não está preenchido adequadamente! Por favor, verifique se você preencheu os campo corretamente!"}), 200

if request.method == 'PUT':
data = request.get_json()

title = data['title']
body = data['body']
description = data['description']

if data_valid(title, body):
update_content(id=id, title=title,body=body, status='published', description=description)
return jsonify({"status_code": 200, 'success': True}), 200

if request.method == "GET":
title, body, description = obtain_draft_title_and_body(id)
return render_template('admin/editor.html', id=id, title=title, body=body, description=description, is_draft_mode=False)


@admin.route('/draft', methods=['POST'])
def draft():
if request.method == "POST":
data = request.get_json()

title = data['title']
content = data['body']
description = data['description']

if data_valid(title, content):
insert_content(
title=title,
body=content,
status='draft',
accessType='public',
description=description
)
return jsonify({"status_code": 200, 'success': True}), 200

return jsonify({
"error": {
"status_code": 400,
"message": "Os campos título e texto não foram preenchidos adequadamente. Por favor, verifique se você preencheu os campos corretamente."
}
}), 400

return jsonify({"status_code": 400, "erro": "Método não permitido"}), 405


@admin.route('/delete/post/<post_id>', methods=['DELETE'])
def delete_post(post_id):
if not session.get("token"):
return jsonify({
"status": "error",
"message": "Você não tem permissão para deletar este post.",
"code": 403
}), 403

Contents.query.filter(Contents.id == post_id).delete()
db.session.commit()

return jsonify({"status_code":200, "success":True}), 200

def obtain_draft_title_and_body(id: str):
query = Contents.query.filter(Contents.id == id)
draft_data = query.first()
title, body, description = draft_data.title, draft_data.body, draft_data.description
return title, body, description

def get_title_content_description():
return request.form.get("title"), request.form.get("markdown-content"), request.form.get('description')

def data_valid(title: str, content: str) -> bool:
return len(title.strip()) > 0 and len(content.strip()) > 0

def update_content(id:str, title: str, body: str,description:str, status:str = None) -> None:
if status is None:
Contents.query.filter_by(id=id).update({Contents.title:title, Contents.body:body, Contents.description:description})
db.session.commit()
return
Contents.query.filter_by(id=id).update({Contents.title:title, Contents.body:body, Contents.status:status, Contents.description:description})
db.session.commit()

def generate_slug(title:str) -> str:
title = unidecode(title)
slug = re.sub(r'[^\w\s-]', '', title.lower())
slug = re.sub(r'\s', '-', slug)
return slug

def insert_content(title: str, body: str, status: str, accessType: str, description:str) -> None:
"""
status: "published" or "draft"
accessType: "public" or "private"
"""
db.session.add(
Contents(
id=str(uuid4()),
title=title,
body=body,
slug=generate_slug(title),
status=status,
accessType=accessType,
description=description
)
)
db.session.commit()
133 changes: 89 additions & 44 deletions app/auth.py
Original file line number Diff line number Diff line change
@@ -1,61 +1,106 @@
import bcrypt
from uuid import uuid4
from flask import Blueprint, redirect, session, jsonify, render_template, request
from flask import Blueprint, redirect, session, render_template, request, flash
from sqlalchemy.sql import exists

from .models import Contents,Users, db
from app.models import Users, db


auth = Blueprint('account', __name__)
auth = Blueprint('auth', __name__)


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

query = Users.query.filter(Users.username==USERNAME, Users.password==PASSWORD)
result = query.first()
error = None
if request.method == 'POST':
username, password = get_username_and_password()

if check_username_exist(username):

hashpass = get_hash_password(username)
user_type = get_user_type(username)

if result:
session["token"] = uuid4()
return redirect("/")
else:
return jsonify({"message": "usuario ou senha incorreta!" })
return render_template('login.html')
if bcrypt.checkpw(password.encode('utf-8'), hashpass):
if user_type == 'admin':
session["token"] = uuid4()
return redirect("/admin")
else:
flash("Você não tem permissão para acessar essa página!\nÉ necessário pedir permissão para o admin da página!")
else:
flash("Usuário ou senha incorretas!")
else:
flash("Usuário não existe!")
return render_template('auth/login.html', error=error)


@auth.route('/logout')
def logout():
session["token"] = None
return redirect("/")
session["token"] = None
print('logout')
return redirect("/admin")


@auth.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
#registrar como admin
if Users.query.count() == 0:
db.session.add(
Users(
id = str(uuid4()),
username=request.form.get('username'),
password=request.form.get('password'),
userType='admin'
)
)
db.session.commit()
return redirect("/login")

else:
db.session.add(
Users(
id = str(uuid4()),
username=request.form.get('username'),
password=request.form.get('password'),
userType='user'
error = None
if request.method == 'POST':
username, password = get_username_and_password()

# registrar como admin
if Users.query.count() == 0:
register_user(
username=username,
password=password,
user_type='admin'
)
)
db.session.commit()
return redirect("/login")

return render_template('register.html')
return redirect("/login")
else:
username_exist = check_username_exist(username)
if not username_exist:
register_user(
username=username,
password=password,
user_type='user'
)
return redirect("/login")
else:
error = "usuário já cadastrado!"
return render_template('auth/register.html', error=error)



def get_hash_password(username):
hash_password = Users.query.filter_by(username=username).first().password
return hash_password


def get_user_type(username):
user_type = Users.query.filter_by(username=username).first().userType
return user_type


def check_username_exist(username):
query = Users.query.filter(Users.username == username)
result = query.first()
return result


def get_username_and_password():
return request.form.get('username'), request.form.get('password')


def register_user(username, password, user_type):
db.session.add(
Users(
id=str(uuid4()),
username=username,
password=encrypt_password(password),
userType=user_type
)
)
db.session.commit()


def encrypt_password(password):
byte_password = password.encode('utf-8')
hash_password = bcrypt.hashpw(byte_password, bcrypt.gensalt())
return hash_password
Loading

0 comments on commit 338589d

Please sign in to comment.