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

Challenge/irene-passport #921

Open
wants to merge 5 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
2 changes: 2 additions & 0 deletions irene-perez/challenge/passport/backend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DDBB_URL=<YOUR CONNECTION STRING>
SESSION_SECRET='Secret'
26 changes: 26 additions & 0 deletions irene-perez/challenge/passport/backend/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module.exports = {
env: {
commonjs: true,
es2021: true,
node: true
},
extends: [
'plugin:react/recommended',
'airbnb'
],
parserOptions: {
ecmaFeatures: {
jsx: true
},
ecmaVersion: 12
},
plugins: [
'react'
],
rules: {
'comma-dangle': [2, 'never'],
'linebreak-style': 0,
'global-require': 0,
'eslint linebreak-style': [0, 'error', 'windows']
}
};
30 changes: 30 additions & 0 deletions irene-perez/challenge/passport/backend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const express = require('express');
const session = require('express-session');
const debug = require('debug')('server');
const morgan = require('morgan');
const authRoutes = require('./src/routes/authRouter')();
const userRoutes = require('./src/routes/usersRouter')();

require('dotenv').config();

require('./src/ddbb/mongoose.config');

const server = express();
const port = process.env.PORT || 4000;

server.use(morgan('dev'));
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true
}));

require('./src/passport/passport.config')(server);

server.set('view engine', 'ejs');
server.set('views', './src/views');
server.use('/', authRoutes);
server.use('/api/users', userRoutes);
server.listen(port, debug(`server is running on port ${port}`));
5,729 changes: 5,729 additions & 0 deletions irene-perez/challenge/passport/backend/package-lock.json

Large diffs are not rendered by default.

37 changes: 37 additions & 0 deletions irene-perez/challenge/passport/backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "set DEBUG=app:db&& nodemon index.js",
"debug": "nodemon --inspect-brk index.js",
"test": "jest --watchAll --collect-coverage"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"eslint": "^7.27.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.23.3",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0"
},
"dependencies": {
"chalk": "^4.1.1",
"connect-ensure-login": "^0.1.1",
"cors": "^2.8.5",
"debug": "^4.3.1",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-session": "^1.17.2",
"jest": "^27.0.1",
"mongoose": "^5.12.11",
"morgan": "^1.10.0",
"nodemon": "^2.0.7",
"passport": "^0.4.1",
"passport-local": "^1.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const User = require('../model/userModel');

function userController() {
async function getAll(req, res) {
const users = await User.find();
res.json(users);
}
async function createOne(req, res) {
const newTask = new User(req.body);
try {
await newTask.save();
res.json(newTask);
} catch (error) {
res.send(error);
}
}
async function getById(req, res) {
try {
const userById = await User.findById(
req.params.userById
);
res.json(userById);
} catch (error) {
res.send(error);
}
}

return {
getAll,
createOne,
getById
};
}

module.exports = userController;
13 changes: 13 additions & 0 deletions irene-perez/challenge/passport/backend/src/ddbb/mongoose.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { connect } = require('mongoose');
const debug = require('debug')('server:mongoose');

connect(
process.env.DDBB_URL,
{
useUnifiedTopology: true,
useNewUrlParser: true
}
).then(
() => debug('database connection stablished'),
(error) => debug('database connection error', error)
);
12 changes: 12 additions & 0 deletions irene-perez/challenge/passport/backend/src/model/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
email: String,
password: String
});

userSchema.methods.isValidPassword = function isValidPassword(password) {
return password === this.password;
};

module.exports = mongoose.model('User', userSchema);
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const passport = require('passport');
require('./strategies/local.strategy')();

module.exports = function passportConfig(server) {
server.use(passport.initialize());
server.use(passport.session());
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const passport = require('passport');
const LocalStrategy = require('passport-local');
const User = require('../../model/userModel');

module.exports = function localStrategyConfig() {
passport.use(
new LocalStrategy.Strategy(
{
usernameField: 'email',
passwordField: 'password'
},
(email, password, done) => {
User.findOne({ email }).then((user) => {
if (!user || !user.isValidPassword(password)) {
return done(null, false);
}
return done(null, user);
}, (error) => done(error));
}
)
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
body {
background-color: lightblue;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
button {
width: 10vw;
height: 5vh;
border-radius: 10px;
background-color: grey;
margin: 10px 10px;
border: none;
font-size: 1rem;
cursor:pointer;
}
button:hover {
background-color: orangered;
}
input {
width:30%;
border-color: khaki;
border-radius: 10px;
}
h2 {
color: lightgray;
}
#show-name {
color: khaki;
}
23 changes: 23 additions & 0 deletions irene-perez/challenge/passport/backend/src/routes/authRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { Router } = require('express');
const passport = require('passport');
const { isAuthenticated } = require('../utils/auth');

module.exports = () => {
const authRoutes = Router();
authRoutes
.route('/')
.all(isAuthenticated)
.get((req, res) => {
res.render('home');
});
authRoutes
.route('/login')
.get((req, res) => {
res.render('login');
})
.post(passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}));
return authRoutes;
};
22 changes: 22 additions & 0 deletions irene-perez/challenge/passport/backend/src/routes/usersRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const { Router } = require('express');
const User = require('../model/userModel');
const { isAuthenticated } = require('../utils/auth');

module.exports = () => {
const userRoutes = Router();

userRoutes
.route('/')
.all(isAuthenticated)
.post(async (req, res) => {
try {
const user = await User.create(req.body);
res.send(user);
} catch (error) {
res.status(500);
res.send(error);
}
});

return userRoutes;
};
10 changes: 10 additions & 0 deletions irene-perez/challenge/passport/backend/src/utils/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function isAuthenticated(req, res, next) {
if (req.user) {
next();
} else {
res.redirect('/login');
}
}
module.exports = {
isAuthenticated
};
1 change: 1 addition & 0 deletions irene-perez/challenge/passport/backend/src/views/home.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Logged</h1>
42 changes: 42 additions & 0 deletions irene-perez/challenge/passport/backend/src/views/login.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<style>
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
body {
display: flex;
align-items: center;
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
</style>
</head>
<body class="text-center">
<main class="form-signin">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<form action="/login" method="POST">
<div class="form-floating">
<input class="form-control" type="text" placeholder="email" id="email" name="email">
<label for="password">email</label>
</div>
<div class="form-floating">
<input class="form-control" type="password" placeholder="password" id="password" name="password">
<label for="password">password</label>
</div>
<input class="w-100 btn btn-lg btn-primary" type="submit" name="login-button" id="login-button" value="login">
</form>
</main>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>
</html>
Loading