Skip to content

Commit

Permalink
continue with the test and fix them b00tc4mp#140
Browse files Browse the repository at this point in the history
  • Loading branch information
AdrianGonzalo committed Jul 20, 2024
1 parent 3dbfcae commit 3b6693a
Show file tree
Hide file tree
Showing 8 changed files with 204 additions and 53 deletions.
16 changes: 16 additions & 0 deletions staff/adrian-martin/socialcode/api/logic/authenticateUser.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()))

Expand Down Expand Up @@ -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()))
})
4 changes: 1 addition & 3 deletions staff/adrian-martin/socialcode/api/logic/createPost.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()])))
Expand Down
6 changes: 3 additions & 3 deletions staff/adrian-martin/socialcode/api/logic/getUserName.js
Original file line number Diff line number Diff line change
@@ -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'


Expand All @@ -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
})
Expand Down
105 changes: 105 additions & 0 deletions staff/adrian-martin/socialcode/api/logic/getUserName.spec.js
Original file line number Diff line number Diff line change
@@ -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: "[email protected]",
username: "MochaChai",
password: hash
}), User.create({
name: "Test",
surname: "User",
email: "[email protected]",
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: '[email protected]', 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: '[email protected]', 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()))
})
6 changes: 3 additions & 3 deletions staff/adrian-martin/socialcode/api/logic/registerUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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(() => { })
})
})
Expand Down
62 changes: 62 additions & 0 deletions staff/adrian-martin/socialcode/api/logic/registerUser.spec.js
Original file line number Diff line number Diff line change
@@ -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', '[email protected]', '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('[email protected]')
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: '[email protected]', username: 'esmeralda', password: hash }))
.then(() => registerUser('Esme', 'Ralda', '[email protected]', '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: "[email protected]", username: "MochaChai", password: hash }))
.then(() => registerUser("Mocha", "Chai", "[email protected]", "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()))
})


32 changes: 1 addition & 31 deletions staff/adrian-martin/socialcode/app/src/logic/loginUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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)

}
Expand Down
26 changes: 13 additions & 13 deletions staff/adrian-martin/socialcode/com/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
}
Expand All @@ -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')
}
Expand All @@ -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
}

Expand Down

0 comments on commit 3b6693a

Please sign in to comment.