Skip to content

Commit 2c3ffad

Browse files
authored
Merge pull request #10 from 4GeeksAcademy/ft008-login
Ft008 login
2 parents 9259f15 + c9c8477 commit 2c3ffad

File tree

5 files changed

+100
-61
lines changed

5 files changed

+100
-61
lines changed

migrations/versions/a9b7f08f1a62_.py migrations/versions/7f479f7b82b2_.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
"""empty message
22
3-
Revision ID: a9b7f08f1a62
3+
Revision ID: 7f479f7b82b2
44
Revises:
5-
Create Date: 2025-03-06 10:20:42.876362
5+
Create Date: 2025-03-08 10:50:02.759160
66
77
"""
88
from alembic import op
99
import sqlalchemy as sa
1010

1111

1212
# revision identifiers, used by Alembic.
13-
revision = 'a9b7f08f1a62'
13+
revision = '7f479f7b82b2'
1414
down_revision = None
1515
branch_labels = None
1616
depends_on = None
@@ -49,7 +49,6 @@ def upgrade():
4949
sa.Column('name', sa.String(length=80), nullable=False),
5050
sa.Column('email', sa.String(length=120), nullable=False),
5151
sa.Column('password', sa.String(length=80), nullable=False),
52-
sa.Column('is_active', sa.Boolean(), nullable=False),
5352
sa.PrimaryKeyConstraint('id'),
5453
sa.UniqueConstraint('email')
5554
)
@@ -60,7 +59,7 @@ def upgrade():
6059
sa.Column('breed', sa.String(length=100), nullable=True),
6160
sa.Column('age', sa.String(), nullable=False),
6261
sa.Column('animal_type', sa.String(), nullable=False),
63-
sa.Column('pathologies', sa.Text(), nullable=False),
62+
sa.Column('pathologies', sa.Text(), nullable=True),
6463
sa.Column('user_id', sa.Integer(), nullable=True),
6564
sa.Column('url', sa.String(length=255), nullable=True),
6665
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),

src/api/models.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ class User(db.Model):
1515
name= db.Column(db.String(80), nullable=False)
1616
email = db.Column(db.String(120), unique=True, nullable=False)
1717
password = db.Column(db.String(80), unique=False, nullable=False)
18-
is_active = db.Column(db.Boolean(), unique=False, nullable=False)
1918

2019
def __repr__(self):
2120
return f'<User {self.email}>'
@@ -24,8 +23,7 @@ def serialize(self):
2423
return {
2524
"id": self.id,
2625
"email": self.email,
27-
"name": self.name,
28-
"is_active": self.is_active
26+
"name": self.name
2927
# do not serialize the password, its a security breach
3028
}
3129

src/api/routes.py

+84-42
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def get_foods():
3535
foods = Food.query.all()
3636
if not foods:
3737
return "food not found", 404
38-
else:
38+
else:
3939
return jsonify([food.serialize() for food in foods]), 200
4040

4141

@@ -47,7 +47,7 @@ def get_food(food_id):
4747
return jsonify({"error": "Food not found"}), 404
4848
return jsonify(food.serialize()), 200
4949

50-
50+
#obtener todos los usuarios
5151
@api.route('/users', methods=['GET'])
5252
def get_users():
5353
users = User.query.all()
@@ -68,7 +68,7 @@ def get_user(user_id):
6868
@api.route('/pets', methods=['GET'])
6969
def get_pets():
7070
pets = Pet.query.all()
71-
if not pets:
71+
if not pets:
7272
return "no pets found", 404
7373
return jsonify([pet.serialize() for pet in pets]), 200
7474

