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

Feat: auth #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"parserOptions": {
"ecmaVersion": "latest"
},
"ignorePatterns": ["models/index.js"],
"rules": {
}
}
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/node_modules
.env
.env
id_rsa_*
13 changes: 13 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
const express = require('express');

const passport = require('passport');

require('dotenv').config();

const app = express();

// passport config
require('./config/passport')(passport);

// initialize passport
app.use(passport.initialize());

// Json Parser
app.use(express.json());

app.use('/api/dashboard', require('./routes/dashboard/auth/auth.route'));

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": "root",
"password": "root",
"database": "eba",
"host": "127.0.0.1",
"dialect": "mysql"
},
"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"
}
}
31 changes: 31 additions & 0 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const fs = require('fs');

const path = require('path');

const JwtStrategy = require('passport-jwt').Strategy;

const { ExtractJwt } = require('passport-jwt');

const { User } = require('../models');

const pathToKey = path.join(__dirname, '..', 'id_rsa_pub.pem');

const options = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: fs.readFileSync(pathToKey, 'utf8'),
algorithms: ['RS256'],
};

const strategy = new JwtStrategy(options, async (payload, done) => {
const user = await User.findOne({ where: { id: payload.sub } });

if (!user) {
return done(null, false);
}

return done(null, user);
});

module.exports = (passport) => {
passport.use(strategy);
};
28 changes: 28 additions & 0 deletions generateKeyPair.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* This module with generate a public and private key pair
*/
const crypto = require('crypto');

const fs = require('fs');

const genKeyPair = () => {
const keyPair = crypto.generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
});

// Create the public key file
fs.writeFileSync(`${__dirname}/id_rsa_pub.pem`, keyPair.publicKey);

// Create the private key file
fs.writeFileSync(`${__dirname}/id_rsa_priv.pem`, keyPair.privateKey);
};

genKeyPair();
42 changes: 42 additions & 0 deletions migrations/20230715145137-create-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, DataTypes) {
await queryInterface.createTable('users', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
role: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE,
},
});
},
// eslint-disable-next-line
async down(queryInterface, DataTypes) {
await queryInterface.dropTable('users');
},
};
43 changes: 43 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
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' &&
file.indexOf('.test.js') === -1
);
})
.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;
55 changes: 55 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const {
Model,
} = require('sequelize');

module.exports = (sequelize, DataTypes) => {
class User 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
// }
}
User.init({
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
role: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE,
},
}, {
sequelize,
modelName: 'User',
tableName: 'users',
});

return User;
};
Loading
Loading