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

update branch #56

Open
wants to merge 4 commits into
base: master
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
4 changes: 3 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
node_modules
PORT=3000
DATABASE_URL=mongodb://localhost:27017/yourdb
JWT_SECRET=yourSecretKey
40 changes: 25 additions & 15 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,35 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')
const express = require('express');
const logger = require('morgan');
const cors = require('cors');

const contactsRouter = require('./routes/api/contacts')

const app = express()
const usersRouter = require('./routes/api/users');

const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short'
// const apiRoutes = require('./api');

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())
const app = express();

app.use('/api/contacts', contactsRouter)

const logFormat = app.get('env') === 'development' ? 'dev' : 'short';

// Middlewares
app.use(logger(logFormat));
app.use(cors());
app.use(express.json());

// Routes

app.use('/api/', usersRouter);


// Middleware for handling 404 Not Found errors
app.use((req, res) => {
res.status(404).json({ message: 'Not found' })
})
res.status(404).json({ message: 'Not found' });
});

// Error handling middleware for handling 500 Internal Server Error
app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})
res.status(500).json({ message: err.message });
});

module.exports = app
module.exports = app;
29 changes: 29 additions & 0 deletions config/config_passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const passport = require('passport')
const passportJWT = require('passport-jwt')
const User = require('../schemas/user')
require('dotenv').config()

const secret = process.env.JWT_SECRET;

const ExtractJWT = passportJWT.ExtractJwt;
const Strategy = passportJWT.Strategy;
const params = {
secretOrKey: secret,
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
};

// JWT Strategy
passport.use(
new Strategy(params, function (payload, done) {
User.find({ _id: payload.id })
.then(([user]) => {
if (!user) {
return done(new Error('User not found'))
}
return done(null, user)
})
.catch((err) => done(err))
}),
);

module.exports = passport;
18 changes: 18 additions & 0 deletions middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

const passport = require("passport");
const auth = (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user) => {
if (!user || err) {
return res.status(401).json({
status: 'error',
code: 401,
message: 'Unauthorized',
data: 'Unauthorized',
})
}
req.user = user
next()
})(req, res, next)
}

module.exports = auth;
14 changes: 14 additions & 0 deletions middlewares/multerPublic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Configure Multer for the "public" folder
const multer = require('multer');
const path = require('path');

const publicStorage = multer.diskStorage({
destination: path.join(__dirname, '..', 'public', 'avatars'), // Store in the "public/avatars" folder
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`);
},
});

const publicUpload = multer({ storage: publicStorage });

module.exports = publicUpload;
14 changes: 14 additions & 0 deletions middlewares/multerTmp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const multer = require('multer');
const path = require('path');

// Configure Multer for the "tmp" folder
const tmpStorage = multer.diskStorage({
destination: path.join(__dirname, '..', 'tmp'), // Temporary storage in the "tmp" folder
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`);
},
});

const tmpUpload = multer({ storage: tmpStorage });

module.exports = tmpUpload;
22 changes: 22 additions & 0 deletions middlewares/token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const invalidatedTokens = new Set();

const validateToken = (req, res, next) => {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(" ")[1];

if (invalidatedTokens.has(token)) {
return res.status(401).json({
status: "error",
code: 401,
message: "Unathorized: Invalid token",
data: "Unathorized",
});
}

next();
};

module.exports = {
validateToken,
invalidatedTokens,
}
19 changes: 0 additions & 19 deletions models/contacts.js

This file was deleted.

62 changes: 0 additions & 62 deletions models/contacts.json

This file was deleted.

Loading