Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mencius Madhyanagara #36

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SECRET_KEY=projecttcgtrade
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.env
17 changes: 17 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
require("dotenv").config();
const cors = require("cors");
const express = require("express");
const app = express();
const port = 3000;

app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.use("/", require("./routers"));

app.listen(port, () => {
console.log("listening to port " + port);
});

module.exports = app;
23 changes: 23 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"development": {
"username": "postgres",
"password": "postgres",
"database": "tcgtrade_dev",
"host": "localhost",
"dialect": "postgres"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
95 changes: 95 additions & 0 deletions controllers/controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"use strict";

const { comparePass, hashPass } = require("../helpers/bcrypt");
const { User, Post, Inbox } = require("../models");

class Controller {
static async createPost(req, res, next) {
try {
const {
requestName,
requestSeries,
uploadImg,
fetchedOfferName,
fetchedOfferSeries,
fetchedOfferImg,
} = req.body;

const { id } = req.user;

const response = Post.create({
UserId: id,
requestName,
requestSeries,
uploadImg,
offerName: fetchedOfferName,
offerSeries: fetchedOfferSeries,
fetchedImg: fetchedOfferImg,
});
console.log(response);
// res.status(201).json(response);
} catch (err) {
next(err);
}
}

static async register(req, res, next) {
try {
let { username, password } = req.body;

password = hashPass(password);

const result = await User.create({
username,
password,
});

res.status(201).json({
data: {
id: result.id,
username: result.username,
},
});
} catch (err) {
next(err);
}
}

static async login(req, res, next) {
try {
const { username, password } = req.body;
const targetUser = await User.findOne({
where: { username: username },
});

if (!targetUser) {
throw { name: "Email/password invalid" };
}

const isPassTrue = comparePass(password, targetUser.password);

if (!isPassTrue) {
throw { name: "Email/password invalid" };
}

//sending token

const payload = {
username: targetUser.username,
};

const token = payloadToToken(payload);

res.status(200).json({
data: {
access_token: token,
id: targetUser.id,
},
});
} catch (err) {
next(err);
}
}
}

module.exports = { Controller };
13 changes: 13 additions & 0 deletions helpers/bcrypt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const bcrypt = require("bcryptjs");

function hashPass(password) {
const hash = bcrypt.hashSync(password);
return hash;
}

function comparePass(password, hashed) {
const compared = bcrypt.compareSync(password, hashed);
return compared;
}

module.exports = { hashPass, comparePass };
15 changes: 15 additions & 0 deletions helpers/errorhandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function errorHandler(err, req, res, next) {
let code = 500;
let message = "internal server error";

if (err.name === "Invalid Token" || err.name === "JsonWebTokenError") {
code = 400;
message = "Access token received is invalid";
}

res.status(code).json({
message,
});
}

module.exports = errorHandler;
12 changes: 12 additions & 0 deletions helpers/jwt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const jwt = require("jsonwebtoken");
const key = process.env.SECRET_KEY;

function payloadToToken(payload) {
return jwt.sign(payload, key, { expiresIn: "7d" });
}

function tokenToPayload(token) {
return jwt.verify(token, key);
}

module.exports = { payloadToToken, tokenToPayload };
34 changes: 34 additions & 0 deletions middlewares/authentication.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const { tokenToPayload } = require("../helpers/jwt");
const { User } = require("../models");

async function authentication(req, res, next) {
try {
const { access_token } = req.headers;

if (!access_token) {
throw { name: "Invalid Token" };
}

const payload = tokenToPayload(access_token);

const isusernameExist = await User.findOne({
where: { username: payload.username },
});

if (!isusernameExist) {
throw { name: "Invalid Token" };
}

req.user = {
id: isusernameExist.id,
role: isusernameExist.role,
username: isusernameExist.username,
};

next();
} catch (err) {
next(err);
}
}

module.exports = authentication;
42 changes: 42 additions & 0 deletions migrations/20220622172419-create-post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"use strict";
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable("Posts", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
UserId: {
type: Sequelize.INTEGER,
},
imageUrl: {
type: Sequelize.STRING,
},
cardId: {
type: Sequelize.STRING,
},
requestedName: {
type: Sequelize.STRING,
},
requestedSeries: {
type: Sequelize.STRING,
},
uploadedImgUrl: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable("Posts");
},
};
30 changes: 30 additions & 0 deletions migrations/20220622172816-create-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Users');
}
};
33 changes: 33 additions & 0 deletions migrations/20220622173222-create-inbox.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Inboxes', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
senderId: {
type: Sequelize.INTEGER
},
receiverId: {
type: Sequelize.INTEGER
},
content: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Inboxes');
}
};
25 changes: 25 additions & 0 deletions models/inbox.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Inbox extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
Inbox.init({
senderId: DataTypes.INTEGER,
receiverId: DataTypes.INTEGER,
content: DataTypes.STRING
}, {
sequelize,
modelName: 'Inbox',
});
return Inbox;
};
37 changes: 37 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
Loading