Skip to content

Commit

Permalink
update username in homepage, start working with logicals of front ass…
Browse files Browse the repository at this point in the history
…ign pack, create new logics and endpoint for find user by email or username b00tc4mp#219
  • Loading branch information
nomadwebs committed Dec 10, 2024
1 parent 569c077 commit 68b5713
Show file tree
Hide file tree
Showing 23 changed files with 204 additions and 55 deletions.
10 changes: 0 additions & 10 deletions staff/francisco-sanchez/project/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,12 @@ db.connect(process.env.MONGO_URL).then(() => {

server.use(cors())

const jsonBodyParser = json()

server.get('/', (_, res) => res.send('API is Up Ready to go'))

//Here will be all the endpoints of the API.
server.use('/users', usersRouter)
server.use('/packs', packsRouter)

//TODO: Quitar el siguiente bloque
server.use((req, res, next) => {
console.log(`Request: ${req.method} ${req.originalUrl}`);
console.log('Headers:', req.headers);
next();
});


server.use(errorHandler)

server.listen(process.env.PORT, () => console.log(`api is up and listening on port ${process.env.PORT}`))
Expand Down
4 changes: 4 additions & 0 deletions staff/francisco-sanchez/project/api/logic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
authenticateUser,
getUserName,
getCustomers,
getUserByEmail,
getUserByUserame
} from './users/index.js'

import {
Expand All @@ -21,6 +23,8 @@ const logic = {
authenticateUser,
getUserName,
getCustomers,
getUserByEmail,
getUserByUserame,

createPack,
assignPack,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export default (userId) => {
basePack.id = basePack._id.toString()
delete basePack._id
})

return basePack
})
}
25 changes: 25 additions & 0 deletions staff/francisco-sanchez/project/api/logic/users/getUserByEmail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { User } from "dat";
import { validate, errors } from "com";

const { SystemError, NotFoundError } = errors;

