Skip to content
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
8 changes: 6 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
**/bin/
**/obj/
.vs/
node_modules/
package-lock.json
yarn.lock
Deepak_Yadav/S5 Dotnetbasics/Dotnetbasics/obj/**
Deepak_Yadav/S5 Dotnetbasic/Dotnetbasics/bin/**
Deepak_Yadav/.vs
Deepak_Yadav/S5 Dotnetbasic/.vs
Shubham_Sharma/Practice/Practice/bin/**
Shubham_Sharma/Practice/Practice/obj/**
**/bin/
**/obj/
983 changes: 983 additions & 0 deletions Himanshu_Sharma/project3_company/.vs/config/applicationhost.config

Large diffs are not rendered by default.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"jwtPrivateKey": "secretKey"
}
3 changes: 3 additions & 0 deletions Himanshu_Sharma/project4_node/config/default.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"jwtPrivateKey": ""
}
37 changes: 37 additions & 0 deletions Himanshu_Sharma/project4_node/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const express = require('express');
const app = express();
const mongoose = require('mongoose');
// const createEmployee = require('./models/employee');
const logger = require('./middleware/logger');
const authenticator = require('./middleware/authenticator');
const employeeRoutes = require('./routes/employees');
const authRoutes = require('./routes/auth');
const config = require('config');

//Fatal Error in case of non-configuration of key
if(!config.get('jwtPrivateKey')){
console.log(config.get('jwtPrivateKey'));
console.error('FATAL ERROR: secretKey not set');
process.exit(1);
}

//Connection for mongoose
mongoose.connect('mongodb://localhost/cybergroup').then(() => console.log('MongoDb connected')).catch(err => console.error('Error occured while connecting to db', err));


//Middleware for parsing json in req.body
app.use(express.json());
app.use(express.static('public'));

app.use(logger);
app.use(authenticator);

app.use('/api/employees', employeeRoutes);
app.use('/api/auth', authRoutes);

//Port will be dynamically assigned by hosting environment
//Environment variable is a variable that is a part of environment in which process runs
const port = process.env.PORT || 3000;
app.listen(3000, () => console.log(`Listening at ${port} port`));

// createEmployee();
6 changes: 6 additions & 0 deletions Himanshu_Sharma/project4_node/middleware/authenticator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
var authenticate = (req, res, next) => {
console.log('Authenticating...');
next();
}

module.exports = authenticate;
7 changes: 7 additions & 0 deletions Himanshu_Sharma/project4_node/middleware/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
var log = (req, res, next) => {
console.log('logging...');
next();
}

module.exports = log;

66 changes: 66 additions & 0 deletions Himanshu_Sharma/project4_node/models/employee.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const mongoose = require("mongoose");
const Joi = require('joi');

employeeSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
minlength: 5
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
firstName: {
type: String,
required: true,
minlength: 2
},
lastName: {
type: String
},
mobile: {
type: String,
},
role: {
type: String,
enum: ['Employee', 'Manager', 'Admin'],
default: 'Employee'
},
manager: {
type: mongoose.Schema.Types.ObjectId
},
projects: [{
projectName: String
}]
});

const Employee = mongoose.model('Employee', employeeSchema);

// async function createEmployee(){
// const employee = new Employee({
// firstName: 'Himanshu'
// });

// const result = await employee.save();
// console.log(result);
// }

function validateEmployee(employee) {
const schema = {
email: Joi.string().min(5).required(),
password: Joi.string().min(5).max(255).required(),
firstName: Joi.string().min(2).required(),
lastName: Joi.string(),
mobile: Joi.string(),
role: Joi.string().tags(['Employee', 'Manager', 'Admin'])
}
console.log(Joi.validate(employee, schema), 'validateEmployee mein hoon');
return Joi.validate(employee, schema);
}

module.exports.Employee = Employee;
module.exports.validateEmployee = validateEmployee;
20 changes: 20 additions & 0 deletions Himanshu_Sharma/project4_node/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "company_using_node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^3.0.8",
"config": "^3.2.5",
"express": "^4.17.1",
"joi": "^14.3.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.8.11"
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
65 changes: 65 additions & 0 deletions Himanshu_Sharma/project4_node/public/assets/scripts/form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
let accessToken = sessionStorage.getItem("accessToken");

let data = parseJwt(accessToken);
let refactoredData = {
id: parseInt(data.id),
role: data.role,
email: data.email,
name: data.name
};

let inputElements = [
"first_name",
"last_name",
"email",
"mobile",
"role",
"manager",
"project"
];

