Skip to content

Commit

Permalink
Merge pull request #179 from Rubix982/verification-feature
Browse files Browse the repository at this point in the history
Verification feature
  • Loading branch information
Rubix982 authored Dec 27, 2020
2 parents 9758687 + 5568582 commit 550b15f
Show file tree
Hide file tree
Showing 18 changed files with 232 additions and 53 deletions.
6 changes: 4 additions & 2 deletions client/src/API/API.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class API {
},
'credentials': 'include',
});
if(response.status===403) {
if(response.status === 401) {
localStorage.removeItem('loggedIn');
localStorage.removeItem('firstLogin');
const data = await response.json();
Expand Down Expand Up @@ -35,8 +35,10 @@ class API {
'credentials': 'include',
});

if(response.status===403) {
if(response.status === 401) {
localStorage.removeItem('loggedIn');
localStorage.removeItem('firstLogin');
localStorage.removeItem('verified');
const data = await response.json();
throw new Error(data.msg);
}
Expand Down
4 changes: 3 additions & 1 deletion client/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Home from './pages/home';
import Feed from './pages/feed';
import Error404 from './pages/error404';
import Post from './pages/post';
import Verify from './pages/Verify';
import Publish from './pages/publish';
import Profile from './pages/profile';
import Search from './pages/search';
Expand Down Expand Up @@ -56,12 +57,13 @@ function App() {
<Route exact path="/settings" component={Settings} />
<Route exact path="/changepassword" component={SettingsCP} />
<Route exact path="/post/:id" component={Post} />
<Route exact path="/verify/:hash" component={Verify} />
<Route exact path="/login">
{loggedIn ? <Feed /> : <Login />}
</Route>
<Route exact path="/register" component={Register} />
<Route exact path="/forgetPassword" component={ForgetPassword} />
<Route exact path="/newPassword/:hashed" component={NewPassword} />
<Route exact path="/newPassword/:hashed" component={NewPassword} />
<Route component={Error404} />
</Switch>
</Router>
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/Login/MainContent.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ const MainContent = () => {
<br />
<input onClick={async () => {
try {
const { status } = await loginUser(email, password);
const { verificationStatus, firstLoginStatus } = await loginUser(email, password);
localStorage.setItem('loggedIn', true);
localStorage.setItem('firstLogin', status);
localStorage.setItem('firstLogin', firstLoginStatus);
setTimeout(() => {
history.push('/feed');
}, 3000);
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/NewsFeed/Content.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import API from '../../API/API';

const Content = () => {
const [feedData, setFeedData] = useState([]);
const [loading, setLoading] = useState(true)
const [loading, setLoading] = useState(true);

useEffect(async () => {
try {
Expand Down
61 changes: 61 additions & 0 deletions client/src/components/Verify/MainContent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { CenterAlign } from '../FlexAlignment';
import Logo from '../../assets/img/icon/Logo.svg';
import ComponentStyling from '../../style/Error/MainContent.module.css';
import { verifyUser } from '../../services/verify';

const MainContent = () => {
const { hash } = useParams();
const [loading, setLoading] = useState(true);

useEffect(async () => {
try {
const status = await verifyUser(hash);
setLoading(!status);
} catch (error) {
alert(error.message);
}
}, [])

if(loading) {
return (
<>
</>
)
}

return (
<div className={ComponentStyling.container}>
<div className={ComponentStyling.content}>
<CenterAlign>
<div className={ComponentStyling.logo}>
<img src={Logo} alt="" />
</div>
</CenterAlign>
<div className={ComponentStyling.title}>
<div className={ComponentStyling.heading}>
<h1>
<a href="/">Terrabuzz</a>
</h1>
</div>
<div className={ComponentStyling.description}>
<p>
Your account is succesfully verified. Please Login to use Terrabuzz.
<br />
<a className={ComponentStyling.textStyling} href="/login">
Login
</a>
<a className={ComponentStyling.textStyling} href="/register">
Register
</a>
</p>
</div>
</div>
</div>
;
</div>
);
};

export default MainContent;
6 changes: 6 additions & 0 deletions client/src/pages/Verify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import React from 'react';
import MainContent from '../components/Verify/MainContent';

const Verify = () => <MainContent />;

export default Verify;
5 changes: 0 additions & 5 deletions client/src/pages/feed.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,9 @@ import FirstLogin from './FirstLogin.js';

// the div is for navbar
import Navbar from '../components/Navbar';
import { loginUserContext } from '../components/LoginUserContext';

const Feed = () => {
const { firstLogin } = useContext(loginUserContext);

if (firstLogin.state) {
return (<FirstLogin />);
}
return (
<Container
style={{
Expand Down
12 changes: 12 additions & 0 deletions client/src/services/verify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import API from '../API/API';

export const verifyUser = async (__hash) => {
try {
const { status } = await API.postRequest(`${process.env.REACT_APP_API_URL}/verify`,
{ hash: __hash }
);
return (status);
} catch (error) {
throw new Error(error.message);
}
};
7 changes: 7 additions & 0 deletions client/src/style/Error/MainContent.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,10 @@
text-decoration: underline;
color: black;
}

.textStyling {
margin-right: 100px;
text-decoration: none;
color: #000;
font-weight: 800;
};
18 changes: 15 additions & 3 deletions server/controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const { postExternDataToDB } = require('../services/postExternalLinks.js');
const { postProfileDataToDB } = require('../services/postExternalProfile.js');
const { postNotification } = require('../services/postNotification.js');
const { getNavbarInformationFromDatabase } = require('../services/getNavbarInfo.js');
const { getUserVerificationStatus, verifyUser } = require('../services/verify.js');
const { getNotificationList } = require('../services/getNotifDatabase.js');

module.exports.getHomePage = async (req, res) => {
Expand Down Expand Up @@ -194,8 +195,9 @@ module.exports.loginUser = async (req, res) => {
try {
const { token, handle } = await generateAccessToken(req.body);
res.cookie('access-token', token, { httpOnly: true, sameSite: true });
const status = await checkForFirstLogin(handle);
return res.status(200).json({ msg: 'User logged in!!', status });
const firstLoginStatus = await checkForFirstLogin(handle);
const verificationStatus = await getUserVerificationStatus(handle);
return res.status(200).json({ msg: 'User logged in!!', firstLoginStatus, verificationStatus });
} catch (error) {
return res.status(401).json({ msg: error.message });
}
Expand Down Expand Up @@ -249,7 +251,7 @@ module.exports.logoutUser = async (req, res) => {
res.clearCookie('access-token');
return res.status(200).json({ msg: 'User succesfully logged out' });
} catch (error) {
return res.status(403).json({ msg: error.message });
return res.status(401).json({ msg: error.message });
}
};

Expand Down Expand Up @@ -289,6 +291,16 @@ module.exports.postCommentNotification = async (req, res) => {
}
};

module.exports.verifyUser = async (req, res) => {
try {
const { hash } = req.body;
const status = await verifyUser(hash);
res.json({ msg: 'User successfully verified', status });
} catch (error) {
res.status(404).json({ msg: error.message });
}
};

module.exports.postLikeNotification = async (req, res) => {
try {
await postNotification('like', req.body, req.userHandle);
Expand Down
46 changes: 27 additions & 19 deletions server/db/mongo/connection.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const MONGOOSE = require('mongoose');
const { PostList } = require('../../models/post.js');
const { ValidationSet } = require('../../models/valdation.js');
// const { NotificationList } = require('../../models/notification.js');
// const { PostList } = require('../../models/post.js');
// const { ValidationSet } = require('../../models/valdation.js');

require('dotenv').config();

const connect = async () => {
Expand All @@ -11,25 +13,31 @@ const connect = async () => {
return console.log('Mongoose not connected, some error occured!');
});

const defaultHandlers = ['TashikMoin', 'hassanzhd', 'Saif', 'Johndoe'];
// const defaultHandlers = ['TashikMoin', 'hassanzhd', 'Saif', 'Johndoe'];

// /* eslint-disable no-await-in-loop */
// for (let i = 0; i < defaultHandlers.length; i += 1) {
// const userPostList = new PostList({
// _id: defaultHandlers[i],
// payload: [],
// });
// await userPostList.save();

/* eslint-disable no-await-in-loop */
for (let i = 0; i < defaultHandlers.length; i += 1) {
const userPostList = new PostList({
_id: defaultHandlers[i],
payload: [],
});
await userPostList.save();
// const notificationList = new NotificationList({
// _id: defaultHandlers[i],
// payload: [],
// });
// await notificationList.save();

const validationSet = new ValidationSet({
_id: defaultHandlers[i],
verificationHash: '',
isVerified: true,
resetHash: '',
isFirstLogin: false,
});
await validationSet.save();
}
// const validationSet = new ValidationSet({
// _id: defaultHandlers[i],
// verificationHash: '',
// isVerified: true,
// resetHash: '',
// isFirstLogin: false,
// });
// await validationSet.save();
// }
/* eslint-enable no-await-in-loop */
};

Expand Down
19 changes: 10 additions & 9 deletions server/db/mysql/sqlScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const fs = require('fs');
const MYSQL_CONNECTOR = (require('./connection.js'));

const createAndInsert = async () => {
let script = fs.readFileSync(path.join(__dirname, './ddl.sql')).toString();
const script = fs.readFileSync(path.join(__dirname, './ddl.sql')).toString();
try {
const result = await MYSQL_CONNECTOR.connection.query(script);
console.log('DDL Created Successfully for MySQL');
Expand All @@ -12,14 +12,15 @@ const createAndInsert = async () => {
console.log(`DDL Creation query not executed successfully for MySQL because --> ${error.message}`);
}

script = fs.readFileSync(path.join(__dirname, './insertSql.sql')).toString();
try {
const result = await MYSQL_CONNECTOR.connection.query(script);
console.log('Insertions Done Successfully for MYSQL');
console.log(result);
} catch (error) {
console.log(`Insertion query Not Executed Successfully For MySQL Because --> ${error.message}`);
}
// script = fs.readFileSync(path.join(__dirname, './insertSql.sql')).toString();
// try {
// const result = await MYSQL_CONNECTOR.connection.query(script);
// console.log('Insertions Done Successfully for MYSQL');
// console.log(result);
// } catch (error) {
// console.log(`Insertion query Not Executed Successfully
// For MySQL Because --> ${error.message}`);
// }
};

module.exports.createAndInsert = createAndInsert;
4 changes: 2 additions & 2 deletions server/middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ module.exports.authorizeUser = (req, res, next) => {
req.userHandle = handle;
return next();
} catch (error) {
return res.status(403).json({ msg: 'Unauthorized! Please login again.' });
return res.status(401).json({ msg: 'Unauthorized! Please login again.' });
}
};

Expand All @@ -38,6 +38,6 @@ module.exports.forwardUnAuthorizedUser = (req, res, next) => {
req.userHandle = handle;
return next();
} catch (error) {
return res.status(403).json({ msg: 'Unauthorized! Please login again.' });
return res.status(401).json({ msg: 'Unauthorized! Please login again.' });
}
};
2 changes: 2 additions & 0 deletions server/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ Router.post('/firstLogin', authorizeUser, indexContoller.postFirstLoginInformati
Router.post('/changepassword', authorizeUser, indexContoller.changePassword);
Router.post('/externalLinks', authorizeUser, indexContoller.postExternalInformationDetails);
Router.post('/externalProfile', authorizeUser, indexContoller.postExternalProfileDetails);
Router.post('/verify', indexContoller.verifyUser);
Router.post('/notification-comment', authorizeUser, indexContoller.postCommentNotification);
Router.post('/notification-like', authorizeUser, indexContoller.postLikeNotification);

module.exports = Router;
22 changes: 20 additions & 2 deletions server/services/forgetPassword.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ const { InsertValidationDocument } = require('./resetHash.js');
const { GmailMailer } = require('./gmailAuth.js');
const { HTMLResetPasswordForm } = require('./template.js');

const emailData = {
title: 'Reset your password',
content: 'You\'re receiving this e-mail because you requested a password reset for your Terrabuzz account.',
description: 'Please tap the button below to choose a new password.',
route: 'newPassword',
buttonText: 'Reset password',
};

const forgetPasswordUpdation = async (__email) => {
// If the user exists in the database
try {
Expand All @@ -24,8 +32,18 @@ const forgetPasswordUpdation = async (__email) => {
} catch (error) {
throw new Error(`InsertValidationDocument failed due to error ${error.message}`);
}
const mail = new GmailMailer(__email, HTMLResetPasswordForm(hashedResetLink));
mail.send();
const mail = new GmailMailer(
__email,
HTMLResetPasswordForm(
hashedResetLink,
emailData.title,
emailData.content,
emailData.description,
emailData.route,
emailData.buttonText,
),
);
await mail.send();
} catch (error) {
throw new Error(`Unable to send a reset email. Encountered error "${error.message}"`);
}
Expand Down
Loading

1 comment on commit 550b15f

@vercel
Copy link

@vercel vercel bot commented on 550b15f Dec 27, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.