Skip to content

Commit

Permalink
Merge pull request #220 from R-Sourabh/App-auth-support
Browse files Browse the repository at this point in the history
Implemented: added support for base permission in the app(dxp-323)
  • Loading branch information
ymaheshwari1 authored Oct 18, 2024
2 parents c9907cd + d50c19b commit ec74dff
Show file tree
Hide file tree
Showing 15 changed files with 315 additions and 32 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ VUE_APP_I18N_FALLBACK_LOCALE=en
VUE_APP_CACHE_MAX_AGE=3600
VUE_APP_VIEW_SIZE=15
VUE_APP_BASE_URL=
VUE_APP_PERMISSION_ID=
VUE_APP_PERMISSION_ID="PICKING_APP_VIEW"
VUE_APP_ALIAS={}
VUE_APP_DEFAULT_LOG_LEVEL="error"
VUE_APP_LOGIN_URL="http://launchpad.hotwax.io/login"
Expand Down
49 changes: 49 additions & 0 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
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@
"@capacitor/android": "^2.5.0",
"@capacitor/core": "^2.4.7",
"@capacitor/ios": "^2.5.0",
"@casl/ability": "^6.0.0",
"@hotwax/app-version-info": "^1.0.0",
"@hotwax/apps-theme": "^1.2.6",
"@hotwax/dxp-components": "^1.12.2",
"@hotwax/oms-api": "^1.13.0",
"@ionic/core": "~7.6.0",
"@ionic/vue": "~7.6.0",
"@ionic/vue-router": "~7.6.0",
"boon-js": "^2.0.3",
"core-js": "^3.6.5",
"luxon": "^3.2.0",
"mitt": "^2.1.0",
Expand Down
3 changes: 3 additions & 0 deletions src/authorization/Actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
"PICKING_APP_VIEW": "PICKING_APP_VIEW"
} as any
3 changes: 3 additions & 0 deletions src/authorization/Rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
"PICKING_APP_VIEW": "PICKING_APP_VIEW"
} as any
124 changes: 124 additions & 0 deletions src/authorization/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { AbilityBuilder, PureAbility } from '@casl/ability';
import { getEvaluator, parse } from 'boon-js';
import { Tokens } from 'boon-js/lib/types'

// TODO Improve this
// We will move this code to an external plugin and use below Actions and Rules accordlingly
let Actions = {} as any;
let Rules = {} as any;

// We are using CASL library to define permissions.
// Instead of using Action-Subject based authorisation we are going with Claim based Authorization.
// We would be defining the permissions for each action and case, map with server permissiosn based upon certain rules.
// https://casl.js.org/v5/en/cookbook/claim-authorization
// Following the comment of Sergii Stotskyi, author of CASL
// https://github.com/stalniy/casl/issues/525
// We are defining a PureAbility and creating an instance with AbilityBuilder.
type ClaimBasedAbility = PureAbility<string>;
const { build } = new AbilityBuilder<ClaimBasedAbility>(PureAbility);
const ability = build();

/**
* The method returns list of permissions required for the rules. We are having set of rules,
* through which app permissions are defined based upon the server permissions.
* When getting server permissions, as all the permissions are not be required.
* Specific permissions used defining the rules are extracted and sent to server.
* @returns permissions
*/
const getServerPermissionsFromRules = () => {
// Iterate for each rule
const permissions = Object.keys(Rules).reduce((permissions: any, rule: any) => {
const permissionRule = Rules[rule];
// some rules may be empty, no permission is required from server
if (permissionRule) {
// Each rule may have multiple permissions along with operators
// Boon js parse rules into tokens, each token may be operator or server permission
// permissionId will have token name as identifier.
const permissionTokens = parse(permissionRule);
permissions = permissionTokens.reduce((permissions: any, permissionToken: any) => {
// Token object with name as identifier has permissionId
if (Tokens.IDENTIFIER === permissionToken.name) {
permissions.add(permissionToken.value);
}
return permissions;
}, permissions)
}
return permissions;
}, new Set())
return [...permissions];
}

/**
* The method is used to prepare app permissions from the server permissions.
* Rules could be defined such that each app permission could be defined based upon certain one or more server permissions.
* @param serverPermissions
* @returns appPermissions
*/
const prepareAppPermissions = (serverPermissions: any) => {
const serverPermissionsInput = serverPermissions.reduce((serverPermissionsInput: any, permission: any) => {
serverPermissionsInput[permission] = true;
return serverPermissionsInput;
}, {})
// Boonjs evaluator needs server permissions as object with permissionId and boolean value
// Each rule is passed to evaluator along with the server permissions
// if the server permissions and rule matches, app permission is added to list
const permissions = Object.keys(Rules).reduce((permissions: any, rule: any) => {
const permissionRule = Rules[rule];
// If for any app permission, we have empty rule we user is assigned the permission
// If rule is not defined, the app permisions is still evaluated or provided to all the users.
if (!permissionRule || (permissionRule && getEvaluator(permissionRule)(serverPermissionsInput))) {
permissions.push(rule);
}
return permissions;
}, [])
const { can, rules } = new AbilityBuilder<ClaimBasedAbility>(PureAbility);
permissions.map((permission: any) => {
can(permission);
})
return rules;
}

/**
*
* Sets the current app permissions. This should be used after perparing the app permissions from the server permissions
* @param permissions
* @returns
*/
const setPermissions = (permissions: any) => {
// If the user has passed undefined or null, it should not break the code
if (!permissions) permissions = [];
ability.update(permissions)
return true;
};

