Browse Source

Incluyo la foto en el registro y la muestro en el botón de la cabecera

politica
Celestino Rey 1 year ago
parent
commit
11f0ca1939
15 changed files with 233 additions and 34 deletions
  1. +107
    -0
      PruebaFoto/app.py
  2. BIN
      PruebaFoto/instance/users.db
  3. BIN
      PruebaFoto/static/uploads/daniel.jpg
  4. BIN
      PruebaFoto/static/uploads/theriver.jpg
  5. +18
    -0
      PruebaFoto/templates/index.html
  6. +17
    -0
      PruebaFoto/templates/login.html
  7. +15
    -0
      PruebaFoto/templates/profile.html
  8. +21
    -0
      PruebaFoto/templates/register.html
  9. BIN
      ReymotaPy/servicios/instance/reymotapy.db
  10. BIN
      ReymotaPy/servicios/instance/uploads/nebraska.jpg
  11. +19
    -22
      ReymotaPy/servicios/reymotapy/auth.py
  12. +1
    -1
      ReymotaPy/servicios/reymotapy/models.py
  13. +1
    -1
      ReymotaPy/servicios/reymotapy/templates/_cabecera.html
  14. +1
    -1
      ReymotaPy/servicios/reymotapy/templates/login.html
  15. +33
    -9
      ReymotaPy/servicios/reymotapy/templates/signup.html

+ 107
- 0
PruebaFoto/app.py View File

@ -0,0 +1,107 @@
import os
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.secret_key = 'your_secret_key' # Cambia esto por una clave secreta segura
# Configuración de la base de datos
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Configuración para subir archivos
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB
# Asegúrate de que el directorio de carga existe
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Inicializa la base de datos
db = SQLAlchemy(app)
# Inicializa Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# Modelo de usuario
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(150), unique=True, nullable=False)
password = db.Column(db.String(150), nullable=False)
photo = db.Column(db.String(150), nullable=True)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
user = User.query.filter_by(email=email).first()
if user and check_password_hash(user.password, password):
login_user(user)
flash('Logged in successfully.')
return redirect(url_for('profile'))
else:
flash('Invalid email or password.')
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('Logged out successfully.')
return redirect(url_for('index'))
@app.route('/profile')
@login_required
def profile():
photo_url = url_for('static', filename='uploads/' + current_user.photo) if current_user.photo else None
return render_template('profile.html', email=current_user.email, photo_url=photo_url)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
confirm_password = request.form['confirm_password']
photo = request.files['photo']
if password != confirm_password:
flash('Passwords do not match.')
return redirect(url_for('register'))
hashed_password = generate_password_hash(password)
if photo:
photo_filename = secure_filename(photo.filename)
photo.save(os.path.join(app.config['UPLOAD_FOLDER'], photo_filename))
else:
photo_filename = None
new_user = User(email=email, password=hashed_password, photo=photo_filename)
try:
db.session.add(new_user)
db.session.commit()
flash('Registration successful.')
return redirect(url_for('login'))
except:
flash('Email address already exists.')
return redirect(url_for('register'))
return render_template('register.html')
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)

BIN
PruebaFoto/instance/users.db View File


BIN
PruebaFoto/static/uploads/daniel.jpg View File

Before After
Width: 959  |  Height: 1280  |  Size: 65 KiB

BIN
PruebaFoto/static/uploads/theriver.jpg View File

Before After
Width: 320  |  Height: 320  |  Size: 34 KiB

+ 18
- 0
PruebaFoto/templates/index.html View File

@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example App</title>
</head>
<body>
<h1>Welcome to the Example App</h1>
{% if current_user.is_authenticated %}
<p>Welcome, {{ current_user.email }}!</p>
<a href="{{ url_for('profile') }}">Profile</a>
<a href="{{ url_for('logout') }}">Logout</a>
{% else %}
<a href="{{ url_for('login') }}">Login</a>
<a href="{{ url_for('register') }}">Register</a>
{% endif %}
</body>
</html>

+ 17
- 0
PruebaFoto/templates/login.html View File

@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="{{ url_for('login') }}" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
</body>
</html>

+ 15
- 0
PruebaFoto/templates/profile.html View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profile</title>
</head>
<body>
<h1>Profile</h1>
<p>Email: {{ email }}</p>
{% if photo_url %}
<img src="{{ photo_url }}" alt="Profile Photo">
{% endif %}
<a href="{{ url_for('logout') }}">Logout</a>
</body>
</html>

+ 21
- 0
PruebaFoto/templates/register.html View File

