Skip to content

Commit

Permalink
Geocoding api setup
Browse files Browse the repository at this point in the history
  • Loading branch information
amogh-nagar committed Aug 29, 2021
1 parent d821dcd commit 2b7610e
Show file tree
Hide file tree
Showing 12 changed files with 150 additions and 135 deletions.
83 changes: 44 additions & 39 deletions backend/controllers/users-controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const HttpError = require('../models/http-error');
const User = require('../models/user');
const jwt=require('jsonwebtoken')
const jwt = require('jsonwebtoken');
const getUsers = async (req, res, next) => {
let users;
try {
Expand Down Expand Up @@ -47,7 +47,7 @@ const signup = async (req, res, next) => {
}
let hashedpassword;
try {
hashedpassword = await bcrypt.hash(password, 10);
hashedpassword = await bcrypt.hash(password, 10);
} catch (err) {
const error = new HttpError('Could not create user', 500);
return next(error);
Expand All @@ -70,22 +70,22 @@ const signup = async (req, res, next) => {
return next(error);
}
let token;
try{

token=jwt.sign({userId:createdUser.id,email:createdUser.email},
"ssuuppeerrsseeccrreettdonotshareit",{
expiresIn:'1h'
})

}catch(err){
const error = new HttpError(
'Could not Sign up.',
500
try {
token = jwt.sign(
{ userId: createdUser.id, email: createdUser.email },
'ssuuppeerrsseeccrreettdonotshareit',
{
expiresIn: '1h',
}
);
} catch (err) {
const error = new HttpError('Could not Sign up.', 500);
return next(error);

}
res.status(201).json({userId:createdUser.id,email:createdUser.email,token:token });
// console.log(token);
res
.status(201)
.json({ userId: createdUser.id, email: createdUser.email, token: token });
};

const login = async (req, res, next) => {
Expand All @@ -102,39 +102,44 @@ const login = async (req, res, next) => {
);
return next(error);
}
let ismatched;
try {
ismatched = await bcrypt.compare(password, exisiting.password);
if (!ismatched) {
const err = new Error('Invalid credentials', 422);
return next(err);
}
} catch (err) {
const errpr = new Error('Could not log yopu in', 500);
return next(error);
}
if (!existingUser) {
const error = new HttpError(
'Invalid credentials, could not log you in.',
401
);
return next(error);
}
let token;
try{
token=jwt.sign({userId:existingUser.id,email:existingUser.email},"ssuuppeerrsseeccrreettdonotshareit",{
expiresIn:'1h'
})}catch(err){
const error = new HttpError(
'Could not log you in.',
500
);
return next(error);
let ismatched;
try {
ismatched = await bcrypt.compare(password, existingUser.password);
} catch (err) {
const error = new Error('Could not log you in, Some error might be occurred', 500);
return next(error);
}
if (!ismatched) {
const err = new Error('Invalid credentials', 422);
return next(err);
}

}
res.json({
let token;
try {
token = jwt.sign(
{ userId: existingUser.id, email: existingUser.email },
'ssuuppeerrsseeccrreettdonotshareit',
{
expiresIn: '1h',
}
);
} catch (err) {
const error = new HttpError('Could not log you in.', 500);
return next(error);
}
// console.log(token);
res.status(201).json({
message: 'Logged in!',
userId:existingUser.id,email:existingUser.email,token:token
userId: existingUser.id,
email: existingUser.email,
token: token,
});
};

Expand Down
5 changes: 4 additions & 1 deletion backend/middleware/check-auth,.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
const HttpError = require('../models/http-error');
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
if(req.method==="OPTIONS"){
return next();
}
try {
const token = res.headers.authorization.split(' ')[1];
const token = req.headers.authorization.split(' ')[1];
if (!token) {
throw new HttpError('Authentication failed', 401);
}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 8 additions & 9 deletions backend/util/location.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,30 @@ const axios = require('axios');

const HttpError = require('../models/http-error');

const API_KEY = 'AIzaSyDgLmMpKCzveJf1_yuA0fUzzhy0WRChvZA';
const API_KEY = '0e2fde51f1ba4bf308b0a9e0c615c8201141760d';

async function getCoordsForAddress(address) {
// return {
// lat: 40.7484474,
// lng: -73.9871516
// };

const response = await axios.get(
`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
address
)}&key=${API_KEY}`
`https://api.geocodify.com/v2/geocode?api_key=${API_KEY}&q=${address}`
);

const data = response.data;

if (!data || data.status === 'ZERO_RESULTS') {
if (data.meta.code !== 200) {
const error = new HttpError(
'Could not find location for the specified address.',
422
);
throw error;
}

const coordinates = data.results[0].geometry.location;

const coordinates = {
lat: data.response.features[0].geometry.coordinates[0],
lng: data.response.features[0].geometry.coordinates[1],
};
return coordinates;
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/places/components/PlaceItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ const PlaceItem = props => {
<Card className="place-item__content">
{isLoading && <LoadingSpinner asOverlay />}
<div className="place-item__image">
<img src={props.image} alt={props.title} />
<img src={`http://localhost:5000/${props.image}`} alt={props.title} />
</div>
<div className="place-item__info">
<h2>{props.title}</h2>
Expand Down
105 changes: 53 additions & 52 deletions frontend/src/shared/hooks/auth-hook.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,56 @@
import {useEffect,useCallback,useState} from 'react'
import { useEffect, useCallback, useState } from 'react';

let logouttimer;
export const useAuth=()=>{
const [token, settoken] = useState(false);
const [userId, setUserId] = useState(false);
const [remainingtime, setremainingtime] = useState(null);
useEffect(() => {
const userData = JSON.parse(localStorage.getItem('userData'));
if (
userData &&
userData.token &&
new Date(userData.expiration) > new Date()
) {
login(userData.userId, userData.token, userData.expiration);
}else if(userData&&new Date(userData.expiration)<new Date()){
logout()
}
}, []);

useEffect(() => {
if (token && remainingtime) {
const remaining = remainingtime.getTime() - new Date().getTime();
logouttimer = setTimeout(logout, remaining);
} else {
clearTimeout(logouttimer);
}
}, [token, remainingtime]);

const login = useCallback((uid, token, expirationdate) => {
settoken(token);
setUserId(uid);
const tokenexpiration =
expirationdate || new Date(new Date.getTime() + 1000 * 60 * 60);
setremainingtime(tokenexpiration);
localStorage.setItem(
'userData',
JSON.stringify({
userId: uid,
token: token,
expiration: tokenexpiration.toISOString(),
})
);
}, []);

const logout = useCallback(() => {
settoken(null);
setUserId(null);
setremainingtime(null)
localStorage.removeItem('userData');
}, []);
export const useAuth = () => {
const [token, settoken] = useState(false);
const [userId, setUserId] = useState(false);
const [remainingtime, setremainingtime] = useState(null);
useEffect(() => {
const userData = JSON.parse(localStorage.getItem('userData'));
console.log(userData);
if (
userData !== null &&
userData.token &&
new Date(userData.expiration) > new Date()
) {
login(userData.userId, userData.token, userData.expiration);
} else if (userData && new Date(userData.expiration) < new Date()) {
logout();
}
}, []);


return {login,logout,token,userId}
}
useEffect(() => {
if (token && remainingtime) {
const remaining = remainingtime.getTime() - new Date().getTime();
logouttimer = setTimeout(logout, remaining);
} else {
clearTimeout(logouttimer);
}
}, [token, remainingtime]);


const login = useCallback((uid, token, expirationdate) => {
settoken(token);
setUserId(uid);
const tokenExpirationDate =
new Date(new Date().getTime() + 1000 * 60 * 60);
setremainingtime(expirationdate?new Date(expirationdate):tokenExpirationDate);
localStorage.setItem(
'userData',
JSON.stringify({
userId: uid,
token: token,
expiration: expirationdate?expirationdate:tokenExpirationDate.toISOString()
})
);
}, []);

const logout = useCallback(() => {
settoken(null);
setUserId(null);
setremainingtime(null);
localStorage.removeItem('userData');
}, []);

return { login, logout, token, userId };
};
Loading

0 comments on commit 2b7610e

Please sign in to comment.