Skip to content

Commit

Permalink
create logics: createGroup, createCommand, retrieveCommand, deleteUse…
Browse files Browse the repository at this point in the history
…rs, registerAdmin, uploadFile | adding testint (HTML & SPECS) | create handlers | modify Group and Files model b00tc4mp#361
  • Loading branch information
Abel Prieto authored and Abel Prieto committed Mar 7, 2024
1 parent d6bd3e3 commit 33f89ee
Show file tree
Hide file tree
Showing 35 changed files with 640 additions and 124 deletions.
48 changes: 31 additions & 17 deletions staff/abel-prieto/PROYECT/API/README.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,29 @@
## API - HIINIT v0.1
# API - HIINIT v0.1

## GUEST REQUEST

`Retrieve Guest`
- Request: GET /guest
- Response: 200 "Content-Type": application/json { username, [ group ], [ role ] }
- Response (error) : 500|404|406 "Content-Type": application/json { error, message }

## USER REQUEST

`Register User`

- Request: POST /users "Content-Type": application/json { name, email, password }
- Response: 201
- Response (error) : 500|409|406 "Content-Type: application/json" { error, message }
- Response (error) : 500|409|406 "Content-Type": application/json" { error, message }

`Authenticate User`

- Request: POST /users/auth "Content-Type": application/json { email, password }
- Response: 200 "Content-Type": application/json { userId }
- Respone (error): 500|404|406|409 "Content-Type": application/json { error, message }

`Retrieve User`

- Request: GET /users Authorization: Bearer ${session.token}
- Response: 200 "Content-Type": application/json { username, [ group ], [ role ] }
- Response (error) : 500|404|406 "Content-Type": application/json { error, message }

`Retrieve Guest`

- Request: GET /users
- Response: 200 "Content-Type": application/json { username, [ group ], [ role ] }
- Response (error) : 500|404|406 "Content-Type": application/json { error, message }

`Upload Files`

- Request: POST /upload Authorization: Bearer ${session.token}
- Response: 201
- Response (error) : 500|404|406|409 "Content-Type": multipart/form-data { error, message }

`Change Email`
- Request: PATCH /users/email
- Response: 200
Expand All @@ -41,3 +33,25 @@
- Request: PATCH /users/password
- Response: 200
- Response (error) : 500|404|406|409 "Content-Type": application/json { error, message }

`Upload Files`
- Request: POST /upload Authorization: Bearer ${session.token}
- Response: 201
- Response (error) : 500|404|406|409 "Content-Type": multipart/form-data { error, message }

