Skip to content

Commit 315604f

Browse files
committed
init commit
0 parents  commit 315604f

21 files changed

+2075
-0
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
config/index.json
2+
.directory
3+
node_modules
4+
TODO.md
5+
.vscode

README.md

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# Express PostgreSQL API
2+
The Express PostgreSQL API is make a secure and reliable API use to Login, Registration and Verify USER.
3+
4+
## Getting started
5+
### Requirements
6+
- [Node](https://nodejs.org/en/ "Node")
7+
- [PostgreSQL ](https://www.postgresql.org/ "PostgreSQL ")
8+
- [OpenSSL](https://wiki.openssl.org/index.php/Binaries "OpenSSL")
9+
10+
### Create Database
11+
12+
First, You need to create a database in PostgreSQL. after that, you need to create 2 tables in that.
13+
14+
the query of tables are following.
15+
16+
##### 1. Client Table
17+
This table stores information about users like Name, Email, Phone Number, etc.
18+
19+
```sql
20+
CREATE TABLE public.clienttable
21+
(
22+
c_id serial NOT NULL PRIMARY KEY,
23+
fname character varying(50) NOT NULL,
24+
lname character varying(50) NOT NULL,
25+
username character varying(50) NOT NULL,
26+
email character varying(355) NOT NULL,
27+
cnumber character varying(355) NOT NULL,
28+
varified boolean NOT NULL,
29+
created_on timestamp without time zone NOT NULL,
30+
last_login timestamp without time zone,
31+
tccheck boolean NOT NULL,
32+
password_expiry boolean,
33+
salt character varying NOT NULL,
34+
hash character varying NOT NULL
35+
)
36+
```
37+
##### 2. User Activity
38+
In this table is stored activity of the user when the user Login, make Registration, Change Password.
39+
40+
```sql
41+
CREATE TABLE public.user_activity
42+
(
43+
a_id serial NOT NULL PRIMARY KEY,
44+
c_id integer NOT NULL,
45+
login_ip inet NOT NULL,
46+
activity character varying NOT NULL,
47+
activity_datetime timestamp without time zone NOT NULL,
48+
CONSTRAINT c_id
49+
FOREIGN KEY(c_id)
50+
REFERENCES clienttable(c_id)
51+
)
52+
```
53+
54+
### Generating keys using OpenSSL
55+
56+
Now you need to create Private and Public Key to generate a Token.
57+
58+
For that first you need to create `Key` Folder in root
59+
60+
1 .Generate an RSA private key, of size 2048, and output it to a file named private.key:
61+
```shell
62+
openssl genrsa -out key/private.key 2048
63+
```
64+
65+
2 .Extract the public key from the key pair, which can be used in a certificate:
66+
```shell
67+
openssl rsa -in key/private.key -outform PEM -pubout -out key/public.key
68+
```
69+
70+
Note: make sure both key `private.key` and `public.key` save in `key` folder.
71+
72+
### Install API
73+
74+
Now you need to install API. For Installation, you need to follow the below steps.
75+
76+
##### Step 1: get the goodies
77+
Note: if you don't have git, you can download a zip file of the project instead.
78+
79+
```shell
80+
git clone https://github.com/jsuyog2/express-postgresql-api.git api
81+
cd api
82+
npm install
83+
```
84+
##### Step 2: add your configuration
85+
86+
Add your Postgres connection information to config/index.json.txt and rename it index.json. Information on the config options can be found [here](https://github.com/jsuyog2/express-postgresql-api/blob/master/config/README.md "here").
87+
88+
##### Step 3: fire it up!
89+
```shell
90+
npm start
91+
```
92+
93+
## Architecture
94+
95+
### Due credit
96+
97+
The real credit for this project goes to the great folks behind the following open source softwares and modules:
98+
99+
#### Softwares
100+
- [PostgreSQL](https://www.postgresql.org/ "PostgreSQL")
101+
- [OpenSSL](https://wiki.openssl.org/index.php/Binaries "OpenSSL")
102+
- [Express](https://expressjs.com/ "Express")
103+
- [JWT Token](https://jwt.io/ "JWT Token")
104+
105+
### How it works
106+
107+
The core of the project is [Express](https://expressjs.com/ "Express").
108+
109+
> Express.js, or simply Express, is a back end web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js.
110+
111+
All routes are stored in the `routes` folder and are automatically loaded on start. Check out the [routes readme](routes/README.md) for more information.
112+
113+
[OpenSSL](https://wiki.openssl.org/index.php/Binaries "OpenSSL") is used for the generation of private and public keys.
114+
115+
> OpenSSL is a software library for applications that secure communications over computer networks against eavesdropping or need to identify the party at the other end. It is widely used by Internet servers, including the majority of HTTPS websites.
116+
117+
OpenSSL is using to encrypt JWT Temporary Token. For generation of keys read documentation [Generating keys using OpenSSL](https://github.com/jsuyog2/express-postgresql-api#generating-keys-using-openssl "Generating keys using OpenSSL").
118+
119+
Data securely transmitting information using [JWT Token](https://jwt.io/ "JWT Token")
120+
121+
> JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
122+
123+
Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. JWT Token is secured using public/private key pairs.
124+
125+
#### Modules
126+
- [pbkdf2-password](https://www.npmjs.com/package/pbkdf2-password "pbkdf2-password")
127+
- [NODEMAILER](https://nodemailer.com/about/ "NODEMAILER")
128+
- [request-ip](https://www.npmjs.com/package/request-ip "request-ip")
129+
130+
Password is secure and hashed using [pbkdf2-password](https://www.npmjs.com/package/pbkdf2-password "pbkdf2-password")
131+
132+
> Easy salt/password creation for Node.js.
133+
134+
Sends a mail to user for verification or change password using [NODEMAILER](https://nodemailer.com/about/ "NODEMAILER").
135+
136+
> Nodemailer is a module for Node.js applications to allow easy as cake email sending.
137+
138+
Retrieving IP address of user for encryption Login JWT Token using [request-ip](https://www.npmjs.com/package/request-ip "request-ip").
139+
140+
> A tiny Node.js module for retrieving a request's IP address.

config/README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Configuration Options
2+
3+
```json
4+
{
5+
"db": "postgres://username:port@hostname/dbname",
6+
"cache": 3600,
7+
"port": 8000,
8+
"jwt_algo":"",
9+
"jwt_temp_algo_name":"",
10+
"jwt_temp_algo": "",
11+
"baseUrl":"http://127.0.0.1:8000/",
12+
"mail": {
13+
"host": "smtp.gmail.com",
14+
"port": 465,
15+
"username": "",
16+
"password": ""
17+
}
18+
}
19+
```
20+
21+
### db
22+
23+
`db` is the database connection string for Postgres.
24+
25+
### cache
26+
27+
`cache` sets the expiration length of the server response, in seconds.
28+
29+
### port
30+
31+
`port` sets the port number the server runs on.
32+
33+
### jwt_algo
34+
35+
`jwt_algo` is the header of a token. this JSON is Base64Url encoded to form the first part of the JWT.
36+
37+
For example:
38+
`eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9`
39+
40+
### jwt_temp_algo_name
41+
42+
`jwt_temp_algo_name` is the algorithm name that use to make a temporary token. such as HMAC SHA256 or RSA.
43+
44+
### jwt_temp_algo
45+
46+
`jwt_temp_algo` is the header of a temporary token. this JSON is Base64Url encoded to form the first part of the JWT.
47+
48+
For example:
49+
`eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9`
50+
51+
### baseUrl
52+
`baseUrl` The server will bind to the `host` name or IP address that is supplied.
53+
54+
### mail
55+
`mail` is a service to Send e-mail from Node.js. for that you need to configure a mail service.
56+
57+
#### host
58+
`host` Set this to true if SMTP host requires authentication to send email
59+
60+
#### port
61+
`port` TCP port to connect to
62+
63+
#### username
64+
`username` SMTP username
65+
66+
#### password
67+
`password` SMTP password
68+
69+
# Error Handling
70+
71+
### error.json
72+
`error.json` is json file that contains all the error messages.

config/errors.json

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
{
2+
"internal_error": "Internal Server Error",
3+
"db_not_connect": "unable to connect to database server.",
4+
"fill_form": "fill full form",
5+
"fill_form_message": "Some Values is missing in form.",
6+
"email_not_found": "Email and/or Password Not Found",
7+
"email_not_found_message": "Email and/or Password Missing.",
8+
"email_validate": "Check Email Format",
9+
"email_validate_message": "Provided Email Does Not Match Proper Email Format.",
10+
"password_not_found": "Password and/or Confirm Password Not Found",
11+
"password_not_found_message": "Password and/or Confirm Password Missing.",
12+
"password_validate": "Password is too short",
13+
"password_validate_message": "Password must be at least 6 characters long.",
14+
"password_match": "Password not match",
15+
"password_match_message": "Password must be same.",
16+
"password_expire": "Password Expired",
17+
"password_expire_message": "Your Password is Expired. Please Check Your Email.",
18+
"user_not_found": "Email Not Found",
19+
"user_not_found_message": "Provided Email Does Not found in Database.",
20+
"user_found": "Email/Username OR Phone No. Found",
21+
"user_found_message": "Provided Email/Username OR Phone No. found in Database.",
22+
"password_wrong": "Wrong password",
23+
"password_wrong_message": "Wrong password. Try again or click Forgot password to reset it.",
24+
"tc_not_checked": "Terms & Conditions Checkbox is not checked",
25+
"tc_not_checked_message": "You need to accept the MapDataLab Terms & Conditions to create an account.",
26+
"email_no_send": "Mail not sent",
27+
"email_no_send_message": "Mail is failed to sent",
28+
"success_login": "Login Successful.",
29+
"success_unvrified_login": "Login Successful but email Unvrified",
30+
"success_registration": "Registration Successful",
31+
"success_changepassword": "Password Change Successful",
32+
"success_verification": "Verification Successful",
33+
"success_mail_sent": "Mail Sent Successful. Please Check out your Indox.",
34+
"access_token_not_found": "Access Token Not Found",
35+
"access_token_not_found_message": "Access Token Not Found. Please Enter Access Token",
36+
"access_token_error": "Access Token Not Valid",
37+
"access_token_error_message": "Access Token is Wrong. Please Enter Vaild Access Token",
38+
"email_verified": "Email is already Verified",
39+
"email_verified_message": "Email is already Verified. Login to your account.",
40+
"email_not_verified": "Email is not Verified",
41+
"email_not_verified_message": "Please verify your Email."
42+
}

config/index.json.txt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"db": "postgres://username:port@hostname/dbname",
3+
"cache": 3600,
4+
"port": 8000,
5+
"corsAllowList":["http://localhost", "http://127.0.0.1","http://localhost:4200"],
6+
"jwt_algo":"",
7+
"jwt_temp_algo_name":"",
8+
"jwt_temp_algo": "",
9+
"baseUrl":"http://127.0.0.1:8000/",
10+
"mail": {
11+
"host": 'smtp.gmail.com',
12+
"port": 465,
13+
"username": '',
14+
"password": ''
15+
}
16+
}

index.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
const path = require('path');
2+
const express = require('express');
3+
const bodyParser = require('body-parser');
4+
var cors = require('cors');
5+
const {
6+
MongoClient
7+
} = require('mongodb')
8+
const config = require('./config');
9+
const app = express();
10+
const port = config.port;
11+
12+
// create application/json parser
13+
app.use(bodyParser.urlencoded({
14+
extended: false,
15+
limit: '500mb'
16+
}));
17+
18+
19+
//Assgin all routes
20+
const routes = require('./routes');
21+
app.use('/', routes);
22+
23+
//mongo db config
24+
const client = new MongoClient(config.db, {
25+
useNewUrlParser: true,
26+
useUnifiedTopology: true
27+
})
28+
client.connect()
29+
const db = client.db('expressmongoapi')
30+
app.set('client', db);
31+
32+
function clientClose(client) {
33+
// client.close();
34+
return null;
35+
}
36+
app.set('clientClose', clientClose(client));
37+
38+
//cors
39+
const allowlist = config.corsAllowList;
40+
41+
const corsOptionsDelegate = (req, callback) => {
42+
let corsOptions;
43+
44+
let isDomainAllowed = allowlist.indexOf(req.header('Origin')) !== -1;
45+
46+
if (isDomainAllowed) {
47+
// Enable CORS for this request
48+
corsOptions = {
49+
origin: true
50+
}
51+
} else {
52+
// Disable CORS for this request
53+
corsOptions = {
54+
origin: false
55+
}
56+
}
57+
callback(null, corsOptions)
58+
}
59+
app.use(cors(corsOptionsDelegate))
60+
61+
app.listen(port, () => {
62+
console.log(`Example app listening on port ${port}!`)
63+
});

key/private.key

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
-----BEGIN RSA PRIVATE KEY-----
2+
MIIEpQIBAAKCAQEAqYxGJHD5IWW3QQaIE6t9uMibo73pz60daaTGHJ+sZI5+uQWQ
3+
GWwxrTf7sCgxOOMcQ4gIrc3RzDcEUVTBEEWCbFf/GGmCtYhtragZN2kxIrugrOhg
4+
Kohc3GAKWwFhOdLIWX6/T1w4MX3CHhUGD+y3JaXXhu5Lum+G7F/FQoLDWHFsS5pO
5+
wFJ1Cm9ejnMbFLSYZBW3JxoryMCWezyL4jzhnQC7se9dF63GXOFTQO31qC/V3eH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6Yvb3gGLEig2BEVmfSpUVRYxYu
22+
54NBpchsTqusOKYrNxSnFZr8L+XImYTmcZcFQvrXNWnDd15C210Q2hL2Jwd8yICj
23+
MTtV2omh8ncvmVQgCxyJZzjbF21h7BhXk88V3Y3xzlb12r12ibRNXLZaC9CZ+WhE
24+
CU9olFECgYEAkWGpjY0j1IyVSEP8pq7iYRUNQHY6zLHZFr087wKiVmR/mCqYIiYx
25+
WRB7ZNAj2kCLJdRr77H3z7kVKoWzEcOKXIKMrlVAXbxj3iu91+WA5DlHKrRKbmRV
26+
m2f4ooujqVLqyfINuMUaW4HHNAxUKBiE+bHLDP7gdiRX/7ALTc01ZvY=
27+
-----END RSA PRIVATE KEY-----

key/public.key

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
-----BEGIN PUBLIC KEY-----
2+
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqYxGJHD5IWW3QQaIE6t9
3+
uMibo73pz60daaTGHJ+sZI5+uQWQGWwxrTf7sCgxOOMcQ4gIrc3RzDcEUVTBEEWC
4+
bFf/GGmCtYhtragZN2kxIrugrOhgKohc3GAKWwFhOdLIWX6/T1w4MX3CHhUGD+y3
5+
JaXXhu5Lum+G7F/FQoLDWHFsS5pOwFJ1Cm9ejnMbFLSYZBW3JxoryMCWezyL4jzh
6+
nQC7se9dF63GXOFTQO31qC/V3eHMShthoIQNH2zNqLI4+CyXDr4AJ9iOdlbHbLDw
7+
FbnF5kpDfDGCyMhNaX0QaLvA6wshfpwzoMQ8EiKwcmih/9t/77KcqD6qoVQUv5Yu
8+
8wIDAQAB
9+
-----END PUBLIC KEY-----

modules/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Modules

0 commit comments

Comments
 (0)