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

Develop #90

Open
wants to merge 3 commits into
base: master
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
22 changes: 11 additions & 11 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
module.exports = {
parser: '@typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
module.exports = {
parser: '@typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
parserOptions: {
ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
parserOptions: {
ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
},
rules: {
rules: {
'@typescript-eslint/explicit-member-accessibility': 0,
'@typescript-eslint/explicit-function-return-type': 0,
'@typescript-eslint/no-parameter-properties': 0,
'@typescript-eslint/interface-name-prefix': 0
'@typescript-eslint/interface-name-prefix': 0,
},
};
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
"argon2": "^0.27.0",
"body-parser": "^1.19.0",
"celebrate": "^13.0.3",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"errorhandler": "^1.5.1",
Expand All @@ -53,6 +55,7 @@
"mongoose": "^5.10.6",
"morgan": "^1.10.0",
"reflect-metadata": "^0.1.13",
"routing-controllers": "^0.9.0-alpha.6",
"typedi": "^0.8.0",
"winston": "^3.3.3"
},
Expand Down
12 changes: 6 additions & 6 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import agendash from './routes/agendash';

// guaranteed to get dependencies
export default () => {
const app = Router();
auth(app);
user(app);
agendash(app);
const app = Router();
auth(app);
user(app);
agendash(app);

return app
}
return app;
};
2 changes: 1 addition & 1 deletion src/api/middlewares/attachCurrentUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Logger } from 'winston';
* @param {*} next Express next Function
*/
const attachCurrentUser = async (req, res, next) => {
const Logger : Logger = Container.get('logger');
const Logger: Logger = Container.get('logger');
try {
const UserModel = Container.get('userModel') as mongoose.Model<IUser & mongoose.Document>;
const userRecord = await UserModel.findById(req.token._id);
Expand Down
1 change: 0 additions & 1 deletion src/api/middlewares/isAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ const isAuth = jwt({
algorithms: [config.jwtAlgorithm], // JWT Algorithm
userProperty: 'token', // Use req.token to store the JWT
getToken: getTokenFromHeader, // How to extract the JWT from the request

});

export default isAuth;
34 changes: 15 additions & 19 deletions src/api/routes/agendash.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@

import { Router } from 'express'
import { Router } from 'express';
import basicAuth from 'express-basic-auth';
import agendash from 'agendash'
import { Container } from 'typedi'
import config from '../../config'
import agendash from 'agendash';
import { Container } from 'typedi';
import config from '../../config';

export default (app: Router) => {
const agendaInstance = Container.get('agendaInstance');

const agendaInstance = Container.get('agendaInstance')

app.use('/dash',
app.use(
'/dash',
basicAuth({
users: {
[config.agendash.user]: config.agendash.password,
},
challenge: true,
}),
agendash(agendaInstance)
)
}



users: {
[config.agendash.user]: config.agendash.password,
},
challenge: true,
}),
agendash(agendaInstance),
);
};
10 changes: 5 additions & 5 deletions src/api/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export default (app: Router) => {
}),
}),
async (req: Request, res: Response, next: NextFunction) => {
const logger:Logger = Container.get('logger');
logger.debug('Calling Sign-Up endpoint with body: %o', req.body );
const logger: Logger = Container.get('logger');
logger.debug('Calling Sign-Up endpoint with body: %o', req.body);
try {
const authServiceInstance = Container.get(AuthService);
const { user, token } = await authServiceInstance.SignUp(req.body as IUserInputDTO);
Expand All @@ -43,15 +43,15 @@ export default (app: Router) => {
}),
}),
async (req: Request, res: Response, next: NextFunction) => {
const logger:Logger = Container.get('logger');
const logger: Logger = Container.get('logger');
logger.debug('Calling Sign-In endpoint with body: %o', req.body);
try {
const { email, password } = req.body;
const authServiceInstance = Container.get(AuthService);
const { user, token } = await authServiceInstance.SignIn(email, password);
return res.json({ user, token }).status(200);
} catch (e) {
logger.error('🔥 error: %o', e );
logger.error('🔥 error: %o', e);
return next(e);
}
},
Expand All @@ -67,7 +67,7 @@ export default (app: Router) => {
* It's really annoying to develop that but if you had to, please use Redis as your data store
*/
route.post('/logout', middlewares.isAuth, (req: Request, res: Response, next: NextFunction) => {
const logger:Logger = Container.get('logger');
const logger: Logger = Container.get('logger');
logger.debug('Calling Sign-Out endpoint with body: %o', req.body);
try {
//@TODO AuthService.Logout(req.user) do some clever stuff
Expand Down
16 changes: 9 additions & 7 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,21 @@ async function startServer() {
* Well, at least in node 10 without babel and at the time of writing
* So we are using good old require.
**/
// eslint-disable-next-line @typescript-eslint/no-var-requires
await require('./loaders').default({ expressApp: app });

app.listen(config.port, () => {
Logger.info(`
app
.listen(config.port, () => {
Logger.info(`
################################################
🛡️ Server listening on port: ${config.port} 🛡️
################################################
`);
}).on('error', err => {
Logger.error(err);
process.exit(1);
});

})
.on('error', err => {
Logger.error(err);
process.exit(1);
});
}

startServer();
6 changes: 3 additions & 3 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export default {
*/
agendash: {
user: 'agendash',
password: '123456'
password: '123456',
},
/**
* API configs
Expand All @@ -61,6 +61,6 @@ export default {
*/
emails: {
apiKey: process.env.MAILGUN_API_KEY,
domain: process.env.MAILGUN_DOMAIN
}
domain: process.env.MAILGUN_DOMAIN,
},
};
2 changes: 1 addition & 1 deletion src/loaders/dependencyInjector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default ({ mongoConnection, models }: { mongoConnection; models: { name:

Container.set('agendaInstance', agendaInstance);
Container.set('logger', LoggerInstance);
Container.set('emailClient', mailgun({ apiKey: config.emails.apiKey, domain: config.emails.domain }));
// Container.set('emailClient', mailgun({ apiKey: config.emails.apiKey, domain: config.emails.domain }));

LoggerInstance.info('✌️ Agenda injected into container');

Expand Down
6 changes: 2 additions & 4 deletions src/loaders/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default ({ app }: { app: express.Application }) => {
// Some sauce that always add since 2014
// "Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it."
// Maybe not needed anymore ?
// eslint-disable-next-line @typescript-eslint/no-var-requires
app.use(require('method-override')());

// Middleware that transforms the raw string of req.body into json
Expand All @@ -47,10 +48,7 @@ export default ({ app }: { app: express.Application }) => {
* Handle 401 thrown by express-jwt library
*/
if (err.name === 'UnauthorizedError') {
return res
.status(err.status)
.send({ message: err.message })
.end();
return res.status(err.status).send({ message: err.message }).end();
}
return next(err);
});
Expand Down
1 change: 1 addition & 0 deletions src/loaders/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export default async ({ expressApp }) => {
const userModel = {
name: 'userModel',
// Notice the require syntax and the '.default'
// eslint-disable-next-line @typescript-eslint/no-var-requires
model: require('../models/user').default,
};

Expand Down
23 changes: 9 additions & 14 deletions src/loaders/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,28 @@ import winston from 'winston';
import config from '../config';

const transports = [];
if(process.env.NODE_ENV !== 'development') {
transports.push(
new winston.transports.Console()
)
if (process.env.NODE_ENV !== 'development') {
transports.push(new winston.transports.Console());
} else {
transports.push(
new winston.transports.Console({
format: winston.format.combine(
winston.format.cli(),
winston.format.splat(),
)
})
)
format: winston.format.combine(winston.format.cli(), winston.format.splat()),
}),
);
}

const LoggerInstance = winston.createLogger({
level: config.logs.level,
levels: winston.config.npm.levels,
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
format: 'YYYY-MM-DD HH:mm:ss',
}),
winston.format.errors({ stack: true }),
winston.format.splat(),
winston.format.json()
winston.format.json(),
),
transports
transports,
});

export default LoggerInstance;
export default LoggerInstance;
5 changes: 2 additions & 3 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ export default class AuthService {
private mailer: MailerService,
@Inject('logger') private logger,
@EventDispatcher() private eventDispatcher: EventDispatcherInterface,
) {
}
) {}

public async SignUp(userInputDTO: IUserInputDTO): Promise<{ user: IUser; token: string }> {
try {
Expand Down Expand Up @@ -122,7 +121,7 @@ export default class AuthService {
name: user.name,
exp: exp.getTime() / 1000,
},
config.jwtSecret
config.jwtSecret,
);
}
}
6 changes: 2 additions & 4 deletions src/services/mailer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import { IUser } from '../interfaces/IUser';

@Service()
export default class MailerService {
constructor(
@Inject('emailClient') private emailClient
) { }
constructor(@Inject('emailClient') private emailClient) {}

public async SendWelcomeEmail(email) {
/**
Expand All @@ -16,7 +14,7 @@ export default class MailerService {
from: 'Excited User <[email protected]>',
to: email, //your email address
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
text: 'Testing some Mailgun awesomness!',
};

this.emailClient.messages().send(data);
Expand Down
Loading