development
Visoth 9 months ago
commit e804cd1da6
  1. 1
      .gitignore
  2. 12
      Config/config.env
  3. 35
      Config/db.js
  4. 25
      Controller/App_Versions.js
  5. 233
      Controller/Authentication.js
  6. 68
      Controller/Database.js
  7. 4
      Middleware/async.js
  8. 106
      Middleware/auth.js
  9. 37
      Middleware/error.js
  10. 30
      Model/AppModel.js
  11. 42
      Model/AppVersion.js
  12. 76
      Model/BC_Data.js
  13. 170
      Model/Customer.js
  14. 73
      Model/Customer_Analysis.js
  15. 53
      Model/Database.js
  16. 59
      Model/Market.js
  17. 140
      Model/User.js
  18. 68
      app.js
  19. 90
      bin/www
  20. 1
      global.log
  21. 4398
      package-lock.json
  22. 24
      package.json
  23. 8
      public/stylesheets/style.css
  24. 13
      routes/authentication.js
  25. 8
      routes/db.js
  26. 9
      routes/index.js
  27. 10
      routes/users.js
  28. 8
      utils/errorResponse.js
  29. 12
      utils/successResponse.js
  30. 6
      views/error.jade
  31. 5
      views/index.jade
  32. 7
      views/layout.jade

1
.gitignore vendored

@ -0,0 +1 @@
node_modules

@ -0,0 +1,12 @@
NODE_ENV=development
JWT_SECRET=fjaowihefjowajif3123ifj
BEARER_HEADER=jdkewowjs@#Dfjsdkk3er@sfdgsdfgwer231
JWT_EXPIRE=7d
JWT_COOKIE_EXPIRE=30
APP_CODE=MBN
ADMIN_USERNAME=bcsa
ADMIN_PASS=Bc@dmin

@ -0,0 +1,35 @@
const sequelize = require("sequelize")
var reconnectOptions = {
max_retries: 999,
onRetry: function (count) {
console.log("connection lost, trying to connect (" + count + ")");
}
}
const db = new sequelize("TDDB", "sa", "TD@dmin168", {
host: "192.168.1.100",
port: 1433,
dialect: "mssql",
dialectOptions: {
options: {
// instanceName: "BCDB",
trustServerCertificate: true,
requestTimeout: 500000
}
},
autoreconnect: true,
reconnect: reconnectOptions,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 0,
requestTimeout: 0
},
})
db.authenticate()
.then(() => console.log("Database Connected..."))
.catch((err) => console.log("Cannot connect to database " + err));
module.exports = db;

@ -0,0 +1,25 @@
const AppVersion = require("../Model/AppVersion");
const AsyncHandler = require("../Middleware/async");
const ErrorResponse = require("../utils/errorResponse");
const sequelize = require("sequelize");
const { Json } = require("sequelize/lib/utils");
exports.getAppVersion = AsyncHandler(async (req, res, next) => {
try {
const appVersions = await AppVersion.findOne({
where: {
app_name: "MBN", // temporary change to MBN
status: 1,
}
});
if (appVersions)
// throw 'Testing Error '
res.status(200).send(JSON.stringify(appVersions));
else return next(new ErrorResponse('No app version of Wholesaler are found', 404));
} catch (e) {
console.log("EE", e)
// return next(new ErrorResponse(e))
res.status(500).send(JSON.stringify(e))
}
});

