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

Added Comments with Team #2

Open
wants to merge 2 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: 1 addition & 1 deletion config/.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
PORT = 2121
DB_STRING = mongodb+srv://demo:demo@cluster0.brdqm.mongodb.net/todolist?retryWrites=true&w=majority
DB_STRING = mongodb+srv://todo-mvc-auth:todo-mvc-auth@cluster0.tehdi.mongodb.net/todo-mvc-auth?retryWrites=true&w=majority
92 changes: 46 additions & 46 deletions config/config.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,47 @@
exports.creds = {
identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',

clientID: '<add your own>',

clientSecret: '<add your own>',

responseType: 'code id_token',

responseMode: 'form_post',

redirectUrl: 'http://localhost:2121/auth/openid/return',

allowHttpForRedirectUrl: true,

validateIssuer: false,

issuer: null,

passReqToCallback: false,

useCookieInsteadOfSession: false,

cookieEncryptionKeys: [
{ 'key': '12345678901234567890123456789012', 'iv': '123456789012' },
{ 'key': 'abcdefghijklmnopqrstuvwxyzabcdef', 'iv': 'abcdefghijkl' }
],

scope: ['profile', 'offline_access', 'https://graph.microsoft.com/mail.read'],

loggingLevel: false,

nonceLifetime: null,

nonceMaxAmount: 5,

clockSkew: null,
};
exports.destroySessionUrl = 'http://localhost:2121';
exports.useMongoDBSessionStore = false;
exports.databaseUri = 'mongodb://localhost/OIDCStrategy';
exports.mongoDBSessionMaxAge = 24 * 60 * 60;
identityMetadata:
"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration",

clientID: "2faf4827-2f8e-4c8d-9740-325e0cc09918", // This ClientID comes from Azure

clientSecret: "1ut__0r.Bx-8Q1CPgNktIo9KUBw.nZRJoU", // This ClientSecret comes from Azure

responseType: "code id_token",

responseMode: "form_post",

redirectUrl: "https://todo-mvc-auth.arnaldopires.repl.co/auth/openid/return",

allowHttpForRedirectUrl: true,

validateIssuer: false,

issuer: null,

passReqToCallback: false,

useCookieInsteadOfSession: false,

cookieEncryptionKeys: [
{ key: "12345678901234567890123456789012", iv: "123456789012" },
{ key: "abcdefghijklmnopqrstuvwxyzabcdef", iv: "abcdefghijkl" },
],

scope: ["profile", "offline_access", "https://graph.microsoft.com/mail.read"],

loggingLevel: false,

nonceLifetime: null,

nonceMaxAmount: 5,

clockSkew: null,
};

exports.destroySessionUrl = "https://todo-mvc-auth.arnaldopires.repl.co"; // This sessionurl comes from Repl

exports.useMongoDBSessionStore = false;

exports.databaseUri = "mongodb://localhost/OIDCStrategy";

exports.mongoDBSessionMaxAge = 24 * 60 * 60;
23 changes: 14 additions & 9 deletions config/database.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
const mongoose = require('mongoose')
const mongoose = require("mongoose"); // Require mongoose ODM

const connectDB = async () => {
// This part is trying to establish a connection with the DB
try {
const conn = await mongoose.connect(process.env.DB_STRING, {
// Gets the DB_STRING from the environment variables, this keep our private keys out of the GIT repo.
// Some options (magic!) we should read the documentation.
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})

console.log(`MongoDB Connected: ${conn.connection.host}`)
});
// Success connection console log message
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (err) {
console.error(err)
process.exit(1)
// Console log error message
console.error(err);
// Crash the app if an error
process.exit(1);
}
}

module.exports = connectDB
};
// Export the functions when 'connectDB' is called.
module.exports = connectDB;
53 changes: 30 additions & 23 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
const OIDCStrategy = require('passport-azure-ad').OIDCStrategy
const mongoose = require('mongoose')
const config = require('../config/config')
const User = require('../models/User')

const OIDCStrategy = require("passport-azure-ad").OIDCStrategy; // Load the Azure's strategies for handling users (Microsoft accounts, access tokens, social media accounts, etc...)
const mongoose = require("mongoose"); // Mongoose again deals with DB communication
const config = require("../config/config"); // Require config file
const User = require("../models/User"); // Require the user model
// The rest is MS passport azure ad magic! //
//User authentication
module.exports = function (passport) {
// Express is calling the function with passport as an argument.
// passport function
passport.use(
new OIDCStrategy({
new OIDCStrategy(
{
identityMetadata: config.creds.identityMetadata,
clientID: config.creds.clientID,
responseType: config.creds.responseType,
Expand All @@ -25,34 +29,37 @@ module.exports = function (passport) {
cookieEncryptionKeys: config.creds.cookieEncryptionKeys,
clockSkew: config.creds.clockSkew,
},
// If a valid token is provided a user object will be created
async (accessToken, refreshToken, profile, done) => {
console.log('auth: ', profile)
console.log("auth: ", profile);
// Creates a user object
const newUser = {
microsoftId: profile.oid,
displayName: profile.displayName,
}
microsoftId: profile.oid, // MS openID
displayName: profile.displayName, // User name
};

try {
let user = await User.findOne({ microsoftId: profile.oid })
let user = await User.findOne({ microsoftId: profile.oid }); // Will search in the DB for a match

if (user) {
done(null, user)
done(null, user); // If found a user will be returned
} else {
user = await User.create(newUser)
done(null, user)
user = await User.create(newUser); // If not a new user will be created in the DB
done(null, user); // Return the new user
}
} catch (err) {
console.error(err)
// Catch any error and display a console log message
console.error(err);
}
}
)
)

);
// Saves the user id into the session
passport.serializeUser((user, done) => {
done(null, user.id)
})

done(null, user.id);
});
// Retreive whole user object
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => done(err, user))
})
}
User.findById(id, (err, user) => done(err, user));
});
};
10 changes: 6 additions & 4 deletions controllers/home.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module.exports = {
getIndex: (req,res)=>{
res.render('index.ejs')
}
}
getIndex: (req, res) => {
res.render("index.ejs");
},
};

