Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PUT || Edit User #67

Merged
merged 20 commits into from
Nov 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions server/controllers/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const { userEstateshandler, login } = require('./users');
const getAllUsers = require('./users/getAllUsers');
const { editEstate, deleteEstate } = require('./estates');
const {
userEstateshandler, putAgent, getAllUsers, login,
} = require('./users');
const { deleteEstate, editEstate } = require('./estates');
const logout = require('./logout');
const { adminLogin } = require('./admins');

module.exports = {
getAllUsers, userEstateshandler, logout, login, deleteEstate, editEstate, adminLogin,
getAllUsers, userEstateshandler, logout, login, deleteEstate, editEstate, putAgent,adminLogin

};
2 changes: 2 additions & 0 deletions server/controllers/users/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const signup = require('./signup');
const userEstateshandler = require('./userEstates');
const getAllUsers = require('./getAllUsers');
const putAgent = require('./putAgent');
const login = require('./login');

module.exports = {
signup,
getAllUsers,
userEstateshandler,
putAgent,
login,
};
4 changes: 2 additions & 2 deletions server/controllers/users/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ const login = async (req, res, next) => {
await loginSchema.validateAsync(req.body);

const { rows } = await checkEmailQuery(email);

if (!rows.length) {
return res.status(400).json({ message: 'Invalid email or password' });
}

const compared = await bcrypt.compare(password, rows[0].password);

if (!compared) {
return res.status(400).json({ message: 'Invalid email or password' });
}
const token = await signToken(email, rows[0].id);
const token = await signToken({ email, userId: rows[0].id });
return res.cookie('token', token).json({ message: 'You are Logged Successfully' });
} catch (err) {
if (err.details) {
Expand Down
24 changes: 24 additions & 0 deletions server/controllers/users/putAgent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const { putAgent } = require('../../database/quieres');
const editAgentSchema = require('../../utils/validation/editAgentSchema');

module.exports = async (req, res, next) => {
try {
const { userId } = req.user;
const { error, value } = editAgentSchema.validate({ ...req.body, userId });
if (error) return res.status(400).json({ message: error.details[0].message });
const { rowCount } = await putAgent(value);
if (rowCount === 1) {
return res.status(200).json({
message: "Agent's data updated successfully",
});
}
return res.status(404).json({
message: 'There\'s no Agent, put correct id',
});
} catch (err) {
if (err.detail) {
return res.status(400).json({ message: err.detail });
}
return next(err);
}
};
6 changes: 4 additions & 2 deletions server/controllers/users/signup.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ module.exports = async (req, res, next) => {
} = agentSchema.validate(req.body);
if (error) return res.status(400).json({ message: error.details[0].message });
const hasedPasword = await hash(password, 10);
await signUpQuery(username, email, phone, hasedPasword);
const token = await signToken(email, username, phone);
const { rows } = await signUpQuery(username, email, phone, hasedPasword);
const token = await signToken({
email, username, phone, userId: rows[0].id,
});
return res.status(201).cookie('token', token).json({ message: 'user created' });
} catch (err) {
if (err.code === '23505') {
Expand Down
2 changes: 1 addition & 1 deletion server/database/config/fakeData.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
--
INSERT INTO agents (name, email, password , phone)
VALUES ('Kai', '[email protected]', '$2b$10$gT8Qb2Qe01W1QMRFmH9IC.3bmbA4PS2yG4XQvdkYWxKday.SbjGI2', '677-871-7450'),
VALUES ('Kai', '[email protected]', '$2b$10$hZZ2f3zk.pV/9ndMRn78ze47MAh8SN8uy01qeoK8P54tTe526Pqz6', '677-871-7450'),
('Trixie', '[email protected]', '$2b$10$oNaAu46EHAyOCiufPgchaOQDq5opRxSFHB20m.e3wzDBlM5Yzztf2', '0599832685'),
('Allina', '[email protected]', '$2b$10$oNaAu46EHAyOCiufPgchaOQDq5opRxSFHB20m.e3wzDBlM5Yzztf2', '630-385-8312');

Expand Down
2 changes: 1 addition & 1 deletion server/database/quieres/account/signUp.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
const connection = require('../../config/connection');

module.exports = (userName, email, phone, password) => connection.query('INSERT INTO agents (name,email,phone,password) VALUES ($1,$2,$3,$4)', [userName, email, phone, password]);
module.exports = (userName, email, phone, password) => connection.query('INSERT INTO agents (name,email,phone,password) VALUES ($1,$2,$3,$4) RETURNING id', [userName, email, phone, password]);
4 changes: 4 additions & 0 deletions server/database/quieres/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const userEstatesQuery = require('./userEstatesQuiery');
const getAllUsersQuery = require('./getAllUsersQuery');
const putAgent = require('./putAgent');
const deleteEstate = require('./deleteEstateQuery');
const checkAdminQuery = require('./checkAdmin');
const checkEmailQuery = require('./checkEmailQuery');
const editEstateQuery = require('./editEstatesQuery');
Expand All @@ -9,6 +11,8 @@ const signUpAdminQuery = require('./signUpAdminQuery');
module.exports = {
getAllUsersQuery,
userEstatesQuery,
putAgent,
deleteEstate,
checkAdminQuery,
checkEmailQuery,
editEstateQuery,
Expand Down
5 changes: 5 additions & 0 deletions server/database/quieres/putAgent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const connection = require('../config/connection');

module.exports = ({
userId, username, email, phone, avater = '',
}) => connection.query('UPDATE agents SET name=$1,email=$2,phone=$3,avater=$4 WHERE id=$5', [username, email, phone, avater, userId]);
7 changes: 0 additions & 7 deletions server/routes/auth.js

This file was deleted.

6 changes: 2 additions & 4 deletions server/routes/estate.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
const router = require('express').Router();

// const { isAuth, isAdmin } = require('../middleware');
const { isAuth } = require('../middleware');
const { editEstate, deleteEstate } = require('../controllers');

router.put('/:estateId', editEstate);

router.delete('/:estateId', deleteEstate);
router.delete('/:estateId', isAuth, deleteEstate);
module.exports = router;
6 changes: 3 additions & 3 deletions server/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const router = require('express').Router();
const auth = require('./auth');
const estate = require('./estate');
const users = require('./users');
const { logout } = require('../controllers');
const admins = require('./admin');

router.use('/users', users);
router.get('/logout', logout);
router.use('/admin', admins);
router.use('/estate', estate);
router.use('/', auth);
router.use('/user', users);

module.exports = router;
8 changes: 7 additions & 1 deletion server/routes/users.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
const router = require('express').Router();
const { userEstateshandler, getAllUsers } = require('../controllers');
const {
userEstateshandler, getAllUsers, putAgent, login,
} = require('../controllers');
const estate = require('./estate');
const signup = require('../controllers/users/signup');
const { isAuth } = require('../middleware');

router.use('/estate', estate);
router.post('/signup', signup);
router.post('/login', login);
router.get('/:userId/estates', userEstateshandler);
router.put('/', isAuth, putAgent);
router.get('/', getAllUsers);
router.post('/login', login);

module.exports = router;
75 changes: 65 additions & 10 deletions server/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ const connection = require('../database/config/connection');
beforeEach(() => dbBuild());
afterAll(() => connection.end());

const userToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImthbGxwb3J0MEBwYXRjaC5jb20iLCJ1c2VySWQiOjEsImlhdCI6MTYzNTk0OTE4OX0.LjriIEoRDmj3_52PO8VlsaqekFiItE7gzamngrlaPDk';

describe('Get all users', () => {
test('get all users', async () => {
const res = await supertest(app)
.get('/api/v1/users')
.get('/api/v1/user')
.expect(200)
.expect('Content-Type', /json/);
return expect(3).toEqual(res.body.data.length);
Expand All @@ -20,18 +22,18 @@ describe('Get all users', () => {
describe('Tests login route', () => {
test(' login route /login ', async () => {
const res = await supertest(app)
.post('/api/v1/login')
.post('/api/v1/user/login')
.send({
email: '[email protected]',
password: '12345',
password: '123456789',
})
.expect(200);
return expect(res.body).toEqual({ message: 'You are Logged Successfully' });
});

test(' login route /login with error in email or password ', async () => {
const res = await supertest(app)
.post('/api/v1/login')
.post('/api/v1/user/login')
.send({
email: '[email protected]',
password: '123456987',
Expand Down Expand Up @@ -68,7 +70,7 @@ describe('Tests login route to admin', () => {
describe('user estates', () => {
test('get users estates', async () => {
const res = await supertest(app)
.get('/api/v1/users/3/estates')
.get('/api/v1/user/3/estates')
.expect(200)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
Expand Down Expand Up @@ -120,7 +122,7 @@ describe('user estates', () => {
describe('user estates', () => {
test('get users estates', async () => {
const res = await supertest(app)
.get('/api/v1/users/three/estates')
.get('/api/v1/user/three/estates')
.expect(404)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
Expand Down Expand Up @@ -180,6 +182,7 @@ describe('Delete Specific Estate By Using Id', () => {
test('/estate/:estateId status 200 ', async () => {
const res = await supertest(app)
.delete('/api/v1/estate/1')
.set('Cookie', [`token=${userToken}`])
.expect(200)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
Expand All @@ -189,6 +192,7 @@ describe('Delete Specific Estate By Using Id', () => {
test('/estate/:estateId status 400, when delete the same estate was deleted or not found ', async () => {
const res = await supertest(app)
.delete('/api/v1/estate/100')
.set('Cookie', [`token=${userToken}`])
.expect(400)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
Expand All @@ -198,17 +202,19 @@ describe('Delete Specific Estate By Using Id', () => {
test('/estate/:estateId status 400, Invalid estate id ', async () => {
const res = await supertest(app)
.delete('/api/v1/estate/-121')
.set('Cookie', [`token=${userToken}`])
.expect(400)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
message: 'Invalid estate id',
});
});
});

describe('test signup endpoint with all cases ', () => {
test('test sign up endpoint when success', async () => {
const res = await supertest(app)
.post('/api/v1/users/signup')
.post('/api/v1/user/signup')
.send({
username: 'test',
password: 'test123456',
Expand All @@ -226,7 +232,7 @@ describe('test signup endpoint with all cases ', () => {

test('test signup error validation phone" length must be 10 characters long ', async () => {
const res = await supertest(app)
.post('/api/v1/users/signup')
.post('/api/v1/user/signup')
.send({
username: 'Kai',
password: '1234567894455',
Expand All @@ -242,7 +248,7 @@ describe('test signup endpoint with all cases ', () => {
});
test('test signup username or phone already exists ', async () => {
const res = await supertest(app)
.post('/api/v1/users/signup')
.post('/api/v1/user/signup')
.send({
username: 'Kai',
password: '1234567894455',
Expand All @@ -259,7 +265,7 @@ describe('test signup endpoint with all cases ', () => {

test('test signup confirmpassword ', async () => {
const res = await supertest(app)
.post('/api/v1/users/signup')
.post('/api/v1/user/signup')
.send({
username: 'test',
password: 'test123456',
Expand All @@ -275,6 +281,55 @@ describe('test signup endpoint with all cases ', () => {
});
});

describe('test Edit Agent data /user/:iduser ', () => {
test('test 200', async () => {
const res = await supertest(app)
.put('/api/v1/user')
.set('Cookie', [`token=${userToken}`])
.send({
username: 'test',
email: '[email protected]',
phone: '059985555555',
})
.expect(200)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
message: 'Agent\'s data updated successfully',
});
});

test('test 400', async () => {
const res = await supertest(app)
.put('/api/v1/user')
.set('Cookie', [`token=${userToken}`])
.send({
username: 'test',
email: '[email protected]',
phone: '0599',
})
.expect(400)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
message: '"phone" length must be at least 9 characters long',
});
});
test('test 404', async () => {
const res = await supertest(app)
.put('/api/v1/user')
.set('Cookie', ['token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hdTdhbW1hZGFiZWRAZ21haWwuY29tIiwidXNlcklkIjo0LCJpYXQiOjE2MzU5NDkyNTl9.St177PIpsDIHAVke6PxoGC8_cJmUrggpyhEcJ4QWKfI'])
.send({
username: 'test',
email: '[email protected]',
phone: '059915587555',
})
.expect(404)
.expect('Content-Type', /json/);
return expect(res.body).toEqual({
message: 'There\'s no Agent, put correct id',
});
});
});

describe('test signup as admin ', () => {
test('test sign up endpoint when success', async () => {
const res = await supertest(app)
Expand Down
1 change: 1 addition & 0 deletions server/utils/tokenFunction.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { verify, sign } = require('jsonwebtoken');
require('env2')('.env');

const {
env: { ACCESS_TOKEN_SECRET },
Expand Down
9 changes: 9 additions & 0 deletions server/utils/validation/editAgentSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const joi = require('joi');

module.exports = joi.object({
username: joi.string().required(),
email: joi.string().email().required(),
phone: joi.string().min(9).required(),
avater: joi.string(),
userId: joi.number().min(1).required(),
});