@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<form action="{{ url_for('register') }}" method="post" enctype="multipart/form-data">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="confirm_password">Confirm Password:</label>
<input type="password" id="confirm_password" name="confirm_password" required>
<label for="photo">Profile Photo:</label>
<input type="file" id="photo" name="photo">
<button type="submit">Register</button>
</form>
</body>
</html>

BIN
ReymotaPy/servicios/instance/reymotapy.db View File


BIN
ReymotaPy/servicios/instance/uploads/nebraska.jpg View File

Before After
Width: 320  |  Height: 320  |  Size: 34 KiB

+ 19
- 22
ReymotaPy/servicios/reymotapy/auth.py View File

@ -1,4 +1,4 @@
from flask import Blueprint, render_template, redirect, url_for, request, flash
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.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from flask_login import login_user, logout_user, login_required from flask_login import login_user, logout_user, login_required
@ -16,14 +16,12 @@ def login():
@bp.route('/login', methods=['POST']) @bp.route('/login', methods=['POST'])
def login_post(): def login_post():
print("Entrando en sesión (o no)")
username = request.form.get('username') username = request.form.get('username')
password = request.form.get('password') password = request.form.get('password')
remember = True if request.form.get('remember') else False remember = True if request.form.get('remember') else False
user = User.query.filter_by(username=username).first() user = User.query.filter_by(username=username).first()
print("Usuario: "+user.username)
# check if the user actually exists # check if the user actually exists
# take the user-supplied password, hash it, and compare it to the hashed password in the database # 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): if not user or not check_password_hash(user.password, password):
@ -41,12 +39,11 @@ def signup():
@bp.route('/signup', methods=['POST']) @bp.route('/signup', methods=['POST'])
def signup_post(): def signup_post():
print("Creando usuario")
email = request.form.get('email')
username = request.form.get('username')
password = request.form.get('password')
confirm_password = request.form.get('confirm_password')
photo = request.files['photo']
username = request.form['username']
email = request.form['email']
password = request.form['password']
confirm_password = request.form['confirm_password']
photo = request.files['fotoperfil']
if password != confirm_password: if password != confirm_password:
flash('Passwords do not match.') flash('Passwords do not match.')
@ -55,29 +52,29 @@ def signup_post():
user = User.query.filter_by(username=username).first() # if this returns a user, then the user already exists in database 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 if user: # if a user is found, we want to redirect back to signup page so user can try again
flash('La dirección de correo ya existe')
flash('Ese usuario ya existe')
return redirect(url_for('auth.signup')) return redirect(url_for('auth.signup'))
if photo: if photo:
photo_filename = secure_filename(photo.filename) photo_filename = secure_filename(photo.filename)
print("Foto: ", photo_filename) print("Foto: ", photo_filename)
photo.save(os.path.join(bp.config['UPLOAD_FOLDER'], photo_filename))
photo.save(os.path.join(current_app.config['UPLOAD_FOLDER'], photo_filename))
else: else:
photo_filename = None
print("No hay foto")
photo_filename = ""
# create a new user with the form data. Hash the password so the plaintext version isn't saved.
# create a new user with the form data. Hash the password so the plaintext version isn't saved.
new_user = User(email=email, username=username, password=generate_password_hash(password, method='pbkdf2:sha256'), photo=photo_filename) new_user = User(email=email, username=username, password=generate_password_hash(password, method='pbkdf2:sha256'), photo=photo_filename)
# add the new user to the database # add the new user to the database
try:
db.session.add(new_user)
db.session.commit()
flash('Registration successful.')
return redirect(url_for('auth.login'))
except:
flash('Email address already exists.')
return redirect(url_for('auth.login'))
# try:
db.session.add(new_user)
db.session.commit()
flash('Registration successful.')
return redirect(url_for('auth.login'))
# except:
# flash('Email address already exists.')
# return redirect(url_for('auth.signup'))
@bp.route('/logout') @bp.route('/logout')


+ 1
- 1
ReymotaPy/servicios/reymotapy/models.py View File

@ -8,5 +8,5 @@ class User(UserMixin, db.Model):
email = db.Column(db.String(150), unique=True, nullable=False) email = db.Column(db.String(150), unique=True, nullable=False)
username = db.Column(db.String(150), unique=True, nullable=False) username = db.Column(db.String(150), unique=True, nullable=False)
password = db.Column(db.String(150), nullable=False) password = db.Column(db.String(150), nullable=False)
photo = db.Column(db.String(150), nullable=True)
photo = db.Column(db.String(150), nullable=False)