@ -0,0 +1,233 @@
const express = require("express");
const asyncHandler = require("../Middleware/async");
const jwt = require("jsonwebtoken")
const User = require("../Model/User");
const AppModel = require("../Model/AppModel");
const ErrorResponse = require("../utils/errorResponse");
const dbInfo = require("../Model/Database")
const DataModel = require("../Model/BC_Data")
// Login User
exports.login = asyncHandler(async (req, res, next) => {
const { username, password, DB_CODE, APP_CODE = 'MBN', CUST_CODE } = req.body
console.log("USERNAME ", username)
console.log("PASSWORD ", password)
console.log("DB CODE ", DB_CODE)
try {
if (!username || !password || !DB_CODE) {
throw "Not enough information"
}
// static admin case
if (username.toLowerCase() == process.env.ADMIN_USERNAME) {
if (password != process.env.ADMIN_PASS) {
throw "Invalid username or password"
}
const token = jwt.sign({
id: 1,
dbCode: DB_CODE,
appCode: APP_CODE,
custCode: CUST_CODE
}, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRE
})
if (!token) {
throw "Something when wrong"
}
return res.status(200).send({
success: "true",
token: token,
userid: 1,
typeof: "SELLER",
typeid: "ADMIN",
dbcode: "DB_CODE",
firstName: "ADMIN",
lastName: "BC",
warehouse: "1-LOC-OFFICE",
address: "Tonaire Digital",
map: '11.58371006791093,104.89721512933093'
})
}
// verify from Database
var user = await User.findOne({
where: {
USER_NAME: username
}
});
console.log("USER ", user)
if (!user) {
throw "Invalid username or password"
}
const validPass = await user.matchPassword(password)
console.log("IS VALID PASS", validPass)
if (validPass == false) {
throw "Invalid Password. Try Again"
}
// check whether user authorize to use the app or not
var app = await AppModel.findOne({
where: {
APP_CODE: process.env.APP_CODE,
USER_ID: user.USER_ID
},
order: [['USER_ID']],
})
console.log("APP ", app)
if (!app) {
throw "You're not allowed to use this app"
}
// CHECK USER TYPE
console.log("USER TYPE ", user.USER_TYPE)
if (user.USER_TYPE == "C") {
token = await user.getSignedJwtToken(
DB_CODE,
APP_CODE,
customer.ADD_CODE
)
} else {
token = await user.getSignedJwtToken(
DB_CODE,
APP_CODE,
CUST_CODE,
)
}
// var customer;
// if (user.USER_TYPE == "C") {
// customer = await Customer.findOne({
// attributes: {
// exclude: ['PICTURE'],
// },
// where: {
// ADD_CODE: user.FIELD_0
// },
// include: [
// {
// attributes: {
// exclude: ["IMAGE"],
// },
// model: Market,
// },
// {
// model: CustomerAnalysis
// },
// ],
// })
// }
if (!token) {
throw "Something Went Wrong"
}
return res.status(200).send({
message: "Login Successful",
app: app,
token: token
})
} catch (error) {
next(new ErrorResponse(error, 400));
}
})
exports.checkUsername = asyncHandler(async (req, res, next) => {
const { username, APP_CODE } = req.query;
console.log("USERNAME ", username)
try {
if (!username) {
return res.status(400).send({
message: "Invalid Username"
})
}
var user = await User.findOne({
where: {
USER_NAME: username
}
});
console.log("USER ", user)
if (user) {
console.log("USER IS APPROVE ", user.APPROVED)
if (user.APPROVED == 0) {
return next(new ErrorResponse("Username is not yet approved", 403))
}
if (user.USER_STATUS == "0") {
return next(new ErrorResponse("Username is disabled", 403))
}
console.log("FINSIH CHECKING USER STATUS")
user = JSON.parse(JSON.stringify(user))
delete user.USER_PASS //remove password from user object when return to client
// chech whether user authorize to use the app or not
const isAllowed = await AppModel.findAll({
where: {
APP_CODE: APP_CODE,
USER_ID: user.USER_ID
},
// we need to specify this order because in APP_MODEL we don't have primary key
// in default sequelize will order by primary key so it will turn into error
order: [['DB_CODE']]
})
console.log("IS ALLOWED ", isAllowed)
if (isAllowed.length == 0) {
return next(new ErrorResponse("User is not allowed to use this app", 403))
} else {
// In this Block we want to return the USER Presets To Client
// Note : Presets is not a column in User Table
user.PRESETS = {}
// GET Database Name from DB_INFO by using DB_CODE from APP_MODEL
await Promise.all(isAllowed.map(async (app) => {
const { DB_NAME } = await dbInfo.findOne({
where: {
DB_CODE: app.DB_CODE
},
raw: true
})
console.log("DB NAME ", DB_NAME)
const DBName = app.DB_CODE + ' - ' + DB_NAME
if (!user.PRESETS[DBName]) {
user.PRESETS[DBName] = []
}
console.log("APP PRESET ", app.PRESET)
console.log("USER TYPE ", user.USER_TYPE)
// check user type
if (user.USER_TYPE == "S" || user.USER_TYPE == "C") {
var userPresets = await DataModel.findAll({
where: {
DATA_CODE: app.PRESET,
},
order: [["DATA_DESC"]]
})
user.PRESETS[DBName].push(userPresets)
}
}))
res.status(200).send(
JSON.stringify(user)
)
}
} else {
return next(new ErrorResponse("Username is not available", 404))
}
} catch (e) {
throw new ErrorResponse(e, 400)
}
})

