Skip to content

Commit

Permalink
'
Browse files Browse the repository at this point in the history
  • Loading branch information
ezzabuzaid committed Nov 23, 2019
1 parent 9c49cf4 commit 5499af3
Show file tree
Hide file tree
Showing 24 changed files with 307 additions and 198 deletions.
62 changes: 42 additions & 20 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Expand Up @@ -29,6 +29,7 @@
"@types/multer": "^1.3.7",
"@types/mysql": "^2.15.6",
"@types/nodegit": "^0.24.11",
"@types/nodemailer": "^6.2.2",
"@types/phone": "^1.0.3",
"@types/reflect-metadata": "^0.1.0",
"@types/sequelize": "^4.28.4",
Expand Down Expand Up @@ -58,6 +59,7 @@
"mysql": "^2.17.1",
"mysql2": "^1.6.5",
"nodegit": "^0.26.2",
"nodemailer": "^6.3.1",
"phone": "^2.3.18",
"reflect-metadata": "^0.1.13",
"sequelize": "^5.16.0",
Expand Down
12 changes: 6 additions & 6 deletions src/app/api/accounts/accounts.service.ts
Expand Up @@ -8,12 +8,12 @@ class AccountService extends CrudService<AccountSchema> {
super(new Repo(AccountModel));
}

public deleteAccount(user_id) {
return this.delete({ user_id });
}
public createAccount(user_id) {
return this.create({ user_id });
}
// public deleteAccount(user_id) {
// return this.delete({ user_id });
// }
// public createAccount(user_id) {
// return this.create({ user_id });
// }

