Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercises/28.1 #29

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
5 changes: 5 additions & 0 deletions bloco_28/dia_1/exercicios/exercicios/hello-jwt/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": [
"trybe-backend"
]
}
181 changes: 181 additions & 0 deletions bloco_28/dia_1/exercicios/exercicios/hello-jwt/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@

# Created by https://www.toptal.com/developers/gitignore/api/node,linux,windows,vscode
# Edit at https://www.toptal.com/developers/gitignore?templates=node,linux,windows,vscode

### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test
.env*.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Storybook build outputs
.out
.storybook-out
storybook-static

# rollup.js default build output
dist/

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# Temporary folders
tmp/
temp/

### vscode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace

### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp

# Windows shortcuts
*.lnk

# End of https://www.toptal.com/developers/gitignore/api/node,linux,windows,vscode
n
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const login = require('./login');
const myself = require('./myself');
const onlyAdmin = require('./onlyAdmin');

module.exports = {
login,
myself,
onlyAdmin,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const jwt = require('jsonwebtoken');
const Joi = require('joi');

const secret = process.env.SECRET;

const jwtOptions = {
expiresIn: '1h',
algorithm: "HS256"
}

module.exports = (req, res) => {
const { username, password } = req.body;

const schema = Joi.object({
username: Joi.string().alphanum().min(5).required(),
password: Joi.string().alphanum().min(5).required(),
}).validate({ username, password });

if (schema.error) {
return res.status(422).json({ message: schema.error.message })
};

const payload = {
data: {
user: username,
admin: true,
}
};

if (username === 'admin' && password === 's3nh4S3gur4???') {
payload.admin = true;
};

const token = jwt.sign(payload, secret, jwtOptions);

res.status(200).json({ token });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const jwt = require('jsonwebtoken');


module.exports = (req, res, next) => {
const { authorization } = req.headers;
const { token } = req;


res.status(200).json({
username: token.data.user,
admin: token.data.admin,
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = (_req, res) => {
return res.status(200).json({ secretInfo: 'Peter Parker é o Homem-Aranha'});
};
34 changes: 34 additions & 0 deletions bloco_28/dia_1/exercicios/exercicios/hello-jwt/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const { PORT } = process.env;

const controllers = require('./controllers');
const middlewares = require('./middlewares');

const app = express();

app.use(
cors({
origin: `http://localhost:${PORT}`,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Authorization'],
}),
);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/users/me', middlewares.auth, controllers.myself);

app.get('/top-secret', middlewares.auth, middlewares.admin,controllers.onlyAdmin);

app.post('/login', controllers.login);

app.use(middlewares.error);

app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = (req, _res, next) => {
if (req.route.path === '/top-secret' && !(req.token.data.admin)) {
next({ statusCode: 403, message: 'Restricted access'})
}

next();
}
16 changes: 16 additions & 0 deletions bloco_28/dia_1/exercicios/exercicios/hello-jwt/middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const jwt = require('jsonwebtoken');

const secret = process.env.SECRET;

module.exports = (req, res, next) => {
const { authorization } = req.headers;

if (!authorization) {
return next({ statusCode: 401, message: "Token not found" })
}

const token = jwt.verify(authorization, secret);

req.token = token;
next();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = (err, _req, res, _next) => {
if (err.isJoi) {
return res.status(422).json({
error: { message: err.details[0].message },
});
}

if (err.statusCode) {
return res.status(err.statusCode).json({
error: { message: err.message },
});
}

return res.status(500).json({
error: {
message: `Internal server error: ${err.message}`,
},
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const error = require('./error');
const auth = require('./auth');
const admin = require('./admin');
module.exports = {
error,
auth,
admin,
};
Loading