Skip to content

Commit

Permalink
Merge ec03712 into fbe1c14
Browse files Browse the repository at this point in the history
  • Loading branch information
angeliski authored Jan 23, 2018
2 parents fbe1c14 + ec03712 commit 04b89af
Show file tree
Hide file tree
Showing 20 changed files with 378 additions and 107 deletions.
20 changes: 14 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,37 @@ Com isso é possível visualizar o atual draft, qualquer sugestão pode ser feit

## Run
As seguintes tecnologias são usadas nesse projeto:
- Firebase
- Node
- Express 4
- ES6
- MongoDB
- Babel (Para uso das novas features)
- Mocha + Sinon + Chai
- Mocha + Chai + Mongo-In-Memory + pow-mongodb-fixtures
- Nodemon

Para rodar o projeto, atualmente é necessário adicionar o arquivo `firebase-admin-sdk.json` na pasta `/src/admin-firebase`. Você pode entender o que é esse arquivo, no seguinte link: [Firebase Admin](https://firebase.google.com/docs/admin/setup?hl=pt-br).
Você pode, se desejar, configurar uma aplicação do github através do arquivo `default.json`, a aplicação atual aponta para o callback `http://localhost:3000/auth/github/callback`.
Você pode, se desejar, configurar uma aplicação do github através do arquivo `dev.json`, a aplicação atual aponta para o callback `http://localhost:3000/auth/callback`.

Para rodar, basta executar `npm i` na raiz, em seguida `npm start`.

## Dev
Para contribuir com o projeto é muito simples!

Você ainda precisa realizar a configuração do [Run](#run).
Após isso, você tem algumas opções:
Você tem algumas opções:
- Para subir a aplicação para desenvolver, você pode rodar o comando `npm run dev`. Isso inicia o servidor com o `nodemon`, o que permite um desenvolvimento mais ágil.
- Você pode rodar o linter do projeto, usando a opção `npm run eslint`. Por favor, faça isso antes de submeter um pull request.
- Você pode rodar os testes do projeto, usando a opção `npm t` ou `npm test`, essa opção já vai rodar o linter por padrão sempre. Por favor, faça isso antes de submeter um pull request.
- Se você quiser, pode usar o comando `npm run watch` para iniciar o modo watch, que roda o lint e os testes sempre que um arquivo for salvo. Isso nos permite agilidade e feedback rápido. :)

## Testes
A nossa aplicação tem dois tipos de testes, **Integração** e **Unidade**.
Todos os testes estão dentro da pasta test.
#### Testes de integração
Os testes de integração são todos os arquivos terminados em _integration.spec.js_.
Todos os testes são rodados com base em um servidor conectado a uma base do mongo-in-memory. É possível fazer um load de dados nessa base, adicionado informações a pasta fixtures. Esses dados são carregados através do [pow-mongodb-fixtures](https://github.com/powmedia/pow-mongodb-fixtures).
#### Testes de unidade
Os testes de unidade são todos os arquivos terminados em _unit.spec.js_.


## Deploy

A plataforma de Deploy escolhida, foi o [WeDeploy](https://wedeploy.com/).
Expand Down
18 changes: 5 additions & 13 deletions config/default.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
{
"port": "80",
"secret": "secret",
"expiresIn": "8h",
"github": {
"clienteId": "93c87ec9bfbea4151180",
"clienteSecret": "8e1d50fb000071ebd47a7c970fce9365c831f287",
"callbackURL": "https://frontendbreventosapi-eventosapi.wedeploy.io/auth/github/callback"
"client_id": "7ce460021a69ec7f56b7",
"client_secret": "d58c251c95c9ce057c9532aacb0fb2f33e0412f8",
"redirect_uri": "http://localhost:3000/auth/callback",
"grant_type": "grant_type"
},
"serviceAccountAdminPath": "./firebase-admin-sdk.json",
"databaseURL": "https://frontend-br-eventos.firebaseio.com",
"mongo": {
"host": "ds227555.mlab.com",
"port": 27555,
"database": "eventos-api",
"username": "admin",
"password": "javascript0"
},
"firebase": {
"apiKey": "AIzaSyDClNYE54DCbk5y91sf-_MCYLIfkto6zwk",
"authDomain": "frontend-br-eventos.firebaseapp.com",
"databaseURL": "https://frontend-br-eventos.firebaseio.com",
"projectId": "frontend-br-eventos",
"storageBucket": "frontend-br-eventos.appspot.com",
"messagingSenderId": "477638030798"
}
}
26 changes: 8 additions & 18 deletions config/dev.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
{
"port": "3000",
"serviceAccountAdminPath": "./firebase-admin-sdk-dev.json",
"databaseURL": "https://frontend-br-eventos-dev.firebaseio.com/",
"firebase": {
"apiKey": "AIzaSyAH12r5RbxzHZA30ZLc-nAMqlEXLmYxzVE",
"authDomain": "frontend-br-eventos-dev.firebaseapp.com",
"databaseURL": "https://frontend-br-eventos-dev.firebaseio.com",
"projectId": "frontend-br-eventos-dev",
"storageBucket": "",
"messagingSenderId": "90026726723"
},
"github": {
"clienteId": "7ce460021a69ec7f56b7",
"clienteSecret": "d58c251c95c9ce057c9532aacb0fb2f33e0412f8",
"callbackURL": "http://localhost:3000/auth/github/callback"
}
}
{
"port": "3000",
"github": {
"clienteId": "7ce460021a69ec7f56b7",
"clienteSecret": "d58c251c95c9ce057c9532aacb0fb2f33e0412f8",
"callbackURL": "http://localhost:3000/auth/github/callback"
}
}
18 changes: 7 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"start": "cross-env NODE_ENV=production ./node_modules/.bin/babel-node src",
"dev": "cross-env NODE_ENV=dev nodemon ./node_modules/.bin/babel-node src",
"test": "cross-env NODE_ENV=test npm-run-all test:unit test:integration",
"test": "cross-env NODE_ENV=test npm-run-all eslint test:unit test:integration",
"test:unit": "cross-env NODE_ENV=test mocha test/**/*.unit.spec.js --require babel-register",
"test:integration": "cross-env NODE_ENV=test ./node_modules/.bin/babel-node test/integration.test.js",
"test:integration:up": "cross-env NODE_ENV=test ./node_modules/.bin/babel-node src",
Expand All @@ -32,6 +32,7 @@
},
"homepage": "https://github.com/frontendbr/eventos-api#readme",
"dependencies": {
"axios": "^0.17.1",
"bluebird": "^3.5.1",
"body-parser": "^1.17.2",
"bodymen": "^1.0.3",
Expand All @@ -41,42 +42,37 @@
"express-authentication": "^0.3.2",
"express-session": "^1.15.3",
"express-validation": "^0.4.5",
"firebase": "^4.1.3",
"firebase-admin": "^5.0.1",
"jsonwebtoken": "^8.1.0",
"lodash": "^4.17.4",
"mongoose": "^4.13.9",
"morgan": "^1.8.0",
"joi": "^7.3.0",
"swagger-ui-express": "^2.0.1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-istanbul": "^0.12.2",
"babel-plugin-istanbul": "^4.1.5",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-register": "^6.26.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.26.0",
"chai": "^3.5.0",
"chai-http": "^2.0.1",
"coveralls": "^2.13.1",
"cross-env": "^5.1.0",
"eslint": "^4.9.0",
"eslint-plugin-import": "^2.8.0",
"firebase-mock": "^1.1.5",
"istanbul": "^0.4.5",
"mocha": "^2.4.5",
"mocha-lcov-reporter": "^1.3.0",
"mongo-in-memory": "0.0.5",
"nodemon": "^1.12.1",
"npm-run-all": "^4.1.1",
"nyc": "^11.4.1",
"pow-mongodb-fixtures": "^0.14.0",
"promise-serial": "^0.1.5",
"proxyquire": "^1.8.0",
"sinon": "^2.3.8",
"sinon-chai": "^2.12.0",
"standard": "^10.0.3",
"supertest": "^3.0.0",
"istanbul": "^0.4.5",
"mocha-lcov-reporter": "^1.3.0"
"supertest": "^3.0.0"
}
}
1 change: 0 additions & 1 deletion src/admin-firebase/firebase-admin-sdk-test.json

This file was deleted.

Binary file not shown.
37 changes: 0 additions & 37 deletions src/admin-firebase/index.js

This file was deleted.

39 changes: 39 additions & 0 deletions src/api/admin/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,42 @@ export const create = (req, res) =>
data: err
})
})

