Skip to content

Commit 0d35992

Browse files
authored
Merge pull request #92 from tcet-opensource/development
[Major] Change from common JS to Modern JS
2 parents efc6251 + c2432e6 commit 0d35992

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+8091
-1432
lines changed

.dockerignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
node_modules
2+
coverage
3+
logs
4+
.env

.eslintrc.cjs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
module.exports = {
2+
env: {
3+
browser: true,
4+
es2021: true,
5+
jest: true
6+
},
7+
extends: "airbnb-base",
8+
overrides: [],
9+
parserOptions: {
10+
ecmaVersion: "latest",
11+
sourceType: "module",
12+
},
13+
rules: {
14+
"linebreak-style": 0,
15+
"no-console": 0,
16+
semi: ["error", "always"],
17+
quotes: ["error", "double"],
18+
"import/prefer-default-export": "off"
19+
},
20+
"settings": {
21+
"import/resolver": {
22+
"alias": {
23+
"map": [
24+
["#app", "./app.js"],
25+
["#util", "./util.js"],
26+
["#constant", "./constant.js"],
27+
["#routes", "./routes"],
28+
["#models", "./models"],
29+
["#middleware", "./middleware"],
30+
["#controller", "./controller"],
31+
["#services", "./services"],
32+
["#error", "./error"]
33+
],
34+
"extensions": [".js"]
35+
}
36+
}
37+
}
38+
};

.prettierrc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"singleQuote": true,
3+
"tabWidth": 2
4+
}

Dockerfile

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
FROM node:18.15.0
2+
3+
WORKDIR /usr/src/app
4+
5+
COPY package*.json ./
6+
7+
RUN npm ci
8+
9+
COPY . .
10+
11+
EXPOSE 3500
12+
CMD ["npm", "run", "start"]
13+
14+
15+

app.js

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
1-
const express = require('express');
2-
const path = require('path');
3-
const logger = require('morgan');
4-
const cookieParser = require('cookie-parser');
5-
const cors = require('cors');
6-
7-
const indexRouter = require('./routes/index');
8-
const usersRouter = require('./routes/users');
9-
const authRouter = require('./routes/auth');
1+
import express from "express";
2+
import path, { dirname } from "path";
3+
import morgan from "morgan";
4+
import cookieParser from "cookie-parser";
5+
import cors from "cors";
6+
import { fileURLToPath } from "url";
7+
import { logger } from "#util";
8+
import indexRouter from "#routes/index";
9+
import usersRouter from "#routes/users";
10+
import authRouter from "#routes/auth";
1011

1112
const app = express();
13+
const currDirName = dirname(fileURLToPath(import.meta.url));
14+
15+
app.use(morgan(
16+
":remote-addr - :remote-user \":method :url HTTP/:http-version\" :status \":referrer\" \":user-agent\"",
17+
{ stream: logger.stream },
18+
));
1219

1320
app.use(cors());
14-
app.use(logger('dev'));
1521
app.use(express.json());
1622
app.use(express.urlencoded({ extended: false }));
1723
app.use(cookieParser());
18-
app.use(express.static(path.join(__dirname, 'public')));
24+
app.use(express.static(path.join(currDirName, "public")));
1925

20-
app.use('/', indexRouter);
21-
app.use('/users', usersRouter);
22-
app.use('/auth', authRouter);
26+
app.use("/", indexRouter);
27+
app.use("/users", usersRouter);
28+
app.use("/auth", authRouter);
2329

24-
module.exports = app;
30+
export default app;

bin/www

Lines changed: 0 additions & 93 deletions
This file was deleted.

