Skip to content
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
37 changes: 22 additions & 15 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
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 contactsRouter = require('./routes/api/contacts');
const usersRouter = require('./routes/api/users'); // Import routera użytkowników

const app = express()
const app = express();

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

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

app.use('/api/contacts', contactsRouter)
// 👉 Podpięcie API dla kontaktów i użytkowników
app.use('/api/contacts', contactsRouter);
app.use('/api/users', usersRouter); // Dodajemy obsługę użytkowników

// 👉 Udostępnienie folderu public dla statycznych plików (np. awatary)
app.use('/public', express.static('public'));

app.use((req, res) => {
res.status(404).json({ message: 'Not found' })
})
res.status(404).json({ message: 'Not found' });
});

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
42 changes: 42 additions & 0 deletions controllers/contacts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const Contact = require('../models/contact');

const getAllContacts = async (req, res) => {
const contacts = await Contact.find({ owner: req.user._id });
res.json(contacts);
};

const getContactById = async (req, res) => {
const contact = await Contact.findById(req.params.id);
if (!contact) {
return res.status(404).json({ message: 'Contact not found' });
}
res.json(contact);
};

const addContact = async (req, res) => {
const newContact = await Contact.create({ ...req.body, owner: req.user._id });
res.status(201).json(newContact);
};

const updateContact = async (req, res) => {
const updatedContact = await Contact.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!updatedContact) {
return res.status(404).json({ message: 'Contact not found' });
}
res.json(updatedContact);
};

const deleteContact = async (req, res) => {
try {
const deletedContact = await Contact.findByIdAndDelete(req.params.id);

if (!deletedContact) {
return res.status(404).json({ message: 'Contact not found' });
}

res.status(200).json({ message: 'Contact deleted successfully' });
} catch (error) {
res.status(500).json({ message: 'Server error while deleting contact' });
}
};

13 changes: 13 additions & 0 deletions controllers/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const sendVerificationEmail = require('../services/emailService');
const { v4: uuidv4 } = require('uuid');

const registerUser = async (req, res) => {
const { email } = req.body;
const verificationToken = uuidv4();

// Logika zapisu użytkownika w bazie danych z verificationToken

await sendVerificationEmail(email, verificationToken);

res.status(201).json({ message: 'Registration successful. Check your email for verification.' });
};
29 changes: 29 additions & 0 deletions middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const jwt = require('jsonwebtoken');
const User = require('../models/user');

const { SECRET_KEY } = process.env;

const authenticate = async (req, res, next) => {
const { authorization = '' } = req.headers;
const [bearer, token] = authorization.split(' ');

if (bearer !== 'Bearer' || !token) {
return res.status(401).json({ message: 'Not authorized' });
}

try {
const { id } = jwt.verify(token, SECRET_KEY);
const user = await User.findById(id);

if (!user || user.token !== token) {
return res.status(401).json({ message: 'Not authorized' });
}

req.user = user;
next();
} catch (error) {
return res.status(401).json({ message: 'Not authorized' });
}
};

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

const tempDir = path.join(__dirname, '../tmp');

const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, tempDir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const extension = path.extname(file.originalname);
cb(null, `${file.fieldname}-${uniqueSuffix}${extension}`);
}
});

const fileFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Nieprawidłowy format pliku. Dozwolone są tylko obrazy.'), false);
}
};

const upload = multer({ storage, fileFilter });

module.exports = upload;
Loading