@ -0,0 +1,68 @@
const asyncHandler = require("../Middleware/async");
const sequelize = require('sequelize')
const DBInfo = require("../Model/Database");
const { log } = require("winston");
exports.getDBInfo = asyncHandler(async (req, res, next) => {
console.log("GET DB INFO EXEC ")
var hasNext = false;
// const decode = decodeURIComponent
const { limit, offset = 0, name = "", nodelivery = 0 } = req.query;
const decode = decodeURIComponent(name);
// console.log("DECODE ", decode)
if (name) {
// get count of all databases
const count = await DBInfo.count({
where: {
DB_NAME: sequelize.where(
sequelize.fn("LOWER", sequelize.col("DB_NAME")),
"LIKE",
"%" + decode.toLowerCase() + "%"
),
},
});
// check if count is greater than offset + limit
if (count > offset + limit) {
hasNext = true;
}
const allDBInfo = await DBInfo.findAll({
where: {
DB_NAME: sequelize.where(
sequelize.fn("LOWER", sequelize.col("DB_NAME")),
"LIKE",
"%" + decode.toLowerCase() + "%"
),
},
offset: offset,
limit: limit,
}).then((db) => {
var list = { databases: db, hasNext: hasNext, count: db.length };
return res.status(200).send(JSON.stringify(list));
});
} else {
// if there is no name provide then get all databases
const count = await DBInfo.count();
if (count > offset + limit) {
hasNext = true;
}
const allDBInfo = await DBInfo.findAll({
where: {
DB_STAT: "A"
},
offset: offset,
limit: limit,
}).then((db) => {
var list = { databases: db, hasNext: hasNext, count: db.length };
return res.status(200).send(JSON.stringify(list));
});
}
// res.status(200).JSON({
// success: True,
// description: allDBInfo
// })
})

@ -0,0 +1,4 @@
const asyncHandler = fn => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
module.exports = asyncHandler;

@ -0,0 +1,106 @@
const jwt = require('jsonwebtoken')
const asyncHandler = require('./async')
const ErrorResponse = require("../utils/errorResponse")
const dotenv = require("dotenv")
const UserModel = require("../Model/User")
const { raw } = require('express')
//Require Dotenv
dotenv.config({
path: "./Config/config.env",
})
// Protect route
exports.protect = asyncHandler(async (req, res, next) => {
let token
if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
next(new ErrorResponse("Invalid Token", 401))
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET)
console.log("decode : ", decoded)
if (decoded.id == 1) {
req.user = {
"USER_ID": 1,
"USER_CODE": "BCSA",
"USER_NAME": "BCSA",
"USER_DESC": "BC Admin",
"FIRST_NAME": "Admin",
"LAST_NAME": "BC",
"ADDRESS": "",
"PHONE": "012345678",
"EMAIL": "",
"MAP": "37.33233141,-122.0312186",
"USER_STATUS": "1",
"USER_TYPE": "S",
"USER_LOG": "",
"USER_CPAS": 0,
"APPROVED": 1,
"APPROVED_BY": "3248",
"EMP_CODE": null,
"USER_PERIOD": null,
"FIELD_0": null,
"FIELD_1": "SELLER",
"FIELD_2": null,
"FIELD_3": null,
"FIELD_4": null,
"FIELD_5": null,
"FIELD_6": null,
"FIELD_7": null,
"FIELD_8": null,
"FIELD_9": null,
"USER_CREATED": "3248",
"USER_CREDATE": "2024-03-18",
"USER_UPDT": "3248",
"DATE_UPDT": "2024-03-18",
}
}
req.user = await UserModel.findOne({
where: {
USER_ID: decoded.id,
},
raw: true
})
if (!req.user) {
return next(new ErrorResponse("User not found", 400));
}
if (req.user.USER_STATUS == 0) {
return next(new ErrorResponse("User disabled", 400));
}
let preset = null
let typeId = ""
let saleType = ""
let warehouse = ""
console.log("USER ", req.user)
} catch (err) {
}
})
//Protect At Login
exports.protectAtlogin = asyncHandler(async (req, res, next) => {
console.log("PROTECT AT LOGIN EXEC")
let token;
console.log("BEARER HEADER ", process.env.BEARER_HEADER)
try {
if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
}
if (token != process.env.BEARER_HEADER) {
next(new ErrorResponse("Invalid Token", 400));
} else {
next();
}
} catch (error) {
console.log("ERRROR ", error)
}
})