bin/www.js

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/env node
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
7+
import http from "http";
8+
import debug from "debug";// ("api:server");
9+
import dotenv from "dotenv";
10+
import app from "#app";
11+
import { logger } from "#util";
12+
13+
dotenv.config();
14+
15+
/**
16+
* Normalize a port into a number, string, or false.
17+
*/
18+
19+
function normalizePort(val) {
20+
const port = parseInt(val, 10);
21+
22+
if (Number.isNaN(port)) {
23+
// named pipe
24+
return val;
25+
}
26+
27+
if (port >= 0) {
28+
// port number
29+
return port;
30+
}
31+
32+
return false;
33+
}
34+
35+
/**
36+
* Get port from environment and store in Express.
37+
*/
38+
39+
const port = normalizePort(process.env.PORT || "3000");
40+
app.set("port", port);
41+
42+
/**
43+
* Create HTTP server.
44+
*/
45+
46+
const server = http.createServer(app);
47+
48+
/**
49+
* Event listener for HTTP server "error" event.
50+
*/
51+
52+
function onError(error) {
53+
if (error.syscall !== "listen") {
54+
throw error;
55+
}
56+
57+
const bind = typeof port === "string"
58+
? `Pipe ${port}`
59+
: `Port ${port}`;
60+
61+
// handle specific listen errors with friendly messages
62+
switch (error.code) {
63+
case "EACCES":
64+
logger.error(`${bind} requires elevated privileges`);
65+
process.exit(1);
66+
break;
67+
case "EADDRINUSE":
68+
logger.error(`${bind} is already in use`);
69+
process.exit(1);
70+
break;
71+
default:
72+
throw error;
73+
}
74+
}
75+
76+
/**
77+
* Event listener for HTTP server "listening" event.
78+
*/
79+
80+
function onListening() {
81+
const addr = server.address();
82+
const bind = typeof addr === "string"
83+
? `pipe ${addr}`
84+
: `port ${addr.port}`;
85+
debug(`Listening on ${bind}`);
86+
}
87+
88+
/**
89+
* Listen on provided port, on all network interfaces.
90+
*/
91+
92+
server.listen(port);
93+
server.on("error", onError);
94+
server.on("listening", onListening);

constant.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export const logLevel = {
2+
local: "silly",
3+
dev: "debug",
4+
prod: "info",
5+
};

controller/auth.js

Lines changed: 61 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,66 @@
1-
const { genrateToken } = require('../util');
2-
const user = require('../models/user');
1+
import util, {logger} from "#util";
2+
import { authenticateUser, userExists, updatePassword } from "#services/user";
33

4-
exports.login = async function(req, res, next) {
5-
const {id, password} = req.body;
6-
let userValidated = await user.validateUser(id, password);
7-
if(userValidated){
8-
userDetails = {
9-
"uid": userValidated.uid,
10-
"name": userValidated.name,
11-
"emailId":userValidated.emailId,
12-
"type": userValidated.userType,
13-
}
14-
let token = genrateToken(userDetails);
15-
userDetails["token"] = token;
16-
res.send({res:"welcome", user:userDetails})
17-
}
18-
else{
19-
res.status(403)
20-
res.send({err:"incorrect ID password"});
21-
}
4+
const otpStore = {};
5+
6+
async function login(req, res) {
7+
const { id, password } = req.body;
8+
try {
9+
const userValidated = await authenticateUser(id, password);
10+
const userDetails = {
11+
uid: userValidated.uid,
12+
name: userValidated.name,
13+
emailId: userValidated.emailId,
14+
type: userValidated.userType,
15+
};
16+
const token = util.generateToken(userDetails, req.ip);
17+
userDetails.token = token;
18+
res.json({ res: "welcome", user: userDetails });
19+
} catch (error) {
20+
logger.error("Error while login", error)
21+
if (error.name === "UserDoesNotExist") {
22+
res.status(403);
23+
res.json({ err: "Incorrect ID password" });
24+
} else {
25+
res.status(500);
26+
res.json({ err: "Something is wrong on our side. Try again" });
27+
}
28+
}
29+
}
30+
31+
function validateUser(req, res) {
32+
res.json({ res: req.user, msg: "user validated", err: null });
33+
}
34+
35+
async function sendOTP(req, res) {
36+
const { uid, emailId } = req.body;
37+
if (await userExists(uid, emailId)) {
38+
const otp = Math.floor(1000 + Math.random() * 9000);
39+
otpStore[uid] = otp;
40+
util.sendOTP(emailId, otp);
41+
res.json({ res: "otp sent to emailID" });
42+
} else {
43+
res.json({ err: "incorrect UID or emailId" });
44+
}
2245
}
2346

24-
exports.validateUser = function(req, res, next) {
25-
res.json({res: req.user, msg: "user validated", err:null})
47+
async function resetPassword(req, res) {
48+
const { uid, otp, password } = req.body;
49+
if (otpStore[uid] === otp) {
50+
try {
51+
await updatePassword(uid, password);
52+
res.json({ res: "successfully updated password" });
53+
} catch (error) {
54+
logger.log("Error while updating", error)
55+
res.status(500);
56+
if (error.name === "UpdateError") res.json({ err: "Something went wrong while updating password" });
57+
else res.json({ err: "something went wrong" });
58+
}
59+
} else {
60+
res.json({ err: "incorrect otp" });
61+
}
2662
}
2763

64+
export default {
65+
validateUser, sendOTP, resetPassword, login,
66+
};

0 commit comments

Comments
 (0)