Skip to content

Commit

Permalink
Merge branch 'feat-login' into development
Browse files Browse the repository at this point in the history
  • Loading branch information
yaskisoba committed Nov 19, 2023
2 parents bae539f + ca67aa9 commit 2bafbb0
Show file tree
Hide file tree
Showing 10 changed files with 122 additions and 78 deletions.
2 changes: 2 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/node_modules
.env
5 changes: 0 additions & 5 deletions backend/.sequelizerc

This file was deleted.

53 changes: 32 additions & 21 deletions backend/controllers/UserControllers.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,48 @@
const { Users } = require('../models/schemas');
const bcrypt = require('bcrypt');
const { sign } = require('jsonwebtoken');
const { createToken, validateToken } = require('./middlewares/Auth');

exports.teste = async(req, res) =>{
res.json('Login endpoint');
};

/* exports.registerUser = async(req, res) => {
exports.userRegister = async(req, res) => {
const { email, password } = req.body;
bcrypt.hash(password, 10).then((hash) => {
bcrypt.hash(password, 15).then((hash) => {
Users.create({
email: email,
password: hash,
}).then(() =>{
res.json('Solicitação bem sucedida!');
}).catch((err) => {
if(err){
res.status(400).json({error: err});
}
});
res.json('Solicitação bem sucedida.');
});
};

exports.loginUser = async(req, res) => {
exports.userLogin = async(req, res) => {
const { email, password } = req.body;
const user = await Users.findOne({where: {email: email}});
if(!user){
res.json({error: 'E-mail não cadastrado no banco de dados!'});
res.status(400).json({error: 'E-mail não cadastrado!'});
} else {
bcrypt.compare(password, user.password).then((validate) =>
if(!validate){
res.json({error: 'E-mail ou senha incorreta!'});
}else{
const token = sign{
{}
}
}
)
}
}*/
bcrypt.compare(password, user.password).then((match) =>{
if(!match){
res.status(400).json({error: 'Senha incorreta!'});
} else {
const accessToken = createToken(user);
res.cookie('access-token', accessToken, {
maxAge: 2592000000,
httpOnly: true,
});
Users.update(
{ token: accessToken },
{ where: { email: user.email } }
).then(() => {
res.json(accessToken);
}).catch((err) => {
res.status(500).json({ error: 'Erro ao atualizar o token no banco de dados.' });
});
};
});
};
};
28 changes: 28 additions & 0 deletions backend/controllers/middlewares/Auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { sign, verify } = require('jsonwebtoken');

const createToken = (user) => {
const accessToken = sign({username: user.email},
process.env.SECRET
);
return accessToken;
};

const validateToken = (req, res, next) => {
const accessToken = req.cookies['access-token'];
if(!accessToken) { //vê se o user já foi autenticado pelo cookie de sessão
return res.status(400).json({error: 'Usuário não autenticado!'});
};

try {
const validToken = verify(accessToken, process.env.SECRET);
if(validToken){
req.authenticated = true;
return next();
}
} catch(err) {
return res.status(400).json({error: err});
};
};

module.exports = { createToken, validateToken };

11 changes: 8 additions & 3 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
const { validateToken } = require('./controllers/middlewares/Auth');
const express = require('express');
const app = express();
const database = require('./models/schemas');
const port = 3001;
const userRoute = require('./views/routes/Users');
const electiveRoute = require('./views/routes/Electives')
const learningPathRoute = require('./views/routes/LearningPaths')
const learningPathRoute = require('./views/routes/LearningPaths')]

require("dotenv").config();
const app = express();
const port = 3001;
app.use(express.json());
app.use(validateToken);

app.use('/', userRoute);
app.use('/elective', electiveRoute);
app.use('/learning_paths', learningPathRoute);


database.sequelize.sync().then(() => {
app.listen(port, () => {
console.log('Server running on port 3001');
Expand Down
26 changes: 26 additions & 0 deletions backend/migrations/Users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

let users = { schema: 'Users', tableName: 'Users'}

module.exports = {
up: async (queryInterface, Sequelize) => {
const transaction = await queryInterface.sequelize.transaction();

try {
await queryInterface.createTable(users, {
co_users: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
ds_email: { type: Sequelize.STRING, allowNull: false, unique: true, validate: {isEmail: {args: true, msg: "O formato do e-mail é inválido",},},},
ds_password: { type: Sequelize.STRING, allowNull: false, validate: {len: [8, Infinity],},},
ds_token: { type: Sequelize.STRING },
})
await transaction.commit()
}catch (e) {
await transaction.rollback()
throw e
}
},

down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable(users)
}
}
43 changes: 0 additions & 43 deletions backend/models/index.js

This file was deleted.

17 changes: 14 additions & 3 deletions backend/models/schemas/Users.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
module.exports = (sequelize, DataTypes) =>{

const Users = sequelize.define("Users", {
id: {
type: DataTypes.INTEGER,
field: "co_users",
primaryKey: true,
autoIncrement: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
field: "ds_email",
validate: {
isEmail: {
args: true,
msg: "O formato do e-mail é inválido",
},
},
},

password: {
field: "ds_password",
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [8, Infinity],
},
},

token: {
type: DataTypes.STRING,
},
tokenExpiration: {
field: "ds_token",
type: DataTypes.STRING,
},
})

return Users;

}
2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.1",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mysql2": "^3.6.3",
Expand Down
13 changes: 10 additions & 3 deletions backend/views/routes/Users.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
const express = require('express');
const router = express.Router();
const userController = require('../../controllers/UserControllers')
const cookieParser = require('cookie-parser');
const userController = require('../../controllers/UserControllers');
const { validateToken } = require('../../controllers/middlewares/Auth');

// router.post("/", userController.registerUser);
// router.post("/teste", userController.teste);
router.use(cookieParser());
router.post('/', userController.userRegister);
router.post('/login', userController.userLogin);

router.get('/profile', validateToken, (req, res) => {
res.json('profile');
});

module.exports = router;

0 comments on commit 2bafbb0

Please sign in to comment.