export const find = (req, res) => {
let find = {}
find = Administrator.find().exec()

find.then((administrator) => {
if (!administrator) {
return res.status(404).json({
status: false,
data: {}
})
}

return res.status(200).json({
status: true,
data: administrator
})
}).catch((err) => {
return res.status(500).json({
status: false,
data: err
})
})
}

export const remove = (req, res) => {
Administrator.findByIdAndRemove(req.params.id)
.then(() => {
return res.status(200).json({
status: true
})
})
.catch((err) => {
return res.status(500).json({
status: false,
data: err
})
})
}
6 changes: 4 additions & 2 deletions src/api/admin/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Router } from 'express'

import { create } from './controller'
import { create, find, remove } from './controller'

const router = (loginManager) => {
console.info('Init Admin module')
const route = Router()

route.post('/', loginManager.authentication, create)
route.post('/', loginManager.admin, create)
route.get('/', loginManager.admin, find)
route.delete('/:id', loginManager.admin, remove)

return route
}
Expand Down
68 changes: 68 additions & 0 deletions src/api/auth/Authentication.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import jwt from 'jsonwebtoken'
import config from 'config'
import Administrator from '../admin/model'

export class Authentication {
constructor () {
this.config = config
this.jwt = jwt
}

checkAuth (request) {
return this._validToken(request)
}

checkAdmin (request) {
return this._validToken(request)
.then(({ email }) => {
return Administrator
.findOne({ email })
.exec()
}).then((adm) => {
if (!adm) {
return Promise.reject(new Error('É necessário ser adm'))
}
return adm
})
}

_validToken (request) {
return new Promise((resolve, reject) => {
const jwtToken = this._getToken(request)
if (!jwtToken) {
reject(new Error('É necessário informar um token'))
}
const userInfo = this.jwt.verify(jwtToken, this.config.secret)

if (!userInfo) {
reject(new Error('É necessário estar logado'))
}

resolve(userInfo)
})
}

createToken (email) {
return { token: this.jwt.sign({ email }, this.config.secret, { expiresIn: this.config.expiresIn }) }
}

_getToken (request) {
const query = request.query
const headers = request.headers

let token = null

const bearerHeader = headers.authorization
if (bearerHeader && bearerHeader.indexOf(' ') > -1) {
token = bearerHeader.split(' ')[1]
}

if (!token && query.token) {
token = query.token
}

return token
}
}

