From 3b6693ae8c4950262cc4b44afad5d700727d5ebb Mon Sep 17 00:00:00 2001 From: Adrian Date: Sat, 20 Jul 2024 06:13:52 +0200 Subject: [PATCH] continue with the test and fix them #140 --- .../api/logic/authenticateUser.spec.js | 16 +++ .../socialcode/api/logic/createPost.spec.js | 4 +- .../socialcode/api/logic/getUserName.js | 6 +- .../socialcode/api/logic/getUserName.spec.js | 105 ++++++++++++++++++ .../socialcode/api/logic/registerUser.js | 6 +- .../socialcode/api/logic/registerUser.spec.js | 62 +++++++++++ .../socialcode/app/src/logic/loginUser.js | 32 +----- .../adrian-martin/socialcode/com/validate.js | 26 ++--- 8 files changed, 204 insertions(+), 53 deletions(-) create mode 100644 staff/adrian-martin/socialcode/api/logic/getUserName.spec.js create mode 100644 staff/adrian-martin/socialcode/api/logic/registerUser.spec.js diff --git a/staff/adrian-martin/socialcode/api/logic/authenticateUser.spec.js b/staff/adrian-martin/socialcode/api/logic/authenticateUser.spec.js index aad85c3ff..606bd78a3 100644 --- a/staff/adrian-martin/socialcode/api/logic/authenticateUser.spec.js +++ b/staff/adrian-martin/socialcode/api/logic/authenticateUser.spec.js @@ -10,6 +10,8 @@ import { ContentError, CredentialError } from 'com/error.js' const { MONGODB_URL_TEST } = process.env +// npm run test-inspect + describe('authenticateUser', () => { before(() => mongoose.connect(MONGODB_URL_TEST).then(() => User.deleteMany())) @@ -59,5 +61,19 @@ describe('authenticateUser', () => { } }) + it('fails on invalid password', () => { + let errorThrown + + try { + authenticateUser('Colacao', '1231231') + } catch (error) { + errorThrown = error + } finally { + expect(errorThrown).to.be.instanceOf(ContentError) + expect(errorThrown.message).to.equal('password is not valid') + } + + }) + after(() => User.deleteMany().then(() => mongoose.disconnect())) }) \ No newline at end of file diff --git a/staff/adrian-martin/socialcode/api/logic/createPost.spec.js b/staff/adrian-martin/socialcode/api/logic/createPost.spec.js index ed2146348..2911cec7e 100644 --- a/staff/adrian-martin/socialcode/api/logic/createPost.spec.js +++ b/staff/adrian-martin/socialcode/api/logic/createPost.spec.js @@ -8,11 +8,9 @@ import { Post, User } from '../data/index.js' import createPost from './createPost.js' -import { ContentError } from 'com/error.js' - const { MONGODB_URL_TEST } = process.env -debugger +// npm run test-inspect describe('createPost', () => { before(() => mongoose.connect(MONGODB_URL_TEST).then(() => Promise.all([Post.deleteMany(), User.deleteMany()]))) diff --git a/staff/adrian-martin/socialcode/api/logic/getUserName.js b/staff/adrian-martin/socialcode/api/logic/getUserName.js index 2e25cadce..618f0cda2 100644 --- a/staff/adrian-martin/socialcode/api/logic/getUserName.js +++ b/staff/adrian-martin/socialcode/api/logic/getUserName.js @@ -1,5 +1,5 @@ import { User } from '../data/index.js' -import { MatchError, NotFoundError } from 'com/error.js' +import { NotFoundError, SystemError } from 'com/error.js' import validate from 'com/validate.js' @@ -11,14 +11,14 @@ const getUserName = (userId, targetUserId) => { .catch(error => { throw new SystemError(error.message) }) .then(user => { if (!user) { - throw new MatchError('user not found') + throw new NotFoundError('User not found') } return User.findById(targetUserId).lean() .catch(error => { throw new SystemError(error.message) }) .then(user => { if (!user) { - throw new NotFoundError('targetUsername not found') + throw new NotFoundError('TargetUser not found') } return user.name }) diff --git a/staff/adrian-martin/socialcode/api/logic/getUserName.spec.js b/staff/adrian-martin/socialcode/api/logic/getUserName.spec.js new file mode 100644 index 000000000..dc935364d --- /dev/null +++ b/staff/adrian-martin/socialcode/api/logic/getUserName.spec.js @@ -0,0 +1,105 @@ +import "dotenv/config" +import mongoose, { get, Types } from "mongoose" + +import bcrypt from "bcryptjs" + + +import getUserName from "./getUserName.js" +import { User } from "../data/index.js" +import { NotFoundError, ContentError } from "com/error.js" + +import { expect } from "chai" + +const { MONGODB_URL_TEST } = process.env + +const { ObjectId } = Types + +// npm run test-inspect + +describe('getUserName', () => { + before(() => mongoose.connect(MONGODB_URL_TEST).then(() => User.deleteMany())) + beforeEach(() => User.deleteMany()) + + it('succeeds get username from existing user', () => + bcrypt.hash('123132123', 8) + .then(hash => Promise.all([User.create({ + name: "Mocha", + surname: "Chai", + email: "Mocha@Chai.com", + username: "MochaChai", + password: hash + }), User.create({ + name: "Test", + surname: "User", + email: "test@user.com", + username: "testuser", + password: hash + })])) + .then(([user, targetUser]) => getUserName(user.id, targetUser.id)) + .then(name => { + expect(name).to.be.a.string + expect(name).to.be.equal('Test') + }) + + ) + + it("fails on non-existing user", () => { + let errorThrown + + return bcrypt.hash("321321321", 8) + .then(hash => User.create({ + name: 'Mocha', surname: 'Chai', email: 'mocha@chai.com', username: 'machachai', + password: hash + })) + .then(targetUserId => getUserName(new ObjectId().toString(), targetUserId.id)) + .catch(error => errorThrown = error) + .finally(() => { + expect(errorThrown).to.be.an.instanceOf(NotFoundError) + expect(errorThrown.message).to.equal("User not found") + }) + }) + + it('fails on non-existing targetUser', () => { + let errorThrown + + return bcrypt.hash('123456789', 8) + .then(hash => User.create({ + name: 'Mocha', surname: 'Chai', email: 'mocha@chai.com', username: 'machachai', + password: hash + })) + .then(user => getUserName(user.id, new ObjectId().toString())) + .catch(error => errorThrown = error) + .finally(() => { + expect(errorThrown).to.be.instanceOf(NotFoundError) + expect(errorThrown.message).to.equal('TargetUser not found') + }) + }) + + // it('fails on invalid userId', () => { + // let errorThrown + + // try { + // getUserName(123456789, new ObjectId().toString()) + // } catch (error) { + // errorThrown = error + // } finally { + // expect(errorThrown).to.be.instanceOf(ContentError) + // expect(errorThrown.message).to.equal('userId is not valid') + // } + // }) + + // it('fails on invalid targetUserid', () => { + // let errorThrown + + // try { + // getUserName(new ObjectId().toString(), 123456789) + // } catch (error) { + // errorThrown = error + // } finally { + // expect(errorThrown).to.be.instanceOf(ContentError) + // expect(errorThrown.message).to.equal('targetUserId is not valid') + // } + // }) + + after(() => User.deleteMany().then(() => mongoose.disconnect())) +}) \ No newline at end of file diff --git a/staff/adrian-martin/socialcode/api/logic/registerUser.js b/staff/adrian-martin/socialcode/api/logic/registerUser.js index d3cf673e8..136f50f2e 100644 --- a/staff/adrian-martin/socialcode/api/logic/registerUser.js +++ b/staff/adrian-martin/socialcode/api/logic/registerUser.js @@ -12,14 +12,14 @@ const registerUser = (name, surname, email, username, password, passwordRepeat) validate.passwordsMatch(password, passwordRepeat) return User.findOne({ $or: [{ email }, { username }] }) - .catch(error => { throw new SystemError(error.message) }) + .catch(() => { throw new SystemError("connection error") }) .then(user => { if (user) { throw new DuplicityError('user already exists') } return bcrypt.hash(password, 8) - .catch(error => { throw new SystemError(error.message) }) + .catch(() => { throw new SystemError("connection error") }) .then(hash => { const newUser = { name: name, @@ -30,7 +30,7 @@ const registerUser = (name, surname, email, username, password, passwordRepeat) } return User.create(newUser) - .catch(error => { throw new SystemError(error.message) }) + .catch(() => { throw new SystemError("connection error") }) .then(() => { }) }) }) diff --git a/staff/adrian-martin/socialcode/api/logic/registerUser.spec.js b/staff/adrian-martin/socialcode/api/logic/registerUser.spec.js new file mode 100644 index 000000000..cb9dab3ae --- /dev/null +++ b/staff/adrian-martin/socialcode/api/logic/registerUser.spec.js @@ -0,0 +1,62 @@ +import 'dotenv/config' +import registerUser from './registerUser.js' +import mongoose from 'mongoose' +import bcrypt from 'bcryptjs' + +import { expect } from 'chai' + +import { User } from '../data/index.js' +import { ContentError, CredentialError, DuplicityError } from 'com/error.js' + +const { MONGODB_URL_TEST } = process.env + +debugger // npm run test-inspect + +describe('registerUser', () => { + before(() => mongoose.connect(MONGODB_URL_TEST).then(() => User.deleteMany())) + beforeEach(() => User.deleteMany()) + + it('succceds on register user', () => { + registerUser('Esme', 'Ralda', 'esme@ralda.com', 'esmeralda', '123123123', '123123123') + .then(() => User.findOne()) + .then(user => { + expect(user.name).to.equal('Esme') + expect(user.surname).to.equal('Ralda') + expect(user.email).to.equal('esme@ralda.com') + expect(user.username).to.equal('esmeralda') + expect(user.password).to.equal('123123123') + + return bcrypt.compare('123123123', user.password) + }) + .then((match) => expect(match).to.be.true) + }) + + it('fails on existing user', () => { + let errorThrown + + return bcrypt.hash('1234', 8) + .then(hash => User.create({ name: 'Esme', surname: 'Ralda', email: 'esme@ralda.com', username: 'esmeralda', password: hash })) + .then(() => registerUser('Esme', 'Ralda', 'esme@ralda.com', 'esmeralda', '1234', '1234')) + .catch(error => errorThrown = error) + .finally(() => { + expect(errorThrown).to.be.instanceOf(DuplicityError) + expect(errorThrown.message).to.equal('user already exists') + }) + }) + + it("fails on existing user", () => { + let errorThrown + + return bcrypt.hash("1234", 8) + .then(hash => User.create({ name: "Mocha", surname: "Chai", email: "Mocha@Chai.com", username: "MochaChai", password: hash })) + .then(() => registerUser("Mocha", "Chai", "Mocha@Chai.com", "MochaChai", "1234", "1234")) + .catch(error => errorThrown = error) + .finally(() => { + expect(errorThrown).to.be.instanceOf(DuplicityError) + expect(errorThrown.message).to.equal("❌ Users already exists ❌") + }) + }) + after(() => User.deleteMany().then(() => mongoose.disconnect())) +}) + + diff --git a/staff/adrian-martin/socialcode/app/src/logic/loginUser.js b/staff/adrian-martin/socialcode/app/src/logic/loginUser.js index 0374cd731..a19f5b823 100644 --- a/staff/adrian-martin/socialcode/app/src/logic/loginUser.js +++ b/staff/adrian-martin/socialcode/app/src/logic/loginUser.js @@ -5,34 +5,6 @@ const loginUser = (username, password) => { validate.username(username) validate.password(password) - // const xhr = new XMLHttpRequest - - // xhr.onload = () => { - // if (xhr.status === 200) { - // const token = JSON.parse(xhr.response) - // sessionStorage.token = token - - // callback(null) - - // return - // } - - // const { error, message } = JSON.parse(xhr.response) - - // const constructor = errors[error] - - // callback(new constructor(message)) - // } - - // xhr.open('POST', `${import.meta.env.VITE_API_URL}/users/auth`) - - // const body = { username, password } - - // const json = JSON.stringify(body) - - // xhr.setRequestHeader('Content-Type', 'application/json') - // xhr.send(json) - return fetch(`${import.meta.env.VITE_API_URL}/users/auth`, { method: 'POST', headers: { @@ -43,10 +15,8 @@ const loginUser = (username, password) => { .catch(() => { throw new SystemError('server error') }) .then(response => { if (response.status === 200) { - callback(null) - return response.json() - .catch(() => {throw new SystemError('server error')}) + .catch(() => { throw new SystemError('server error') }) .then(token => sessionStorage.token = token) } diff --git a/staff/adrian-martin/socialcode/com/validate.js b/staff/adrian-martin/socialcode/com/validate.js index 4caa2b68c..0971fa892 100644 --- a/staff/adrian-martin/socialcode/com/validate.js +++ b/staff/adrian-martin/socialcode/com/validate.js @@ -6,7 +6,7 @@ const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+") const NAME_REGEX = /^[a-zA-Z=\[\]\{\}\<\>\(\)]{1,}$/ const ID_REGEX = /^[0-9a-z]+$/ -function validateName(name, explain = 'name'){ +function validateName(name, explain = 'name') { if (typeof name !== 'string' || !NAME_REGEX.test(name)) throw new ContentError(`${explain} is not valid`) } @@ -20,12 +20,12 @@ function validatePassword(password) { if (typeof password !== 'string' || !PASSWORD_REGEX.test(password)) throw new ContentError('password is not valid') } -function validatePasswordsMatch(password, passwordRepeat){ +function validatePasswordsMatch(password, passwordRepeat) { if (password !== passwordRepeat) throw new MatchError('password don\'t match') } -function validateEmail(email){ +function validateEmail(email) { if (typeof email !== 'string' || !EMAIL_REGEX.test(email)) throw new ContentError('email is not valid') } @@ -35,30 +35,30 @@ function validateCallback(callback) { throw new TypeError('callback is not a function') } -function validateText(text, explain = 'text', maxLength = Infinity){ +function validateText(text, explain = 'text', maxLength = Infinity) { if (typeof text !== 'string' || !text.length || text.length > maxLength) throw new ContentError(`${explain} is not valid`) } -function validateUrl(url, explain = 'url'){ +function validateUrl(url, explain = 'url') { if (typeof url !== 'string' || !url.startsWith('http')) throw new ContentError(`${explain} is not valid`) } -function validateId(id, explain = 'id'){ +function validateId(id, explain = 'id') { if (!ID_REGEX.test(id)) throw new ContentError(`${explain} is not a string`) } const validate = { - name: validateName, - username: validateUsername, - password: validatePassword, + name: validateName, + username: validateUsername, + password: validatePassword, passwordsMatch: validatePasswordsMatch, - email: validateEmail, - callback: validateCallback, - text: validateText, - url: validateUrl, + email: validateEmail, + callback: validateCallback, + text: validateText, + url: validateUrl, id: validateId }