// We are serving the index.ejs when the user ask for the front page.
138 changes: 86 additions & 52 deletions controllers/todos.js
Original file line number Diff line number Diff line change
@@ -1,57 +1,91 @@
const Todo = require('../models/Todo')
const Todo = require("../models/Todo");

module.exports = {
getTodos: async (req,res)=>{
console.log(req.user)
try{
//Do we want to grab all the todos?
const todoItems = await Todo.find({microsoftId: req.user.microsoftId})
//How can we grab our logged in users left to dos?
const itemsLeft = await Todo.countDocuments({microsoftId: req.user.microsoftId, completed: false})
res.render('todos.ejs', {todos: todoItems, left: itemsLeft, user: req.user})
}catch(err){
console.log(err)
}
},
createTodo: async (req, res)=>{
try{
await Todo.create({todo: req.body.todoItem, completed: false, microsoftId: req.user.microsoftId})
console.log('Todo has been added!')
res.redirect('/todos')
}catch(err){
console.log(err)
}
},
markComplete: async (req, res)=>{
try{
await Todo.findOneAndUpdate({_id:req.body.todoIdFromJSFile},{
completed: true
})
console.log('Marked Complete')
res.json('Marked Complete')
}catch(err){
console.log(err)
}
},
markIncomplete: async (req, res)=>{
try{
await Todo.findOneAndUpdate({_id:req.body.todoIdFromJSFile},{
completed: false
})
console.log('Marked Incomplete')
res.json('Marked Incomplete')
}catch(err){
console.log(err)
// When user makes a request retrives the todos from the DB matching his microsoftID
getTodos: async (req, res) => {
console.log(req.user);
try {
//Do we want to grab all the todos? No just the ones that match the MicrosoftId
const todoItems = await Todo.find({ microsoftId: req.user.microsoftId });
//How can we grab our logged in users left to dos?
const itemsLeft = await Todo.countDocuments({
microsoftId: req.user.microsoftId,
completed: false,
});
// Render is serving HTML as a response we pass the data from the DB
res.render("todos.ejs", {
todos: todoItems,
left: itemsLeft,
user: req.user,
});
} catch (err) {
console.log(err);
}
},
// Create a new todo
createTodo: async (req, res) => {
try {
// Express is getting a json object from the frontend and serving it to the server.
// Set the completed value as false (default)
// Adds the microsoftID
await Todo.create({
todo: req.body.todoItem,
completed: false,
microsoftId: req.user.microsoftId,
});
// Just console log a success message
console.log("Todo has been added!");
// Reloads the page after the todo is created
res.redirect("/todos");
} catch (err) {
console.log(err);
}
},

//
markComplete: async (req, res) => {
try {
// Uses the unique id of the task when the user wants to mark it as completed
// Changes the completed value to true
await Todo.findOneAndUpdate(
{ _id: req.body.todoIdFromJSFile },
{
completed: true,
}
},
deleteTodo: async (req, res)=>{
console.log(req.body.todoIdFromJSFile)
try{
await Todo.findOneAndDelete({_id:req.body.todoIdFromJSFile})
console.log('Deleted Todo')
res.json('Deleted It')
}catch(err){
console.log(err)
);
// Just console log message to confirm the operation server side
console.log("Marked Complete");
// Respond to front end.
res.json("Marked Complete");
} catch (err) {
console.log(err);
}
},
// Almost the same thing as markComplete but the oposite operation
// Mark the task completed as false
markIncomplete: async (req, res) => {
try {
await Todo.findOneAndUpdate(
{ _id: req.body.todoIdFromJSFile },
{
completed: false,
}
);
console.log("Marked Incomplete");
res.json("Marked Incomplete");
} catch (err) {
console.log(err);
}
},
// Gets the id, finds the match in the DB and deletes it
deleteTodo: async (req, res) => {
console.log(req.body.todoIdFromJSFile);
try {
await Todo.findOneAndDelete({ _id: req.body.todoIdFromJSFile });
console.log("Deleted Todo");
res.json("Deleted It");
} catch (err) {
console.log(err);
}
}
},
};
Loading