`Retrieve Commands`
- Request: GET /* Authorization: Bearer ${session.token}
- Response: 200 "Content-Type": application/json { command_NAME }
- Respose (error): 500 "Content-Type": application/json { error, message }

## ADMIN

`Register Admin`
- Request: POST /admin "Content-Type": application/json { name, email, password, group: 'root', role: 'admin' }
- Response: 201
- Response (error) : 500|409|406|401 "Content-Type": application/json { error, message }

`Delete User`
- Request: DELETE /users Authorization: Bearer ${session.token}
- Response: 200
- Response (error): 500|404|406|401 "Content-Type": application/json { error, message }
20 changes: 6 additions & 14 deletions staff/abel-prieto/PROYECT/API/data/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,13 @@ const user = new Schema({
const group = new Schema({
name: {
type: String,
unique: true,
default: 'localhost'
}
},
members: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
})

// COMMAND
Expand Down Expand Up @@ -72,19 +77,6 @@ const file = new Schema({
}
})

// ASIGN GROUP & USER TYPE
user.pre('save', function (next) {
if (!this.group || this.group.length === 0) {
this.group.push('localhost');
}

if (!this.role || this.role.length === 0) {
this.role.push('user');
}

next()
})

const User = new model('User', user)
const Group = new model('Group', group)
const Command = new model('Command', command)
Expand Down
18 changes: 10 additions & 8 deletions staff/abel-prieto/PROYECT/API/handlers/authenticateUserHandler.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import jwt from 'jsonwebtoken'
import authenticateUser from '../logic/authenticateUser.js'
import { errors } from 'com'
const { NotFoundError, CredentialsError, ContentError } = errors
const { NotFoundError, CredentialsError, ContentError, TokenError } = errors
const { JsonWebTokenError } = jwt

export default (req, res) => {
try {
const { email, password } = req.body

authenticateUser(email, password)
.then(userId => {
const token = jwt.sign({ sub: userId }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE })

res.json(token)
})
.catch(error => {
let status = 500

Expand All @@ -20,19 +26,15 @@ export default (req, res) => {
}

res.status(status).json({ error: error.constructor.name, message: error.message })

return
})
.then(userId => {
const token = jwt.sign({ sub: userId }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE })

res.json(token)
})
} catch (error) {
let status = 500

if (error instanceof ContentError || error instanceof TypeError) {
status = 406
} else if (error instanceof JsonWebTokenError) {
status = 401
error = new TokenError(error.message)
}

res.status(status).json({ error: error.constructor.name, message: error.message })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ export default (req, res) => {
}

res.status(status).json({ error: error.constructor.name, message: error.message })

return
})
} catch (error) {
let status = 500
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,13 @@ export default (req, res) => {
}

res.status(status).json({ error: error.constructor.name, message: error.message })

return
})
} catch (error) {
let status = 500

if (error instanceof TypeError || error instanceof ContentError) {
status = 409
}

if (error instanceof JsonWebTokenError) {
} else if (error instanceof JsonWebTokenError) {
status = 401
error = new TokenError(error.message)
}
Expand Down
5 changes: 4 additions & 1 deletion staff/abel-prieto/PROYECT/API/handlers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import changeUserEmailHandler from './changeUserEmailHandler.js'
import changeUserPasswordHandler from './changeUserPasswordHandler.js'

import uploadFileHandler from './uploadFileHandler.js'
import uploadFileBBHandler from './uploadFileBBHandler.js'

export {
authenticateUserHandler,
Expand All @@ -14,5 +15,7 @@ export {
retrieveGuestHandler,
changeUserEmailHandler,
changeUserPasswordHandler,
uploadFileHandler

uploadFileHandler,
uploadFileBBHandler
}
2 changes: 0 additions & 2 deletions staff/abel-prieto/PROYECT/API/handlers/registerUserHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ export default (req, res) => {
}

res.status(status).json({ error: error.constructor.name, message: error.message })

return
})
} catch (error) {
let status = 500
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { NotFoundError, ContentError } = errors
export default (req, res) => {
try {
retrieveGuest()
.then(guest => res.json(guest))
.catch(error => {
let status = 500

Expand All @@ -13,10 +14,7 @@ export default (req, res) => {
}

res.status(status).json({ error: error.constructor.name, message: error.message })

return
})
.then(guest => res.json(guest))
} catch (error) {
let status = 500

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default (req, res) => {
const { sub: userId } = jwt.verify(token, process.env.JWT_SECRET)

retrieveUser(userId)
.then(user => res.json(user))
.catch(error => {
let status = 500

Expand All @@ -18,10 +19,7 @@ export default (req, res) => {
}

res.status(status).json({ error: error.constructor.name, message: error.message })

return
})
.then(user => res.json(user))
} catch (error) {
let status = 500

Expand Down
55 changes: 55 additions & 0 deletions staff/abel-prieto/PROYECT/API/handlers/uploadFileBBHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import jwt from 'jsonwebtoken'
import busboy from 'busboy'
import fs from 'fs'
import uploadFileBB from '../logic/uploadFileBB.js'
import { errors } from 'com'

const { NotFoundError, ContentError, TokenError } = errors
const { JsonWebTokenError } = jwt

export default (req, res) => {
try {
const token = req.headers.authorization.substring(7)
const { sub: userId } = jwt.verify(token, process.env.JWT_SECRET)

const bb = new busboy({ body: req.body })

bb.on('file', async (name, file, info) => {
const { filename, mimeType } = info

try {
const saveFile = await uploadFileBB(userId, filename, mimeType)

const writeStream = fs.createWriteStream(saveFile)
file.pipe(writeStream)

writeStream.on('close', () => {
res.sendStatus(200)
})
} catch (error) {
let status = 500

if (error instanceof NotFoundError) {
status = 404
}

res.status(status).json({ error: error.constructor.name, message: error.message })
}
})

req.pipe(bb)
} catch (error) {
let status = 500

if (error instanceof TypeError || error instanceof ContentError) {
status = 406
}

if (error instanceof JsonWebTokenError) {
status = 401
error = new TokenError(error.message)
}

res.status(status).json({ error: error.constructor.name, message: error.message })
}
}
27 changes: 5 additions & 22 deletions staff/abel-prieto/PROYECT/API/handlers/uploadFileHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,17 @@ const { JsonWebTokenError } = jwt
import uploadFile from '../logic/uploadFile.js'
import { errors } from 'com'

const { SystemError, DuplicityError, NotFoundError, ContentError, TokenError } = errors

async function saveFile(file) {
const newPath = `./uploads/${file.originalname}`

try {
await fs.renameSync(file.path, newPath)
return newPath
} catch (error) {
throw new SystemError(`Failed to save file: ${error.message}`)
}
}
const { NotFoundError, ContentError, TokenError } = errors

export default async (req, res) => {
const token = req.headers.authorization.substring(7)
const { sub: userId } = jwt.verify(token, process.env.JWT_SECRET)

const { originalname, mimetype } = req.file

const { originalname, mimetype, path } = req.file
const oldPath = path
try {
await saveFile(req.file)
const result = await uploadFile(userId, originalname, mimetype)

res.json({ user: result.user, file: result.file })
await uploadFile(userId, originalname, mimetype, oldPath)
res.status(200).send()

} catch (error) {
let status = 500
Expand All @@ -39,10 +26,6 @@ export default async (req, res) => {
status = 406
}

if (error instanceof DuplicityError) {
status = 409
}

if (error instanceof JsonWebTokenError) {
status = 401

Expand Down
6 changes: 4 additions & 2 deletions staff/abel-prieto/PROYECT/API/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
retrieveGuestHandler,
changeUserEmailHandler,
changeUserPasswordHandler,
uploadFileHandler
uploadFileHandler,
uploadFileBBHandler
} from './handlers/index.js'

dotenv.config()
Expand All @@ -37,7 +38,7 @@ mongoose.connect(process.env.URL_MONGODB_HIINIT_API)
server.get('/users', retrieveUserHandler)

// RETRIEVE GUEST
server.get('/users', retrieveGuestHandler)
server.get('/guest', retrieveGuestHandler)

// CHANGE USER EMAIL
server.patch('/users/email', jsonBodyParser, changeUserEmailHandler)
Expand All @@ -47,6 +48,7 @@ mongoose.connect(process.env.URL_MONGODB_HIINIT_API)

// UPLOAD FILE
server.post('/upload', upload.single('file'), uploadFileHandler)
// server.post('/upload', uploadFileBBHandler)

server.listen(process.env.PORT, () => console.log(`server online! Listen on: ${process.env.PORT}`))
})
Expand Down
1 change: 1 addition & 0 deletions staff/abel-prieto/PROYECT/API/logic/changeUserEmail.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { validate, errors } from 'com'
const { SystemError, NotFoundError, CredentialsError } = errors

function changeUserEmail(userId, newEmail, password, againPassword) {
validate.id(userId, 'ID user')
validate.email(newEmail, 'New email')
validate.password(password, 'Password')
validate.password(againPassword, 'Repeat password')
Expand Down
1 change: 1 addition & 0 deletions staff/abel-prieto/PROYECT/API/logic/changeUserPassword.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { validate, errors } from 'com'
const { SystemError, NotFoundError, CredentialsError } = errors

function changeUserPassword(userId, password, newPassword, againNewPassword) {
validate.id(userId, 'ID user')
validate.password(password, 'Password')
validate.password(newPassword, 'New password')
validate.password(againNewPassword, 'Repeat new password')
Expand Down
Loading

0 comments on commit 33f89ee

Please sign in to comment.