export default new Authentication()
31 changes: 31 additions & 0 deletions src/api/auth/controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import axios from 'axios'
import config from 'config'
import { success, error } from './../../constants'
import Authentication from './Authentication'

export const auth = (request, response) => {
const { code } = request.body

let data = Object.assign({ code }, config.github)

axios
.post('https://github.com/login/oauth/access_token', data, params)
.then(getUserInfo)
.then(success(response))
.catch(error(response))
}

const params = {
headers: {
'Content-Type': 'application/json', 'Accept': 'application/json'
}
}

const generateJWT = ({ email }) => Authentication.createToken(email)

const getUserInfo = ({ data }) => {
return axios
.get(`https://api.github.com/user?access_token=${data.access_token}`, params)
.then((resp) => resp.data)
.then(generateJWT)
}
14 changes: 14 additions & 0 deletions src/api/auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Router } from 'express'

import { auth } from './controller'

const router = () => {
console.info('Init Auth module')
const route = Router()

route.post('/', auth)

return route
}

export default router
2 changes: 2 additions & 0 deletions src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import loginMiddleware from '../middleware/login-request-middleware'
import Docs from './docs'
import Events from './events'
import Admin from './admin'
import Auth from './auth'

const router = ({
config,
Expand All @@ -17,6 +18,7 @@ const router = ({

const api = Router()

api.use('/auth', Auth())
api.use('/admin', Admin(loginManager))
api.use('/event', Events(loginManager))

Expand Down
Loading

0 comments on commit 04b89af

Please sign in to comment.