Skip to content

Commit

Permalink
add authenticate user spec, refactor create event and create service …
Browse files Browse the repository at this point in the history
  • Loading branch information
benjo12 committed Feb 28, 2024
1 parent fbbe176 commit ce16e10
Show file tree
Hide file tree
Showing 51 changed files with 2,930 additions and 73 deletions.
50 changes: 29 additions & 21 deletions staff/benjamin-mayiba/project/api/logic/authenticateUser.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
import { validate, errors } from 'com'
import { User } from '../data/models.js'
const { SystemError, CredentialsError, NotFoundError } = errors
import bcrypt from "bcryptjs";

export default function authenticateUser(email, password){
validate.email(email, 'email')
validate.password(password, 'password')

return (async () => {
let user
import { validate, errors } from "com";
import { User } from "../data/models.js";
const { SystemError, CredentialsError, NotFoundError } = errors;

try {
user = await User.findOne({ email })
if(!user)
throw new NotFoundError('user not found')
} catch (error) {
throw new SystemError(error.message)
}
export default function authenticateUser(email, password) {
validate.email(email, "email");
validate.password(password, "password");

if (user.password !== password)

throw new CredentialsError('wrong password')
return (async () => {
let user;

return user.id
})()
try {
user = await User.findOne({ email });
} catch (error) {
throw new SystemError(error.message);
}

if (!user) throw new NotFoundError("user not found");
let match;
try {
match = await bcrypt.compare(password, user.password);
} catch (error) {
throw new SystemError(error.message);
}

if (!match) {
throw new CredentialsError("wrong password");
}

return user.id;
})();
}
76 changes: 76 additions & 0 deletions staff/benjamin-mayiba/project/api/logic/authenticateUser.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import dotenv from 'dotenv'
dotenv.config()

import mongoose from 'mongoose'
import { expect } from 'chai'
import random from './helpers/random.js'
import bcrypt from 'bcryptjs'

import authenticateUser from './authenticateUser.js'
import { User } from '../data/models.js'

import { errors} from 'com'

const { NotFoundError, CredentialsError } = errors

describe('authenticateUser', () =>{
before(async () => await mongoose.connect(process.env.PRUEBA_MONGODB_URL))

beforeEach(async () => await User.deleteMany())

it('succeeds on correct credentials', async () =>{
const name = random.name()
const email = random.email()
const password = random.password()

const hash = await bcrypt.hash(password, 8)
const user = await User.create({name, email, password: hash })
const userId = await authenticateUser(email, password)

expect(userId).to.be.a('string')
expect(userId).to.have.lengthOf(24)
expect(userId).to.equal(user.id)
})

it('fails on wrong email', async () =>{
const name = random.name()
const email = random.email()
const email2 = random.email()
const password = random.password()

const hash = await bcrypt.hash(password, 8)
const user = await User.create({name, email, password: hash })

try {
const userId = await authenticateUser(email2, password)

throw new Error('should not reach this point')

} catch (error) {

expect(error).to.be.instanceOf(NotFoundError)
expect(error.message).to.equal('user not found')
}

})

it('fails on wrong password', async () =>{
const name = random.name()
const email = random.email()
const password = random.password()
const password2 = random.password()

const hash = await bcrypt.hash(password, 8)
const userId = await User.create({name, email, password: hash})

try {
const userId = await authenticateUser(email, password2)
throw new Error('should not reach this point')
} catch (error) {

expect(error).to.be.instanceOf(CredentialsError)
expect(error.message).to.equal('wrong password')

}
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import authenticateUser from './authenticateUser.js'
await mongoose.connect(process.env.MONGODB_URL)

try{
const userId = await authenticateUser('ben@jamin.com', '123123123')
const userId = await authenticateUser('debo@rah.com', '123123123')
console.log('user authenticated', userId)

}catch(error){
Expand Down
72 changes: 46 additions & 26 deletions staff/benjamin-mayiba/project/api/logic/createEvent.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,50 @@

import { validate, errors } from 'com';
import { User, Service, Event } from '../data/models.js'
import { validate, errors } from "com";
import { User, Service, Event } from "../data/models.js";

const { SystemError, NotFoundError } = errors
const { SystemError, NotFoundError } = errors;

export default async function createEvent(userId,serviceId, date, time){
validate.id(userId, 'user id')
validate.id(serviceId, 'service id')
validate.text(date, 'date')
validate.text(time, 'time')

try{
const user = await User.findById(userId)
if(!user){
throw new NotFoundError('user not found')
}
const service = await Service.findById(serviceId)
if(!service){
throw new NotFoundError('service not found')
}
const event = await Event.create({user:userId, service: serviceId, date, time})
user.reminders.push(event.id)
await user.save()
}catch(error){
throw new SystemError(error.message)
}
export default async function createEvent(userId, serviceId, date, time) {
validate.id(userId, "user id");
validate.id(serviceId, "service id");
validate.text(date, "date");
validate.text(time, "time");

let user;
try {
user = await User.findById(userId);
} catch (error) {
throw new SystemError(error.message);
}

}
if (!user) {
throw new NotFoundError("user not found");
}
let service;
try {
service = await Service.findById(serviceId);
} catch (error) {
throw new SystemError(error.message);
}

if (!service) {
throw new NotFoundError("service not found");
}

try {
const event = await Event.create({
user: userId,
service: serviceId,
date,
time,
});
user.reminders.push(event.id);
} catch (error) {
throw new SystemError(error.message);
}

try {
await user.save();
} catch (error) {
throw new SystemError(error.message);
}
}
50 changes: 30 additions & 20 deletions staff/benjamin-mayiba/project/api/logic/createService.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
import { validate, errors } from 'com';
import { User, Service } from '../data/models.js';
import { validate, errors } from "com";
import { User, Service } from "../data/models.js";

const { SystemError, NotFoundError } = errors;

export default async function createService(userId, name, description) {
try {
// Validar los argumentos de entrada
validate.id(userId, 'userId');
validate.text(name, 'name');
validate.text(description, 'description');
// Validar los argumentos de entrada
validate.id(userId, "userId");
validate.text(name, "name");
validate.text(description, "description");

// Buscar al usuario por su ID
const user = await User.findById(userId);
if (!user) {
throw new NotFoundError('User not found');
}
let user;
try {
// Buscar al usuario por su ID
user = await User.findById(userId);
} catch (error) {
// Manejar errores y lanzar un SystemError
throw new SystemError(error.message);
}

// Crear el servicio asociado al usuario encontrado
const serviceId = await Service.create({ author: userId, name, description });
return serviceId
} catch (error) {
// Manejar errores y lanzar un SystemError
throw new SystemError(error.message);
}
}
if (!user) {
throw new NotFoundError("user not found");
}
let serviceId
try {
// Crear el servicio asociado al usuario encontrado
serviceId = await Service.create({
author: userId,
name,
description,
});
} catch (error) {
throw new SystemError(error.message);
}
return serviceId;
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import createService from './createService.js'
await mongoose.connect(process.env.MONGODB_URL)

try{
const serviceId = await createService('65cd25d856588d95e5a811d2', 'Yoga', 'Mente pura, cuerpo sano')
const serviceId = await createService('65df870db9cc2e56782c467e', 'Yoga', 'Mente pura, cuerpo sano')

console.log('service created', serviceId)

Expand Down
44 changes: 44 additions & 0 deletions staff/benjamin-mayiba/project/api/logic/helpers/random.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
function name() {
return `name-${Math.random()}`
}

function email() {
return `e-${Math.random()}@mail.com`
}

function password() {
return `password-${Math.random()}`
}

function image() {
return `image-${Math.random()}`
}

function text() {
return `text-${Math.random()}`
}

function date() {
return `date-${Math.random()}`
}

function time() {
return `time-${Math.random()}`
}

function description() {
return `description-${Math.random()}`
}

const random = {
name,
email,
password,
image,
text,
date,
time,
description
}

export default random
7 changes: 5 additions & 2 deletions staff/benjamin-mayiba/project/api/logic/registerUser.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import bcrypt from 'bcryptjs'

import { User } from '../data/models.js'
import { validate, errors } from 'com'

Expand All @@ -10,11 +12,12 @@ export default async function registerUser(name, email, password) {
validate.password(password, 'password')

try {
await User.create({ name, email, password })
const hash = await bcrypt.hash(password, 8)
await User.create({ name, email, password: hash })
} catch (error) {
if (error.code === 11000) {
throw new DuplicityError('user already exists')
}
throw new SystemError(error.message)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import registerUser from './registerUser.js'
await mongoose.connect(process.env.MONGODB_URL)

try {
await registerUser('De Borah', 'debo@rah.com', '123123123')
await registerUser('Mi Zuki', 'mi@zuki.com', '123123123')

console.log('user registered')

Expand Down
6 changes: 6 additions & 0 deletions staff/benjamin-mayiba/project/api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions staff/benjamin-mayiba/project/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"chai": "^5.1.0",
"com": "file:../com",
"cors": "^2.8.5",
Expand Down
Loading

0 comments on commit ce16e10

Please sign in to comment.