Skip to content

Commit

Permalink
Signin page
Browse files Browse the repository at this point in the history
  • Loading branch information
firtanaelif committed Dec 13, 2020
1 parent 1647679 commit 572cafe
Show file tree
Hide file tree
Showing 1,212 changed files with 65,447 additions and 27,510 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
MONGODB_URL=mongodb://localhost/project
JWT_SECRET=somethingsecret
43 changes: 31 additions & 12 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ dotenv.config();

export default {
MONGODB_URL: process.env.MONGODB_URL,
JWT_SECRET: process.env.JWT_SECRET
};
54 changes: 40 additions & 14 deletions backend/routers/userRouter.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,46 @@
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import User from '../models/userModel';
import { generateToken } from '../utils';

const userRouter = express.Router();

userRouter.get('/createadmin', async (req, res) => {
try {
const user = new User({
name: 'admin',
email: '[email protected]',
password: '12345',
isAdmin: true,
userRouter.get(
'/createadmin',
expressAsyncHandler(async (req, res) => {
try {
const user = new User({
name: 'elif',
email: '[email protected]',
password: 'elif12345',
isAdmin: true,
});
const createdUser = await user.save();
res.send(createdUser);
} catch (err) {
res.status(500).send({ message: err.message });
}
})
);
userRouter.post(
'/signin',
expressAsyncHandler(async (req, res) => {
const signinUser = await User.findOne({
email: req.body.email,
password: req.body.password,
});
const createdUser = await user.save();
res.send(createdUser);
} catch (err) {
res.status(500).send({ message: err.message });
}
});
export default userRouter;
if (!signinUser) {
res.status(401).send({
message: 'Invalid Email or Password',
});
} else {
res.send({
_id: signinUser._id,
name: signinUser.name,
email: signinUser.email,
isAdmin: signinUser.isAdmin,
token: generateToken(signinUser),
});
}
})
);
13 changes: 8 additions & 5 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import data from './data';
import config from './config';
import userRouter from './routers/userRouter';

mongoose
.connect(config.MONGODB_URL, {
useNewUrlParser: true,
Expand All @@ -15,11 +15,11 @@ mongoose
console.log('Connected to mongodb.');
})
.catch((error) => {
console.log('Connected not mongodb.',error.reason);
console.log(error.reason);
});

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use('/api/users', userRouter);
app.get('/api/products', (req, res) => {
res.send(data.products);
Expand All @@ -32,7 +32,10 @@ app.get('/api/products/:id', (req, res) => {
res.status(404).send({ message: 'Product Not Found!' });
}
});

app.use((err, req, res, next) => {
const status = err.name && err.name === 'ValidationError' ? 400 : 500;
res.status(status).send({ message: err.message });
});
app.listen(5000, () => {
console.log('server at http://localhost:5000');
console.log('serve at http://localhost:5000');
});
14 changes: 14 additions & 0 deletions backend/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import jwt from 'jsonwebtoken';
import config from './config';

export const generateToken = (user) => {
return jwt.sign(
{
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
},
config.JWT_SECRET
);
};
10 changes: 1 addition & 9 deletions frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,7 @@

<body>
<div class="grid-container">
<header>
<div class="brand">
<a href="/#/">///QR-MENU</a>
</div>
<div>
<a href="/#/signin">Sign-In</a>
<a href="/#/cart">Cart</a>
</div>
</header>
<header id="header-container"></header>
<main id="main-container"></main>
<footer>
All right reserved by @firtanaelif
Expand Down
22 changes: 22 additions & 0 deletions frontend/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,25 @@ export const getProduct = async (id) => {
return { error: err.response.data.message || err.message };
}
};
export const signin = async ({ email, password }) => {
try {
const response = await axios({
url: `${apiUrl}/api/users/signin`,
method: 'POST',
header: {
'Content-Type': 'application/json',
},
data: {
email,
password,
},
});
if (response.statusText !== 'OK') {
throw new Error(response.data.message);
}
return response.data;
} catch (err) {
console.log(err);
return { error: err.response.data.message || err.message };
}
};
18 changes: 18 additions & 0 deletions frontend/src/components/Header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {getUserInfo} from '../localStorage';

const Header = {
render: () => {
const {name} = getUserInfo();
return `
<div class="brand">
<a href="/#/">QuickOrder</a>
</div>
<div>
${name ? `<a href="/#/profile">${name}</a>` : `<a href="/#/signin">Sign-In</a>`}
<a href="/#/cart">Cart</a>
</div>`;
},
after_render: () => {
},
};
export default Header;
5 changes: 4 additions & 1 deletion frontend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Error404Screen from "./screens/Error404Screen";
import CartScreen from './screens/CartScreen';
import {parseRequestUrl} from "./utils";
import SigninScreen from './screens/SigninScreen';

import Header from './components/Header';

const routes = {
'/': HomeScreen,
Expand All @@ -17,6 +17,9 @@ const router = async () => {
const request = parseRequestUrl();
const parseUrl = (request.resource ? `/${request.resource}` : '/') + (request.id ? '/:id' : '') + (request.verb ? `/${request.verb}` : '');
const screen = routes[parseUrl]? routes[parseUrl]: Error404Screen;
const header = document.getElementById('header-container');
header.innerHTML = await Header.render();
await Header.after_render();
const main = document.getElementById('main-container');
main.innerHTML = await screen.render();
await screen.after_render();
Expand Down
25 changes: 25 additions & 0 deletions frontend/src/localStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,28 @@ export const getCartItems = () => {
export const setCartItems = (cartItems) => {
localStorage.setItem('cartItems', JSON.stringify(cartItems));
};
export const setUserInfo = ({
_id = '',
name = '',
email = '',
password = '',
token = '',
isAdmin = false,
}) => {
localStorage.setItem(
'userInfo',
JSON.stringify({
_id,
name,
email,
password,
token,
isAdmin,
})
);
};
export const getUserInfo = () => {
return localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: { name: '', email: '', password: '' };
};
21 changes: 21 additions & 0 deletions frontend/src/screens/SigninScreen.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
import { signin } from '../api';
import { getUserInfo, setUserInfo } from '../localStorage';

const SigninScreen = {
after_render: () => {
document
.getElementById('signin-form')
.addEventListener('submit', async (e) => {
e.preventDefault();
const data = await signin({
email: document.getElementById('email').value,
password: document.getElementById('password').value,
});
if (data.error) {
alert(data.error);
} else {
setUserInfo(data);
document.location.hash = '/';
}
});
},
render: () => {
if (getUserInfo().name) {
document.location.hash = '/';
}
return `
<div class="form-container">
<form id="signin-form">
Expand Down
27 changes: 27 additions & 0 deletions frontend/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,36 @@ export const parseRequestUrl = () => {
verb: request[3],
};
};

export const rerender = async (component) => {
document.getElementById(
'main-container'
).innerHTML = await component.render();
await component.after_render();
};

export const setUserInfo = ({
_id = '',
name = '',
email = '',
password = '',
token = '',
isAdmin = false,
}) => {
localStorage.setItem(
'userInfo',
JSON.stringify({
_id,
name,
email,
password,
token,
isAdmin,
})
);
};
export const getUserInfo = () => {
return localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: { name: '', email: '', password: '' };
};
2 changes: 1 addition & 1 deletion node_modules/.bin/semver

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 572cafe

Please sign in to comment.