uiUpdateAccordingToRolesAndState();

//functions
function uiUpdateAccordingToRolesAndState(){
console.log(sessionStorage.getItem("state"));
if(sessionStorage.getItem("state") === "read"){
document.querySelector('.submit-btn').classList.add('hide');
document.querySelector('.btn-addproject').classList.add('hide');
document.querySelector('.project').classList.add('hide');

inputElements.forEach((cur) => {
console.log(cur);
if(cur === "role"){
document.querySelector(`.${cur}`).setAttribute('disabled', 'true');
return;
}
document.querySelector(`.${cur}`).setAttribute('readonly', 'true');
});
}

if(sessionStorage.getItem("state") === "update"){
if(sessionStorage.getItem("role") !== "Admin"){
document.querySelector('.projects-parent').classList.add('hide');
document.querySelector('.manager-parent').classList.add('hide');
document.querySelector('.role-parent').classList.add('hide');
}
}

document.querySelector('.logout-btn').textContent = `Logout ${refactoredData.name}`;
}

function parseJwt(token) {
var base64Url = token.split(".")[1];
var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
var jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map(function(c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);

return JSON.parse(jsonPayload);
}
124 changes: 124 additions & 0 deletions Himanshu_Sharma/project4_node/public/assets/scripts/home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
let accessToken = sessionStorage.getItem("accessToken");

let data = parseJwt(accessToken);
let refactoredData = {
role: data.role,
email: data.email,
name: data.name
};

let employeeList;

requestToApi();

//Functions
function uiUpdateAccordingToRoles() {
var newhtml;
var html = `
<li class="list-group-item list-group-item-success">
<ul class="employee-details list-group list-group-horizontal row">
<li class="employee-details__id list-group-item col-sm-auto mr-2">%index%</li>
<li class="employee-details__name list-group-item col-sm-auto mr-2">%name%</li>
<li class="employee-details__email list-group-item col-sm-auto mr-2">
%email%
</li>
<li class="employee-details__role list-group-item col-sm-auto mr-2">%role%</li>
</ul>
<div class="button-group float-right">
<button type="button" class="btn btn-info btn--read">Read</button>
<button type="button" class="btn btn-secondary btn--update">Update</button>
<button type="button" class="btn btn-danger btn--delete">Delete</button>
</div>
</li>
`;

if (employeeList !== "") {
var employeeListObj = JSON.parse(employeeList);
console.log(employeeListObj);
}

if (Array.isArray(employeeListObj)) {
employeeListObj.forEach((cur, index) => {
newhtml = html.replace("%index%", index + 1);
newhtml = newhtml.replace("%name%", `${cur.firstName} ${cur.lastName}`);
newhtml = newhtml.replace("%email%", cur.email);
newhtml = newhtml.replace("%role%", cur.role);

console.log(newhtml);

document
.querySelector(".list-group")
.insertAdjacentHTML("beforeend", newhtml);
});
}

if (refactoredData.role === "Admin") {
document.querySelector(".btn-create").classList.toggle("hide");
}

document.querySelector(
".logout-btn"
).textContent = `Logout ${refactoredData.name}`;

document.querySelectorAll(".btn--read").forEach((cur) => cur.addEventListener("click", (e) => {
sessionStorage.setItem("state", "read");
setEmailInSessionStorage(e);
window.location.href = "form.html";
}));

document.querySelectorAll(".btn--update").forEach((cur) => cur.addEventListener("click", (e) => {
sessionStorage.setItem("state", "update");
setEmailInSessionStorage(e);
window.location.href = "form.html";
}));

document.querySelector(".btn-create").addEventListener("click", () => {
sessionStorage.setItem("state", "create");
window.location.href = "form.html";
});
}

function setEmailInSessionStorage(e) {
let email = e.target.parentNode.parentNode.firstElementChild.children[2].textContent;
console.log(email);
sessionStorage.setItem("email", email);
}

function requestToApi() {
const http = new XMLHttpRequest();
const url = "http://localhost:49228/api/home";

http.open("POST", url);
http.setRequestHeader("Content-type", "application/json");

console.log(JSON.stringify(refactoredData));

http.send(JSON.stringify(refactoredData));

http.onprogress = () => {
console.log(http.response);
employeeList = http.response;
console.log(
employeeList,
"Main onreadystatechange mein hoon!! employeeList",
http.response,
"http.response"
);
uiUpdateAccordingToRoles();
};
}

function parseJwt(token) {
var base64Url = token.split(".")[1];
var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
var jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map(function(c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);

return JSON.parse(jsonPayload);
}
Loading