@ -0,0 +1,37 @@
const winston = require('winston');
const { createLogger, format, transports } = require('winston');
const logger = winston.createLogger({
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss',
}),
format.printf((info) =>
JSON.stringify({
t: info.timestamp,
l: info.level,
m: info.message,
s: info.splat !== undefined ? `${info.splat}` : '',
}) + ','
)
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'global.log' })
]
})
const errorHandler = (err, req, res, next) => {
console.log("ERROR NAME", err);
logger.log({
level: 'info',
message: err.message
});
res.status(err.statusCode || 500).json({
success: false,
description: err.message || "Server Error",
})
}
module.exports = errorHandler

@ -0,0 +1,30 @@
const sequelize = require("sequelize");
const db = require("../Config/db");
const AppModel = db.define(
"TDMSAPP", // BCMSAPP use for checking user access
{
USER_ID: {
type: sequelize.STRING,
},
APP_CODE: {
type: sequelize.STRING,
},
DB_CODE: {
type: sequelize.STRING,
}, // BRANCH CODE
CREATE_DATE: {
type: sequelize.STRING,
},
PRESET: {
type: sequelize.STRING,
},
},
{
timestamps: false,
freezeTableName: true,
}
);
AppModel.removeAttribute("id")
module.exports = AppModel;

@ -0,0 +1,42 @@
const sequelize = require("sequelize");
const db = require("../Config/db");
const AppVersions = db.define(
"APP_VERSIONS",
{
id: {
type: sequelize.INTEGER,
primaryKey: true,
},
app_version: {
type: sequelize.FLOAT,
},
ios_version: {
type: sequelize.FLOAT,
},
android_version: {
type: sequelize.FLOAT,
},
api_version: {
type: sequelize.FLOAT,
},
app_name: {
type: sequelize.STRING
},
deploy_date: {
type: sequelize.STRING
},
status: {
type: sequelize.INTEGER
},
force: {
type: sequelize.INTEGER
}
},
{
timestamps: false,
freezeTableName: true,
}
);
// AppVersions.removeAttribute("id");
module.exports = AppVersions;

