try {
const response = await fetch(url, {
method,
body,
headers
});
require('dotenv').config();
const express = require('express');
const sequelize = require('./db');
const PORT = process.env.PORT || 6660;
const app = express();
app.use(express.json({ extended: true }));
app.use('/api/auth', require('./routes/auth.routes'));
async function start() {
try {
await sequelize.authenticate();
await sequelize.sync();
app.listen(PORT, () => console.log(`Hello on port: ${PORT}`));
} catch (e) {
console.log('Server error: ' + e.message);
}
}
start();
require('dotenv').config();
const { Router } = require('express');
const bcrypt = require('bcryptjs');
const { check, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const router = Router();
// /api/auth/register
router.post(
'/register',
[
check('email', 'Invalid email').isEmail(),
check('password', 'Minimum password length 8 characters').isLength({
min: 8,
}),
],
async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty) {
return res.status(400).json({
errors: errors.array(),
message: 'Incorrect registration data',
});
}
const { email, password } = req.body;
const cadidate = await User.findOne({ email });
if (cadidate) {
return res.status(400).json({ message: 'This user already exists' });
}
const hashedPassword = await bcrypt.hash(password, 12);
const user = User(email, hashedPassword);
await user.save();
res.status(201).json({ message: 'User successfully created' });
} catch (e) {
res
.status(500)
.json({ message: 'Something went wrong, please try again' });
}
}
);
// /api/auth/login
router.post(
'/login',
[
check('email', 'Please enter a valid email').normalizeEmail().isEmail(),
check('password', 'password must contain at least 8 characters').isLength({
min: 8,
}),
],
async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty) {
return res.status(400).json({
errors: errors.array(),
message: 'Incorrect login details',
});
}
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).jason({ message: 'User is not found' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).jason({ message: 'Invalid email or password' });
}
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET_KEY, {
expiresIn: '1h',
});
res.json({ token, userId: user.id });
} catch (e) {
res
.status(500)
.json({ message: 'Something went wrong, please try again' });
}
}
);
module.exports = router;
# SERVER
PORT = 6660
# DATABASE
DB_HOST = 127.0.0.1
DB_PORT = 8889
DB_NAME = altairdb
DB_USER = root
DB_PASSWORD = root1
import React from 'react';
import { useHttp } from '../../hooks/http.hook';
import './_auth.scss';
export const AuthPage = () => {
const { loading, request } = useHttp();
const [form, setForm] = React.useState({
email: '',
password: '',
});
const changeHandler = event => {
setForm({ ...form, [event.target.name]: event.target.value });
};
const registerHandler = async () => {
try {
const data = await request('/api/auth/register', 'POST', { form });
console.log('Data', data);
} catch (e) {}
};
React.useEffect(() => {
const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () =>
container.classList.add('right-panel-active')
);
signInButton.addEventListener('click', () =>
container.classList.remove('right-panel-active')
);
});
return (
<div className='auth_page'>
<div className='container' id='container'>
<div className='form-container sign-up-container'>
<div className='form'>
<h1>Create Account</h1>
<span>or use your email for registration</span>
<input
name='email'
type='email'
placeholder='Email'
onChange={changeHandler}
/>
<input
name='password'
type='password'
placeholder='Password'
onChange={changeHandler}
/>
<button onClick={registerHandler} disabled={loading}>
Sign Up
</button>
</div>
</div>
<div className='form-container sign-in-container'>
<div className='form'>
<h1>Sign in</h1>
<span>or use your account</span>
<input type='email' placeholder='Email' onChange={changeHandler} />
<input
type='password'
placeholder='Password'
onChange={changeHandler}
/>
<a href='/#'>Forgot your password?</a>
<button>Sign In</button>
</div>
</div>
<div className='overlay-container'>
<div className='overlay'>
<div className='overlay-panel overlay-left'>
<h1>Welcome Back!</h1>
<p>
To keep connected with us please login with your personal info
</p>
<button className='ghost' id='signIn'>
Sign In
</button>
</div>
<div className='overlay-panel overlay-right'>
<h1>Hello, Friend!</h1>
<p>Enter your personal details and start journey with us</p>
<button className='ghost' id='signUp'>
Sign Up
</button>
</div>
</div>
</div>
</div>
</div>
);
};
import { useState, useCallback } from 'react';
export const useHttp = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const request = useCallback(
async (url, method = 'GET', body = null, headers = {}) => {
setLoading(true);
try {
const response = await fetch(url, {
method,
body,
headers,
});
const data = await response.json();
console.log(data);
if (!response.ok) {
throw new Error(data.message || 'Something went wrong');
}
setLoading(false);
return data;
} catch (e) {
setLoading(false);
setError(e.message);
throw e;
}
},
[]
);
const clearError = () => setError(null);
return { loading, request, error, clearError };
};