diff --git a/backend/package.json b/backend/package.json index 68f4450..14c5947 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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": { diff --git a/backend/src/controllers/Login.ts b/backend/src/controllers/Login.ts new file mode 100644 index 0000000..da0ea14 --- /dev/null +++ b/backend/src/controllers/Login.ts @@ -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 \ No newline at end of file diff --git a/backend/src/helpers/authentication.ts b/backend/src/helpers/authentication.ts new file mode 100644 index 0000000..d7731f2 --- /dev/null +++ b/backend/src/helpers/authentication.ts @@ -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() \ No newline at end of file diff --git a/backend/src/index.ts b/backend/src/index.ts index 42599b7..d901db4 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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() @@ -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}`) diff --git a/backend/src/middlewares/auth.ts b/backend/src/middlewares/auth.ts new file mode 100644 index 0000000..b65b7a4 --- /dev/null +++ b/backend/src/middlewares/auth.ts @@ -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 \ No newline at end of file diff --git a/backend/src/routes/Login.ts b/backend/src/routes/Login.ts new file mode 100644 index 0000000..edbcc11 --- /dev/null +++ b/backend/src/routes/Login.ts @@ -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 diff --git a/backend/src/routes/User.ts b/backend/src/routes/User.ts index 2b47bf1..5468bcd 100644 --- a/backend/src/routes/User.ts +++ b/backend/src/routes/User.ts @@ -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) @@ -7,6 +8,4 @@ router.get('/', findAll) router.patch('/:id', updateById) router.delete('/:id',deleteById) -//router.post('/validate', validate) - export default router