Skip to content

Commit

Permalink
Merge pull request #59 from #14
Browse files Browse the repository at this point in the history
Cerradogo#14
  • Loading branch information
seraphritt authored Aug 21, 2022
2 parents 8ed8e52 + 1e5b834 commit bd622c6
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 4 deletions.
2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"dependencies": {
"dotenv": "^16.0.1",
"express": "^4.18.1",
"express-handler-errors": "^2.3.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.5.1"
},
"devDependencies": {
Expand Down
16 changes: 16 additions & 0 deletions backend/src/controllers/Login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {Request, Response} from 'express'
import authentication from '../helpers/authentication'
const key = "teste"
const create = async (req: Request, res: Response) => {
console.log('teste')
const {username, password} = req.body
try{
const token = await authentication.auth({username, password}, key)
res.send(token)
} catch(e){
console.error(e)
res.status(401).end()
}
}

export default create
44 changes: 44 additions & 0 deletions backend/src/helpers/authentication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {verify, sign} from 'jsonwebtoken'
import UserModel from '../models/User'
import { CustomError } from 'express-handler-errors'
class Auth{
async auth(user: {username: string; password: string}, key: string): Promise<{token: string}>{
const {username, password} = user
try{
const res = await UserModel.findOne({nickname: username, password})
if (!res) {
throw new CustomError({
code: 'USER_NOT_FOUND',
message: 'Usuario não foi encontrado',
status: 404
})
}

const token = await sign({
_id: res._id,
name: res.name
}, key, {
expiresIn: 3000
})
return {token}

} catch (e){
console.error(e)
throw new Error()
}
}

validate(token: string, key: string): boolean{
const jwt = token.split(' ')[1]
let isValid = false
verify(jwt, key, (err)=>{
if(err) {
return
}
isValid = true
})
return isValid
}
}

export default new Auth()
6 changes: 4 additions & 2 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import mongoose from 'mongoose'

//import routes
import User from './routes/User'
import Question from './routes/Question'
import Login from './routes/Login'

dotenv.config()

Expand All @@ -14,11 +16,11 @@ const port = process.env.PORT
const dbUser = process.env.DB_USERNAME
const dbPasswd = process.env.DB_PASSWORD

// mongoose.connect(`mongodb://cerradogo:cerradogo@localhost:27017`)
mongoose.connect(`mongodb+srv://${dbUser}:${dbPasswd}@cluster0.ub24ryp.mongodb.net/?retryWrites=true&w=majority`)
//mongoose.connect(`mongodb://cerradogo:cerradogo@localhost:27017`)

app.use('/user', User)
app.use('/question', Question)
app.use('/login', Login)

app.listen(port, () => {
console.log(`server rodando na porta ${port}`)
Expand Down
20 changes: 20 additions & 0 deletions backend/src/middlewares/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {Request, Response, NextFunction} from 'express'
import authentication from '../helpers/authentication'
const key = "teste"
const create = async (req: Request, res: Response, next: NextFunction) => {
const token: string | undefined = req.headers.authorization
if(!token){
res.status(401).send('Não autorizado')
return
}
const isValid = authentication.validate(token, key)
if(isValid){
next()
} else {
res.status(401).send('Token Invalido')
return
}

}

export default create
7 changes: 7 additions & 0 deletions backend/src/routes/Login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import express, {Router} from 'express'
import Login from '../controllers/Login'
const router: Router = express.Router()
router.post('/', Login)
//router.post('/validate', validate)

export default router
3 changes: 1 addition & 2 deletions backend/src/routes/User.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import express, {Router} from 'express'
import Validate from '../middlewares/auth'
import {create, deleteById, findById, findAll, updateById} from '../controllers/User'
const router: Router = express.Router()
router.post('/', create)
Expand All @@ -7,6 +8,4 @@ router.get('/', findAll)
router.patch('/:id', updateById)
router.delete('/:id',deleteById)

//router.post('/validate', validate)

export default router

0 comments on commit bd622c6

Please sign in to comment.