public async getEntityByUserId(user_id) {
const entity = await this.one({ user_id });
Expand Down
20 changes: 4 additions & 16 deletions src/app/api/favorites/favorites.model.ts
@@ -1,27 +1,15 @@
import { Constants } from '@core/helpers';
import { BaseModel, Entity, Field } from '@lib/mongoose';
import { Types } from 'mongoose';
import { Types, Schema } from 'mongoose';

@Entity(Constants.Schemas.favorites)
export class FavoritesSchema {
@Field({ lowercase: false }) public user_id: Types.ObjectId;
@Field({ lowercase: false }) public item_id: Types.ObjectId;
// TODO: constructor(schema: Schema) { }
@Field() public user_id: Types.ObjectId;
@Field() public item_id: Types.ObjectId;
@Field({
enum: [Constants.Schemas.meals, Constants.Schemas.MENUS]
}) public type: string;

// @Virtual('assigned') assignedVirtual() {
// return {
// ref: this.type,
// localField: 'item_id',
// foreignField: '_id',
// justOne: false
// };
// }

// get test(): Partial<string> {
// return this.type;
// }
}
export const FavoritesModel = BaseModel<FavoritesSchema>(FavoritesSchema);
FavoritesModel.schema.virtual('item', {
Expand Down
3 changes: 2 additions & 1 deletion src/app/api/favorites/favorites.routes.ts
Expand Up @@ -4,9 +4,10 @@ import { Delete, Get, Post, Router } from '@lib/methods';
import { translate } from '@lib/translation';
import { Request, Response } from 'express';
import { FavoritesRepo } from './favorites.repo';
import { CrudRouter } from '@shared/crud';

@Router(Constants.Endpoints.favorites)
export class FavoritesRouter {
export class FavoritesRouter extends CrudRouter<any> {
private repo = FavoritesRepo;

@Post(':type', Auth.isAuthenticated)
Expand Down
9 changes: 7 additions & 2 deletions src/app/api/meals/meals.spec.ts
@@ -1,9 +1,14 @@
import { superAgent } from '@test/index';
import { Constants, NetworkStatus } from '@core/helpers';

global.console = {
...global.console,
log: jest.fn(),
info: jest.fn(),
error: jest.fn(),
};
describe('#Get All', () => {
it('Should return data without token', async () => {
const res = await (await superAgent).post(`/api/${Constants.Endpoints.MEALS}`);
const res = await (await superAgent).get(`/api/${Constants.Endpoints.MEALS}`);
expect(res.body.data).toBeInstanceOf(Array);
expect(res.status).toBe(NetworkStatus.OK);
});
Expand Down
5 changes: 3 additions & 2 deletions src/app/api/menus/menus.spec.ts
Expand Up @@ -2,9 +2,10 @@ import { superAgent } from '@test/index';
import { Constants, NetworkStatus } from '@core/helpers';

describe('#Get All', () => {
it('Should return data without token', async () => {
const res = await (await superAgent).post(`/api/${Constants.Endpoints.MENUS}`);
it('Should return data without token', async (done) => {
const res = await (await superAgent).get(`/api/${Constants.Endpoints.MENUS}`);
expect(res.body.data).toBeInstanceOf(Array);
expect(res.status).toBe(NetworkStatus.OK);
done();
});
});
57 changes: 52 additions & 5 deletions src/app/api/portal/portal.routes.ts
Expand Up @@ -3,25 +3,72 @@ import { Post, Router } from '@lib/methods';
import { translate } from '@lib/translation';
import { Request, Response } from 'express';
import usersService from '@api/users/users.service';
import { UsersSchema } from '@api/users';
import { Body } from '@lib/mongoose';

// TODO: create the profile / acount strategy
// TODO: create the profile / account strategy

@Router(Constants.Endpoints.PORTAL)
export class PortalRoutes {

@Post(`login/${Constants.Endpoints.USERS}`)
public async loginUser(req: Request, res: Response) {
const { username, password } = req.body;
@Post(`login`)
public async login(req: Request, res: Response) {
const { username, password } = req.body as Body<UsersSchema>;
const entity = await usersService.one({ username });
if (!!entity) {
const isPasswordEqual = await entity.comparePassword(password);
if (isPasswordEqual) {
// TODO: replace the response with login response and not user info
const response = new SuccessResponse(entity, translate('success'));
response.token = tokenService.generateToken({ id: entity.id });
response.token = tokenService.generateToken({
id: entity.id,
role: entity.role
});
return res.status(response.code).json(response);
}
}
throw new ErrorResponse(translate('wrong_credintals'));
}

public async forgotPassword(req: Request, res: Response) {
const { username } = req.body as Body<UsersSchema>;
const entity = await throwIfNotExist({ username });
// sendEmail(entity.email);
}

}

async function throwIfNotExist(query: Partial<Body<UsersSchema>>) {
const entity = await usersService.one(query);
if (!!entity) {
return entity;
}
throw new ErrorResponse(translate('not_exist'));
}

import nodemailer from 'nodemailer';

// const transporter = nodemailer.createTransport({
// service: 'gmail',
// auth: {
// }
// });

// const message = {
// from: 'ezzabuzaid@gmail.com',
// to: 'ezzabuzaid@hotmail.com',
// subject: 'Nodemailer is unicode friendly ✔',
// text: 'Hello to myself!',
// html: '<p><b>Hello</b> to myself!</p>'
// };

// transporter.sendMail(message, (err, info) => {
// if (err) {
// console.log('Error occurred. ' + err.message);
// return process.exit(1);
// }

// console.log('Message sent: %s', info.messageId);
// // Preview only available when sending through an Ethereal account
// console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// });
47 changes: 27 additions & 20 deletions src/app/api/portal/portal.spec.ts
@@ -1,42 +1,49 @@
import { UsersSchema } from '@api/users';
import { UsersSchema, ERoles } from '@api/users';
import { Body } from '@lib/mongoose';
import { superAgent } from '@test/index';
import { Constants, NetworkStatus } from '@core/helpers';
import { UserFixture } from '@test/fixture';
import { UserFixture as userFixture, getUri } from '@test/fixture';
import { AppUtils } from '@core/utils';

const ENDPOINT = `/api/${Constants.Endpoints.PORTAL}/login/${Constants.Endpoints.USERS}/`;
const ENDPOINT = getUri(`${Constants.Endpoints.PORTAL}/login`);

let user: UserFixture = null;
const mockUser = {
password: '123456789',
username: 'portalLogin',
email: 'portal@login.com',
mobile: '0792807794',
profile: null,
role: ERoles.SUPERADMIN
} as Body<UsersSchema>;
let userFixture: userFixture = null;

beforeAll(async () => {
const body = {
password: '123456789',
username: 'portalLogin',
email: 'portal@login.com',
mobile: '0792807794'
} as Body<UsersSchema>;
const req = (await superAgent).post(ENDPOINT);
const res = await req.send(body);
user = res.body.data;
const res = await req.send(mockUser);
userFixture = res.body.data;
});

describe('Login should fail if..', () => {
it('`Request with non existing user`', async () => {
const body = {
password: '123456789',
username: 'portalLogin'
} as Body<UsersSchema>;
const req = (await superAgent).post(ENDPOINT);
const res = await req.send(body);
const res = await req.send({ username: 'fakeUsername', password: 'fakePassword' });
expect(res.status).toBe(NetworkStatus.BAD_REQUEST);
});
it('The Username was wrong', async () => {
const req = (await superAgent).post(ENDPOINT);
const res = await req.send(AppUtils.assignObject({}, mockUser, { username: 'fakeUsername' }));
expect(res.status).toBe(NetworkStatus.BAD_REQUEST);
});
it('The password was wrong', async () => {
const req = (await superAgent).post(ENDPOINT);
const res = await req.send(AppUtils.assignObject({}, mockUser, { password: 'fakePassword' }));
expect(res.status).toBe(NetworkStatus.BAD_REQUEST);
});
it.todo('The Username was wrong');
it.todo('The password was wrong');
it.todo('User trying to login with an old password');
it.todo('User has more than three session');
});

describe('Login should success when', () => {
it.todo('Token is valid');
it.todo('Token has the appropriate schem');
it.todo('Token has the appropriate schema');
});
9 changes: 9 additions & 0 deletions src/app/api/profiles/profile.service.ts
@@ -0,0 +1,9 @@
import accountsService from '@api/accounts/accounts.service';

export class ProfileService {
constructor() { }

public update() {
// accountsService.update();
}
}

0 comments on commit 5499af3

Please sign in to comment.