Skip to content

Commit 4fd7f32

Browse files
committed
first add basic project
0 parents  commit 4fd7f32

File tree

13 files changed

+2045
-0
lines changed

13 files changed

+2045
-0
lines changed

.gitignore

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
.idea/
2+
.vscode/
3+
node_modules/
4+
build
5+
.DS_Store
6+
*.tgz
7+
my-app*
8+
template/src/__tests__/__snapshots__/
9+
lerna-debug.log
10+
npm-debug.log*
11+
yarn-debug.log*
12+
yarn-error.log*
13+
/.changelog

app/routes.js

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
module.exports = function(app, passport, SERVER_SECRET) {
2+
3+
// default message
4+
app.get('/', function (req, res) {
5+
res.send('<html><body><p>Welcome to the database</p></body></html>');
6+
});
7+
8+
// =========== authenticate login info and generate access token ===============
9+
10+
app.post('/login', function(req, res, next) {
11+
passport.authenticate('local-login', function(err, user, info) {
12+
if (err) { return next(err); }
13+
// stop if it fails
14+
if (!user) { return res.json({ message: 'Invalid Username of Password' }); }
15+
16+
req.logIn(user, function(err) {
17+
// return if does not match
18+
if (err) { return next(err); }
19+
20+
// generate token if it succeeds
21+
const db = {
22+
updateOrCreate: function(user, cb){
23+
cb(null, user);
24+
}
25+
};
26+
db.updateOrCreate(req.user, function(err, user){
27+
if(err) {return next(err);}
28+
// store the updated information in req.user again
29+
req.user = {
30+
id: user.username
31+
};
32+
});
33+
34+
// create token
35+
const jwt = require('jsonwebtoken');
36+
req.token = jwt.sign({
37+
id: req.user.id,
38+
}, SERVER_SECRET);
39+
40+
// lastly respond with json
41+
return res.status(200).json({
42+
user: req.user,
43+
token: req.token
44+
});
45+
});
46+
})(req, res, next);
47+
});
48+
49+
// =============================================================================
50+
51+
// ==================== Allows users to create accounts ========================
52+
53+
app.post('/signup', passport.authenticate('local-signup', {
54+
successRedirect : '/signup/successjson',
55+
failureRedirect : '/signup/failurejson',
56+
failureFlash : true
57+
}));
58+
// return messages for signup users
59+
app.get('/signup/successjson', function(req, res) {
60+
res.json({ message: 'Successfully created user' });
61+
});
62+
63+
app.get('/signup/failurejson', function(req, res) {
64+
res.json({ message: 'This user already exists' });
65+
});
66+
67+
// =============================================================================
68+
69+
// ================= Protected APIs for authenticated Users ====================
70+
71+
// get tools and routes
72+
var expressJwt = require('express-jwt'),
73+
REST_POST = require('../routes/REST_POST'),
74+
REST_GET = require('../routes/REST_GET'),
75+
REST_EDIT = require('../routes/REST_EDIT'),
76+
REST_DELETE = require('../routes/REST_DELETE');
77+
78+
// authenticate access token
79+
const authenticate = expressJwt({secret : SERVER_SECRET});
80+
81+
// GET, EndPoint:
82+
// https://127.0.0.1:5000/product/api/all?order={orderby}
83+
app.get('/product/api/get/all', authenticate, REST_GET.getAllRecords);
84+
85+
// GET, Endpoint:
86+
// https://127.0.0.1:5000/product/api/?c={target_column}&q={target_value}&order={orderby}
87+
app.get('/product/api/get', authenticate, REST_GET.findByColumn);
88+
89+
// GET, EndPoint:
90+
// https://127.0.0.1:5000/product/api/search/?c={target_column}&start={start}&end={end}&order={orderby}
91+
app.get('/product/api/get/search', authenticate, REST_GET.rangeSearch);
92+
93+
// POST, Endpoint:
94+
// https://127.0.0.1:5000/product/api/add/?content=1,2,3...
95+
app.post('/product/api/add', authenticate, REST_POST.addOne);
96+
97+
// POST, Endpoint:
98+
// https://127.0.0.1:5000/product/api/add/?content[0]=1,2,3,...&content[1]=1,2,3...
99+
app.post('/product/api/add/batch/', authenticate, REST_POST.addBatch);
100+
101+
// EDIT, Endpoint:
102+
// https://127.0.0.1:5000/product/api/edit/:orderID/?content={}
103+
app.post('/product/api/edit/:id', authenticate, REST_EDIT);
104+
105+
// Endpoint: https://127.0.0.1:5000/product/api/delete/?id={orderID}
106+
app.delete('/product/api/delete/', authenticate, REST_DELETE);
107+
108+
// =============================================================================
109+
110+
}