@ -0,0 +1,76 @@
const sequelize = require("sequelize");
const db = require("../Config/db");
// what is this use for ?
const DataModel = db.define(
"BCDATA",
{
ID: {
type: sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
DB_CODE: {
type: sequelize.STRING,
primaryKey: true,
},
DATA_CODE: {
type: sequelize.STRING,
},
DATA_NAME: {
type: sequelize.STRING,
},
DATA_DESC: {
type: sequelize.STRING,
},
DATA_TYPE: {
type: sequelize.STRING,
},
// AREA_ID
FIELD_1: {
type: sequelize.STRING,
},
// Sale type
FIELD_2: {
type: sequelize.STRING,
},
// Warehouse
FIELD_3: {
type: sequelize.STRING,
},
// sianad code for area
FIELD_4: {
type: sequelize.STRING,
},
FIELD_5: {
type: sequelize.STRING,
},
FIELD_6: {
type: sequelize.STRING,
},
FIELD_7: {
type: sequelize.STRING,
},
FIELD_8: {
type: sequelize.STRING,
},
FIELD_9: {
type: sequelize.STRING,
},
CREATED_DATE: {
type: sequelize.STRING,
},
CREATED_BY: {
type: sequelize.STRING,
},
},
{
timestamps: false,
freezeTableName: true,
}
)
DataModel.removeAttribute("id")
module.exports = DataModel

@ -0,0 +1,170 @@
const sequelize = require("sequelize")
const db = require("../Config/db")
const Customer = db.define(
"SIADD",
{
DB_CODE: {
type: sequelize.STRING,
// primaryKey: true,
// autoIncrement: true
},
ADD_CODE: {
primaryKey: true,
type: sequelize.STRING,
},
ADD_LOOKUP: {
type: sequelize.STRING,
},
ADD_LINE_1: {
type: sequelize.STRING,
},
ADD_LINE_2: {
type: sequelize.STRING,
},
ADD_LINE_3: {
type: sequelize.STRING,
},
ADD_LINE_4: {
type: sequelize.STRING,
},
ADD_LINE_5: {
type: sequelize.STRING,
},
ADD_LINE_6: {
type: sequelize.STRING,
},
ADD_TEL: {
type: sequelize.STRING,
},
ADD_FAX: {
type: sequelize.STRING,
},
ADD_EMAIL: {
type: sequelize.STRING,
},
ADD_WEB: {
type: sequelize.STRING,
},
ADD_CONT: {
type: sequelize.STRING,
},
ADD_COM_1: {
type: sequelize.STRING,
},
ADD_COM_2: {
type: sequelize.STRING,
},
ADD_STAT: {
type: sequelize.STRING,
},
ADD_TYPE: {
type: sequelize.STRING,
},
ADD_LINE_1KH: {
type: sequelize.STRING,
},
ADD_LINE_2KH: {
type: sequelize.STRING,
},
ADD_LINE_3KH: {
type: sequelize.STRING,
},
TRANS_PRES: {
type: sequelize.STRING,
},
USER_CREA: {
type: sequelize.STRING,
},
USER_UPDT: {
type: sequelize.STRING,
},
USER_CODE: {
type: sequelize.STRING,
},
AREA_ID: {
type: sequelize.STRING,
},
MARKET_ID: {
type: sequelize.STRING,
},
STORE: {
type: sequelize.STRING,
},
GOOGLE_MAP: {
type: sequelize.STRING,
},
BUSINESS_TYPE: {
type: sequelize.STRING,
},
CREDIT_LIMIT: {
type: sequelize.FLOAT,
},
ID_CARD: {
type: sequelize.STRING,
},
PICTURE_ID: {
type: sequelize.STRING,
},
SALE_MAN_CODE: {
type: sequelize.STRING,
},
PICTURE: {
type: sequelize.BLOB,
},
SEX: {
type: sequelize.STRING,
},
HOUSE_NO: {
type: sequelize.STRING,
},
ROAD_NO: {
type: sequelize.STRING,
},
PROVINCE_ID: {
type: sequelize.STRING,
},
DISTRICT_ID: {
type: sequelize.STRING,
},
COMMUNE_ID: {
type: sequelize.STRING,
},
BANK_ACC: {
type: sequelize.STRING,
},
CUSTOM_FIELD_1: {
type: sequelize.STRING,
},
CUSTOM_FIELD_2: {
type: sequelize.STRING,
},
CUSTOM_FIELD_3: {
type: sequelize.STRING,
},
CUSTOM_FIELD_4: {
type: sequelize.STRING,
},
CUSTOM_FIELD_5: {
type: sequelize.STRING,
},
},
{
timestamps: false,
freezeTableName: true,
}
)
Customer.checkExistedById = async function (id = "") {
var obj = await Customer.findOne(
{
where: {
ADD_CODE: id
}
}
);
return obj ? true : false;
}
Customer.removeAttribute("id")
module.exports = Customer

@ -0,0 +1,73 @@
const sequelize = require("sequelize");
const db = require("../Config/db");
const CustomerAnalysis = db.define(
"SIADDANAL",
{
DB_CODE: {
type: sequelize.STRING,
// primaryKey: true,
// autoIncrement: true
},
ADD_CODE: {
primaryKey: true,
type: sequelize.STRING,
},
ACC_CODE: {
type: sequelize.STRING,
},
ANAL_C0: {
type: sequelize.STRING,
},
ANAL_C1: {
type: sequelize.STRING,
},
ANAL_C2: {
type: sequelize.STRING,
},
ANAL_C3: {
type: sequelize.STRING,
},
ANAL_C4: {
type: sequelize.STRING,
},
ANAL_C5: {
type: sequelize.STRING,
},
ANAL_C6: {
type: sequelize.STRING,
},
ANAL_C7: {
type: sequelize.STRING,
},
ANAL_C8: {
type: sequelize.STRING,
},
ANAL_C9: {
type: sequelize.STRING,
},
ADD_MISC: {
type: sequelize.FLOAT,
},
ADD_TYPE: {
type: sequelize.STRING,
},
TRANS_PRES: {
type: sequelize.STRING,
},
USER_CREA: {
type: sequelize.STRING,
},
USER_UPDT: {
type: sequelize.STRING,
},
USER_CODE: {
type: sequelize.STRING,
},
},
{
timestamps: false,
freezeTableName: true,
}
);
CustomerAnalysis.removeAttribute("id");
module.exports = CustomerAnalysis;

@ -0,0 +1,53 @@
const sequelize = require("sequelize");
const db = require("../Config/db");
const dbinfo = db.define(
"SIDBINFO",
{
DB_CODE: {
type: sequelize.STRING,
primaryKey: true,
},
DB_NAME: {
type: sequelize.STRING,
},
DATE_DEFAULT: {
type: sequelize.STRING,
},
DATE_FORMAT: {
type: sequelize.STRING,
},
SA_DECIMAL: {
type: sequelize.INTEGER,
},
SB_DECICMA: {
type: sequelize.INTEGER,
},
DEC_SEP: {
type: sequelize.STRING,
},
THO_SEP: {
type: sequelize.STRING,
},
DB_STAT: {
type: sequelize.STRING,
},
USER_CREA: {
type: sequelize.STRING,
},
DATE_CREA: {
type: sequelize.STRING,
},
USER_UPDT: {
type: sequelize.STRING,
},
DATE_UPDT: {
type: sequelize.STRING,
},
},
{
timestamps: false,
freezeTableName: true,
}
);
dbinfo.removeAttribute("id");
module.exports = dbinfo;

@ -0,0 +1,59 @@
const sequelize = require("sequelize");
const db = require("../Config/db");
const market = db.define(
"TB_BCMARKET",
{
MARKET_ID: {
type: sequelize.STRING,
primaryKey: true,
},
DB_CODE: {
type: sequelize.STRING,
},
MARKET_NAME: {
type: sequelize.STRING,
},
MARKET_KHMER_NAME: {
type: sequelize.STRING,
},
AREA_ID: {
type: sequelize.STRING,
},
CITY: {
type: sequelize.STRING,
},
DISTRICT: {
type: sequelize.STRING,
},
OTHER: {
type: sequelize.STRING,
},
IMAGE: {
type: sequelize.BLOB,
},
STATUS: {
type: sequelize.STRING,
},
USER_CREATE: {
type: sequelize.STRING,
},
CREATE_DATE: {
type: sequelize.STRING,
},
USER_UPDATE: {
type: sequelize.STRING,
},
UPDATE_DATE: {
type: sequelize.STRING,
},
MAP: {
type: sequelize.STRING,
},
},
{
timestamps: false,
freezeTableName: true,
}
);
market.removeAttribute("id");
module.exports = market;

@ -0,0 +1,140 @@
const sequelize = require("sequelize");
const db = require("../Config/db");
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
const UserModel = db.define(
"TDUSERS",
{
USER_CODE: {
type: sequelize.STRING,
primaryKey: true,
},
USER_NAME: {
type: sequelize.STRING,
},
USER_PASS: {
type: sequelize.STRING,
},
USER_DESC: {
type: sequelize.STRING,
},
USER_CPAS: {
type: sequelize.STRING,
},
USER_STAT: {
type: sequelize.CHAR,
},
USER_LOG: {
type: sequelize.CHAR,
},
EMAIL: {
type: sequelize.STRING,
},
MAP: {
type: sequelize.STRING,
},
USER_PASS: {
type: sequelize.STRING,
},
USER_STATUS: {
type: sequelize.CHAR, // 1 = Active, 0 = Inactive
},
USER_TYPE: {
type: sequelize.CHAR, // S = Sale , U = User, D = Delivery , C = Customer
},
USER_LOG: {
type: sequelize.STRING,
},
USER_CPAS: {
type: sequelize.INTEGER,
},
APPROVED: {
type: sequelize.INTEGER,
},
APPROVED_BY: {
type: sequelize.STRING,
},
EMP_CODE: {
type: sequelize.STRING,
},
USER_PERIOD: {
type: sequelize.INTEGER,
},
FIELD_0: {
type: sequelize.STRING,
},
FIELD_1: {
type: sequelize.STRING,
},
FIELD_2: {
type: sequelize.STRING,
},
FIELD_3: {
type: sequelize.STRING,
},
FIELD_4: {
type: sequelize.STRING,
},
FIELD_5: {
type: sequelize.STRING,
},
FIELD_6: {
type: sequelize.STRING,
},
FIELD_7: {
type: sequelize.STRING,
},
FIELD_8: {
type: sequelize.INTEGER,
},
FIELD_9: {
type: sequelize.DATE,
},
USER_CREATED: {
type: sequelize.STRING,
},
USER_CREDATE: {
type: sequelize.DATE,
},
USER_UPDT: {
type: sequelize.STRING,
},
DATE_UPDT: {
type: sequelize.DATE,
},
DEPARTMENT_ID: {
type: sequelize.INTEGER,
},
ROLE_TYPE: {
type: sequelize.STRING,
},
DEVICE_TOKEN: {
type: sequelize.STRING,
},
},
{
timestamps: false,
freezeTableName: true,
}
)
UserModel.removeAttribute("id")
//hashPassword
UserModel.encryptPass = function (pass) {
return bcrypt.hashSync(pass, bcrypt.genSaltSync(10), null)
};
UserModel.prototype.getSignedJwtToken = function (dbCode, appCode, custCode) {
return jwt.sign({ id: this.USER_ID, dbCode: dbCode, appCode: appCode, custCode: custCode }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRE,
})
}
//comparePassword
UserModel.prototype.matchPassword = function (enteredPassword) {
return bcrypt.compareSync(enteredPassword, this.USER_PASS)
};
module.exports = UserModel

