Skip to content

Commit

Permalink
chg: added authentication middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
wemakshaychavan committed Feb 23, 2023
1 parent 7d790f4 commit a5acb59
Show file tree
Hide file tree
Showing 10 changed files with 198 additions and 85 deletions.
8 changes: 2 additions & 6 deletions seller/app/lib/bootstrap/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ const env = process.env.NODE_ENV || 'development'; // By default development env
// default users fordevelopment and staging/production environment
const users = (env === 'development') ? [
{
"firstName": "Abhinandan",
"middleName": "Ashok",
"lastName": "Satpute",
"name": "Abhinandan",
"username": "sa@mailinator.com",
"email": "sa@mailinator.com",
"roleName": 'Super Admin',
Expand All @@ -18,9 +16,7 @@ const users = (env === 'development') ? [
}
] : [
{
"firstName": "Abhinandan",
"middleName": "Ashok",
"lastName": "Satpute",
"name": "Abhinandan",
"username": "sa@mailinator.com",
"email": "sa@mailinator.com",
"roleName": 'Super Admin',
Expand Down
14 changes: 14 additions & 0 deletions seller/app/modules/authentication/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ class UserController {
}
}

async invite(req, res, next) {
try {

console.log("user data------------------",req.body);
const data = req.body;
const user = await userService.invite(data);
return res.send(user);

} catch (error) {
console.log('[userController] [createUser] Error -', error);
next(error);
}
}

/**
* Update user
* @param {*} req HTTP request object
Expand Down
76 changes: 40 additions & 36 deletions seller/app/modules/authentication/models/organization.model.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,63 @@
import mongoose from'mongoose';
import { uuid } from 'uuidv4';

import s3 from '../../../lib/utils/s3Utils'
const organizationSchema = new mongoose.Schema({ //Users who has login ability should go under User schema
_id:{
type: String,
required:true,
default: () => uuid(),
},
name: {
type: String,
},
modules:[{ type: Object, ref: 'Model' }],
welcomeScreenContent:{
type:String,
},
shortCode: {
type: String,
required: true,
},
isActive: {
type: Boolean,
},
profilePic:{
type:String,
},
colors:{
pageBackGroundColor:{
type: String,
},
iconButtonBackgroundColor: {
type: String,
},
iconColor:{
type: String,
},
linkColor:{
type: String,
},
formFieldBackgroundColor:{
type: String,
},
},
name: {type:String,required:true},
address: {type:String},
contactEmail:{type:String},
contactMobile:{type:String},
addressProof:{type:String},
idProof:{type:String},
bankDetails:{
accHolderName:{type:String},
accNumber:{type:String},
IFSC:{type:String},
cancelledCheque:{type:String},
bankName:{type:String},
branchName:{type:String}
},
PAN:{PAN:{type:String},proof:{type:String}},
GSTN:{GSTN:{type:String},proof:{type:String}},
FSSAI:{type:String},
createdAt:{
type:Number,
default:Date.now()
},
updatedAt:{
type:Number,
default:Date.now()
}
},
createdBy:{type:String}
},{
strict: true,
timestamps:true
});

organizationSchema.post('findOne',async function(doc, next) {
if(doc){
let idProof = await s3.getSignedUrlForRead({path:doc.idProof});
doc.idProof =idProof

let addressProof = await s3.getSignedUrlForRead({path:doc.addressProof});
doc.addressProof =addressProof

let cancelledCheque = await s3.getSignedUrlForRead({path:doc.bankDetails.cancelledCheque});
doc.bankDetails.cancelledCheque =cancelledCheque

let PAN = await s3.getSignedUrlForRead({path:doc.PAN.proof});
doc.PAN.proof =PAN

let GSTN = await s3.getSignedUrlForRead({path:doc.GSTN.proof});
doc.GSTN.proof =GSTN
}
next();
});

organizationSchema.index({name:1,shortCode:1}, {unique: false});
const Organization = mongoose.model('Organization',organizationSchema);
module.exports = Organization;
9 changes: 2 additions & 7 deletions seller/app/modules/authentication/models/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,10 @@ const userSchema = new mongoose.Schema({ //Users who has login ability should go
required:true,
default: () => uuid(),
},
firstName: {
name: {
type: String,
required: true,
},
middleName: {
type: String,
},
lastName: {
type: String,
},
mobile: {
type: String,
required: true,
Expand All @@ -37,6 +31,7 @@ const userSchema = new mongoose.Schema({ //Users who has login ability should go
default:true
},
role: { type: String, ref: 'Role' },
organization: { type: String, ref: 'Organization' },
isSystemGeneratedPassword: {
type: Boolean,
default:true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import OrganizationController from '../controllers/organization.controller';
import apiParamsValidator from '../v1/middleware/api.params.validator';
import organisationSchema from '../v1/validationSchema/api-params-validation-schema/organization.validate.schema';
import express from 'express';
import {authentication} from "../../../lib/middlewares";
const router = express.Router();

const organizationController = new OrganizationController();
Expand All @@ -14,18 +15,21 @@ const organizationController = new OrganizationController();
* API to create ORG
*/
router.post('/v1/organizations',
authentication.middleware(),
apiParamsValidator.middleware({ schema: organisationSchema.create() }),
organizationController.create);

/**
* API to get all list
*/
router.get('/v1/iam/organizations',
router.get('/v1/organizations',
authentication.middleware(),
apiParamsValidator.middleware({ schema: organisationSchema.list() }),
organizationController.list,
);

router.get('/v1/iam/organization/:organizationId',
router.get('/v1/organizations/:organizationId',
authentication.middleware(),
apiParamsValidator.middleware({ schema: organisationSchema.get() }),
organizationController.get,
);
Expand Down
9 changes: 9 additions & 0 deletions seller/app/modules/authentication/routes/user.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,27 @@ const authController = new AuthenticationController();
// router.use('/auth', authentication.middleware());

router.post('/v1/users/create',
authentication.middleware(),
userController.create
);

router.post('/v1/users/invite/admin',
authentication.middleware(),
userController.invite
);

router.get('/v1/users/:userId',
authentication.middleware(),
userController.getUsersById
);

router.get('/v1/users',
authentication.middleware(),
userController.getUsers
);

router.get('/v1/upload/:category',
authentication.middleware(),
userController.upload
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class AuthenticationService {
//find user with email
data.email = data.email.toLowerCase();

let currentUser = await User.findOne({email:data.email},{enabled:0}).populate('role');
let currentUser = await User.findOne({email:data.email},{enabled:0}).populate([{path:'role'},{path:'organization'}]);
if (!currentUser) {
throw new UnauthenticatedError(MESSAGES.INVALID_PIN);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { v1 as uuidv1 } from 'uuid';
import MESSAGES from '../../../../lib/utils/messages';
import Organization from '../../models/organization.model';
import User from '../../models/user.model';
import UserService from "./user.service";
import {
NoRecordFoundError,
DuplicateRecordFoundError,
Expand All @@ -10,28 +12,33 @@ import {
//import axios from 'axios';
//import ServiceApi from '../../../../lib/utils/serviceApi';

const userService = new UserService()
class OrganizationService {
async create(data) {
try {
let query = {};
query.shortCode = data.shortCode;
const organizationExist = await Organization.findOne(query);

let orgDetails = data.providerDetails;
const organizationExist = await Organization.findOne({name:orgDetails.name});

if (organizationExist) {
throw new DuplicateRecordFoundError(MESSAGES.ORGANIZATION_ALREADY_EXISTS);
}

let organization = new Organization;
organization.name = data.name;
organization.modules = data.modules;
organization.shortCode = data.shortCode;
organization.welcomeScreenContent = data.welcomeScreenContent;
organization.isActive = data.isActive;
organization.profilePic = data.profilePic;
organization.colors = data.colors;
let userExist = await User.findOne({email:data.user.email})

if (userExist) {
throw new DuplicateRecordFoundError(MESSAGES.USER_ALREADY_EXISTS);
}

let organization = new Organization(orgDetails);
let savedOrg = await organization.save();

return organization;
//create a user
let user = await userService.create({...data.user,organization:organization._id,role:"Organization Admin"})

return {user:user,providerDetail:organization};

} catch (err) {
console.log(`[OrganizationService] [create] Error in creating organization ${data.organizationId}`,err);
throw err;
Expand All @@ -44,8 +51,8 @@ class OrganizationService {
if(params.name){
query.name = { $regex: params.name, $options: 'i' };
}
const organizations = await Organization.find(query).sort({createdAt:1}).skip(params.offset).limit(params.limit);
const count = await Organization.find(query).countDocuments();
const organizations = await Organization.find(query).sort({createdAt:1}).skip(params.offset).limit(params.limit);
const count = await Organization.count(query)
let organizationData={
count,
organizations
Expand All @@ -59,10 +66,12 @@ class OrganizationService {

async get(organizationId) {
try {
let organization = await Organization.findById(organizationId);
let organization = await Organization.findOne({_id:organizationId}).lean();

console.log("organization----->",organization)
let user = await User.findOne({organization:organizationId},{password:0})
if (organization) {
return organization;
return {user:user,providerDetail:organization};
} else {
throw new NoRecordFoundError(MESSAGES.ORGANIZATION_NOT_EXISTS);
}
Expand Down
Loading

0 comments on commit a5acb59

Please sign in to comment.