@@ -85,11 +85,11 @@ def get_pet(pet_id):
8585
@api.route('/foods/suggestions/<int:pet_id>', methods=['GET'])
8686
def get_pet_suggestions(pet_id):
8787
pet = Pet.query.get(pet_id).serialize()
88-
# Problema: Un animal puede tener varias patologias en su campo, habría que coger este campo y tratarlo,
89-
# separar las patologias en una lista y hacer la query para cada patologia.
88+
# Problema: Un animal puede tener varias patologias en su campo, habría que coger este campo y tratarlo,
89+
# separar las patologias en una lista y hacer la query para cada patologia.
9090
# Solucion simple: limitar a 1 patologia cada animal por ahora
9191
#if para pet# anymal_type == perro, animal size #si no no hace falta size
92-
if pet["animal_type"] == "perro":
92+
if pet["animal_type"] == "perro":
9393
food_suggestions = db.session.execute(select(Food).where(and_(Food.animal_type==pet["animal_type"]),
9494
Food.size==pet["size"],
9595
Food.age==pet["age"],
@@ -99,38 +99,38 @@ def get_pet_suggestions(pet_id):
9999
Food.age==pet["age"],
100100
Food.pathologies==pet["pathologies"]).all()
101101
if not food_suggestions :
102-
return "no suggestions found", 404
102+
return "no suggestions found", 404
103103
return [food[0].serialize() for food in food_suggestions], 200
104104

105105

106106
#obtener todos los alimentos según tipo de animal
107107
@api.route('/foods/cat', methods=['GET'])
108108
def get_all_cat_food():
109109
food_cat = db.session.query(Food).filter(Food.animal_type.ilike("%gato%")).all()
110-
111-
print("Datos obtenidos:", food_cat)
112-
110+
111+
print("Datos obtenidos:", food_cat)
112+
113113
if not food_cat:
114-
return jsonify({"error": "No cat food found"}), 404
115-
114+
return jsonify({"error": "No cat food found"}), 404
115+
116116
print("Datos obtenidos:", food_cat)
117117
if not food_cat:
118118
return jsonify({"error": "No cat food found"}), 404
119119

120120
return jsonify([food.serialize() for food in food_cat]), 200
121-
121+
122122

123123

124124
@api.route('/foods/dog', methods=['GET'])
125125
def get_all_dog_food():
126126
food_dog = db.session.query(Food).filter(Food.animal_type.ilike("%perro%")).all()
127127

128-
129-
print("Datos obtenidos:", food_dog)
130-
128+
129+
print("Datos obtenidos:", food_dog)
130+
131131
if not food_dog:
132-
return jsonify({"error": "No dog food found"}), 404
133-
132+
return jsonify({"error": "No dog food found"}), 404
133+
134134

135135
print("Datos obtenidos:", food_dog)
136136
if not food_dog:
@@ -142,12 +142,12 @@ def get_all_dog_food():
142142
def get_all_exotic_food():
143143
food_exotic = db.session.query(Food).filter(Food.animal_type.ilike("%exótico%")).all()
144144

145-
146-
print("Datos obtenidos:", food_exotic)
147-
145+
146+
print("Datos obtenidos:", food_exotic)
147+
148148
if not food_exotic:
149-
return jsonify({"error": "No exotic food found"}), 404
150-
149+
return jsonify({"error": "No exotic food found"}), 404
150+
151151

152152
print("Datos obtenidos:", food_exotic)
153153
if not food_exotic:
@@ -160,7 +160,7 @@ def get_all_exotic_food():
160160
def get_accessories():
161161
accessories = Accessories.query.all()
162162
if not accessories:
163-
return "no accessories found", 404
163+
return "no accessories found", 404
164164
return jsonify([accessory.serialize() for accessory in accessories]), 200
165165

166166

@@ -192,34 +192,76 @@ def create_food():
192192
db.session.commit()
193193
return jsonify(new_food.serialize()), 201
194194

195-
#registrar nuevo usuario
196-
@api.route('/users', methods=['POST'])
195+
196+
#registrar nuevo usuario(signup)
197+
@api.route('/signup', methods=['POST'])
197198
def create_user():
198199
data = request.get_json()
199200
new_user = User(
200201
name=data["name"],
201202
email=data["email"],
202-
password=data["password"],
203-
is_active=data["is_active"]
203+
password=data["password"]
204204
)
205205
if User.query.filter_by(email=data["email"]).first():
206206
return jsonify({"msg": "El usuario ya existe"}), 400
207-
207+
208208
db.session.add(new_user)
209209
db.session.commit()
210210
return jsonify(new_user.serialize()), 201
211211

212-
# iniciar sesion
213-
@api.route('loging/user', methods=['POST'])
214-
def logging_user():
215-
data = request.get_json()
216-
user = User.query.filter_by(email=data["email"]).first()
212+
# iniciar sesion(login)
213+
# @api.route('/login', methods=['POST'])
214+
# def logging_user():
215+
# data = request.get_json()
216+
# user = User.query.filter_by(email=data["email"]).first()
217+
218+
219+
# if User.query.filter_by(email=data["email"]).first() and User.query.filter_by(password=data["password"]).first():
220+
# access_token=create_access_token(identity=user.email)
221+
# return jsonify(access_token=access_token), 200
217222

223+
# return jsonify ({"nsg":"credenciales invalidas"}), 400
224+
225+
@api.route('/login', methods=['POST'])
226+
def login_user():
218227

219-
if User.query.filter_by(email=data["email"]).first() and User.query.filter_by(password=data["password"]).first():
220-
access_token=create_access_token(identity=user.email)
221-
return jsonify(access_token=access_token), 200
222-
return jsonify ({"nsg":"credenciales invalidas"}), 400
228+
body = request.get_json()
229+
230+
if not body or "email" not in body or "password" not in body:
231+
return jsonify({"msg": "credenciales no validas"}), 400
232+
233+
email = body["email"]
234+
password = body["password"]
235+
236+
user = User().query.filter_by(email=email, password=password).first()
237+
token=create_access_token(identity=user.email)
238+
user_data = {
239+
"id": user.id,
240+
"email": user.email,
241+
"name": user.name
242+
}
243+
244+
return jsonify({"msg": "inicio de sesion exitoso", "token": token, "user": user_data}), 200
245+
246+
#Vista privada del usuario CON el token
247+
@api.route('/user', methods=['GET'])
248+
@jwt_required()
249+
def get_user_info():
250+
251+
current_user_email = get_jwt_identity()
252+
253+
user = User().query.filter_by(email=current_user_email).first()
254+
255+
if not user:
256+
return jsonify({"msg": "usuario no encontrado"}), 400
257+
258+
user_data = {
259+
"id": user.id,
260+
"email": user.email,
261+
"name": user.name
262+
}
263+
264+
return jsonify(user_data), 200
223265

224266

225267
#crear un nuevo accesorio
@@ -251,8 +293,8 @@ def create_pet():
251293
animal_type=data["animal_type"],
252294
pathologies=data["pathologies"],
253295
user_id=data["user_id"],
254-
255-
296+
297+
256298
)
257299
db.session.add(new_accessory)
258300
db.session.commit()
@@ -265,7 +307,7 @@ def create_pet():
265307
# return jsonify({"message": "Food not found"}), 404
266308