@ -0,0 +1,68 @@
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var dotenv = require("dotenv")
var app = express();
dotenv.config({
path: "./Config/config.env",
})
// //Route Files
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var authenticationRouter = require('./routes/authentication')
var dbInfoRouter = require('./routes/db')
//CORS
var cors = require("cors");
//Body parser
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({
extended: true
}))
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
//Mount Route
app.use("/api/v1/authentication", cors(), authenticationRouter);
app.use("/api/v1/database", dbInfoRouter)
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
console.log("ERROR NAME", err);
// logger.log({
// level: 'info',
// message: err.message
// });
res.status(err.statusCode || 500).json({
success: false,
description: err.message || "Server Error",
})
});
module.exports = app;

@ -0,0 +1,90 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('api:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
console.log("SERVER LISTEN ON PORT ", port)
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}

@ -0,0 +1 @@
{"t":"2024-07-04 09:27:05","l":"info","m":"Invalid Email or Password","s":""},

4398
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,24 @@
{
"name": "api",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "nodemon ./bin/www"
},
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"dotenv": "^16.4.5",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"jsonwebtoken": "^9.0.2",
"morgan": "~1.9.1",
"nodemon": "^3.1.4",
"sequelize": "^6.37.3",
"tedious": "^18.2.1",
"winston": "^3.13.0"
}
}