+ 1
- 1
ReymotaPy/servicios/reymotapy/templates/_cabecera.html View File

@ -119,7 +119,7 @@
</div><!--//app-utility-item--> </div><!--//app-utility-item-->
<div class="app-utility-item app-user-dropdown dropdown"> <div class="app-utility-item app-user-dropdown dropdown">
{% if current_user.is_authenticated %} {% if current_user.is_authenticated %}
<a class="dropdown-toggle" id="user-dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false"><img src="{{ url_for('paginas.uploaded_file', filename=user.photo) }}" alt="user profile"></a>
<a class="dropdown-toggle" id="user-dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false"><img src="{{ url_for('paginas.uploaded_file', filename=current_user.photo) }}" alt="user profile"></a>
{% else %} {% else %}
<a class="dropdown-toggle" id="user-dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false"><img src="{{ url_for('static', filename='images/reymota-logo.svg') }}" alt="user profile"></a> <a class="dropdown-toggle" id="user-dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false"><img src="{{ url_for('static', filename='images/reymota-logo.svg') }}" alt="user profile"></a>
{% endif %} {% endif %}


+ 1
- 1
ReymotaPy/servicios/reymotapy/templates/login.html View File

@ -10,7 +10,7 @@
<div class="auth-form-container text-start"> <div class="auth-form-container text-start">
{% with messages = get_flashed_messages() %} {% with messages = get_flashed_messages() %}
{% if messages %} {% if messages %}
<div class="notification is-danger">
<div class="app-card alert alert-dismissible shadow-sm mb-4 border-left-decoration">
{{ messages[0] }} {{ messages[0] }}
</div> </div>
{% endif %} {% endif %}


+ 33
- 9
ReymotaPy/servicios/reymotapy/templates/signup.html View File

@ -12,36 +12,60 @@
{% with messages = get_flashed_messages() %} {% with messages = get_flashed_messages() %}
{% if messages %} {% if messages %}
<div class="notification is-danger">
<div class="app-card alert alert-dismissible shadow-sm mb-4 border-left-decoration">
{{ messages[0] }}. Go to <a href="{{ url_for('auth.login') }}">login page</a>. {{ messages[0] }}. Go to <a href="{{ url_for('auth.login') }}">login page</a>.
</div> </div>
{% endif %} {% endif %}
{% endwith %} {% endwith %}
<form class="auth-form auth-signup-form" method="POST" action="/signup">
<div class="email mb-3">
<form class="auth-form auth-signup-form" method="POST" action="{{ url_for('auth.signup') }}" enctype="multipart/form-data">
<div class="username mb-3">
<label class="sr-only" for="signup-name">Your Name</label> <label class="sr-only" for="signup-name">Your Name</label>
<input id="signup-name" name="username" type="text" class="form-control signup-name" placeholder="Nombre de usuario" required="required">
<input id="signup-name"
name="username"
type="text"
class="form-control signup-name"
placeholder="Nombre de usuario"
required="required">
</div> </div>
<div class="email mb-3"> <div class="email mb-3">
<label class="sr-only" for="email">Your Email</label> <label class="sr-only" for="email">Your Email</label>
<input id="signup-email" name="email" type="email" class="form-control signup-email" placeholder="Email" required="required">
<input id="signup-email"
name="email"
type="email"
class="form-control signup-email"
placeholder="Email"
required="required">
</div> </div>
<div class="password mb-3"> <div class="password mb-3">
<label class="sr-only" for="password">Password</label> <label class="sr-only" for="password">Password</label>
<input id="signup-password" name="password" type="password" class="form-control signup-password" placeholder="Create a password" required="required">
<input id="signup-password"
name="password"
type="password"
class="form-control signup-password"
placeholder="Create a password"
required="required">
</div> </div>
<div class="password mb-3"> <div class="password mb-3">
<label class="sr-only" for="confirm_password">Confirm password</label> <label class="sr-only" for="confirm_password">Confirm password</label>
<input id="confirm_password" name="confirm_password" type="password" class="form-control signup-password" placeholder="Confirm password" required="required">
<input id="confirm_password"
name="confirm_password"
type="password"
class="form-control signup-password"
placeholder="Confirm password"
required="required">
</div> </div>
<div class="text mb-3"> <div class="text mb-3">
<label for="photo">Foto de perfil:</label>
<input class="form-control" name="photo" type="file" id="photo">
<label for="fotoperfil">Foto de perfil:</label>
<input id="fotoperfil"
name="fotoperfil"
type="file"
class="form-control"
required="required">
</div> </div>
<!-- <!--


Loading…
Cancel
Save