config/database.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// config/database.js
2+
module.exports = {
3+
'connection': {
4+
'host': 'localhost',
5+
'user': 'root',
6+
'password': ''
7+
},
8+
'database': 'excelData',
9+
'users_table': 'users'
10+
};

config/passport.js

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// load all the things needed
2+
var LocalStrategy = require('passport-local').Strategy;
3+
4+
// load up the user model
5+
var mysql = require('mysql');
6+
var bcrypt = require('bcrypt');
7+
var dbconfig = require('./database');
8+
var connection = mysql.createConnection(dbconfig.connection);
9+
10+
connection.query('USE ' + dbconfig.database);
11+
12+
module.exports = function(passport) {
13+
14+
// passport set up; required for persistent login sessions
15+
// passport needs ability to serialize and unserialize users out of session
16+
17+
// used to serialize the user for the session
18+
passport.serializeUser(function(user, done) {
19+
done(null, user.id);
20+
});
21+
22+
// used to deserialize the user
23+
passport.deserializeUser(function(id, done) {
24+
connection.query("SELECT * FROM users WHERE id = ? ",[id], function(err, rows){
25+
done(err, rows[0]);
26+
});
27+
});
28+
29+
// handles signup
30+
passport.use(
31+
'local-signup',
32+
new LocalStrategy({
33+
usernameField : 'username',
34+
passwordField : 'password',
35+
nameField : 'name',
36+
passReqToCallback : true
37+
},
38+
function(req, username, password, done) {
39+
connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows) {
40+
if (err)
41+
return done(err);
42+
if (rows.length) {
43+
return done(null, false, req.flash('signupMessage', 'That username is already taken.'));
44+
} else {
45+
console.log(req.body)
46+
// if there is no user with that username then create the user
47+
48+
var newUserMysql = {
49+
username: username,
50+
password: bcrypt.hashSync(password, bcrypt.genSaltSync(10)), // use the generateHash function in our user model
51+
name: req.body.name
52+
};
53+
54+
var insertQuery = "INSERT INTO users ( username, password, name ) values (?,?,?)";
55+
56+
connection.query(insertQuery,[newUserMysql.username, newUserMysql.password, newUserMysql.name],function(err, rows) {
57+
newUserMysql.id = rows.insertId;
58+
59+
return done(null, newUserMysql);
60+
});
61+
}
62+
});
63+
})
64+
);
65+
66+
// handles login
67+
passport.use(
68+
'local-login',
69+
new LocalStrategy({
70+
usernameField : 'username',
71+
passwordField : 'password',
72+
passReqToCallback : true
73+
},
74+
function(req, username, password, done) {
75+
connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows){
76+
if (err)
77+
return done(err);
78+
if (!rows.length) {
79+
return done(null, false, req.flash('loginMessage', 'No user found.'));
80+
}
81+
82+
// if the user is found but the password is wrong
83+
if (!bcrypt.compareSync(password, rows[0].password))
84+
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
85+
86+
// all is well, return successful user
87+
return done(null, rows[0]);
88+
});
89+
})
90+
);
91+
};

model/dbconnection.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
var mysql = require('mysql');
2+
3+
var connection = mysql.createConnection({
4+
host : 'http://localhost:8080',
5+
user : 'root',
6+
password : '',
7+
database : 'excelData'
8+
});
9+
10+
try {
11+
connection.connect();
12+
console.log('Connected to the MYSQL database');
13+
14+
} catch(e) {
15+
console.log('Database Connetion failed:' + e);
16+
}
17+
18+
module.exports = connection;