267309
# data = request.get_json()
268-
310+
269311
# food.name = data.get("name", food.name)
270312
# food.brand = data.get("brand", food.brand)
271313
# food.description = data.get("description", food.description)
@@ -288,7 +330,7 @@ def create_pet():
288330
# "animal_type": food.animal_type,
289331
# "price": food.price,
290332
# "weight": food.weight,
291-
# "size" : food.size,
333+
# "size" : food.size,
292334
# "pathologies": food.pathologies,
293335
# "url": food.url
294336
# })

src/front/js/pages/loginSignup.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ import "../../styles/home.css";
55

66
export const LoginSignup = () => {
77

8-
const { actions } = useContext(Context);
8+
const { actions, store } = useContext(Context);
99
const navigate = useNavigate();
1010

11-
const [username, setUsername] = useState('');
11+
const [name, setName] = useState('');
1212
const [email, setEmail] = useState('');
1313
const [password, setPassword] = useState('');
1414
const [isSignup, setIsSignup] = useState(false);
@@ -21,13 +21,13 @@ export const LoginSignup = () => {
2121
setError('');
2222

2323
try {
24-
const dataUser = { username, email, password };
24+
const dataUser = { name, email, password };
2525
if (isSignup) {
2626
await actions.signup(dataUser, navigate);
2727
} else {
2828
await actions.login(email, password, navigate);
2929
}
30-
setUsername('');
30+
setName('');
3131
setEmail('');
3232
setPassword('');
3333
} catch (err) {
@@ -68,10 +68,10 @@ export const LoginSignup = () => {
6868
<form className="auth-form signup-form" onSubmit={handleSubmit}>
6969
<h2>Regístrate</h2>
7070
<input
71-
type="username"
72-
placeholder="Nombre de usuario"
73-
value={username}
74-
onChange={(e) => setUsername(e.target.value)}
71+
type="name"
72+
placeholder="Nombre"
73+
value={name}
74+
onChange={(e) => setName(e.target.value)}
7575
required
7676
/>
7777
<input

src/front/js/store/flux.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const getState = ({ getStore, getActions, setStore }) => {
2828

2929
login: async (email, password, navigate) => {
3030
try {
31-
const resp = await fetch(`${process.env.BACKEND_URL}api/login/user`, {
31+
const resp = await fetch(`${process.env.BACKEND_URL}/api/login`, {
3232
method: "POST",
3333
headers: {
3434
"Content-Type": "application/json"
@@ -61,7 +61,7 @@ const getState = ({ getStore, getActions, setStore }) => {
6161
},
6262
signup: async (dataUser, navigate) => {
6363
try {
64-
const resp = await fetch(`${process.env.BACKEND_URL}api/signup`, {
64+
const resp = await fetch(`${process.env.BACKEND_URL}/api/signup`, {
6565
method: "POST",
6666
headers: {
6767
"Content-Type": "application/json"
@@ -95,7 +95,7 @@ const getState = ({ getStore, getActions, setStore }) => {
9595
const token = localStorage.getItem("token");
9696
if (!token) throw new Error("No token found");
9797

98-
const resp = await fetch(`${process.env.BACKEND_URL}api/user`, {
98+
const resp = await fetch(`${process.env.BACKEND_URL}/api/user`, {
9999
headers: {
100100
"Authorization": `Bearer ${token}`
101101
}

0 commit comments

Comments
 (0)