/**
* Resets the permissions list. Used for cases like logout
*/
const resetPermissions = () => setPermissions([]);

/**
*
* @param permission
* @returns
*/
const hasPermission = (permission: string) => ability.can(permission);

export { Actions, getServerPermissionsFromRules, hasPermission, prepareAppPermissions, resetPermissions, setPermissions};

// TODO Move this code to an external plugin, to be used across the apps
export default {
install(app: any, options: any) {

// Rules and Actions could be app and OMS package specific
Rules = options.rules;
Actions = options.actions;

// TODO Check why global properties is not working and apply across.
app.config.globalProperties.$permission = this;
},
getServerPermissionsFromRules,
hasPermission,
prepareAppPermissions,
resetPermissions,
setPermissions
}
7 changes: 7 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ import store from './store'
import { dxpComponents } from '@hotwax/dxp-components'
import { login, logout, loader } from './user-utils';
import { getConfig, getProductIdentificationPref, initialise, setProductIdentificationPref } from '@/adapter'
import permissionPlugin from '@/authorization';
import permissionRules from '@/authorization/Rules';
import permissionActions from '@/authorization/Actions';
import localeMessages from './locales';

const app = createApp(App)
Expand All @@ -40,6 +43,10 @@ const app = createApp(App)
.use(router)
.use(i18n)
.use(store)
.use(permissionPlugin, {
rules: permissionRules,
actions: permissionActions
})
.use(dxpComponents, {
defaultImgUrl: require("@/assets/images/defaultImage.png"),
login,
Expand Down
97 changes: 88 additions & 9 deletions src/services/UserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,93 @@ const login = async (username: string, password: string): Promise <any> => {
});
}

const checkPermission = async (payload: any): Promise <any> => {
const getUserPermissions = async (payload: any, token: any): Promise<any> => {
const baseURL = store.getters['user/getBaseUrl'];
return client({
url: "checkPermission",
method: "post",
baseURL: baseURL,
...payload
});
let serverPermissions = [] as any;

// If the server specific permission list doesn't exist, getting server permissions will be of no use
// It means there are no rules yet depending upon the server permissions.
if (payload.permissionIds && payload.permissionIds.length == 0) return serverPermissions;
// TODO pass specific permissionIds
let resp;
// TODO Make it configurable from the environment variables.
// Though this might not be an server specific configuration,
// we will be adding it to environment variable for easy configuration at app level
const viewSize = 200;

try {
const params = {
"viewIndex": 0,
viewSize,
permissionIds: payload.permissionIds
}
resp = await client({
url: "getPermissions",
method: "post",
baseURL,
data: params,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
}
})
if (resp.status === 200 && resp.data.docs?.length && !hasError(resp)) {
serverPermissions = resp.data.docs.map((permission: any) => permission.permissionId);
const total = resp.data.count;
const remainingPermissions = total - serverPermissions.length;
if (remainingPermissions > 0) {
// We need to get all the remaining permissions
const apiCallsNeeded = Math.floor(remainingPermissions / viewSize) + (remainingPermissions % viewSize != 0 ? 1 : 0);
const responses = await Promise.all([...Array(apiCallsNeeded).keys()].map(async (index: any) => {
const response = await client({
url: "getPermissions",
method: "post",
baseURL,
data: {
"viewIndex": index + 1,
viewSize,
permissionIds: payload.permissionIds
},
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
}
})
if (!hasError(response)) {
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
}))
const permissionResponses = {
success: [],
failed: []
}
responses.reduce((permissionResponses: any, permissionResponse: any) => {
if (permissionResponse.status !== 200 || hasError(permissionResponse) || !permissionResponse.data?.docs) {
permissionResponses.failed.push(permissionResponse);
} else {
permissionResponses.success.push(permissionResponse);
}
return permissionResponses;
}, permissionResponses)

serverPermissions = permissionResponses.success.reduce((serverPermissions: any, response: any) => {
serverPermissions.push(...response.data.docs.map((permission: any) => permission.permissionId));
return serverPermissions;
}, serverPermissions)

// If partial permissions are received and we still allow user to login, some of the functionality might not work related to the permissions missed.
// Show toast to user intimiting about the failure
// Allow user to login
// TODO Implement Retry or improve experience with show in progress icon and allowing login only if all the data related to user profile is fetched.
if (permissionResponses.failed.length > 0) Promise.reject("Something went wrong while getting complete user permissions.");
}
}
return serverPermissions;
} catch (error: any) {
return Promise.reject(error);
}
}

const getCurrentEComStore = async (token: any, facilityId: any): Promise<any> => {
Expand Down Expand Up @@ -88,6 +167,6 @@ export const UserService = {
getAvailableTimeZones,
getProfile,
setUserTimeZone,
checkPermission,
getCurrentEComStore
getCurrentEComStore,
getUserPermissions
}
4 changes: 3 additions & 1 deletion src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import userModule from './modules/user';
import picklistModule from "./modules/picklist"
import productModule from "./modules/product"
import partyModule from './modules/party'

import { setPermissions } from "@/authorization"

// TODO check how to register it from the components only
// Handle same module registering multiple time on page refresh
Expand Down Expand Up @@ -39,6 +39,8 @@ const store = createStore<RootState>({
},
})

setPermissions(store.getters['user/getUserPermissions']);

export default store
export function useStore(): typeof store {
return useVuexStore()
Expand Down
Loading

0 comments on commit ec74dff

Please sign in to comment.