You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

78 lines
2.7 KiB

from flask import Blueprint, render_template, redirect, url_for, request, flash, current_app
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from flask_login import login_user, logout_user, login_required
from .models import User
import os
from . import db
bp = Blueprint('auth', __name__)
@bp.route('/login')
def login():
return render_template('login.html')
@bp.route('/login', methods=['POST'])
def login_post():
username = request.form.get('username')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
user = User.query.filter_by(username=username).first()
# check if the user actually exists
# take the user-supplied password, hash it, and compare it to the hashed password in the database
if not user or not check_password_hash(user.password, password):
flash('Por favor, comprueba los datos de registro y vuelve a intentarlo.')
return redirect(url_for('auth.login')) # if the user doesn't exist or password is wrong, reload the page
# if the above check passes, then we know the user has the right credentials
login_user(user, remember=remember)
return redirect(url_for('paginas.index'))
@bp.route('/signup')
def signup():
return render_template('signup.html')
@bp.route('/signup', methods=['POST'])
def signup_post():
username = request.form.get('username')
password = request.form.get('password')
confirm_password = request.form.get('confirm_password')
photo = request.files['fotoperfil']
if password != confirm_password:
flash('Passwords do not match.')
return redirect(url_for('auth.signup'))
user = User.query.filter_by(username=username).first() # if this returns a user, then the user already exists in database
if user: # if a user is found, we want to redirect back to signup page so user can try again
flash('Ese usuario ya existe')
return redirect(url_for('auth.signup'))
if photo:
photo_filename = secure_filename(photo.filename)
print("Foto: ", photo_filename)
photo.save(os.path.join(current_app.config['UPLOAD_FOLDER'], photo_filename))
else:
print("No hay foto")
photo_filename = ""
# create a new user with the form data. Hash the password so the plaintext version isn't saved.
new_user = User(username=username, password=generate_password_hash(password, method='pbkdf2:sha256'), photo=photo_filename)
# add the new user to the database
db.session.add(new_user)
db.session.commit()
return redirect(url_for('auth.login'))
@bp.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('paginas.index'))