Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
adding folders
  • Loading branch information
biffysix authored Mar 16, 2021
1 parent 151e32f commit a80659e
Show file tree
Hide file tree
Showing 10 changed files with 314 additions and 0 deletions.
37 changes: 37 additions & 0 deletions controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const userModel = require("../models/userModel").userModel;

const getUserByEmailIdAndPassword = (email, password) => {
let user = userModel.findOne(email);
if (user) {
if (isUserValid(user, password)) {
return user;
}
}
return null;
};
const getUserById = (id) => {
let user = userModel.findById(id);
if (user) {
return user;
}
return null;
};
const getUserByGitHubIdOrCreate = (profile) => {
console.log("findbygithub_ID");
let user = userModel.findByProfile(profile.id)
if (user) {
return user;
}
// let createdUser = userModel.createUserWithGithubId(profile);
// return createdUser;
};

function isUserValid(user, password) {
return user.password === password;
}

module.exports = {
getUserByEmailIdAndPassword,
getUserById,
getUserByGitHubIdOrCreate,
};
14 changes: 14 additions & 0 deletions middleware/checkAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
ensureAuthenticated: function (req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/auth/login");
},
forwardAuthenticated: function (req, res, next) {
if (!req.isAuthenticated()) {
return next();
}
res.redirect("/dashboard");
},
};
61 changes: 61 additions & 0 deletions middleware/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
require('dotenv').config();
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const userController = require("../controllers/userController");
const GitHubStrategy = require('passport-github').Strategy;
//added GitHubStrategy above in passport.js

const localLogin = new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
(email, password, done) => {
const user = userController.getUserByEmailIdAndPassword(email, password);
return user
? done(null, user)
: done(null, false, {
message: "Your login details are not valid. Please try again",
});
}
);


passport.serializeUser(function (user, done) {
console.log("serial");
console.log(user);
done(null, user.id);
});

passport.deserializeUser(function (id, done) {
let user = userController.getUserById(id);
if (user) {
done(null, user);
} else {
done({ message: "User not found" }, null);
}
});



let githublogin = new GitHubStrategy(
{
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: "http://localhost:8000/auth/github/callback"
},//from authRoute.js
function(accessToken, refreshToken, profile, done) {
// let user = userController.getUserByGitHubIdOrCreate(profile);
// return done(null, user);
// }
// );
//use the profile info (mainly profile id) to check if user is registered in our db
//User.findOrCreate({ githubId: profile.id }, function (err, user){
return done(null, profile);
//});
}
);
//console.log(require('dotenv').config());
module.exports = passport.use(githublogin).use(localLogin);
//above returns an instance of passport that has been configured
// with new githubstrategy and local strategy
64 changes: 64 additions & 0 deletions models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const database = [
{
id: 1,
name: "Jimmy Smith",
email: "[email protected]",
password: "jimmy123!",
},
{
id: 2,
name: "Johnny Doe",
email: "[email protected]",
password: "johnny123!",
},
{
id: 3,
name: "Jonathan Chen",
email: "[email protected]",
password: "jonathan123!",
},
{
id: 4,
name: "biffysix",
email: "[email protected]",
password: "brucewong123!",
},
{
id: 13098012,
name: "Don Zhao",
email: "[email protected]",
password: "donzhao123!",
}
];

const userModel = {
findOne: (email) => {
const user = database.find((user) => user.email === email);
if (user) {
return user;
}
throw new Error(`Couldn't find user with email: ${email}`);
},
findById: (id) => {
const user = database.find((user) => user.id === id);
if (user) {
return user;
}
throw new Error(`Couldn't find user with id: ${id}`);
},
//createUserWithGithubId: (id) => {
findByProfile: (email) =>{
const user = database.find((user) => user.email === email);
if (user){
return user;
}
throw new Error(`Couldn't find githubuser with id: ${email}`);

// const user = { id: profile.id,
// name: profile.displayName,};
// database.push(user);
// return user;
}
};

module.exports = { database, userModel }
Binary file added public/secure-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 33 additions & 0 deletions routes/authRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const express = require("express");
const passport = require("../middleware/passport");
const { forwardAuthenticated } = require("../middleware/checkAuth");

const router = express.Router();

router.get("/login", forwardAuthenticated, (req, res) => res.render("login"));

router.post( //from login page"app.use("/auth", authRoute);"
"/login",
passport.authenticate("local", {
successRedirect: "/dashboard",
failureRedirect: "/auth/login",
})
);

router.get("/github",
passport.authenticate("github"));
//once signed into github will come back here
// don't see /auth because already in auth
router.get('/github/callback',
passport.authenticate('github'), //{ failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/dashboard');
});

router.get("/logout", (req, res) => {
req.logout();
res.redirect("/auth/login");
});

module.exports = router;
16 changes: 16 additions & 0 deletions routes/indexRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const express = require("express");
const router = express.Router();
const { ensureAuthenticated, isAdmin } = require("../middleware/checkAuth");

//---this is after authentication?-------//
router.get("/", (req, res) => {
res.send("welcome to express/passport/github");
});

router.get("/dashboard", ensureAuthenticated, (req, res) => {
res.render("dashboard", {
user: req.user,
});
});

module.exports = router;
3 changes: 3 additions & 0 deletions views/dashboard.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<h1 class="mt-4">Dashboard</h1>
<p class="lead mb-3">Welcome <%= user.name %></p>
<a href="/auth/logout" class="btn btn-secondary">Logout</a>
47 changes: 47 additions & 0 deletions views/layout.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="shortcut icon" type="image/x-icon" href="/secure-icon.png" />
<!-- Styles -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<!-- Icons CDN -->
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>
<script
src="https://kit.fontawesome.com/761d42c757.js"
crossorigin="anonymous"
></script>
<title>NodeJS Auth App</title>
</head>

<body>
<div class="container"><%- body %></div>

<!-- Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"
></script>
</body>
</html>
39 changes: 39 additions & 0 deletions views/login.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<div class="row mt-5">
<div class="col-md-6 m-auto">
<div class="card card-body text-center">
<h1 class="mb-3">
<img src="/secure-icon.png" alt="icon" width="20%" />
</h1>
<h2>Login</h2>
<form action="/auth/login" method="POST">
<div class="form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
name="email"
class="form-control"
placeholder="Enter Email"
/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
id="password"
name="password"
class="form-control"
placeholder="Enter Password"
/>
</div>
<button type="submit" class="btn btn-primary btn-block">Login</button>

OR

</form>
<p class="btn btn-secondary" background-color="white"><a href="/auth/github">Login with GITHUB</a></p>
<p class="mt-4">New User? <a href="/auth/register">Register</a></p>
<p>Forgot Password? <a href="/auth/forgot">Reset</a></p>
</div>
</div>
</div>

0 comments on commit a80659e

Please sign in to comment.