package.json

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
{
2+
"name": "node-api",
3+
"version": "1.0.0",
4+
"private": true,
5+
"scripts": {
6+
"start": "node server.js",
7+
"database": "node scripts/create_database.js"
8+
},
9+
"dependencies": {
10+
"bcrypt": "^1.0.3",
11+
"body-parser": "^1.17.2",
12+
"connect-flash": "^0.1.1",
13+
"cookie-parser": "^1.4.3",
14+
"cors": "^2.8.4",
15+
"debug": "~2.6.3",
16+
"ejs": "^2.5.7",
17+
"express": "^4.15.4",
18+
"express-jwt": "^5.3.0",
19+
"express-session": "^1.15.5",
20+
"fs": "0.0.1-security",
21+
"https": "^1.0.0",
22+
"jade": "~1.11.0",
23+
"jsonwebtoken": "^7.4.3",
24+
"morgan": "^1.8.2",
25+
"mysql": "^2.14.1",
26+
"passport": "^0.4.0",
27+
"passport-http-bearer": "^1.0.1",
28+
"passport-local": "^1.0.0",
29+
"path": "^0.12.7",
30+
"serve-favicon": "~2.4.2"
31+
}
32+
}

routes/REST_DELETE.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// product/api/delete/?id={orderID}
2+
module.exports = function (req,res) {
3+
var connection = require('../model/dbconnection');
4+
// Delete by order id
5+
var id = req.query.id;
6+
7+
connection.query('DELETE FROM saleData WHERE Order_ID = ?', [id], function(err, result) {
8+
if (!err){
9+
var response = [];
10+
11+
if (result.affectedRows != 0) {
12+
response.push({'result' : 'success'});
13+
} else {
14+
response.push({'msg' : 'No Result Found'});
15+
}
16+
17+
res.setHeader('Content-Type', 'application/json');
18+
res.status(200).send(JSON.stringify(response));
19+
} else {
20+
res.status(400).send(err);
21+
}
22+
});
23+
};

routes/REST_EDIT.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// product/api/edit/:orderID/?content={}
2+
module.exports = function (req,res) {
3+
var connection = require('../model/dbconnection');
4+
var response = [];
5+
6+
// split content in the url to arrays
7+
var arr = req.query.content.split(',');
8+
9+
// Make sure required content is provided
10+
if (
11+
typeof req.params.id !== 'undefined' &&
12+
arr.length == 21
13+
) {
14+
15+
// Pair content with column
16+
var id = req.params.id;
17+
var content = {
18+
Row_ID: arr[0], // Order_ID cannot be edited
19+
Order_Date: arr[2],
20+
Order_Priority: arr[3],
21+
Order_Quantity: arr[4],
22+
Sales: arr[5],
23+
Discount: arr[6],
24+
Ship_Mode: arr[7],
25+
Profit: arr[8],
26+
Unit_Price: arr[9],
27+
Shipping_Cost: arr[10],
28+
Customer_Name: arr[11],
29+
Province: arr[12],
30+
Region: arr[13],
31+
Customer_Segment: arr[14],
32+
Product_Category: arr[15],
33+
Product_Sub_Category: arr[16],
34+
Product_Name: arr[17],
35+
Product_Container: arr[18],
36+
Product_Base_Margin: arr[19],
37+
Ship_Date: arr[20]
38+
};
39+
40+
connection.query('UPDATE saleData SET ? WHERE Order_ID = ?', [content, id],
41+
function(err, result) {
42+
if (!err){
43+
44+
if (result.affectedRows != 0) {
45+
response.push({'result' : 'success'});
46+
} else {
47+
response.push({'msg' : 'No Result Found'});
48+
}
49+
50+
res.setHeader('Content-Type', 'application/json');
51+
res.status(200).send(JSON.stringify(response));
52+
} else {
53+
res.status(400).send(err);
54+
}
55+
});
56+
57+
} else {
58+
response.push({'result' : 'error', 'msg' : 'Please fill required information'});
59+
res.setHeader('Content-Type', 'application/json');
60+
res.send(200, JSON.stringify(response));
61+
}
62+
};

0 commit comments

Comments
 (0)