@ -0,0 +1,8 @@
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}

@ -0,0 +1,13 @@
const express = require("express");
const route = express.Router();
const { protect, protectAtlogin } = require("../Middleware/auth");
const controller = require("../Controller/Authentication");
const appVersion = require("../Controller/App_Versions")
route.route("/login").post(protectAtlogin, controller.login);
route.route("/appversion").get(appVersion.getAppVersion);
route.route("/checkusername").get(protectAtlogin, controller.checkUsername);
module.exports = route;

@ -0,0 +1,8 @@
const express = require('express')
const route = express.Router()
const controller = require("../Controller/Database")
const { protect } = require("../Middleware/auth")
route.route("/").get(controller.getDBInfo)
module.exports = route;

@ -0,0 +1,9 @@
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;

@ -0,0 +1,10 @@
var express = require('express');
var router = express.Router();
const { protect } = require("../Middleware/auth");
/* GET users listing. */
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
module.exports = router;

@ -0,0 +1,8 @@
class ErrorResponse extends Error {
constructor(message, status) {
super(message);
this.statusCode = status;
}
}
module.exports = ErrorResponse;

@ -0,0 +1,12 @@
class SuccessResponse {
constructor(description, data, status) {
this.statusCode = status || 200;
return {
success: "true",
description: description,
data: data,
};
}
}
module.exports = SuccessResponse;

@ -0,0 +1,6 @@
extends layout
block content
h1= message
h2= error.status
pre #{error.stack}

@ -0,0 +1,5 @@
extends layout
block content
h1= title
p Welcome to #{title}

@ -0,0 +1,7 @@
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
Loading…
Cancel
Save