Skip to content

Commit

Permalink
connected Google auth with MVC structure
Browse files Browse the repository at this point in the history
  • Loading branch information
kylemettling committed May 1, 2021
1 parent c4f23d4 commit 4f0759c
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 61 deletions.
9 changes: 5 additions & 4 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const mongoose = require('mongoose');
const User = require('../models/User');
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const mongoose = require("mongoose");
const User = require("../models/User");

// TODO: Set up google cloud console so below code will work
module.exports = (passport) => {
Expand All @@ -9,9 +9,10 @@ module.exports = (passport) => {
{
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: '/auth/google/callback',
callbackURL: "/auth/google/callback",
},
async (accessToken, refreshToken, profile, done) => {
console.log(profile);
const newUser = {
googleId: profile.id,
displayName: profile.displayName,
Expand Down
9 changes: 4 additions & 5 deletions controllers/home.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
const User = require('../models/User');
const User = require("../models/User");

module.exports = {
//The getHome method receives a promise, handles said promise and responds with some JSON
getHome: (req, res) => {
res.render('index.ejs');
res.render("index.ejs");
},
getProfile: async (req, res) => {
try {
//console.log(req.body);
const profile = await User.find({ googleId: req.body.id });
const profile = await User.find({ googleId: req.user.googleId });
console.log(profile);
res.render('profileTest.ejs', { user: profile });
res.render("profile.ejs", { user: profile[0] });
} catch (err) {
console.log(err);
}
Expand Down
7 changes: 5 additions & 2 deletions controllers/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ const Post = require("../models/Post");
module.exports = {
getPosts: async (req, res) => {
try {
// const posts = await Post.find({ user: req.user.id });
const posts = await Post.find();
console.log(posts);
console.log(`posts: ${posts}`);
res.render("posts.ejs", { posts });
} catch (err) {
console.log(err);
Expand All @@ -19,15 +20,17 @@ module.exports = {
createPost: async (req, res) => {
try {
const post = await req.body;
console.log(post);
console.log(req.user);
await Post.create({
caption: post.caption,
content: post.content,
user: req.user.id,
});
console.log(`Post has been added!`);
res.redirect("/posts");
} catch (err) {
console.log(err);
}
},
getUserPosts: async (req, res) => {},
};
4 changes: 2 additions & 2 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ module.exports = {
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/');
res.redirect("/");
}
},
ensureGuest: function (req, res, next) {
if (!req.isAuthenticated()) {
return next();
} else {
res.redirect('/dashboard');
res.redirect("/profile");
}
},
};
8 changes: 6 additions & 2 deletions models/Post.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const mongoose = require('mongoose');
const mongoose = require("mongoose");

const PostSchema = new mongoose.Schema({
caption: {
Expand All @@ -8,6 +8,10 @@ const PostSchema = new mongoose.Schema({
type: String,
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
});

module.exports = mongoose.model('Post', PostSchema);
module.exports = mongoose.model("Post", PostSchema);
10 changes: 5 additions & 5 deletions routes/home.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//calling our dependencies
const express = require('express');
const express = require("express");
const router = express.Router();
const { ensureAuth, ensureGuest } = require('../middleware/auth');
const { ensureAuth, ensureGuest } = require("../middleware/auth");

//importing in the home controller
const homeController = require('../controllers/home');
const homeController = require("../controllers/home");

//Get Request to the '/' route will be handed off to the homeController's getHome method
router.get('/', homeController.getHome);
router.get('/profile', ensureAuth, homeController.getProfile);
router.get("/", ensureGuest, homeController.getHome);
router.get("/profile", ensureAuth, homeController.getProfile);

//These Routes arent needed, they were to test our server.
// router.get('/login', homeController.login);
Expand Down
4 changes: 2 additions & 2 deletions routes/posts.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const express = require("express");
const router = express.Router();

const { ensureAuth } = require("../middleware/auth");
const postsController = require("../controllers/posts.js");

router.get("/", postsController.getPosts);
router.get("/", ensureAuth, postsController.getPosts);
router.get("/randomPage", postsController.randomPage);
router.get("/addPost", postsController.addPost);
router.post("/addPost", postsController.createPost);
Expand Down
44 changes: 23 additions & 21 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
//Requiring our dependencies
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const cors = require('cors');
const morgan = require('morgan');
const dotenv = require('dotenv');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const connectDb = require('./config/database');
const homeRoutes = require('./routes/home');
const usersRoutes = require('./routes/users');
const authRoutes = require('./routes/auth');
const express = require("express");
const mongoose = require("mongoose");
const passport = require("passport");
const cors = require("cors");
const morgan = require("morgan");
const dotenv = require("dotenv");
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);
const connectDb = require("./config/database");
const homeRoutes = require("./routes/home");
const usersRoutes = require("./routes/users");
const authRoutes = require("./routes/auth");
const postsRoutes = require("./routes/posts");

// initialize express
const app = express();

//Load config setting the .env path to /config/.env
dotenv.config({ path: './config/.env' });
dotenv.config({ path: "./config/.env" });

// Load passport config
require('./config/passport')(passport);
require("./config/passport")(passport);

// connect to database
connectDb();

//Calling our packages
app.set('view engine', 'ejs'); // sets the view engine to render our ejs
app.use(express.static('public')); // tells express to serve up these 'static' files
app.set("view engine", "ejs"); // sets the view engine to render our ejs
app.use(express.static("public")); // tells express to serve up these 'static' files
app.use(cors()); //allows for cross origin resource sharing(Not used for this project but very important so make it a habit)
app.use(morgan('dev')); //logging middleware. Check console for logs
app.use(morgan("dev")); //logging middleware. Check console for logs

//body-parsing middleware (required to parse incoming JSON)
app.use(express.json());
Expand All @@ -38,7 +39,7 @@ app.use(express.urlencoded({ extended: true }));
// TODO: add mongo-connect V3
app.use(
session({
secret: 'keyboard cat',
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
Expand All @@ -50,9 +51,10 @@ app.use(passport.initialize());
app.use(passport.session());

// // Routes
app.use('/', homeRoutes);
app.use('/users', usersRoutes);
app.use('/auth', authRoutes);
app.use("/", homeRoutes);
app.use("/users", usersRoutes);
app.use("/posts", postsRoutes);
app.use("/auth", authRoutes);

//Initializing our PORT
let PORT = process.env.PORT;
Expand Down
3 changes: 3 additions & 0 deletions views/posts.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
<div class="content">
<p>Content: <%= post.content%></p>
</div>
<div class="author">
<p>User: <%= post.user %></p>
</div>
</div>
<% } %>
</body>
Expand Down
6 changes: 5 additions & 1 deletion views/profile.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,15 @@
</section>
</section>
</section>
<h1>This is <%= user.firstName %>'s profile</h1>
<h2>This was created at: <%= user.createdAt %></h2>
<img src="<%= user.image %>" />
<section class="column">
<section class="right">
<ul class="nav">
<li>Home</li>
<li>Logout</li>
<li><a href='/posts/addPost'>Create Post</a></li>
<li><a href='/auth/logout'>Logout</a></li>
</ul>
</section>
</section>
Expand Down
6 changes: 2 additions & 4 deletions views/profileTest.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
<title>Document</title>
</head>
<body>
<% { %>
<h1>This is <%= user.firstName%> profile</h1>
<h2>This is my bio: <%= user.bio%></h2>
<h1>This is <%= user.firstName%>'s profile</h1>
<h2>This was created at: <%= user.createdAt%></h2>
<img src="<%= user.image%>" />
<% } %>
</body>
</html>
13 changes: 0 additions & 13 deletions views/users.ejs

This file was deleted.

0 comments on commit 4f0759c

Please sign in to comment.