export default async (userId, userEmail) => {
// Validaciones de entrada
validate.id(userId, "userId");
validate.email(userEmail, "userEmail");

try {
// Busca el usuario principal por ID
const user = await User.findById(userId).lean();
if (!user) throw new NotFoundError("User not found");

// Busca el usuario objetivo por email
const targetUser = await User.findOne({ email: userEmail }).lean();
if (!targetUser) throw new NotFoundError("Email not found");

// Devuelve el _id del usuario objetivo
return targetUser._id.toString();
} catch (error) {
throw new SystemError(error.message);
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'dotenv/config'
import db from 'dat'

import getUserByEmail from './getUserByEmail.js'

//await db.connect(process.env.MONGO_URL)
await db.connect('mongodb://127.0.0.1:27017/hourify')

try {
const userId = await getUserByEmail('675036c010473f3d809e5359', 'greygandalf4@themiddleearth.com')
console.log(userId)
} catch (error) {
console.error(error)
} finally {
await db.disconnect()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { User } from "dat";
import { validate, errors } from "com";

const { SystemError, NotFoundError } = errors;

export default async (userId, userUsername) => {
// Validaciones de entrada
validate.id(userId, "userId");
validate.username(userUsername, "username");

try {
// Busca el usuario principal por ID
const user = await User.findById(userId).lean();
if (!user) throw new NotFoundError("User not found");

// Busca el usuario objetivo por email
const targetUser = await User.findOne({ username: userUsername }).lean();
if (!targetUser) throw new NotFoundError("Target user not found");

// Devuelve el _id del usuario objetivo
return targetUser._id.toString();
} catch (error) {
throw new SystemError(error.message);
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'dotenv/config'
import db from 'dat'

import getUserByUserame from './getUserByUserame.js'

//await db.connect(process.env.MONGO_URL)
await db.connect('mongodb://127.0.0.1:27017/hourify')

try {
const userId = await getUserByUserame('675036c010473f3d809e5359', 'greygandalf2')
console.log(userId)
} catch (error) {
console.error(error)
} finally {
await db.disconnect()
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const { SystemError, NotFoundError } = errors
export default (userId, targetUserId) => {
validate.id(userId, 'userId')
validate.id(targetUserId, 'targetUserId')
console.log('llego a getUserName de API')

return (async () => {
let users
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@ import db from 'dat'

import getUserName from './getUserName.js'

//await db.connect(process.env.MONGO_URL)
await db.connect('mongodb://127.0.0.1:27017/hourify')


await db.connect(process.env.MONGO_URL)
//await db.connect('mongodb://127.0.0.1:27017/hourify')

try {
const name = await getUserName('6751994806347a4b6bd70cdb', '6751994806347a4b6bd70cdb')

console.log(name)
} catch (error) {
console.error(error)
Expand Down
6 changes: 5 additions & 1 deletion staff/francisco-sanchez/project/api/logic/users/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import authenticateUser from './authenticateUser.js'
import registerUser from './registerUser.js'
import getUserName from './getUserName.js'
import getCustomers from './getCustomers.js'
import getUserByEmail from './getUserByEmail.js'
import getUserByUserame from './getUserByUserame.js'

export {
authenticateUser,
registerUser,
getUserName,
getCustomers
getCustomers,
getUserByEmail,
getUserByUserame
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export default (req, res, next) => {
//console.log('token is: ' + token)

req.userId = userId
console.log('userIdf ' + userId)

console.log('userId ' + userId)
next() //Next will go to the next function
} catch (error) {
next(new AuthorizationError(error.message))
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import logic from "../../../logic/index.js";

import { createFunctionalHandler } from "../../helpers/index.js";

export default createFunctionalHandler((req, res) => {
const { userId } = req; // Esto viene del token
const { email } = req.params; // Esto viene de la URL

return logic.getUserByEmail(userId, email)
.then(userId => res.json(userId))
.catch(error => {
console.error('Error in findUserByEmailHandler:', error.message);
throw error;
});
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import logic from "../../../logic/index.js";

import { createFunctionalHandler } from "../../helpers/index.js";

export default createFunctionalHandler((req, res) => {
const { userId } = req; // Esto viene del token
const { username } = req.params; // Esto viene de la URL

return logic.getUserByUserame(userId, username)
.then(userId => res.json(userId))
.catch(error => {
console.error('Error in findUserByUsernameHandler:', error.message);
throw error;
});
})
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import authenticateUserHandler from './authenticateUserHandler.js';
import registerUserHandler from './registerUserHandler.js';
import getUserNameHandler from './getUserNameHandler.js';
import getCustomersHandler from './getCustomersHandler.js';
import findUserByEmailHandler from './findUserByEmailHandler.js';
import findUserByUsernameHandler from './findUserByUsernameHandler.js';

export {
authenticateUserHandler,
registerUserHandler,
getUserNameHandler,
getCustomersHandler
getCustomersHandler,
findUserByEmailHandler,
findUserByUsernameHandler
}
13 changes: 11 additions & 2 deletions staff/francisco-sanchez/project/api/routes/users/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
import { Router, json } from "express"

import { authorizationHandler, jsonBodyParser } from "../helpers/index.js"
import { authenticateUserHandler, registerUserHandler, getUserNameHandler, getCustomersHandler } from "./handlers/index.js"
import {
authenticateUserHandler,
registerUserHandler,
getUserNameHandler,
getCustomersHandler,
findUserByEmailHandler,
findUserByUsernameHandler
} from "./handlers/index.js"

const usersRouter = Router()

usersRouter.post('/auth', jsonBodyParser, authenticateUserHandler)
usersRouter.post('/register', jsonBodyParser, registerUserHandler)
usersRouter.get('/:targetUserId/name', authorizationHandler, getUserNameHandler) //TODO: Diferencia entre esto y la llamada al getBasePacks de packs
usersRouter.get('/:targetUserId/name', authorizationHandler, getUserNameHandler)
usersRouter.get('/customers', getCustomersHandler)
usersRouter.get('/findbyemail/:email', authorizationHandler, findUserByEmailHandler)
usersRouter.get('/findbyusername/:username', authorizationHandler, findUserByUsernameHandler)

export default usersRouter
19 changes: 19 additions & 0 deletions staff/francisco-sanchez/project/api/test/get-user-name.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const xhr = new XMLHttpRequest();

// Callback para manejar la respuesta de la solicitud
xhr.addEventListener('load', () => {
console.log(`Status: ${xhr.status}`);
console.log(`Response: ${xhr.response}`);
});

// Configura la solicitud
xhr.open('GET', 'http://localhost:8080/users/675036c010473f3d809e5359/name');

// Define el token JWT
const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NzUwMzZjMDEwNDczZjNkODA5ZTUzNTkiLCJyb2xlIjoic3RhbmRhcmQiLCJpYXQiOjE3MzM4Mjg0MTYsImV4cCI6MTczMzg1NzIxNn0.VancAL12ZxtfLX1i96PqkszViUjsA534bkUN8H1oR4c'; // Sustituye por tu token válido

// Añade el encabezado Authorization con Bearer Token
xhr.setRequestHeader('Authorization', `Bearer ${jwtToken}`);

// Envía la solicitud
xhr.send();
2 changes: 1 addition & 1 deletion staff/francisco-sanchez/project/api/test/get-user-name.sh
Original file line number Diff line number Diff line change
@@ -1 +1 @@
curl -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NzUwMzZjMDEwNDczZjNkODA5ZTUzNTkiLCJyb2xlIjoic3RhbmRhcmQiLCJpYXQiOjE3MzM3NDMxODcsImV4cCI6MTczMzc3MTk4N30.NmuT8VrU_heulQg10FTX9VuzYUSnzyvbtp9kKv6L8BU' http://localhost:8080/users/675036c010473f3d809e5359/name -v
curl -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NzUwMzZjMDEwNDczZjNkODA5ZTUzNTkiLCJyb2xlIjoic3RhbmRhcmQiLCJpYXQiOjE3MzM4Mjg0MTYsImV4cCI6MTczMzg1NzIxNn0.VancAL12ZxtfLX1i96PqkszViUjsA534bkUN8H1oR4c' http://localhost:8080/users/675036c010473f3d809e5359/name -v
16 changes: 2 additions & 14 deletions staff/francisco-sanchez/project/app/src/logic/users/getUserName.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,18 @@ import { errors } from 'com'
import { extractPayloadJWt } from '../../util'

const { SystemError } = errors

export default () => {
console.log('llego a la función getUserName')
const { sub: userId } = extractPayloadJWt(localStorage.token)
console.log(`El userId que paso a la url es: ${userId}`)

//const userId = '675036c010473f3d809e5359'
return fetch(`${import.meta.env.VITE_API_URL}/users/${userId}/name`, {
headers: {
Authorization: `Bearer ${localStorage.token}`
}
})
.catch(error => {
console.log('paso por el error')
throw new SystemError(error.message)
})

.catch(error => { throw new SystemError(error.message) })
.then(res => {
console.log('Respuesta del servidor:', res) // Depuración
if (res.ok)
return res.json()
.then(data => {
console.log('Datos obtenidos del servidor:', data) // Depuración
return data
})
.catch(error => { throw new SystemError(error.message) })

return res.json()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function getCurrencySymbol(basePack) {
if (!basePack || !basePack.currency) {
throw new Error('Currency not provided or basePack is invalid');
}

return basePack.currency === 'EUR' ? '€' : '$';
}
4 changes: 3 additions & 1 deletion staff/francisco-sanchez/project/app/src/util/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import extractPayloadJWt from "./extractPayloadJWt.js";
import getCurrencySymbol from "./getCurrencySymbol.js";

export {
extractPayloadJWt
extractPayloadJWt,
getCurrencySymbol
}
Loading

0 comments on commit 68b5713

Please sign in to comment.