bad request error on login route

This commit is contained in:
Mikayla Dobson
2022-07-05 13:23:42 -05:00
parent 20d704851f
commit 638d9a56d4
13 changed files with 231 additions and 277 deletions

View File

@@ -20,21 +20,25 @@ function LoginForm() {
const displaySession = async () => {
if (username === '' || password === '') return;
const response = await handleLogin(username, password);
const json = await response?.json();
if (json) {
const { session, userProfile } = json;
let thisUser: userInfo = {
firstName: userProfile.first_name,
lastName: userProfile.last_name,
id: userProfile.id,
email: userProfile.email,
password: userProfile.password,
headers: session
try {
const response = await handleLogin(username, password);
const json = await response?.json();
if (json) {
const { session, userProfile } = json;
let thisUser: userInfo = {
firstName: userProfile.first_name,
lastName: userProfile.last_name,
id: userProfile.id,
email: userProfile.email,
password: userProfile.password,
headers: session
}
dispatch({ type: ActionType.USERLOGIN, payload: thisUser });
}
dispatch({ type: ActionType.USERLOGIN, payload: thisUser });
} catch(e) {
console.log(e);
}
}

View File

@@ -1,21 +1,22 @@
import { userInfo } from '../types/main';
const APISTRING = 'http://localhost:8088/api';
export const getAllUsers = async () => {
let serverCall = await fetch('http://localhost:8088/users')
let serverCall = await fetch(APISTRING + '/users')
.then(res => res.json());
return serverCall;
}
export const getOneUser = async (email: string) => {
let serverCall = await fetch(`http://localhost:8088/users?email=${email}`)
let serverCall = await fetch(`${APISTRING}/users?email=${email}`)
.then(res => res.json());
return serverCall;
}
export const registerNewUser = async (user: userInfo) => {
let serverCall = await fetch('http://localhost:8088/register', {
let serverCall = await fetch(APISTRING + '/register', {
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -28,7 +29,7 @@ export const registerNewUser = async (user: userInfo) => {
}
export const handleLogin = async (email: string, password: string) => {
let serverCall = await fetch('http://localhost:8088/login', {
let serverCall = await fetch(APISTRING + '/login', {
method: "POST",
headers: {
"Content-Type": "application/json"
@@ -47,7 +48,7 @@ export const unwrapLogin = async (email: string, password: string) => {
}
export const getAllProducts = async () => {
let serverCall = await fetch('http://localhost:8088/products', {
let serverCall = await fetch(APISTRING + '/products', {
method: "GET",
headers: {
"Content-Type": "application/json"
@@ -58,7 +59,7 @@ export const getAllProducts = async () => {
}
export const getProductDetails = async (productID: string) => {
let serverCall = await fetch(`http://localhost:8088/products/${productID}`, {
let serverCall = await fetch(`${APISTRING}/products/${productID}`, {
method: "GET",
headers: {
"Content-Type": "application/json"

View File

@@ -11,8 +11,6 @@ module.exports = (app) => {
extended: true
}));
app.use(require('../routes/API'));
app.use(session({
secret: process.env.EXPRESS_SECRET,
cookie: { maxAge: 8 * 60 * 60 * 1000, secure: false },
@@ -25,15 +23,5 @@ module.exports = (app) => {
})
}));
// app.use(session({
// secret: process.env.EXPRESS_SECRET,
// cookie: { maxAge: 8*60*60*1000, secure: false },
// resave: false,
// saveUninitialized: true,
// store: new (require('connect-pg-simple')(session))({
// conString: process.env.CONNECTION,
// createTableIfMissing: true,
// pruneSessionInterval: 60 * 30
// })
// }));
return app;
}

View File

@@ -1,9 +1,17 @@
const passportLoader = require('./passport');
const expressLoader = require('./express');
const routes = require('../routes/API');
module.exports = async (app) => {
// const passport = await passportLoader(app);
const express = await expressLoader(app);
const passport = await passportLoader(express);
await routes(app, passport);
app.use((err, req, res, next) => {
const { message, status } = err;
return res.status(status).send({ message });
});
}

View File

@@ -1,6 +1,6 @@
const passport = require('passport');
const LocalStrategy = require('passport-local');
const { connect } = require('../db/Pool');
const { LoginService } = require('../services/Auth');
module.exports = (app) => {
app.use(passport.initialize());
@@ -18,8 +18,14 @@ module.exports = (app) => {
** TO DO: FINISH CONFIGURING LOCAL STRATEGY
***/
app.use(new LocalStrategy(async (email, password, done) => {
const client = await connect();
const account = await client.query("SELECT * FROM users WHERE email = ($1)", [email])
passport.use(new LocalStrategy(async (email, password, done) => {
try {
const response = await LoginService(email, password);
return done(null, response);
} catch(e) {
return done(e);
}
}));
return passport;
}

View File

@@ -1,10 +1,14 @@
const express = require('express');
const apiRouter = express.Router();
apiRouter.use('/users', require('./user'));
apiRouter.use('/products', require('./products'));
apiRouter.use('/register', require('./register'));
apiRouter.use('/login', require('./login'));
apiRouter.use('/pool-experiment', require('./_experimental'));
const userRouter = require('./user');
const productsRouter = require('./products');
const registerRouter = require('./register');
const loginRouter = require('./login');
module.exports = apiRouter;
module.exports = (app, passport) => {
loginRouter(app, passport);
productsRouter(app);
registerRouter(app);
userRouter(app);
};

View File

@@ -1,72 +0,0 @@
const experimentRouter = require('express').Router();
const { connect, query, end } = require('../db/Pool');
experimentRouter.route('/').get(async (req, res) => {
const client = await connect()
.then(console.log("Connection successful"));
if (client) {
try {
res.send("Pool appears to work?");
} catch(e) {
console.log(e);
} finally {
await end();
}
}
});
experimentRouter.route('/').put(async (req, res) => {
const { name, description, information } = req.body;
const input = `
INSERT INTO experimental (name, description, information)
VALUES ($1, $2, $3)
`
const client = await connect()
.then(console.log("Connection successful."));
if (client) {
try {
await client.query('BEGIN');
await client.query(input, [name, description, information]);
await client.query('COMMIT');
res.sendStatus(200);
} catch(e) {
await client.query('ROLLBACK');
throw new Error(e);
} finally {
client.release();
console.log("Client disconnected.");
}
}
})
experimentRouter.route('/create-exp-db').put(async (req, res) => {
const input = `
CREATE TABLE IF NOT EXISTS experimental (
id SERIAL,
name VARCHAR,
description VARCHAR,
information JSON
);
`
const client = await connect()
.then(console.log("Connection successful."));
if (client) {
try {
await query(input, null, (err, result) => {
if (err) throw err;
res.send(result);
});
} catch(e) {
console.log(e);
} finally {
await end();
}
}
})
module.exports = experimentRouter;

View File

@@ -1,16 +1,17 @@
const loginRouter = require('express').Router();
const { connect } = require('../db/Pool');
const { LoginService } = require('../services/Auth');
const bcrypt = require('bcrypt');
loginRouter.post('/', passport.authenticate('local'), async (req, res, next) => {
try {
const data = req.body;
const response = await LoginService(data);
if (response) res.status(200).send(response);
} catch(e) {
next(e);
}
});
// module.exports = loginRouter;
module.exports = (app, passport) => {
app.use('/api/login', loginRouter);
module.exports = loginRouter;
loginRouter.post('/', passport.authenticate('local'), async (req, res, next) => {
try {
const { email, password } = req.body;
const response = await LoginService(email, password);
if (response) console.log(response);
} catch(e) {
next(e);
}
});
}

View File

@@ -2,65 +2,67 @@ const express = require('express');
const productsRouter = express.Router();
const { connect } = require('../db/Pool');
// route to get all products
productsRouter.route('/').get(async (req, res) => {
const client = await connect();
try {
await client.query("BEGIN");
const result = await client.query("SELECT * FROM products");
await client.query("COMMIT");
if (result) res.send(result.rows);
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
client.release();
console.log("Client disconnected.");
}
});
// route to get a product by id
productsRouter.route('/:id').get(async (req, res) => {
const { id } = req.params;
const client = await connect();
try {
await client.query("BEGIN");
const result = await client.query(("SELECT * FROM products WHERE id = ($1)"), [id]);
await client.query("COMMIT");
if (result) res.send(result.rows[0]);
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
client.release()
console.log("Client disconnected.");
}
});
// post a product from req.body
productsRouter.route('/').post(async (req, res) => {
const { name, description, category, categoryID, price } = req.body;
const input = `
INSERT INTO products (name, description, category, category_id, price)
VALUES ($1, $2, $3, $4, $5)
`
const client = await connect();
try {
await client.query("BEGIN");
await client.query(input, [name, description, category, categoryID, price]);
await client.query("COMMIT");
res.sendStatus(204);
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
await client.release()
.then(console.log("Client disconnected."));
}
});
module.exports = productsRouter;
module.exports = (app) => {
app.use('/api/products', productsRouter);
// route to get all products
productsRouter.route('/').get(async (req, res) => {
const client = await connect();
try {
await client.query("BEGIN");
const result = await client.query("SELECT * FROM products");
await client.query("COMMIT");
if (result) res.send(result.rows);
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
client.release();
console.log("Client disconnected.");
}
});
// route to get a product by id
productsRouter.route('/:id').get(async (req, res) => {
const { id } = req.params;
const client = await connect();
try {
await client.query("BEGIN");
const result = await client.query(("SELECT * FROM products WHERE id = ($1)"), [id]);
await client.query("COMMIT");
if (result) res.send(result.rows[0]);
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
client.release()
console.log("Client disconnected.");
}
});
// post a product from req.body
productsRouter.route('/').post(async (req, res) => {
const { name, description, category, categoryID, price } = req.body;
const input = `
INSERT INTO products (name, description, category, category_id, price)
VALUES ($1, $2, $3, $4, $5)
`
const client = await connect();
try {
await client.query("BEGIN");
await client.query(input, [name, description, category, categoryID, price]);
await client.query("COMMIT");
res.sendStatus(204);
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
await client.release()
.then(console.log("Client disconnected."));
}
});
}

View File

@@ -1,28 +1,17 @@
const registerRouter = require('express').Router();
const { connect } = require('../db/Pool');
const bcrypt = require('bcrypt');
const { RegisterService } = require('../services/Auth');
registerRouter.route('/').post(async (req, res) => {
const { firstName, lastName, email, password } = req.body;
const input = "INSERT INTO users (first_name, last_name, email, password) values ($1, $2, $3, $4)";
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password, salt);
const client = await connect();
try {
await client.query("BEGIN");
await client.query(input, [firstName, lastName, email, hash]);
await client.query("COMMIT");
res.sendStatus(200);
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
client.release();
console.log("Client disconnected.");
}
});
module.exports = registerRouter;
// module.exports = registerRouter;
module.exports = (app) => {
app.use('/api/register', registerRouter);
registerRouter.route('/').post(async (req, res, done) => {
const { firstName, lastName, email, password } = req.body;
try {
const response = await RegisterService(firstName, lastName, email, password);
if (response) res.sendStatus(200);
} catch(e) {
done(e);
}
});
}

View File

@@ -1,22 +1,57 @@
const express = require('express');
const userRouter = express.Router();
// const client = require('../db/Client');
const userRouter = require('express').Router();
const { connect } = require('../db/Pool');
// get a list of all users, or a single user matching an email passed in as a query param
userRouter.route('/').get(async (req, res) => {
const { email } = req.query;
const client = await connect()
.then(console.log('Connection successful.'))
.catch(e => console.log(e));
if (!email) {
module.exports = (app) => {
app.use('/api/user', userRouter);
// get a list of all users, or a single user matching an email passed in as a query param
userRouter.route('/').get(async (req, res) => {
const { email } = req.query;
const client = await connect()
.then(console.log('Connection successful.'))
.catch(e => console.log(e));
if (!email) {
try {
await client.query("BEGIN");
const results = await client.query("SELECT * FROM users");
await client.query("COMMIT");
if (results) res.send(results.rows);
} catch(e) {
await client.query('ROLLBACK');
throw new Error(e);
} finally {
await client.release();
console.log("Client disconnected.");
}
} else {
try {
await client.query("BEGIN");
const result = await client.query(("SELECT * FROM users WHERE email = ($1)"), [email])
await client.query("COMMIT");
if (result) res.send(result.rows);
} catch(e) {
await client.query('ROLLBACK');
throw new Error(e);
} finally {
await client.release();
console.log("Client disconnected.");
}
}
});
// post a new user to the database
userRouter.route('/').post(async (req, res) => {
const { name, email } = req.body;
const client = await connect()
.then(console.log('Connection successful.'));
const input = "INSERT INTO users (name, email) VALUES ($1, $2)";
try {
await client.query("BEGIN");
const results = await client.query("SELECT * FROM users");
await client.query(input, [name, email]);
await client.query("COMMIT");
if (results) res.send(results.rows);
res.sendStatus(200);
} catch(e) {
await client.query('ROLLBACK');
throw new Error(e);
@@ -24,41 +59,5 @@ userRouter.route('/').get(async (req, res) => {
await client.release();
console.log("Client disconnected.");
}
} else {
try {
await client.query("BEGIN");
const result = await client.query(("SELECT * FROM users WHERE email = ($1)"), [email])
await client.query("COMMIT");
if (result) res.send(result.rows);
} catch(e) {
await client.query('ROLLBACK');
throw new Error(e);
} finally {
await client.release();
console.log("Client disconnected.");
}
}
});
// post a new user to the database
userRouter.route('/').post(async (req, res) => {
const { name, email } = req.body;
const client = await connect()
.then(console.log('Connection successful.'));
const input = "INSERT INTO users (name, email) VALUES ($1, $2)";
try {
await client.query("BEGIN");
await client.query(input, [name, email]);
await client.query("COMMIT");
res.sendStatus(200);
} catch(e) {
await client.query('ROLLBACK');
throw new Error(e);
} finally {
await client.release();
console.log("Client disconnected.");
}
});
module.exports = userRouter;
});
};

View File

@@ -13,6 +13,4 @@ async function start() {
});
}
start();
module.exports = app;
start();

View File

@@ -1,7 +1,7 @@
const { connect } = require('../db/Pool');
const bcrypt = require('bcrypt');
async function LoginService(data) {
const { email, password } = data;
async function LoginService(email, password) {
const client = await connect();
try {
@@ -17,18 +17,44 @@ async function LoginService(data) {
let fullUserProfile = await client.query("SELECT * FROM users WHERE email = ($1)", [email]);
res.send({
return {
session: req.session,
userProfile: fullUserProfile.rows[0]
});
}
}
} catch(e) {
await client.query("ROLLBACK");
throw new Error(e);
} finally {
client.release()
client.release();
console.log("Client disconnected.");
}
}
module.exports = { LoginService }
async function RegisterService(firstName, lastName, email, password) {
const input = "INSERT INTO users (first_name, last_name, email, password) values ($1, $2, $3, $4)";
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password, salt);
const client = await connect();
let success;
try {
await client.query("BEGIN");
await client.query(input, [firstName, lastName, email, hash]);
await client.query("COMMIT");
success = true;
} catch(e) {
await client.query("ROLLBACK");
console.log(e);
success = false;
} finally {
client.release();
console.log("Client disconnected.");
return success;
}
}
module.exports = { LoginService, RegisterService }