Skip to content

Commit

Permalink
Merge pull request #481 from JaviFdez7/develop
Browse files Browse the repository at this point in the history
Cambios del feedback de Antonio
  • Loading branch information
Moffinguer authored May 17, 2024
2 parents 64bd967 + 5a3fa19 commit 7f5e64a
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 38 deletions.
37 changes: 21 additions & 16 deletions api/v1/modules/user/middlewares/UserMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,11 @@ export const checkRealUser: any = async (req: Request, res: Response, next: Next
const data = req.body
// Comprobar si el usuario existe
const userByEmail = await User.findOne({ email: data.usernameOrEmail })
const userByUsername=await User.findOne({ username: data.usernameOrEmail })
const userByUsername = await User.findOne({ username: data.usernameOrEmail })
if (!userByEmail && !userByUsername) {
const message = 'User not found'
ApiResponse.sendError(res, [{ title: 'Not Found', detail: message }], 404)
}else {
} else {
next()
}
} catch (error: any) {
Expand All @@ -211,19 +211,18 @@ export const checkCorrectToken: any = async (req: Request, res: Response, next:
return
}
const decodedToken = verifyJWT(token)
if(!decodedToken.sub){
if (!decodedToken.sub) {
const message = 'Incorrect token'
ApiResponse.sendError(res, [{ title: 'Bad Request', detail: message }], 401)
return
}
const user= await User.findById(decodedToken.sub)
if(!user){
const user = await User.findById(decodedToken.sub)
if (!user) {
const message = 'User not found'
ApiResponse.sendError(res, [{ title: 'Not Found', detail: message }], 404)
}else {
} else {
next()
}

} catch (error: any) {
ApiResponse.sendError(res, [
{
Expand All @@ -234,21 +233,24 @@ export const checkCorrectToken: any = async (req: Request, res: Response, next:
}
}

export const checkRepeatedPassword: any = async (req: Request, res: Response, next: NextFunction) => {
export const checkRepeatedPassword: any = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const {newPassword,repeatedPassword} = req.body
const compare=newPassword === repeatedPassword
if(newPassword.lenght ===0 || repeatedPassword.lenght===0){
const { newPassword, repeatedPassword } = req.body
const compare = newPassword === repeatedPassword
if (newPassword.lenght === 0 || repeatedPassword.lenght === 0) {
const message = 'There are empty fields'
ApiResponse.sendError(res, [{ title: 'Bad Request', detail: message }], 400)
}else if(!(compare)){
} else if (!compare) {
const message = 'The passwords dont match'
ApiResponse.sendError(res, [{ title: 'Bad Request', detail: message }], 400)
}else {
req.body.encryptedPassword=await encrypt(newPassword)
} else {
req.body.encryptedPassword = await encrypt(newPassword)
next()
}

} catch (error: any) {
ApiResponse.sendError(res, [
{
Expand All @@ -273,7 +275,10 @@ export const checkLoginUser: any = async (req: Request, res: Response, next: Nex
return
}
// Comprobar si el usuario existe
const user = await User.findOne({ username: data.username })
const userByEmail = await User.findOne({ email: data.username })
const userByUsername = await User.findOne({ username: data.username })
const user = userByEmail ?? userByUsername

if (!user) {
const message = 'User not found'
ApiResponse.sendError(res, [{ title: 'Not Found', detail: message }], 404)
Expand Down
45 changes: 24 additions & 21 deletions api/v1/modules/user/services/UserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,45 +100,44 @@ export const deleteUser: any = async (id: any, role: string) => {
}
}

export const sendEmail: any = async (to: string, subject: string, text: string,html: string) =>{
try{
const from= process.env.SENGRID_EMAIL ?? ''
export const sendEmail: any = async (to: string, subject: string, text: string, html: string) => {
try {
const from = process.env.SENGRID_EMAIL ?? ''
const msg = {
to,
from,
subject,
text,
html,
};
}
await sgMail
.send(msg)
.then(() => {
console.log('Email sent')
})
.catch((error:any) => {
console.error(error)
})
}catch(error:any){
.send(msg)
.then(() => {
console.log('Email sent')
})
.catch((error: any) => {
console.error(error)
})
} catch (error: any) {
console.error('Error creating your request:', error)
throw error
}
}

export const createChangePasswordRequest: any = async (data: any,originalUrl: string) => {
export const createChangePasswordRequest: any = async (data: any, originalUrl: string) => {
try {
const userByEmail = await User.findOne({ email: data.usernameOrEmail })
const userByUsername=await User.findOne({ username: data.usernameOrEmail })
const userByUsername = await User.findOne({ username: data.usernameOrEmail })
const user = userByEmail ?? userByUsername
const id = user?._id.toString()
const token = generateJWTWithSoonerExpiration(id)
const result = originalUrl+"/"+token
const text=`To change the forgotten password, access this link: ${result}. \n
const result = originalUrl + '/' + token
const text = `The user with the username: ${user?.username} and email: ${user?.email} has requested to change the password.
To change the forgotten password, access this link: ${result}. \n
\n
In case of error, simply ignore the message.
Thank you very much for using IT TALENT :3`
await sendEmail(user?.email,'Verify password change',
text,`<strong> ${text} </strong>`
)
await sendEmail(user?.email, 'Verify password change', text, `<strong> ${text} </strong>`)
} catch (error) {
console.error('Error creating your request:', error)
throw error
Expand All @@ -147,7 +146,10 @@ export const createChangePasswordRequest: any = async (data: any,originalUrl: st

export const loginUser: any = async (data: any) => {
try {
const user = await User.findOne({ username: data.username })
const userByEmail = await User.findOne({ email: data.username })
const userByUsername = await User.findOne({ username: data.username })
const user = userByEmail ?? userByUsername

const id = user?._id.toString()
const token = generateJWT(id)
const result = { token, user }
Expand All @@ -166,5 +168,6 @@ export default {
updateUserProfilePicture,
updateUserPassword,
deleteUser,
loginUser,createChangePasswordRequest
loginUser,
createChangePasswordRequest,
}
4 changes: 3 additions & 1 deletion app/src/pages/auth/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,15 @@ export default function Login() {
}}>
<label
htmlFor='Username'
className='block text-lg font-bold text-white self-center'
className='block text-lg font-bold text-white self-center text-center'
style={{
marginBottom: '1rem',
marginRight: '2rem',
marginLeft: '4rem',
}}>
Username
<br></br>
or email
</label>
<div
className='flex-grow'
Expand Down
31 changes: 31 additions & 0 deletions app/src/pages/search/SearchForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const apiURL = import.meta.env.VITE_BACKEND_URL
import axios from 'axios'
import Select from 'react-select'
import { useAuthContext } from './../../context/authContext'
import Swal from "sweetalert2";

export default function SearchForm() {
const talentColor = 'var(--talent-secondary)'
Expand Down Expand Up @@ -259,6 +260,23 @@ export default function SearchForm() {
})
}
const [formErrors, setFormErrors] = useState({})

const noSearchesPopUp = () => {
Swal.fire({
title: "You are out of searches",
showDenyButton: false,
confirmButtonText: "Ok",
denyButtonText: ``,
confirmButtonColor: "var(--talent-highlight)",
background: "var(--talent-secondary)",
color: "white",
}).then((result) => {
if (result.isConfirmed) {
navigate("/");
}
});
};

async function handleSubmit(e) {
e.preventDefault()
let isValid = true
Expand Down Expand Up @@ -295,7 +313,20 @@ export default function SearchForm() {
const config = {
headers: { Authorization: `${token}` },
}

const subscription = localStorage.getItem('subscriptionType')
const subsciptionUser = await axios.get(`${import.meta.env.VITE_BACKEND_URL}/subscriptions/${userId}`,
{
headers: {
'Content-type': 'application/json',
Authorization: token,
},
}
)
if (subsciptionUser.data.data.remainingSearches <= 0) {
noSearchesPopUp()
return
}

const formArray = Object.values(form)
const response = await axios.post(apiURL + '/team-creator', formArray, config)
Expand Down

0 comments on commit 7f5e64a

Please sign in to comment.