Merge branch 'tenant-improve' of https://gitlab.com/entgra/carbon-device-mgt into tenant-improve

revert-70ac1926
inoshperera 4 years ago
commit 640a50ccd9

@ -66,7 +66,6 @@
<phase>generate-resources</phase>
<configuration>
<nodeVersion>${node.version}</nodeVersion>
<npmVersion>${npm.version}</npmVersion>
</configuration>
</execution>
<execution>
@ -101,46 +100,6 @@
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.codehaus.mojo</groupId>-->
<!-- <artifactId>exec-maven-plugin</artifactId>-->
<!-- <version>1.5.0</version>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>npm install (initialize)</id>-->
<!-- <goals>-->
<!-- <goal>exec</goal>-->
<!-- </goals>-->
<!-- <phase>initialize</phase>-->
<!-- <configuration>-->
<!-- <workingDirectory>react-app</workingDirectory>-->
<!-- <executable>${npm.executable}</executable>-->
<!-- <arguments>-->
<!-- <argument>install</argument>-->
<!-- <argument>&#45;&#45;silent</argument>-->
<!-- </arguments>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- <execution>-->
<!-- <id>npm run build (compile)</id>-->
<!-- <goals>-->
<!-- <goal>exec</goal>-->
<!-- </goals>-->
<!-- <phase>compile</phase>-->
<!-- <configuration>-->
<!-- <workingDirectory>react-app</workingDirectory>-->
<!-- <executable>${npm.executable}</executable>-->
<!-- <arguments>-->
<!-- <argument>run</argument>-->
<!-- <argument>${npm.build.command}</argument>-->
<!-- </arguments>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- <configuration>-->
<!-- <workingDirectory>${npm.working.dir}</workingDirectory>-->
<!-- </configuration>-->
<!-- </plugin>-->
</plugins>
</build>
<profiles>

@ -10,15 +10,17 @@
},
"license": "Apache License 2.0",
"dependencies": {
"@ant-design/compatible": "^1.0.0",
"@ant-design/dark-theme": "^0.2.2",
"@ant-design/icons": "^4.0.6",
"@babel/polyfill": "^7.6.0",
"acorn": "^6.2.0",
"antd": "^3.23.6",
"antd": "^4.0.0",
"axios": "^0.19.0",
"babel-eslint": "^9.0.0",
"d3": "^5.9.7",
"dagre": "^0.8.4",
"entgra-icons-react": "^1.0.0",
"eslint": "^5.16.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
@ -58,6 +60,7 @@
"chai": "^4.1.2",
"cross-env": "^7.0.0",
"css-loader": "^0.28.11",
"entgra-icons": "^1.4.0",
"eslint": "^5.16.0",
"eslint-config-prettier": "4.3.0",
"eslint-plugin-babel": "5.3.0",

@ -18,73 +18,69 @@
},
"defaultPlatformIcons": {
"default": {
"icon": "global",
"color": "#535c68",
"theme": "outlined"
"icon": "fw-globe",
"color": "#535c68"
},
"android": {
"icon": "android",
"color": "#7db343",
"theme": "filled"
"icon": "fw-android",
"color": "#7db343"
},
"ios": {
"icon": "apple",
"color": "#535c68",
"theme": "filled"
"icon": "fw-apple",
"color": "#535c68"
},
"windows": {
"icon": "windows",
"color": "#008cc4",
"theme": "filled"
"icon": "fw-windows",
"color": "#008cc4"
}
},
"lifecycle": {
"CREATED": {
"title": "Created",
"text": "The initial most state of an application.\n You can only proceed to one of the following states:",
"icon": "file-text",
"icon": "fw-document",
"step": 0
},
"IN-REVIEW": {
"title": "In-Review",
"text": "In this state the application is being reviewed by approvers. You can move from this state to APPROVED state if it is approved by reviewers. Otherwise, you can move the application into either REJECTED state or CREATED state based on the feedback getting by reviewers.",
"icon": "audit",
"icon": "fw-throttling-policy",
"step": 1
},
"APPROVED": {
"title": "Approved",
"text": "The approved state is a compulsory state prior to publishing the application.\n You can only proceed to one of the following states:",
"icon": "file-done",
"icon": "fw-check",
"step": 2
},
"PUBLISHED": {
"title": "Published",
"text": "The state which is applied for applications which are qualified for your Corporate App Store. Only the applications of Published state can be installed to your corporate devices.\n You can only proceed to one of the following states:",
"icon": "global",
"icon": "fw-globe",
"step": 3
},
"BLOCKED": {
"title": "Blocked",
"text": "This state allows you to block your application either to publish or deprecate at a future date.\n You can only proceed to one of the following states:",
"icon": "exception",
"icon": "fw-lock",
"step": 4
},
"DEPRECATED": {
"title": "Deprecated",
"text": "The applications which are outdated and no longer suit your app store.\n You can only proceed to one of the following states:",
"icon": "file-excel",
"icon": "fw-warning",
"step": 5
},
"REJECTED": {
"title": "Rejected",
"text": "The Approvers can reject an application due to a faulty of the app or not being in compliance with company policies.\n You can only proceed to one of the following states:",
"icon": "frown",
"icon": "fw-error",
"step": 6
},
"RETIRED": {
"title": "Retired",
"text": "The final state of an application, where no transition of states will be allowed after this.",
"icon": "rest",
"icon": "fw-delete",
"step": 7
}
},

@ -17,7 +17,8 @@
*/
import React from 'react';
import { notification, Menu, Icon } from 'antd';
import { LogoutOutlined } from '@ant-design/icons';
import { notification, Menu } from 'antd';
import axios from 'axios';
import { withConfigContext } from '../../../../components/ConfigContext';
@ -70,7 +71,7 @@ class Logout extends React.Component {
return (
<Menu>
<Menu.Item key="1" onClick={this.handleSubmit}>
<Icon type="logout" />
<LogoutOutlined />
Logout
</Menu.Item>
</Menu>

@ -17,7 +17,19 @@
*/
import React from 'react';
import { Layout, Menu, Icon, Drawer, Button } from 'antd';
import {
AndroidFilled,
AppstoreOutlined,
ControlOutlined,
PlusOutlined,
SettingOutlined,
UserOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
} from '@ant-design/icons';
import { Layout, Menu, Drawer, Button } from 'antd';
import { Switch, Link } from 'react-router-dom';
import RouteWithSubRoutes from '../../components/RouteWithSubRoutes';
import { Redirect } from 'react-router';
@ -81,7 +93,7 @@ class Dashboard extends React.Component {
>
<Menu.Item key="1">
<Link to="/publisher/apps">
<Icon type="appstore" />
<AppstoreOutlined />
Apps
</Link>
</Menu.Item>
@ -92,7 +104,7 @@ class Dashboard extends React.Component {
<SubMenu
title={
<span className="submenu-title-wrapper">
<Icon type="plus" />
<PlusOutlined />
Add New App
</span>
}
@ -118,21 +130,20 @@ class Dashboard extends React.Component {
<SubMenu
title={
<span className="submenu-title-wrapper">
<Icon type="control" />
<ControlOutlined />
Manage
</span>
}
>
<Menu.Item key="manage">
<Link to="/publisher/manage">
<Icon type="setting" /> General
<SettingOutlined /> General
</Link>
</Menu.Item>
{this.config.androidEnterpriseToken != null && (
<Menu.Item key="manage-android-enterprise">
<Link to="/publisher/manage/android-enterprise">
<Icon type="android" theme="filled" /> Android
Enterprise
<AndroidFilled /> Android Enterprise
</Link>
</Menu.Item>
)}
@ -142,7 +153,7 @@ class Dashboard extends React.Component {
className="profile"
title={
<span className="submenu-title-wrapper">
<Icon type="user" />
<UserOutlined />
{this.config.username}
</span>
}
@ -157,10 +168,11 @@ class Dashboard extends React.Component {
<Layout className="mobile-layout">
<div className="mobile-menu-button">
<Button type="link" onClick={this.showMobileNavigationBar}>
<Icon
type={this.state.collapsed ? 'menu-fold' : 'menu-unfold'}
className="bar-icon"
/>
{this.state.collapsed ? (
<MenuFoldOutlined />
) : (
<MenuUnfoldOutlined />
)}
</Button>
</div>
</Layout>
@ -194,14 +206,14 @@ class Dashboard extends React.Component {
>
<Menu.Item key="1">
<Link to="/publisher/apps">
<Icon type="appstore" />
<AppstoreOutlined />
Apps
</Link>
</Menu.Item>
<SubMenu
title={
<span className="submenu-title-wrapper">
<Icon type="plus" />
<PlusOutlined />
Add New App
</span>
}
@ -223,7 +235,7 @@ class Dashboard extends React.Component {
</SubMenu>
<Menu.Item key="2">
<Link to="/publisher/manage">
<Icon type="control" />
<ControlOutlined />
Manage
</Link>
</Menu.Item>
@ -238,7 +250,7 @@ class Dashboard extends React.Component {
<SubMenu
title={
<span className="submenu-title-wrapper">
<Icon type="user" />
<UserOutlined />
</span>
}
>

@ -17,7 +17,9 @@
*/
import React from 'react';
import { Alert, Button, Col, Form, Input, Row, Select, Spin } from 'antd';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Alert, Button, Col, Input, Row, Select, Spin } from 'antd';
import axios from 'axios';
import { withConfigContext } from '../../../../../../../../components/ConfigContext';
import { handleApiError } from '../../../../../../../../services/utils/errorHandler';

@ -17,11 +17,12 @@
*/
import React from 'react';
import { MinusOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
Button,
Col,
Form,
Icon,
Input,
Row,
Select,
@ -280,7 +281,7 @@ class NewAppUploadForm extends React.Component {
} = this.state;
const uploadButton = (
<div>
<Icon type="plus" />
<PlusOutlined />
<div className="ant-upload-text">Select</div>
</div>
);
@ -315,7 +316,7 @@ class NewAppUploadForm extends React.Component {
>
{binaryFiles.length !== 1 && (
<Button>
<Icon type="upload" /> Click to upload
<UploadOutlined /> Click to upload
</Button>
)}
</Upload>,
@ -577,7 +578,7 @@ class NewAppUploadForm extends React.Component {
<Button
type="dashed"
shape="circle"
icon="minus"
icon={<MinusOutlined />}
onClick={() => {
metaData.splice(index, 1);
this.setState({
@ -592,7 +593,7 @@ class NewAppUploadForm extends React.Component {
})}
<Button
type="dashed"
icon="plus"
icon={<PlusOutlined />}
onClick={this.addNewMetaData}
>
Add

@ -17,7 +17,9 @@
*/
import React from 'react';
import { Card, Button, Steps, Row, Col, Form, Result, Spin } from 'antd';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Steps, Row, Col, Result, Spin } from 'antd';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
import NewAppDetailsForm from './components/NewAppDetailsForm';

@ -17,7 +17,8 @@
*/
import React from 'react';
import { PageHeader, Typography, Breadcrumb, Icon, Result } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { PageHeader, Typography, Breadcrumb, Result } from 'antd';
import AddNewAppForm from '../../components/AddNewAppForm';
import { Link } from 'react-router-dom';
import Authorized from '../../../../../../components/Authorized/Authorized';
@ -58,7 +59,7 @@ class AddNewCustomApp extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Add New Custom App</Breadcrumb.Item>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { PageHeader, Typography, Breadcrumb, Icon, Result } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { PageHeader, Typography, Breadcrumb, Result } from 'antd';
import AddNewAppForm from '../../components/AddNewAppForm';
import { Link } from 'react-router-dom';
import Authorized from '../../../../../../components/Authorized/Authorized';
@ -52,7 +53,7 @@ class AddNewEnterpriseApp extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Add New Enterprise App</Breadcrumb.Item>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { Icon, PageHeader, Typography, Breadcrumb, Result } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { PageHeader, Typography, Breadcrumb, Result } from 'antd';
import AddNewAppForm from '../../components/AddNewAppForm';
import { Link } from 'react-router-dom';
import Authorized from '../../../../../../components/Authorized/Authorized';
@ -59,7 +60,7 @@ class AddNewPublicApp extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Add New Public App</Breadcrumb.Item>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { Icon, PageHeader, Typography, Breadcrumb, Result } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { PageHeader, Typography, Breadcrumb, Result } from 'antd';
import AddNewAppForm from '../../components/AddNewAppForm';
import { Link } from 'react-router-dom';
import Authorized from '../../../../../../components/Authorized/Authorized';
@ -55,7 +56,7 @@ class AddNewEnterpriseApp extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Add New Web Clip</Breadcrumb.Item>

@ -17,7 +17,9 @@
*/
import React from 'react';
import { Form, notification, Spin, Card, Row, Col } from 'antd';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { notification, Spin, Card, Row, Col } from 'antd';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
import { withConfigContext } from '../../../../../../components/ConfigContext';

@ -17,7 +17,8 @@
*/
import React from 'react';
import { Icon, PageHeader, Typography, Breadcrumb } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { PageHeader, Typography, Breadcrumb } from 'antd';
import AddNewReleaseForm from './components/AddNewReleaseForm';
import { Link } from 'react-router-dom';
@ -40,7 +41,7 @@ class AddNewRelease extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Add New Release</Breadcrumb.Item>

@ -29,7 +29,6 @@ import {
Button,
Spin,
message,
Icon,
Card,
Badge,
Tooltip,
@ -48,7 +47,14 @@ import ManagedConfigurationsIframe from './components/ManagedConfigurationsIfram
import { handleApiError } from '../../../../../../../../../services/utils/errorHandler';
import Authorized from '../../../../../../../../../components/Authorized/Authorized';
import { isAuthorized } from '../../../../../../../../../services/utils/authorizationHandler';
import { MoreOutlined } from '@ant-design/icons';
import {
CheckCircleOutlined,
EditOutlined,
MoreOutlined,
StarOutlined,
UploadOutlined,
CheckOutlined,
} from '@ant-design/icons';
import DeleteApp from './components/DeleteApp';
import RetireApp from './components/RetireApp';
@ -56,13 +62,6 @@ const { Meta } = Card;
const { Text, Title } = Typography;
const { Option } = Select;
const IconText = ({ type, text }) => (
<span>
<Icon type={type} style={{ marginRight: 8 }} />
{text}
</span>
);
const modules = {
toolbar: [
['bold', 'italic', 'underline', 'strike', 'blockquote'],
@ -603,13 +602,12 @@ class AppDetailsDrawer extends React.Component {
title="Published"
count={
<Tooltip title="Published">
<Icon
<CheckCircleOutlined
style={{
backgroundColor: '#52c41a',
borderRadius: '50%',
color: 'white',
}}
type="check-circle"
/>
</Tooltip>
}
@ -633,24 +631,15 @@ class AppDetailsDrawer extends React.Component {
description={
<div
style={{
fontSize: '0.7em',
fontSize: '0.8em',
}}
className="description-view"
>
<IconText
type="check"
text={release.currentStatus}
/>
<CheckOutlined /> {release.currentStatus}
<Divider type="vertical" />
<IconText
type="upload"
text={release.releaseType}
/>
<UploadOutlined /> {release.releaseType}
<Divider type="vertical" />
<IconText
type="star-o"
text={release.rating.toFixed(1)}
/>
<StarOutlined /> {release.rating.toFixed(1)}
</div>
}
/>
@ -698,7 +687,7 @@ class AppDetailsDrawer extends React.Component {
}}
onClick={this.enableDescriptionEdit}
>
<Icon type="edit" />
<EditOutlined />
</Text>
)
}
@ -754,7 +743,7 @@ class AppDetailsDrawer extends React.Component {
}}
onClick={this.enableCategoriesEdit}
>
<Icon type="edit" />
<EditOutlined />
</Text>
)
}
@ -821,7 +810,7 @@ class AppDetailsDrawer extends React.Component {
}}
onClick={this.enableTagsEdit}
>
<Icon type="edit" />
<EditOutlined />
</Text>
)
}

@ -17,13 +17,15 @@
*/
import React from 'react';
import { Avatar, Table, Tag, Icon, Badge, Alert, Tooltip } from 'antd';
import { CheckCircleOutlined } from '@ant-design/icons';
import { Avatar, Table, Tag, Badge, Alert, Tooltip } from 'antd';
import axios from 'axios';
import pSBC from 'shade-blend-color';
import './styles.css';
import { withConfigContext } from '../../../../../../../../components/ConfigContext';
import AppDetailsDrawer from './AppDetailsDrawer';
import { handleApiError } from '../../../../../../../../services/utils/errorHandler';
import { EntgraIcon } from 'entgra-icons-react';
let config = null;
@ -69,13 +71,12 @@ const columns = [
}}
count={
<Tooltip title="Published">
<Icon
<CheckCircleOutlined
style={{
backgroundColor: '#52c41a',
borderRadius: '50%',
color: 'white',
}}
type="check-circle"
/>
</Tooltip>
}
@ -139,15 +140,13 @@ const columns = [
const defaultPlatformIcons = config.defaultPlatformIcons;
let icon = defaultPlatformIcons.default.icon;
let color = defaultPlatformIcons.default.color;
let theme = defaultPlatformIcons.default.theme;
if (defaultPlatformIcons.hasOwnProperty(platform)) {
icon = defaultPlatformIcons[platform].icon;
color = defaultPlatformIcons[platform].color;
theme = defaultPlatformIcons[platform].theme;
}
return (
<span style={{ fontSize: 20, color: color, textAlign: 'center' }}>
<Icon type={icon} theme={theme} />
<EntgraIcon type={icon} />
</span>
);
},

@ -17,16 +17,9 @@
*/
import React from 'react';
import {
Card,
Col,
Row,
Typography,
Divider,
Select,
Button,
Form,
} from 'antd';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Col, Row, Typography, Divider, Select, Button } from 'antd';
import axios from 'axios';
import { withConfigContext } from '../../../../../../../../components/ConfigContext';
import { handleApiError } from '../../../../../../../../services/utils/errorHandler';
@ -196,7 +189,8 @@ class FiltersForm extends React.Component {
permission="/permission/admin/app-mgt/publisher/application/update"
yes={
<div>
<Form.Item label="Categories">
<p>Categories:</p>
<Form.Item>
{getFieldDecorator('categories', {
rules: [
{
@ -221,7 +215,8 @@ class FiltersForm extends React.Component {
</Select>,
)}
</Form.Item>
<Form.Item label="Tags">
<p>Tags:</p>
<Form.Item>
{getFieldDecorator('tags', {
rules: [
{
@ -244,10 +239,11 @@ class FiltersForm extends React.Component {
</div>
}
/>
<p>Device Type:</p>
<Authorized
permission="/permission/admin/device-mgt/admin/device-type/view"
yes={
<Form.Item label="Device Type">
<Form.Item>
{getFieldDecorator('deviceType', {
rules: [
{
@ -271,7 +267,8 @@ class FiltersForm extends React.Component {
</Form.Item>
}
/>
<Form.Item label="App Type">
<p>App Type:</p>
<Form.Item>
{getFieldDecorator('appType', {})(
<Select style={{ width: '100%' }} placeholder="Select app type">
<Option value="ENTERPRISE">Enterprise</Option>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { Row, Typography, Icon } from 'antd';
import { TeamOutlined } from '@ant-design/icons';
import { Row, Typography } from 'antd';
import StarRatings from 'react-star-ratings';
import './styles.css';
import axios from 'axios';
@ -118,7 +119,7 @@ class DetailedRating extends React.Component {
/>
<br />
<Text type="secondary" className="people-count">
<Icon type="team" /> {totalCount} total
<TeamOutlined /> {totalCount} total
</Text>
</div>
<div className="bar-containers">

@ -17,6 +17,7 @@
*/
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Modal, Button, Tag, List, Typography } from 'antd';
import pSBC from 'shade-blend-color';
import { withConfigContext } from '../../../../../../../../../../components/ConfigContext';
@ -47,7 +48,11 @@ class LifeCycleDetailsModal extends React.Component {
const { lifecycle } = this.props;
return (
<div>
<Button size="small" icon="question-circle" onClick={this.showModal}>
<Button
size="small"
icon={<QuestionCircleOutlined />}
onClick={this.showModal}
>
Learn more
</Button>
<Modal

@ -25,7 +25,6 @@ import {
Modal,
notification,
Steps,
Icon,
Alert,
Tabs,
} from 'antd';
@ -36,7 +35,7 @@ import './styles.css';
import { withConfigContext } from '../../../../../../../../components/ConfigContext';
import { handleApiError } from '../../../../../../../../services/utils/errorHandler';
import LifeCycleHistory from './components/LifeCycleHistory';
import { EntgraIcon } from 'entgra-icons-react';
const { Text, Title, Paragraph } = Typography;
const { TabPane } = Tabs;
@ -216,7 +215,6 @@ class LifeCycle extends React.Component {
) {
proceedingStates = lifecycle[currentStatus].proceedingStates;
}
return (
<div>
<Title level={4}>Manage Lifecycle</Title>
@ -236,36 +234,38 @@ class LifeCycle extends React.Component {
onChange={this.onChange}
size="small"
>
{lifecycleSteps.map((step, index) => (
<Step
key={index}
icon={<Icon type={step.icon} />}
title={step.title}
disabled={current !== step.step}
description={
current === step.step && (
<div style={{ width: 400 }}>
<p>{step.text}</p>
{proceedingStates.map(lifecycleState => {
return (
<Button
size={'small'}
style={{ marginRight: 3 }}
onClick={() =>
this.showReasonModal(lifecycleState)
}
key={lifecycleState}
type={'primary'}
>
{lifecycleState}
</Button>
);
})}
</div>
)
}
/>
))}
{lifecycleSteps.map((step, index) => {
return (
<Step
key={index}
icon={<EntgraIcon type={step.icon} />}
title={step.title}
disabled={current !== step.step}
description={
current === step.step && (
<div style={{ width: 400 }}>
<p>{step.text}</p>
{proceedingStates.map(lifecycleState => {
return (
<Button
size={'small'}
style={{ marginRight: 3 }}
onClick={() =>
this.showReasonModal(lifecycleState)
}
key={lifecycleState}
type={'primary'}
>
{lifecycleState}
</Button>
);
})}
</div>
)
}
/>
);
})}
</Steps>
</div>
</TabPane>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { Modal, Button, Icon, notification } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { Modal, Button, notification } from 'antd';
import axios from 'axios';
import { handleApiError } from '../../../../../../../../../../services/utils/errorHandler';
import { withConfigContext } from '../../../../../../../../../../components/ConfigContext';
@ -77,7 +78,7 @@ class DeleteRelease extends React.Component {
type="danger"
onClick={this.showModal}
>
<Icon type="delete" /> Delete
<DeleteOutlined /> Delete
</Button>
</>
);

@ -17,16 +17,22 @@
*/
import React from 'react';
import {
EditOutlined,
MinusOutlined,
PlusOutlined,
UploadOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
Modal,
Button,
Icon,
notification,
Spin,
Tooltip,
Upload,
Input,
Form,
Divider,
Row,
Col,
@ -397,7 +403,7 @@ class EditReleaseModal extends React.Component {
const config = this.props.context;
const uploadButton = (
<div>
<Icon type="plus" />
<PlusOutlined />
<div className="ant-upload-text">Select</div>
</div>
);
@ -417,7 +423,7 @@ class EditReleaseModal extends React.Component {
type="primary"
onClick={this.showModal}
>
<Icon type="edit" /> Edit
<EditOutlined /> Edit
</Button>
</Tooltip>
<Modal
@ -450,7 +456,7 @@ class EditReleaseModal extends React.Component {
>
{binaryFiles.length !== 1 && (
<Button>
<Icon type="upload" /> Change
<UploadOutlined /> Change
</Button>
)}
</Upload>,
@ -676,7 +682,7 @@ class EditReleaseModal extends React.Component {
<Button
type="dashed"
shape="circle"
icon="minus"
icon={<MinusOutlined />}
onClick={() => {
metaData.splice(index, 1);
this.setState({
@ -691,7 +697,7 @@ class EditReleaseModal extends React.Component {
})}
<Button
type="dashed"
icon="plus"
icon={<PlusOutlined />}
onClick={this.addNewMetaData}
>
Add

@ -63,7 +63,7 @@ class SingleReview extends React.Component {
);
return (
<div>
<div style={{ width: '100%' }}>
<List.Item.Meta
avatar={
<Avatar

@ -17,16 +17,8 @@
*/
import React from 'react';
import {
Divider,
Row,
Col,
Typography,
Button,
Icon,
Tooltip,
Alert,
} from 'antd';
import { ShopOutlined } from '@ant-design/icons';
import { Divider, Row, Col, Typography, Button, Tooltip, Alert } from 'antd';
import StarRatings from 'react-star-ratings';
import Reviews from './components/Reviews';
import '../../../../../../../../App.css';
@ -35,6 +27,7 @@ import EditRelease from './components/EditRelease';
import { withConfigContext } from '../../../../../../../../components/ConfigContext';
import Authorized from '../../../../../../../../components/Authorized/Authorized';
import DeleteRelease from './components/DeleteRelease';
import { EntgraIcon } from 'entgra-icons-react';
const { Title, Text, Paragraph } = Typography;
@ -64,12 +57,10 @@ class ReleaseView extends React.Component {
const defaultPlatformIcons = config.defaultPlatformIcons;
let icon = defaultPlatformIcons.default.icon;
let color = defaultPlatformIcons.default.color;
let theme = defaultPlatformIcons.default.theme;
if (defaultPlatformIcons.hasOwnProperty(platform)) {
icon = defaultPlatformIcons[platform].icon;
color = defaultPlatformIcons[platform].color;
theme = defaultPlatformIcons[platform].theme;
}
let metaData = [];
try {
@ -98,7 +89,7 @@ class ReleaseView extends React.Component {
<br />
<Text>Platform : </Text>
<span style={{ fontSize: 20, color: color, textAlign: 'center' }}>
<Icon type={icon} theme={theme} />
<EntgraIcon type={icon} />
</span>
<Divider type="vertical" />
<Text>Version : {release.version}</Text>
@ -140,7 +131,7 @@ class ReleaseView extends React.Component {
style={{ float: 'right' }}
htmlType="button"
type="primary"
icon="shop"
icon={<ShopOutlined />}
disabled={!isAppInstallable}
onClick={() => {
window.open(
@ -161,7 +152,7 @@ class ReleaseView extends React.Component {
</Col>
</Row>
<Divider />
<Row className="release-images">
<Row className="release-images" style={{ flexFlow: 'nowrap' }}>
{release.screenshots.map((screenshotUrl, index) => {
return (
<div key={index} className="release-screenshot">

@ -17,11 +17,11 @@
*/
import React from 'react';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
Card,
Tag,
message,
Icon,
Input,
notification,
Divider,
@ -157,11 +157,10 @@ class ManageCategories extends React.Component {
<>
<Divider type="vertical" />
<Tooltip title="edit">
<Icon
<EditOutlined
onClick={() => {
this.openEditModal(categoryName);
}}
type="edit"
/>
</Tooltip>
<Divider type="vertical" />
@ -182,7 +181,7 @@ class ManageCategories extends React.Component {
okText="Yes"
cancelText="No"
>
<Icon type="delete" />
<DeleteOutlined />
</Popconfirm>
</Tooltip>
</>
@ -399,7 +398,7 @@ class ManageCategories extends React.Component {
{!isAddNewVisible && (
<div style={{ float: 'right' }}>
<Button
icon="plus"
icon={<PlusOutlined />}
// type="primary"
size="small"
onClick={() => {
@ -456,7 +455,7 @@ class ManageCategories extends React.Component {
onClick={this.showInput}
style={{ background: '#fff', borderStyle: 'dashed' }}
>
<Icon type="plus" /> New Category
<PlusOutlined /> New Category
</Tag>
)}
</TweenOneGroup>

@ -17,11 +17,11 @@
*/
import React from 'react';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
Card,
Tag,
message,
Icon,
Input,
notification,
Divider,
@ -151,11 +151,10 @@ class ManageTags extends React.Component {
<>
<Divider type="vertical" />
<Tooltip title="edit">
<Icon
<EditOutlined
onClick={() => {
this.openEditModal(tagName);
}}
type="edit"
/>
</Tooltip>
<Divider type="vertical" />
@ -176,7 +175,7 @@ class ManageTags extends React.Component {
okText="Yes"
cancelText="No"
>
<Icon type="delete" />
<DeleteOutlined />
</Popconfirm>
</Tooltip>
</>
@ -390,7 +389,7 @@ class ManageTags extends React.Component {
{!isAddNewVisible && (
<div style={{ float: 'right' }}>
<Button
icon="plus"
icon={<PlusOutlined />}
// type="primary"
size="small"
onClick={() => {
@ -447,7 +446,7 @@ class ManageTags extends React.Component {
onClick={this.showInput}
style={{ background: '#fff', borderStyle: 'dashed' }}
>
<Icon type="plus" /> New Tag
<PlusOutlined /> New Tag
</Tag>
)}
</TweenOneGroup>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { PageHeader, Typography, Breadcrumb, Row, Col, Icon } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { PageHeader, Typography, Breadcrumb, Row, Col } from 'antd';
import ManageCategories from './components/Categories';
import ManageTags from './components/Tags';
import { Link } from 'react-router-dom';
@ -40,7 +41,7 @@ class Manage extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Manage</Breadcrumb.Item>

@ -18,13 +18,13 @@
import React from 'react';
import axios from 'axios';
import { DeleteOutlined, HomeOutlined } from '@ant-design/icons';
import {
Tag,
notification,
Table,
Typography,
Divider,
Icon,
Popconfirm,
Button,
} from 'antd';
@ -239,7 +239,7 @@ class Pages extends React.Component {
<Button
disabled={page.id === this.state.homePageId}
className="btn-warning"
icon="home"
icon={<HomeOutlined />}
type="link"
onClick={() => {
this.updateHomePage(page.id);
@ -259,7 +259,7 @@ class Pages extends React.Component {
>
<span className="action">
<Text type="danger">
<Icon type="delete" /> delete
<DeleteOutlined /> delete
</Text>
</span>
</Popconfirm>

@ -17,6 +17,7 @@
*/
import React from 'react';
import { SyncOutlined } from '@ant-design/icons';
import { Button, notification } from 'antd';
import axios from 'axios';
import { withConfigContext } from '../../../../../../../../components/ConfigContext';
@ -69,7 +70,7 @@ class SyncAndroidApps extends React.Component {
loading={loading}
style={{ marginTop: 16 }}
type="primary"
icon="sync"
icon={<SyncOutlined />}
>
Sync{loading && 'ing...'}
</Button>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { PageHeader, Breadcrumb, Divider, Icon, Result } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { PageHeader, Breadcrumb, Divider, Result } from 'antd';
import { Link } from 'react-router-dom';
import SyncAndroidApps from './components/SyncAndroidApps';
import { withConfigContext } from '../../../../../../components/ConfigContext';
@ -41,7 +42,7 @@ class ManageAndroidEnterprise extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Manage</Breadcrumb.Item>

@ -17,7 +17,8 @@
*/
import React from 'react';
import { Modal, Icon, Table, Avatar } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Modal, Table, Avatar } from 'antd';
import '../../styles.css';
import { withConfigContext } from '../../../../../../../../../../../../components/ConfigContext';
@ -84,7 +85,7 @@ class AddAppsToClusterModal extends React.Component {
<div className="btn-add-new-wrapper">
<div className="btn-add-new">
<button className="btn" onClick={this.showModal}>
<Icon style={{ position: 'relative' }} type="plus" />
<PlusOutlined style={{ position: 'relative' }} />
</button>
</div>
<div className="title">Add app</div>

@ -17,11 +17,18 @@
*/
import React from 'react';
import {
CaretDownOutlined,
CaretLeftFilled,
CaretRightFilled,
CaretUpOutlined,
CloseCircleFilled,
DeleteOutlined,
} from '@ant-design/icons';
import {
Button,
Col,
Divider,
Icon,
message,
notification,
Popconfirm,
@ -304,7 +311,7 @@ class Cluster extends React.Component {
this.swapProduct(index, index - 1);
}}
>
<Icon type="caret-left" theme="filled" />
<CaretLeftFilled />
</button>
)}
</div>
@ -324,7 +331,7 @@ class Cluster extends React.Component {
}}
className="btn btn-right"
>
<Icon type="caret-right" theme="filled" />
<CaretRightFilled />
</button>
</div>
<div className="delete-btn">
@ -334,7 +341,7 @@ class Cluster extends React.Component {
this.removeProduct(index);
}}
>
<Icon type="close-circle" theme="filled" />
<CloseCircleFilled />
</button>
</div>
</>
@ -363,7 +370,7 @@ class Cluster extends React.Component {
<Tooltip title="Move Up">
<Button
type="link"
icon="caret-up"
icon={<CaretUpOutlined />}
size="large"
onClick={() => {
this.props.swapClusters(index, index - 1);
@ -374,7 +381,7 @@ class Cluster extends React.Component {
<Tooltip title="Move Down">
<Button
type="link"
icon="caret-down"
icon={<CaretDownOutlined />}
size="large"
onClick={() => {
this.props.swapClusters(index, index + 1);
@ -391,7 +398,7 @@ class Cluster extends React.Component {
>
<Button
type="danger"
icon="delete"
icon={<DeleteOutlined />}
shape="circle"
htmlType="button"
/>

@ -17,12 +17,12 @@
*/
import React from 'react';
import { HomeOutlined, PlusOutlined } from '@ant-design/icons';
import {
PageHeader,
Typography,
Breadcrumb,
Button,
Icon,
Col,
Row,
notification,
@ -326,7 +326,7 @@ class Page extends React.Component {
<Breadcrumb style={{ paddingBottom: 16 }}>
<Breadcrumb.Item>
<Link to="/publisher/apps">
<Icon type="home" /> Home
<HomeOutlined /> Home
</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Manage</Breadcrumb.Item>
@ -406,7 +406,7 @@ class Page extends React.Component {
<Button
type="dashed"
shape="round"
icon="plus"
icon={<PlusOutlined />}
size="large"
onClick={() => {
this.toggleAddNewClusterVisibility(true);

@ -17,12 +17,13 @@
*/
import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
Typography,
Row,
Col,
Form,
Icon,
Input,
Button,
message,
@ -156,7 +157,7 @@ class NormalLoginForm extends React.Component {
})(
<Input
style={{ height: 32 }}
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Username"
/>,
)}
@ -167,7 +168,7 @@ class NormalLoginForm extends React.Component {
})(
<Input
style={{ height: 32 }}
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
prefix={<LockOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Password"
/>,

@ -69,7 +69,6 @@
<phase>generate-resources</phase>
<configuration>
<nodeVersion>${node.version}</nodeVersion>
<npmVersion>${npm.version}</npmVersion>
</configuration>
</execution>
<execution>

@ -95,7 +95,7 @@ public class FCMNotificationStrategy implements NotificationStrategy {
OutputStream os = null;
byte[] bytes = getFCMRequest(message, getFCMToken(device.getProperties())).getBytes();
HttpURLConnection conn;
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(FCM_ENDPOINT).openConnection();
conn.setRequestProperty("Content-Type", "application/json");
@ -108,6 +108,9 @@ public class FCMNotificationStrategy implements NotificationStrategy {
if (os != null) {
os.close();
}
if (conn != null) {
conn.disconnect();
}
}
int status = conn.getResponseCode();
if (log.isDebugEnabled()) {

@ -2273,4 +2273,58 @@ public interface DeviceManagementService {
response = ErrorResponse.class)
})
Response getDeviceFilters();
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{clientId}/{clientSecret}/default-token")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the default token",
notes = "Getting the default access token by using given client ID and the client secret value.",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:enroll")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully returned the default token details.",
response = Policy.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the default token.",
response = ErrorResponse.class)
}
)
Response getDefaultToken(
@ApiParam(
name = "client ID",
value = "Client Id.",
required = true)
@PathParam("clientId")
String clientId,
@ApiParam(
name = "client secret",
value = "Client Secret",
required = true)
@PathParam("clientSecret")
String clientSecret
);
}

@ -35,7 +35,6 @@
package org.wso2.carbon.device.mgt.jaxrs.service.api;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Info;
import io.swagger.annotations.ExtensionProperty;
@ -50,6 +49,7 @@ import io.swagger.annotations.ResponseHeader;
import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.device.mgt.common.otp.mgt.wrapper.OTPMailWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList;
import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfo;
import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfoList;
@ -1221,4 +1221,50 @@ public interface UserManagementService {
response = ErrorResponse.class)
})
Response getPermissionsOfUser();
@POST
@Path("/one-time-pin")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the permission details of the current user",
notes = "A user may granted more than one permission in IoTS. Using this REST API "
+ "you can get the permission/permission the current user has granted. ",
tags = "User Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:user:permission-view")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of permissions the user "
+ "has granted.",
response = PermissionList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 404,
message = "Not Found. \n The specified resource does not exist.\n",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the "
+ "list of roles assigned to the specified user.",
response = ErrorResponse.class)
})
Response sendEmailVerifyingMail(OTPMailWrapper otpMailWrapper);
}

@ -36,6 +36,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -50,6 +51,9 @@ import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.validation.Valid;
@ -95,6 +99,10 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
device.getEnrolmentInfo().setDateOfEnrolment(System.currentTimeMillis());
device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis());
boolean status = dms.enrollDevice(device);
PolicyAdministratorPoint pap = DeviceMgtAPIUtils.getPolicyManagementService().getPAP();
DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
DeviceMgtAPIUtils.getPolicyManagementService().getEffectivePolicy(deviceId);
pap.publishChanges();
return Response.status(Response.Status.OK).entity(status).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while enrolling the device, which carries the id '" +
@ -104,6 +112,9 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
} catch (InvalidConfigurationException e) {
log.error("failed to add operation", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (PolicyManagementException e) {
log.error("failed to add designated policies against newly enrolled device.", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}

@ -38,11 +38,13 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import java.util.LinkedList;
import java.util.Queue;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceFilters;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -102,6 +104,10 @@ import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException;
@ -1328,4 +1334,21 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/{clientId}/{clientSecret}/default-token")
@Override
public Response getDefaultToken(@PathParam("clientId") String clientId, @PathParam("clientSecret") String clientSecret) {
JWTClientManagerService jwtClientManagerService = DeviceMgtAPIUtils.getJWTClientManagerService();
try {
JWTClient jwtClient = jwtClientManagerService.getJWTClient();
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(clientId, clientSecret,
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(), "default");
return Response.status(Response.Status.OK).entity(accessTokenInfo).build();
} catch (JWTClientException e) {
String msg = "Error occurred while getting default access token by using given client Id and client secret.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -25,15 +25,19 @@ import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
@ -42,6 +46,10 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
@ -259,6 +267,16 @@ public class GroupManagementServiceImpl implements GroupManagementService {
public Response addDevicesToGroup(int groupId, List<DeviceIdentifier> deviceIdentifiers) {
try {
DeviceMgtAPIUtils.getGroupManagementProviderService().addDevices(groupId, deviceIdentifiers);
PolicyAdministratorPoint pap = DeviceMgtAPIUtils.getPolicyManagementService().getPAP();
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
for(DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
Device device = dms.getDevice(deviceIdentifier, false);
if(!device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.REMOVED)) {
pap.removePolicyUsed(deviceIdentifier);
DeviceMgtAPIUtils.getPolicyManagementService().getEffectivePolicy(deviceIdentifier);
}
}
pap.publishChanges();
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while adding devices to group.";
@ -266,6 +284,15 @@ public class GroupManagementServiceImpl implements GroupManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceNotFoundException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (PolicyManagementException e) {
log.error("Error occurred while adding policies against device(s).", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// } catch (PolicyEvaluationException e) {
// log.error("Error occurred while retrieving policies against device(s).", e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (DeviceManagementException e) {
log.error("Error occurred while retrieving device information.", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -273,6 +300,16 @@ public class GroupManagementServiceImpl implements GroupManagementService {
public Response removeDevicesFromGroup(int groupId, List<DeviceIdentifier> deviceIdentifiers) {
try {
DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice(groupId, deviceIdentifiers);
PolicyAdministratorPoint pap = DeviceMgtAPIUtils.getPolicyManagementService().getPAP();
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
for(DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
Device device = dms.getDevice(deviceIdentifier, false);
if(!device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.REMOVED)) {
pap.removePolicyUsed(deviceIdentifier);
DeviceMgtAPIUtils.getPolicyManagementService().getEffectivePolicy(deviceIdentifier);
}
}
pap.publishChanges();
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while removing devices from group.";
@ -280,6 +317,12 @@ public class GroupManagementServiceImpl implements GroupManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceNotFoundException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}catch (PolicyManagementException e) {
log.error("Error occurred while adding policies against device(s).", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}catch (DeviceManagementException e) {
log.error("Error occurred while retrieving device information.", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -290,6 +333,8 @@ public class GroupManagementServiceImpl implements GroupManagementService {
deviceIdentifiers.add(deviceToGroupsAssignment.getDeviceIdentifier());
GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService();
List<DeviceGroup> deviceGroups = service.getGroups(deviceToGroupsAssignment.getDeviceIdentifier(), false);
PolicyAdministratorPoint pap = DeviceMgtAPIUtils.getPolicyManagementService().getPAP();
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
for (DeviceGroup group : deviceGroups) {
Integer groupId = group.getGroupId();
if (deviceToGroupsAssignment.getDeviceGroupIds().contains(groupId)) {
@ -300,7 +345,12 @@ public class GroupManagementServiceImpl implements GroupManagementService {
}
for (int groupId : deviceToGroupsAssignment.getDeviceGroupIds()) {
DeviceMgtAPIUtils.getGroupManagementProviderService().addDevices(groupId, deviceIdentifiers);
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
pap.removePolicyUsed(deviceIdentifier);
DeviceMgtAPIUtils.getPolicyManagementService().getEffectivePolicy(deviceIdentifier);
}
}
pap.publishChanges();
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while assigning device to groups.";
@ -308,6 +358,9 @@ public class GroupManagementServiceImpl implements GroupManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceNotFoundException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (PolicyManagementException e) {
log.error("Failed to add policies for device assigned to group.", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -325,4 +378,4 @@ public class GroupManagementServiceImpl implements GroupManagementService {
}
}
}
}

@ -45,8 +45,11 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.OTPManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.spi.OTPManagementService;
import org.wso2.carbon.device.mgt.common.otp.mgt.wrapper.OTPMailWrapper;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
@ -1115,6 +1118,53 @@ public class UserManagementServiceImpl implements UserManagementService {
}
}
/**
* Method used to send an invitation email to a existing user to enroll a device.
*
* @param otpMailWrapper Username list of the users to be invited
*/
@POST
@Path("/one-time-pin")
@Produces({MediaType.APPLICATION_JSON})
public Response sendEmailVerifyingMail(OTPMailWrapper otpMailWrapper) {
if (log.isDebugEnabled()) {
log.debug("Sending enrollment invitation mail to existing user.");
}
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
OTPManagementService oms = DeviceMgtAPIUtils.getOTPManagementService();
try {
String otpToken = oms.createOTPToken(otpMailWrapper);
Properties props = new Properties();
props.setProperty("first-name", otpMailWrapper.getFirstName());
props.setProperty("otp-token", otpToken);
EmailMetaInfo metaInfo = new EmailMetaInfo(otpMailWrapper.getEmail(), props);
dms.sendEnrolmentInvitation(DeviceManagementConstants.EmailAttributes.USER_VERIFY_TEMPLATE,
metaInfo);
} catch (DeviceManagementException e) {
String msg = "Error occurred while inviting user to enrol their device";
if (e.getMessage() != null && !e.getMessage().isEmpty()) {
msg = e.getMessage();
}
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (ConfigurationManagementException e) {
String msg = "Error occurred while sending the email invitations. Mail server not configured.";
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (OTPManagementException e) {
String msg = "Error occurred while generating and storing the OTP data";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (org.wso2.carbon.device.mgt.common.exceptions.BadRequestException e) {
String msg = "Bad Request : Found invalid request payload to create OTP toke.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
return Response.status(Response.Status.OK).entity("Invitation mails have been sent.").build();
}
private Map<String, String> buildDefaultUserClaims(String firstName, String lastName, String emailAddress,
boolean isFresh) {
Map<String, String> defaultUserClaims = new HashMap<>();

@ -52,6 +52,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
import org.wso2.carbon.device.mgt.common.spi.OTPManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion;
@ -134,13 +135,14 @@ public class DeviceMgtAPIUtils {
public static final String DAS_ADMIN_SERVICE_EP = "https://" + DAS_HOST_NAME + ":" + DAS_PORT + "/services/";
private static SSLContext sslContext;
private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class);
private static final Log log = LogFactory.getLog(DeviceMgtAPIUtils.class);
private static KeyStore keyStore;
private static KeyStore trustStore;
private static char[] keyStorePassword;
private static IntegrationClientService integrationClientService;
private static MetadataManagementService metadataManagementService;
private static volatile OTPManagementService otpManagementService;
static {
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
@ -459,6 +461,29 @@ public class DeviceMgtAPIUtils {
return metadataManagementService;
}
/**
* Initializing and accessing method for OTPManagementService.
*
* @return OTPManagementService instance
* @throws IllegalStateException if OTPManagementService cannot be initialized
*/
public static OTPManagementService getOTPManagementService() {
if (otpManagementService == null) {
synchronized (DeviceMgtAPIUtils.class) {
if (otpManagementService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
otpManagementService = (OTPManagementService) ctx.getOSGiService(OTPManagementService.class, null);
if (otpManagementService == null) {
String msg = "OTP Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
}
}
return otpManagementService;
}
/**
* Method for initializing ReportManagementService
* @return ReportManagementServie Instance

@ -48,7 +48,8 @@
<context-param>
<param-name>nonSecuredEndPoints</param-name>
<param-value>
/api/device-mgt/v1.0/users/validate
/api/device-mgt/v1.0/users/validate,
/api/device-mgt/v1.0/users/one-time-pin,
</param-value>
</context-param>

@ -93,6 +93,7 @@ public class DeviceAgentServiceTest {
private static final String AUTHENTICATED_USER = "admin";
private static final String MONITOR_OPERATION = "POLICY_MONITOR";
private static Device demoDevice;
private PolicyManagerService policyManagerService;
@ObjectFactory
public IObjectFactory getObjectFactory() {
@ -108,6 +109,7 @@ public class DeviceAgentServiceTest {
this.deviceAgentService = new DeviceAgentServiceImpl();
this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class,
Mockito.RETURNS_MOCKS);
this.policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS);
this.privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class, Mockito.RETURNS_MOCKS);
this.eventStreamAdminServiceStub = Mockito.mock(EventStreamAdminServiceStub.class, Mockito.RETURNS_MOCKS);
demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
@ -167,6 +169,8 @@ public class DeviceAgentServiceTest {
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser"))
.toReturn(AUTHENTICATED_USER);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagerService);
EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
demoDevice.setEnrolmentInfo(enrolmentInfo);

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
@ -42,10 +43,12 @@ import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceToGroupsAssignment;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
@ -61,6 +64,8 @@ import java.util.List;
public class GroupManagementServiceImplTest {
private GroupManagementService groupManagementService;
private GroupManagementProviderService groupManagementProviderService;
private PolicyManagerService policyManagerService;
private DeviceManagementProviderService deviceManagementProviderService;
private PrivilegedCarbonContext context;
@ObjectFactory
@ -72,6 +77,8 @@ public class GroupManagementServiceImplTest {
public void init() {
groupManagementService = new GroupManagementServiceImpl();
groupManagementProviderService = Mockito.mock(GroupManagementProviderService.class);
this.policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS);
this.deviceManagementProviderService = Mockito.mock(DeviceManagementProviderService.class, Mockito.RETURNS_MOCKS);
context = Mockito.mock(PrivilegedCarbonContext.class);
Mockito.doReturn("admin").when(context).getUsername();
}
@ -298,6 +305,10 @@ public class GroupManagementServiceImplTest {
public void testAddDevicesToGroup() throws GroupManagementException, DeviceNotFoundException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService"))
.toReturn(groupManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagerService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(deviceManagementProviderService);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
Mockito.doNothing().when(groupManagementProviderService).addDevices(1, deviceIdentifiers);
Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).addDevices(2,
@ -319,6 +330,10 @@ public class GroupManagementServiceImplTest {
public void testRemoveDevicesFromGroup() throws GroupManagementException, DeviceNotFoundException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService"))
.toReturn(groupManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagerService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(deviceManagementProviderService);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
Mockito.doNothing().when(groupManagementProviderService).removeDevice(1, deviceIdentifiers);
Mockito.doThrow(new GroupManagementException()).when(groupManagementProviderService).removeDevice(2,
@ -357,6 +372,10 @@ public class GroupManagementServiceImplTest {
public void testUpdateDeviceAssigningToGroups() throws GroupManagementException, DeviceNotFoundException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getGroupManagementProviderService"))
.toReturn(groupManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagerService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(deviceManagementProviderService);
Mockito.reset(groupManagementProviderService);
DeviceToGroupsAssignment deviceToGroupsAssignment = new DeviceToGroupsAssignment();
List<Integer> groupIds = new ArrayList<>();

@ -0,0 +1,33 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.exceptions;
/**
* Exception thrown due to Database Connection issues.
*/
public class DBConnectionException extends Exception {
private static final long serialVersionUID = -6779125067467878014L;
public DBConnectionException(String message, Throwable cause) {
super(message, cause);
}
public DBConnectionException(String msg) {
super(msg);
}
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.exceptions;
public class OTPManagementException extends Exception {
private static final long serialVersionUID = 397485329551276175L;
public OTPManagementException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public OTPManagementException(String message, Throwable cause) {
super(message, cause);
}
public OTPManagementException(String msg) {
super(msg);
}
public OTPManagementException() {
super();
}
public OTPManagementException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,104 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.otp.mgt.dto;
import java.sql.Timestamp;
public class OTPMailDTO {
int id;
String otpToken;
String tenantDomain;
String email;
String emailType;
String metaInfo;
Timestamp createdAt;
int expiryTime;
boolean isExpired;
boolean isTenantCreated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOtpToken() {
return otpToken;
}
public void setOtpToken(String otpToken) {
this.otpToken = otpToken;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getMetaInfo() { return metaInfo; }
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public int getExpiryTime() {
return expiryTime;
}
public void setExpiryTime(int expiryTime) {
this.expiryTime = expiryTime;
}
public boolean isExpired() {
return isExpired;
}
public void setExpired(boolean expired) {
isExpired = expired;
}
public String getTenantDomain() { return tenantDomain; }
public void setTenantDomain(String tenantDomain) { this.tenantDomain = tenantDomain; }
public boolean isTenantCreated() { return isTenantCreated; }
public void setTenantCreated(boolean tenantCreated) { isTenantCreated = tenantCreated; }
}

@ -0,0 +1,84 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.otp.mgt.wrapper;
public class OTPMailWrapper {
private String firstName;
private String lastName;
private String tenantDomain;
private String adminUsername;
private String adminPassword;
private String email;
private String emailType;
public String getTenantDomain() {
return tenantDomain;
}
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public String getAdminUsername() {
return adminUsername;
}
public void setAdminUsername(String adminUsername) {
this.adminUsername = adminUsername;
}
public String getAdminPassword() {
return adminPassword;
}
public void setAdminPassword(String adminPassword) {
this.adminPassword = adminPassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

@ -44,6 +44,7 @@ public class Item {
private Text text;
private InputList inputList;
private String nullableValue;
private String divider;
@XmlElement(name = "Label")
public String getLabel() {
@ -197,4 +198,13 @@ public class Item {
public void setNullableValue(String nullableValue) {
this.nullableValue = nullableValue;
}
@XmlElement(name = "Divider")
public String getDivider() {
return divider;
}
public void setDivider(String divider) {
this.divider = divider;
}
}

@ -0,0 +1,49 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.roles.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "DefaultRoles")
public class DefaultRoles {
private boolean enabled;
private List<Role> roles;
@XmlElement(name = "Enabled", required = true)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@XmlElementWrapper(name = "Roles", required = true)
@XmlElement(name = "Role", required = true)
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}

@ -0,0 +1,49 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.roles.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "Role")
public class Role {
private String name;
private List<String> permissions;
@XmlElement(name = "Name", required = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "Permissions", required = true)
@XmlElement(name = "Permission", required = true)
public List<String> getPermissions() {
return permissions;
}
public void setPermissions(List<String> permissions) {
this.permissions = permissions;
}
}

@ -0,0 +1,34 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.spi;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.OTPManagementException;
import org.wso2.carbon.device.mgt.common.otp.mgt.wrapper.OTPMailWrapper;
public interface OTPManagementService {
/**
* Cretae OTP token and store tenant details in the DB
* @param otpMailWrapper OTP Mail Wrapper object which contains tenant details of registering user
* @return OTPToken
* @throws OTPManagementException if error occurs while creating OTP token and storing tenant details.
* @throws BadRequestException if found and incompatible payload to create OTP token.
*/
String createOTPToken (OTPMailWrapper otpMailWrapper) throws OTPManagementException, BadRequestException;
}

@ -116,6 +116,7 @@ public final class DeviceManagementConstants {
public static final String USER_REGISTRATION_TEMPLATE = "user-registration";
public static final String USER_ENROLLMENT_TEMPLATE = "user-enrollment";
public static final String USER_VERIFY_TEMPLATE = "user-verify";
public static final String DEFAULT_ENROLLMENT_TEMPLATE = "default-enrollment-invitation";
}

@ -270,8 +270,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
return tenantProviders;
}
private void registerPushNotificationStrategy(DeviceManagementService deviceManagementService)
throws DeviceManagementException {
private void registerPushNotificationStrategy(DeviceManagementService deviceManagementService) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
deviceManagementService.getProvisioningConfig().getProviderTenantDomain(), true);

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.core.config;
import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotificationConfiguration;
import org.wso2.carbon.device.mgt.common.roles.config.DefaultRoles;
import org.wso2.carbon.device.mgt.core.config.analytics.OperationAnalyticsConfiguration;
import org.wso2.carbon.device.mgt.core.config.archival.ArchivalConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration;
@ -60,7 +61,7 @@ public final class DeviceManagementConfig {
private RemoteSessionConfiguration remoteSessionConfiguration;
private ArchivalConfiguration archivalConfiguration;
private EnrollmentNotificationConfiguration enrollmentNotificationConfiguration;
private DefaultRoles defaultRoles;
@XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
@ -215,5 +216,10 @@ public final class DeviceManagementConfig {
EnrollmentNotificationConfiguration enrollmentNotificationConfiguration) {
this.enrollmentNotificationConfiguration = enrollmentNotificationConfiguration;
}
@XmlElement(name = "DefaultRoles", required = true)
public DefaultRoles getDefaultRoles() { return defaultRoles; }
public void setDefaultRoles(DefaultRoles defaultRoles) { this.defaultRoles = defaultRoles; }
}

@ -66,7 +66,7 @@ import java.util.Map;
public class DeviceInformationManagerImpl implements DeviceInformationManager {
private final DeviceDetailsDAO deviceDetailsDAO;
private DeviceDAO deviceDAO;
private final DeviceDAO deviceDAO;
private static final Log log = LogFactory.getLog(DeviceInformationManagerImpl.class);
private static final String LOCATION_EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream";
private static final String DEVICE_INFO_EVENT_STREAM_DEFINITION = "org.wso2.iot.DeviceInfoStream";

@ -27,6 +27,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier;
import org.wso2.carbon.device.mgt.core.privacy.PrivacyComplianceProvider;
@ -48,10 +49,11 @@ import java.util.Map;
public class DeviceManagementDataHolder {
private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder();
private static final DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder();
private RealmService realmService;
private TenantManager tenantManager;
private DeviceManagementProviderService deviceManagerProvider;
private DeviceInformationManager deviceInformationManager;
private LicenseManager licenseManager;
private RegistryService registryService;
private LicenseConfig licenseConfig;
@ -59,7 +61,7 @@ public class DeviceManagementDataHolder {
private AppManagementConfig appManagerConfig;
private OperationManager operationManager;
private ConfigurationContextService configurationContextService;
private HashMap<String,Boolean> requireDeviceAuthorization = new HashMap<>();
private final HashMap<String,Boolean> requireDeviceAuthorization = new HashMap<>();
private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
private GroupManagementProviderService groupManagementProviderService;
private TaskService taskService;
@ -69,10 +71,10 @@ public class DeviceManagementDataHolder {
private DeviceStatusTaskManagerService deviceStatusTaskManagerService;
private DeviceTypeGeneratorService deviceTypeGeneratorService;
private PrivacyComplianceProvider privacyComplianceProvider;
private Map<DeviceType, DeviceStatusTaskPluginConfig> deviceStatusTaskPluginConfigs = Collections.synchronizedMap(
new HashMap<DeviceType, DeviceStatusTaskPluginConfig>());
private final Map<DeviceType, DeviceStatusTaskPluginConfig> deviceStatusTaskPluginConfigs = Collections.synchronizedMap(
new HashMap<>());
private Map<String, OperationMonitoringTaskConfig> map = new HashMap<>();
private final Map<String, OperationMonitoringTaskConfig> map = new HashMap<>();
public Map<String, OperationMonitoringTaskConfig> getMap(){
return this.map;
@ -276,4 +278,12 @@ public class DeviceManagementDataHolder {
public void setPrivacyComplianceProvider(PrivacyComplianceProvider privacyComplianceProvider) {
this.privacyComplianceProvider = privacyComplianceProvider;
}
public DeviceInformationManager getDeviceInformationManager() {
return deviceInformationManager;
}
public void setDeviceInformationManager(DeviceInformationManager deviceInformationManager) {
this.deviceInformationManager = deviceInformationManager;
}
}

@ -35,6 +35,7 @@ import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
import org.wso2.carbon.device.mgt.common.spi.OTPManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagerProviderServiceImpl;
@ -56,6 +57,8 @@ import org.wso2.carbon.device.mgt.core.notification.mgt.NotificationManagementSe
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.OTPManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.otp.mgt.service.OTPManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.privacy.PrivacyComplianceProvider;
import org.wso2.carbon.device.mgt.core.privacy.impl.PrivacyComplianceProviderImpl;
@ -72,9 +75,11 @@ import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
import org.wso2.carbon.device.mgt.core.config.ui.UIConfigurationManager;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.DeviceMgtTenantMgtListener;
import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import org.wso2.carbon.utils.ConfigurationContextService;
@ -133,10 +138,10 @@ import java.util.concurrent.TimeUnit;
public class DeviceManagementServiceComponent {
private static final Object LOCK = new Object();
private static Log log = LogFactory.getLog(DeviceManagementServiceComponent.class);
private static List<PluginInitializationListener> listeners = new ArrayList<>();
private static List<DeviceManagementService> deviceManagers = new ArrayList<>();
private static List<DeviceManagerStartupListener> startupListeners = new ArrayList<>();
private static final Log log = LogFactory.getLog(DeviceManagementServiceComponent.class);
private static final List<PluginInitializationListener> listeners = new ArrayList<>();
private static final List<DeviceManagementService> deviceManagers = new ArrayList<>();
private static final List<DeviceManagerStartupListener> startupListeners = new ArrayList<>();
public static void registerPluginInitializationListener(PluginInitializationListener listener) {
synchronized (LOCK) {
@ -176,6 +181,7 @@ public class DeviceManagementServiceComponent {
NotificationManagementDAOFactory.init(dsConfig);
OperationManagementDAOFactory.init(dsConfig);
MetadataManagementDAOFactory.init(dsConfig);
OTPManagementDAOFactory.init(dsConfig.getJndiLookupDefinition().getJndiName());
/*Initialize the device cache*/
DeviceManagerUtil.initializeDeviceCache();
@ -245,6 +251,9 @@ public class DeviceManagementServiceComponent {
componentContext.getBundleContext().registerService(PrivacyComplianceProvider.class.getName(),
privacyComplianceProvider, null);
componentContext.getBundleContext()
.registerService(TenantMgtListener.class.getName(), new DeviceMgtTenantMgtListener(), null);
if (log.isDebugEnabled()) {
log.debug("Device management core bundle has been successfully initialized");
}
@ -325,7 +334,10 @@ public class DeviceManagementServiceComponent {
MetadataManagementService metadataManagementService = new MetadataManagementServiceImpl();
bundleContext.registerService(MetadataManagementService.class.getName(), metadataManagementService, null);
/* Registering App Management service */
OTPManagementService otpManagementService = new OTPManagementServiceImpl();
bundleContext.registerService(OTPManagementService.class.getName(), otpManagementService, null);
/* Registering App Management service */
try {
AppManagementConfigurationManager.getInstance().initConfig();
AppManagementConfig appConfig =
@ -340,7 +352,10 @@ public class DeviceManagementServiceComponent {
PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance();
bundleContext.registerService(PermissionManagerService.class.getName(), permissionManagerService, null);
bundleContext.registerService(DeviceInformationManager.class, new DeviceInformationManagerImpl(), null);
DeviceInformationManager deviceInformationManager = new DeviceInformationManagerImpl();
bundleContext.registerService(DeviceInformationManager.class, deviceInformationManager, null);
DeviceManagementDataHolder.getInstance().setDeviceInformationManager(deviceInformationManager);
bundleContext.registerService(SearchManagerService.class, new SearchManagerServiceImpl(), null);
}

@ -0,0 +1,33 @@
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.dao;
import org.wso2.carbon.device.mgt.common.exceptions.DBConnectionException;
import org.wso2.carbon.device.mgt.core.otp.mgt.util.ConnectionManagerUtil;
import java.sql.Connection;
/**
* This class deals with getting the DB connection.
*/
public abstract class AbstractDAOImpl {
protected Connection getDBConnection() throws DBConnectionException {
return ConnectionManagerUtil.getDBConnection();
}
}

@ -0,0 +1,32 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.dao;
import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OTPMailDTO;
import org.wso2.carbon.device.mgt.core.otp.mgt.exception.OTPManagementDAOException;
public interface OTPManagementDAO {
/**
* Save OTP token data and tenant details of registering user
* @param otpMailDTO OTPMailDTO
* @return Primary key of the newly adding data raw
* @throws OTPManagementDAOException if error occurred whule storing data
*/
int addOTPData(OTPMailDTO otpMailDTO) throws OTPManagementDAOException;
}

@ -0,0 +1,76 @@
/*
* Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineException;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl.GenericOTPManagementDAOImpl;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl.OracleOTPManagementDAOImpl;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl.PostgreSQLOTPManagementDAOImpl;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl.SQLServerOTPManagementDAOImpl;
import org.wso2.carbon.device.mgt.core.otp.mgt.util.ConnectionManagerUtil;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* This class intends to act as the primary entity that hides all DAO instantiation related complexities and logic so
* that the business objection handling layer doesn't need to be aware of the same providing seamless plug-ability of
* different data sources, connection acquisition mechanisms as well as different forms of DAO implementations to the
* high-level implementations that require Application management related metadata persistence.
*/
public class OTPManagementDAOFactory {
private static String databaseEngine;
private static final Log log = LogFactory.getLog(OTPManagementDAOFactory.class);
public static void init(String datasourceName) {
ConnectionManagerUtil.resolveDataSource(datasourceName);
databaseEngine = ConnectionManagerUtil.getDatabaseType();
}
public static void init(DataSource dtSource) {
try (Connection connection = dtSource.getConnection()) {
databaseEngine = connection.getMetaData().getDatabaseProductName();
} catch (SQLException e) {
log.error("Error occurred while retrieving config.datasource connection", e);
}
}
public static OTPManagementDAO getOTPManagementDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL:
return new GenericOTPManagementDAOImpl();
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL:
return new PostgreSQLOTPManagementDAOImpl();
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL:
return new SQLServerOTPManagementDAOImpl();
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
return new OracleOTPManagementDAOImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
}
}

@ -0,0 +1,85 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.exceptions.DBConnectionException;
import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OTPMailDTO;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.AbstractDAOImpl;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.OTPManagementDAO;
import org.wso2.carbon.device.mgt.core.otp.mgt.exception.OTPManagementDAOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Calendar;
public class GenericOTPManagementDAOImpl extends AbstractDAOImpl implements OTPManagementDAO {
private static final Log log = LogFactory.getLog(GenericOTPManagementDAOImpl.class);
@Override
public int addOTPData(OTPMailDTO otpMailDTO) throws OTPManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to create an OTP data entry");
log.debug("OTP Details : ");
log.debug("OTP key : " + otpMailDTO.getOtpToken() + " Email : " + otpMailDTO.getEmail());
}
String sql = "INSERT INTO DM_OTP_DATA "
+ "(OTP_TOKEN, "
+ "TENANT_DOMAIN,"
+ "EMAIL, "
+ "EMAIL_TYPE, "
+ "META_INFO, "
+ "CREATED_AT) VALUES (?, ?, ?, ?, ?, ?)";
try {
Connection conn = this.getDBConnection();
Calendar calendar = Calendar.getInstance();
Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, otpMailDTO.getOtpToken());
stmt.setString(2, otpMailDTO.getTenantDomain());
stmt.setString(3, otpMailDTO.getEmail());
stmt.setString(4, otpMailDTO.getEmailType());
stmt.setString(5, otpMailDTO.getMetaInfo());
stmt.setTimestamp(6, timestamp);
stmt.executeUpdate();
try (ResultSet rs = stmt.getGeneratedKeys()) {
if (rs.next()) {
return rs.getInt(1);
}
return -1;
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to create an opt entry for email "
+ otpMailDTO.getEmail();
log.error(msg, e);
throw new OTPManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing SQL to create an otp entry for email " + otpMailDTO.getEmail();
log.error(msg, e);
throw new OTPManagementDAOException(msg, e);
}
}
}

@ -0,0 +1,24 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl;
/**
* This handles OTP managing DAO methods which are specific to Oracle.
*/
public class OracleOTPManagementDAOImpl extends GenericOTPManagementDAOImpl{
}

@ -0,0 +1,25 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl;
/**
* This handles OTP managing DAO methods which are specific to PostgreSQL.
*/
public class PostgreSQLOTPManagementDAOImpl extends GenericOTPManagementDAOImpl{
}

@ -0,0 +1,24 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl;
/**
* This handles OTP managing DAO methods which are specific to MSSQL.
*/
public class SQLServerOTPManagementDAOImpl extends GenericOTPManagementDAOImpl{
}

@ -0,0 +1,31 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.exception;
/**
* Exception thrown during the ApplicationDTO Management DAO operations.
*/
public class OTPManagementDAOException extends Exception {
public OTPManagementDAOException(String message, Throwable throwable) {
super(message, throwable);
}
public OTPManagementDAOException(String message) {
super(message, new Exception());
}
}

@ -0,0 +1,132 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.service;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.DBConnectionException;
import org.wso2.carbon.device.mgt.common.exceptions.OTPManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OTPMailDTO;
import org.wso2.carbon.device.mgt.common.spi.OTPManagementService;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.OTPManagementDAO;
import org.wso2.carbon.device.mgt.common.otp.mgt.wrapper.OTPMailWrapper;
import org.wso2.carbon.device.mgt.core.otp.mgt.dao.OTPManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.otp.mgt.exception.OTPManagementDAOException;
import org.wso2.carbon.device.mgt.core.otp.mgt.util.ConnectionManagerUtil;
import java.util.UUID;
public class OTPManagementServiceImpl implements OTPManagementService {
private static final Log log = LogFactory.getLog(OTPManagementServiceImpl.class);
private OTPManagementDAO otpManagementDAO;
public OTPManagementServiceImpl() {
initDataAccessObjects();
}
private void initDataAccessObjects() {
otpManagementDAO = OTPManagementDAOFactory.getOTPManagementDAO();
}
@Override
public String createOTPToken(OTPMailWrapper otpMailWrapper) throws OTPManagementException, BadRequestException {
if (!isValidOTPTokenCreatingRequest(otpMailWrapper)){
String msg = "Found invalid payload with OTP creating request";
log.error(msg);
throw new BadRequestException(msg);
}
Gson gson = new Gson();
String metaInfo = gson.toJson(otpMailWrapper);
String otpValue = UUID.randomUUID().toString();
OTPMailDTO otpMailDTO = new OTPMailDTO();
otpMailDTO.setEmail(otpMailWrapper.getEmail());
otpMailDTO.setTenantDomain(otpMailWrapper.getTenantDomain());
otpMailDTO.setEmailType(otpMailWrapper.getEmailType());
otpMailDTO.setMetaInfo(metaInfo);
otpMailDTO.setOtpToken(otpValue);
try {
ConnectionManagerUtil.beginDBTransaction();
if (this.otpManagementDAO.addOTPData(otpMailDTO) == -1) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "OTP data saving failed. Please, contact Administrator";
log.error(msg);
throw new OTPManagementException(msg);
}
ConnectionManagerUtil.commitDBTransaction();
return otpValue;
} catch (TransactionManagementException e) {
String msg = "Error occurred while disabling AutoCommit.";
log.error(msg, e);
throw new OTPManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occurred while getting database connection.";
log.error(msg, e);
throw new OTPManagementException(msg, e);
} catch (OTPManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while saving the OTP data. Email address: " + otpMailDTO.getEmail();
log.error(msg, e);
throw new OTPManagementException(msg, e);
}
}
/**
* Validate OTP token creating payload
* @param otpMailWrapper OTPMailWrapper
* @return true if its valid payload otherwise returns false
*/
private boolean isValidOTPTokenCreatingRequest(OTPMailWrapper otpMailWrapper) {
if (StringUtils.isBlank(otpMailWrapper.getFirstName())) {
log.error("Received empty or blank first name field with OTP creating payload.");
return false;
}
if (StringUtils.isBlank(otpMailWrapper.getLastName())) {
log.error("Received empty or blank last name field with OTP creating payload.");
return false;
}
if (StringUtils.isBlank(otpMailWrapper.getAdminUsername())) {
log.error("Received empty or blank admin username field with OTP creating payload.");
return false;
}
if (StringUtils.isBlank(otpMailWrapper.getAdminPassword())) {
log.error("Received empty or blank admin password field with OTP creating payload.");
return false;
}
if (StringUtils.isBlank(otpMailWrapper.getEmail())) {
log.error("Received empty or blank email field with OTP creating payload.");
return false;
}
if (StringUtils.isBlank(otpMailWrapper.getEmailType())) {
log.error("Received empty or blank email type field with OTP creating payload.");
return false;
}
if (StringUtils.isBlank(otpMailWrapper.getTenantDomain())) {
log.error("Received empty or blank tenant domain field with OTP creating payload.");
return false;
}
return true;
}
}

@ -0,0 +1,211 @@
/*
* Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.otp.mgt.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.exceptions.DBConnectionException;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.IllegalTransactionStateException;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* ConnectionManagerUtil is responsible for handling all the datasource connections utilities.
*/
public class ConnectionManagerUtil {
private static final Log log = LogFactory.getLog(ConnectionManagerUtil.class);
private static final ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
private static DataSource dataSource;
public static void openDBConnection() throws DBConnectionException {
Connection conn = currentConnection.get();
if (conn != null) {
String msg = "Database connection has already been obtained.";
log.error(msg);
throw new IllegalTransactionStateException(msg);
}
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
String msg = "Failed to get a database connection.";
log.error(msg, e);
throw new DBConnectionException(msg, e);
}
currentConnection.set(conn);
}
public static Connection getDBConnection() throws DBConnectionException {
Connection conn = currentConnection.get();
if (conn == null) {
try {
conn = dataSource.getConnection();
currentConnection.set(conn);
} catch (SQLException e) {
throw new DBConnectionException("Failed to get database connection.", e);
}
}
return conn;
}
public static void beginDBTransaction() throws TransactionManagementException, DBConnectionException {
Connection conn = currentConnection.get();
if (conn == null) {
conn = getDBConnection();
} else if (inTransaction(conn)) {
String msg = "Transaction has already been started.";
log.error(msg);
throw new IllegalTransactionStateException(msg);
}
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
String msg = "Error occurred while starting a database transaction.";
log.error(msg, e);
throw new TransactionManagementException(msg, e);
}
}
public static void endDBTransaction() throws TransactionManagementException {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("Database connection is not active.");
}
if (!inTransaction(conn)) {
throw new IllegalTransactionStateException("Transaction has not been started.");
}
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
throw new TransactionManagementException("Error occurred while ending database transaction.", e);
}
}
public static void commitDBTransaction() {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("Database connection is not active.");
}
if (!inTransaction(conn)) {
throw new IllegalTransactionStateException("Transaction has not been started.");
}
try {
conn.commit();
} catch (SQLException e) {
log.error("Error occurred while committing the transaction", e);
}
}
public static void rollbackDBTransaction() {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("Database connection is not active.");
}
if (!inTransaction(conn)) {
throw new IllegalTransactionStateException("Transaction has not been started.");
}
try {
conn.rollback();
} catch (SQLException e) {
log.warn("Error occurred while roll-backing the transaction", e);
}
}
public static void closeDBConnection() {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("Database connection is not active.");
}
try {
conn.close();
} catch (SQLException e) {
log.error("Error occurred while closing the connection", e);
}
currentConnection.remove();
}
private static boolean inTransaction(Connection conn) {
boolean inTransaction = true;
try {
if (conn.getAutoCommit()) {
inTransaction = false;
}
} catch (SQLException e) {
throw new IllegalTransactionStateException("Failed to get transaction state.");
}
return inTransaction;
}
public static boolean isTransactionStarted() throws DBConnectionException {
Connection connection = getDBConnection();
return inTransaction(connection);
}
/**
* Resolve the datasource from the datasource definition.
*
* @param dataSourceName Name of the datasource
* @return DataSource resolved by the datasource name
*/
public static DataSource resolveDataSource(String dataSourceName) {
try {
dataSource = InitialContext.doLookup(dataSourceName);
} catch (Exception e) {
throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e);
}
return dataSource;
}
public static String getDatabaseType() {
try (Connection connection = dataSource.getConnection()) {
return connection.getMetaData().getDatabaseProductName();
} catch (SQLException e) {
log.error("Error occurred while retrieving config.datasource connection", e);
}
return null;
}
/**
* To check whether particular database that is used for application management supports batch query execution.
*
* @return true if batch query is supported, otherwise false.
*/
public static boolean isBatchQuerySupported() {
try (Connection connection = dataSource.getConnection()) {
return connection.getMetaData().supportsBatchUpdates();
} catch (SQLException e) {
log.error("Error occurred while checking whether database supports batch updates", e);
}
return false;
}
public static void init(DataSource dtSource) {
dataSource = dtSource;
}
}

@ -63,7 +63,6 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySna
import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotificationConfiguration;
import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotifier;
import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotifierException;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException;
@ -103,7 +102,6 @@ import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion;
@ -149,7 +147,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private static final String OPERATION_RESPONSE_EVENT_STREAM_DEFINITION = "org.wso2.iot.OperationResponseStream";
private final DeviceManagementPluginRepository pluginRepository;
private final DeviceInformationManager deviceInformationManager;
private final DeviceDAO deviceDAO;
private final DeviceTypeDAO deviceTypeDAO;
private final EnrollmentDAO enrollmentDAO;
@ -157,8 +154,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
public DeviceManagementProviderServiceImpl() {
this.pluginRepository = new DeviceManagementPluginRepository();
this.deviceInformationManager = new DeviceInformationManagerImpl();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO();
this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
@ -398,6 +393,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
extractDeviceLocationToUpdate(device);
try {
if (device.getDeviceInfo() != null) {
DeviceInformationManager deviceInformationManager = DeviceManagementDataHolder
.getInstance().getDeviceInformationManager();
deviceInformationManager.addDeviceInfo(device, device.getDeviceInfo());
}
} catch (DeviceDetailsMgtException e) {
@ -2837,7 +2834,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
if (log.isDebugEnabled()) {
log.debug("Add device:" + deviceIdentifier.getId() + " to default group");
}
GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl();
GroupManagementProviderService groupManagementProviderService = DeviceManagementDataHolder
.getInstance().getGroupManagementProviderService();
try {
DeviceGroup defaultGroup = createDefaultGroup(groupManagementProviderService, ownership.toString());
if (defaultGroup != null) {
@ -3102,6 +3100,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
DeviceInfo info;
try {
DeviceInformationManager deviceInformationManager = DeviceManagementDataHolder
.getInstance().getDeviceInformationManager();
info = deviceInformationManager.getDeviceInfo(device);
} catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while retrieving advance info of '" + device.getType() +
@ -3401,6 +3401,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
* @param device Device object
*/
private void extractDeviceLocationToUpdate(Device device) {
DeviceInformationManager deviceInformationManager = DeviceManagementDataHolder
.getInstance().getDeviceInformationManager();
List<Device.Property> properties = device.getProperties();
if (properties != null) {
String latitude = null;

@ -55,10 +55,10 @@ import java.util.Map;
public class GroupManagementProviderServiceImpl implements GroupManagementProviderService {
private static Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class);
private static final Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class);
private GroupDAO groupDAO;
private DeviceDAO deviceDAO;
private final GroupDAO groupDAO;
private final DeviceDAO deviceDAO;
/**
* Set groupDAO from GroupManagementDAOFactory when class instantiate.
@ -912,9 +912,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
log.debug("Get groups of device " + deviceIdentifier.getId());
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl();
DeviceManagementProviderService managementProviderService = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider();
Device device;
try {
device = managementProviderService.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving device groups.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
}
return getDeviceGroups(requireGroupProps, tenantId, device);
}
private List<DeviceGroup> getDeviceGroups(boolean requireGroupProps, int tenantId, Device device) throws GroupManagementException {
try {
Device device = managementProviderService.getDevice(deviceIdentifier, false);
GroupManagementDAOFactory.openConnection();
List<DeviceGroup> deviceGroups = groupDAO.getGroups(device.getId(), tenantId);
if (requireGroupProps) {
@ -925,7 +937,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
}
return deviceGroups;
} catch (DeviceManagementException | GroupManagementDAOException | SQLException e) {
} catch (GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving device groups.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
@ -950,28 +962,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
log.debug("Get groups of device " + device.getDeviceIdentifier());
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
GroupManagementDAOFactory.openConnection();
List<DeviceGroup> deviceGroups = groupDAO.getGroups(device.getId(), tenantId);
if (requireGroupProps) {
if (deviceGroups != null && !deviceGroups.isEmpty()) {
for (DeviceGroup group : deviceGroups) {
populateGroupProperties(group, tenantId);
}
}
}
return deviceGroups;
} catch (GroupManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving device groups.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getGroups";
log.error(msg, e);
throw new GroupManagementException(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
return getDeviceGroups(requireGroupProps, tenantId, device);
}
/**

@ -0,0 +1,148 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.roles.config.Role;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DeviceMgtTenantMgtListener implements TenantMgtListener {
private static final Log log = LogFactory.getLog(DeviceMgtTenantMgtListener.class);
private static final int EXEC_ORDER = 10;
private static final String PERMISSION_ACTION = "ui.execute";
@Override
public void onTenantCreate(TenantInfoBean tenantInfoBean) {
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
if (config.getDefaultRoles().isEnabled()) {
Map<String, List<Permission>> roleMap = getValidRoleMap(config);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(tenantInfoBean.getTenantDomain(), true);
UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService()
.getTenantUserRealm(tenantInfoBean.getTenantId()).getUserStoreManager();
roleMap.forEach((key, value) -> {
try {
userStoreManager.addRole(key, null, value.toArray(new Permission[0]));
} catch (UserStoreException e) {
log.error("Error occurred while adding default roles into user store.", e);
}
});
} catch (UserStoreException e) {
log.error("Error occurred while getting user store manager.", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
@Override
public void onTenantUpdate(TenantInfoBean tenantInfoBean) {
// doing nothing
}
@Override
public void onTenantDelete(int i) {
// doing nothing
}
@Override
public void onTenantRename(int i, String s, String s1) {
// doing nothing
}
@Override
public void onTenantInitialActivation(int i) {
// doing nothing
}
@Override
public void onTenantActivation(int i) {
// doing nothing
}
@Override
public void onTenantDeactivation(int i) {
// doing nothing
}
@Override
public void onSubscriptionPlanChange(int i, String s, String s1) {
// doing nothing
}
@Override
public int getListenerOrder() {
return EXEC_ORDER;
}
@Override
public void onPreDelete(int i) {
// doing nothing
}
/**
* Use the default roles defined in the cdm-config and evaluate the defined permissions. If permissions does not
* exist then exclude them and return role map which contains defined roles in the cdm-config and existing
* permission list as a roleMap
* @param config cdm-config
* @return {@link Map} key is role name and value is list of permissions which needs to be assigned to the role
* defined in the key.
*/
private Map<String, List<Permission>> getValidRoleMap(DeviceManagementConfig config) {
Map<String, List<Permission>> roleMap = new HashMap<>();
try {
for (Role role : config.getDefaultRoles().getRoles()) {
List<Permission> permissionList = new ArrayList<>();
for (String permissionPath : role.getPermissions()) {
if (PermissionUtils.checkResourceExists(permissionPath)) {
Permission permission = new Permission(permissionPath, PERMISSION_ACTION);
permissionList.add(permission);
} else {
log.warn("Permission " + permissionPath + " does not exist. Hence it will not add to role "
+ role.getName());
}
}
roleMap.put(role.getName(), permissionList);
}
} catch (PermissionManagementException | RegistryException e) {
log.error("Error occurred while checking permission existence.", e);
}
return roleMap;
}
}

@ -77,6 +77,7 @@ import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
@ -124,6 +125,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService());
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl());
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
DeviceManagementDataHolder.getInstance().setDeviceInformationManager(new DeviceInformationManagerImpl());
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));

@ -69,9 +69,9 @@ public class PolicyManagerServiceImpl implements PolicyManagerService {
private static final Log log = LogFactory.getLog(PolicyManagerServiceImpl.class);
PolicyAdministratorPoint policyAdministratorPoint;
MonitoringManager monitoringManager;
private PolicyManager policyManager;
private final PolicyAdministratorPoint policyAdministratorPoint;
private final MonitoringManager monitoringManager;
private final PolicyManager policyManager;
public PolicyManagerServiceImpl() {
policyAdministratorPoint = new PolicyAdministratorPointImpl();

@ -41,15 +41,14 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.PolicyTransformException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
@ -60,8 +59,8 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
private static final Log log = LogFactory.getLog(PolicyEnforcementDelegatorImpl.class);
private List<Device> devices;
private List<Integer> updatedPolicyIds;
private final List<Device> devices;
private final List<Integer> updatedPolicyIds;
public PolicyEnforcementDelegatorImpl(List<Device> devices, List<Integer> updatedPolicyIds) {
@ -75,7 +74,6 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
}
this.devices = devices;
this.updatedPolicyIds = updatedPolicyIds;
}
@Override
@ -111,7 +109,8 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
@Override
public Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException {
try {
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
PolicyManagerService policyManagerService = PolicyManagementDataHolder.getInstance()
.getPolicyManagerService();
PolicyAdministratorPoint policyAdministratorPoint;
Policy policy = policyManagerService.getPEP().getEffectivePolicy(identifier);
@ -124,11 +123,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
}
return policy;
//return PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint().getEffectivePolicy(identifier);
} catch (PolicyEvaluationException e) {
String msg = "Error occurred while retrieving the effective policy for devices.";
log.error(msg, e);
throw new PolicyDelegationException(msg, e);
} catch (PolicyManagementException e) {
} catch (PolicyEvaluationException | PolicyManagementException e) {
String msg = "Error occurred while retrieving the effective policy for devices.";
log.error(msg, e);
throw new PolicyDelegationException(msg, e);
@ -199,7 +194,8 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
*/
public Policy getAppliedPolicyToDevice(Device device) throws PolicyDelegationException {
try {
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
PolicyManagerService policyManagerService = PolicyManagementDataHolder.getInstance()
.getPolicyManagerService();
return policyManagerService.getAppliedPolicyToDevice(device);
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving the applied policy for devices.";

@ -40,17 +40,19 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.PIPDevice;
import org.wso2.carbon.policy.mgt.common.PolicyFilter;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
@ -68,9 +70,9 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
private static final Log log = LogFactory.getLog(PolicyInformationPointImpl.class);
PolicyManager policyManager;
FeatureManager featureManager;
DeviceManagementProviderService deviceManagementService;
private final PolicyManager policyManager;
private final FeatureManager featureManager;
private final DeviceManagementProviderService deviceManagementService;
public PolicyInformationPointImpl() {
deviceManagementService =
@ -85,8 +87,8 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
Device device;
DeviceType deviceType = new DeviceType();
deviceType.setName(deviceIdentifier.getType());
DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl();
GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl();
GroupManagementProviderService groupManagementProviderService = PolicyManagementDataHolder
.getInstance().getGroupManagementService();
try {
device = deviceManagementService.getDevice(deviceIdentifier, false);
@ -184,11 +186,10 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
}
}
private List<Policy> removeDuplicatePolicies(List<List<Policy>> policies) {
Map<Integer, Policy> map = new HashMap<Integer, Policy>();
List<Policy> finalPolicies = new ArrayList<Policy>();
Map<Integer, Policy> map = new HashMap<>();
List<Policy> finalPolicies = new ArrayList<>();
for (List<Policy> policyList : policies) {
for (Policy policy : policyList) {
if (!map.containsKey(policy.getId())) {
@ -200,8 +201,4 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
return finalPolicies;
}
private DeviceManagementProviderService getDeviceManagementService() {
return new DeviceManagementProviderServiceImpl();
}
}

@ -18,16 +18,18 @@
package org.wso2.carbon.policy.mgt.core.internal;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import java.util.HashMap;
import java.util.Map;
@ -35,16 +37,16 @@ import java.util.Map;
public class PolicyManagementDataHolder {
private RealmService realmService;
private TenantManager tenantManager;
private PolicyEvaluationPoint policyEvaluationPoint;
private Map<String, PolicyEvaluationPoint> policyEvaluationPoints = new HashMap<>();
private final Map<String, PolicyEvaluationPoint> policyEvaluationPoints = new HashMap<>();
private PolicyInformationPoint policyInformationPoint;
private DeviceManagementProviderService deviceManagementService;
private GroupManagementProviderService groupManagementService;
private PolicyManagerService policyManagerService;
private MonitoringManager monitoringManager;
private PolicyManager policyManager;
private TaskService taskService;
private static PolicyManagementDataHolder thisInstance = new PolicyManagementDataHolder();
private static final PolicyManagementDataHolder thisInstance = new PolicyManagementDataHolder();
private PolicyManagementDataHolder() {}
@ -74,18 +76,6 @@ public class PolicyManagementDataHolder {
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
this.setTenantManager(realmService);
}
private void setTenantManager(RealmService realmService) {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
}
this.tenantManager = realmService.getTenantManager();
}
public TenantManager getTenantManager() {
return tenantManager;
}
public PolicyEvaluationPoint getPolicyEvaluationPoint() {
@ -127,4 +117,25 @@ public class PolicyManagementDataHolder {
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
public synchronized GroupManagementProviderService getGroupManagementService() {
if (groupManagementService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
groupManagementService = (GroupManagementProviderService)
ctx.getOSGiService(GroupManagementProviderService.class, null);
if (groupManagementService == null) {
String msg = "GroupImpl Management service has not initialized.";
throw new IllegalStateException(msg);
}
}
return groupManagementService;
}
public PolicyManagerService getPolicyManagerService() {
return policyManagerService;
}
public void setPolicyManagerService(PolicyManagerService policyManagerService) {
this.policyManagerService = policyManagerService;
}
}

@ -67,7 +67,7 @@ import org.wso2.carbon.user.core.service.RealmService;
@SuppressWarnings("unused")
public class PolicyManagementServiceComponent {
private static Log log = LogFactory.getLog(PolicyManagementServiceComponent.class);
private static final Log log = LogFactory.getLog(PolicyManagementServiceComponent.class);
protected void activate(ComponentContext componentContext) {
@ -77,8 +77,10 @@ public class PolicyManagementServiceComponent {
DataSourceConfig dsConfig = config.getPolicyManagementRepository().getDataSourceConfig();
PolicyManagementDAOFactory.init(dsConfig);
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
componentContext.getBundleContext().registerService(
PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null);
PolicyManagerService.class.getName(), policyManagerService, null);
PolicyManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService);
PolicyConfiguration policyConfiguration =
DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration();

@ -56,9 +56,7 @@ import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl;
import org.wso2.carbon.policy.mgt.core.dao.*;
@ -74,12 +72,12 @@ import java.util.*;
public class PolicyManagerImpl implements PolicyManager {
private PolicyDAO policyDAO;
private ProfileDAO profileDAO;
private FeatureDAO featureDAO;
private ProfileManager profileManager;
private PolicyConfiguration policyConfiguration;
private static Log log = LogFactory.getLog(PolicyManagerImpl.class);
private final PolicyDAO policyDAO;
private final ProfileDAO profileDAO;
private final FeatureDAO featureDAO;
private final ProfileManager profileManager;
private final PolicyConfiguration policyConfiguration;
private static final Log log = LogFactory.getLog(PolicyManagerImpl.class);
public PolicyManagerImpl() {
this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO();
@ -495,10 +493,11 @@ public class PolicyManagerImpl implements PolicyManager {
Policy policy) throws PolicyManagementException {
List<Device> deviceList = new ArrayList<>();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
for (DeviceIdentifier deviceIdentifier : deviceIdentifierList) {
try {
Device device = service.getDevice(deviceIdentifier, false);
Device device = deviceManagementService.getDevice(deviceIdentifier, false);
deviceList.add(device);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while retrieving device information", e);
@ -732,19 +731,23 @@ public class PolicyManagerImpl implements PolicyManager {
List<Integer> policyIdList;
List<Policy> policies = new ArrayList<>();
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier, false);
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
Device device;
try {
device = deviceManagementService.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting device related to device identifier (" +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType() + ")", e);
}
try {
PolicyManagementDAOFactory.openConnection();
policyIdList = policyDAO.getPolicyIdsOfDevice(device);
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policies for device identifier (" +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType() + ")", e);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting device related to device identifier (" +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType() + ")", e);
} catch (SQLException e) {
throw new PolicyManagementException("Error occurred while open a data source connection", e);
} finally {
@ -814,7 +817,6 @@ public class PolicyManagerImpl implements PolicyManager {
try {
PolicyManagementDAOFactory.openConnection();
policyIdList = policyDAO.getPolicyOfRole(roleName);
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policies.", e);
} catch (SQLException e) {
@ -882,9 +884,16 @@ public class PolicyManagerImpl implements PolicyManager {
List<Device> deviceList = new ArrayList<>();
List<Integer> deviceIds;
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
List<Device> allDevices;
try {
allDevices = deviceManagementService.getAllDevices();
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" +
policyId + ")", e);
}
try {
DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance().getDeviceManagementService();
List<Device> allDevices = service.getAllDevices();
PolicyManagementDAOFactory.openConnection();
deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId);
HashMap<Integer, Device> allDeviceMap = new HashMap<>();
@ -906,9 +915,6 @@ public class PolicyManagerImpl implements PolicyManager {
policyId + ")", e);
} catch (SQLException e) {
throw new PolicyManagementException("Error occurred while opening a connection to the data source", e);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" +
policyId + ")", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
@ -918,12 +924,18 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
public void addAppliedPolicyFeaturesToDevice(DeviceIdentifier deviceIdentifier,
Policy policy) throws PolicyManagementException {
int deviceId = -1;
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
Device device;
try {
device = deviceManagementService.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
}
int deviceId = device.getId();
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier, false);
deviceId = device.getId();
PolicyManagementDAOFactory.beginTransaction();
boolean exist = policyDAO.checkPolicyAvailable(deviceId, device.getEnrolmentInfo().getId());
if (exist) {
@ -936,9 +948,6 @@ public class PolicyManagerImpl implements PolicyManager {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while adding the evaluated policy to device (" +
deviceId + " - " + policy.getId() + ")", e);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
@ -997,12 +1006,18 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
public void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy)
throws PolicyManagementException {
int deviceId = -1;
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
Device device;
try {
device = deviceManagementService.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
}
int deviceId = device.getId();
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier, false);
deviceId = device.getId();
PolicyManagementDAOFactory.beginTransaction();
Policy policySaved = policyDAO.getAppliedPolicy(deviceId, device.getEnrolmentInfo().getId());
@ -1016,10 +1031,6 @@ public class PolicyManagerImpl implements PolicyManager {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while adding the evaluated policy to device (" +
deviceId + " - " + policy.getId() + ")", e);
} catch (DeviceManagementException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
@ -1027,12 +1038,18 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
public void removeAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
int deviceId = -1;
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
Device device;
try {
device = deviceManagementService.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
}
int deviceId = device.getId();
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier, false);
deviceId = device.getId();
PolicyManagementDAOFactory.beginTransaction();
Policy policySaved = policyDAO.getAppliedPolicy(deviceId, device.getEnrolmentInfo().getId());
@ -1044,10 +1061,6 @@ public class PolicyManagerImpl implements PolicyManager {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while removing the applied policy to device (" +
deviceId + ")", e);
} catch (DeviceManagementException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
@ -1057,17 +1070,21 @@ public class PolicyManagerImpl implements PolicyManager {
public boolean checkPolicyAvailable(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
boolean exist;
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
Device device;
try {
device = deviceManagementService.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
}
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier, false);
PolicyManagementDAOFactory.openConnection();
exist = policyDAO.checkPolicyAvailable(device.getId(), device.getEnrolmentInfo().getId());
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while checking whether device has a policy " +
"to apply.", e);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
} catch (SQLException e) {
throw new PolicyManagementException("Error occurred while opening a connection to the data source", e);
} finally {
@ -1078,19 +1095,24 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
public boolean setPolicyApplied(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
Device device;
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier, false);
device = deviceManagementService.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
}
try {
PolicyManagementDAOFactory.openConnection();
policyDAO.setPolicyApplied(device.getId(), device.getEnrolmentInfo().getId());
return true;
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while setting the policy has applied to device (" +
deviceIdentifier.getId() + ")", e);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the device details (" +
deviceIdentifier.getId() + ")", e);
} catch (SQLException e) {
throw new PolicyManagementException("Error occurred while opening a connection to the data source", e);
} finally {
@ -1115,10 +1137,11 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
@Deprecated
public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceId) throws PolicyManagementException {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
Device device;
try {
device = service.getDevice(deviceId, false);
device = deviceManagementService.getDevice(deviceId, false);
if (device == null) {
if (log.isDebugEnabled()) {
log.debug("No device is found upon the device identifier '" + deviceId.getId() +
@ -1163,17 +1186,18 @@ public class PolicyManagerImpl implements PolicyManager {
}
}
private List<DeviceGroupWrapper> getDeviceGroupNames(List<DeviceGroupWrapper> groupWrappers) throws GroupManagementException {
GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl();
private List<DeviceGroupWrapper> getDeviceGroupNames(List<DeviceGroupWrapper> groupWrappers)
throws GroupManagementException {
GroupManagementProviderService groupManagementService = PolicyManagementDataHolder
.getInstance().getGroupManagementService();
for (DeviceGroupWrapper wrapper : groupWrappers) {
DeviceGroup deviceGroup = groupManagementProviderService.getGroup(wrapper.getId(), false);
DeviceGroup deviceGroup = groupManagementService.getGroup(wrapper.getId(), false);
wrapper.setName(deviceGroup.getName());
wrapper.setOwner(deviceGroup.getOwner());
}
return groupWrappers;
}
private List<DeviceIdentifier> convertDevices(List<Device> devices) {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
for (Device device : devices) {
@ -1185,7 +1209,6 @@ public class PolicyManagerImpl implements PolicyManager {
return deviceIdentifiers;
}
private void addPolicyRevokeOperation(List<DeviceIdentifier> deviceIdentifiers) throws PolicyManagementException {
try {
String type = null;

@ -16,7 +16,6 @@
* under the License.
*/
package org.wso2.carbon.policy.mgt.core.task;
import org.apache.commons.logging.Log;
@ -29,11 +28,9 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.ntask.core.Task;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager;
import org.wso2.carbon.user.api.UserStoreException;
import java.util.ArrayList;
import java.util.List;
@ -43,11 +40,8 @@ public class MonitoringTask implements Task {
private static final Log log = LogFactory.getLog(MonitoringTask.class);
Map<String, String> properties;
@Override
public void setProperties(Map<String, String> map) {
this.properties = map;
}
@Override
@ -84,7 +78,8 @@ public class MonitoringTask implements Task {
log.debug("Monitoring task started to run for all tenants.");
}
try {
DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl();
DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder
.getInstance().getDeviceManagementService();
List<Integer> tenants = deviceManagementService.getDeviceEnrolledTenants();
for (Integer tenant : tenants) {
if (MultitenantConstants.SUPER_TENANT_ID == tenant) {

@ -39,6 +39,7 @@ import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationSe
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
@ -112,11 +113,17 @@ public abstract class BasePolicyManagementDAOTest {
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(
new DeviceAccessAuthorizationServiceImpl());
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupMgtService);
DeviceManagementDataHolder.getInstance().setDeviceInformationManager(new DeviceInformationManagerImpl());
DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null);
PolicyEvaluationPoint policyEvaluationPoint = new SimplePolicyEvaluationTest();
PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint("Simple", policyEvaluationPoint);
PolicyManagementDataHolder.getInstance().setDeviceManagementService(deviceMgtService);
PolicyManagementDataHolder.getInstance().setPolicyManagerService(new PolicyManagerServiceImpl());
Field groupManagementService = PolicyManagementDataHolder.class.getDeclaredField("groupManagementService");
groupManagementService.setAccessible(true);
groupManagementService.set(PolicyManagementDataHolder.getInstance(), groupMgtService);
profileManager = new ProfileManagerImpl();
}

@ -22,16 +22,19 @@ package org.wso2.carbon.policy.mgt.core;
import junit.framework.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
@ -55,7 +58,11 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
public void testMonitorDao() {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(service);
DeviceManagementDataHolder.getInstance().setDeviceInformationManager(new DeviceInformationManagerImpl());
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl());
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
PolicyManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService);
List<Policy> policies = null;
List<Device> devices = null;

@ -55,6 +55,8 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@BeforeClass
public void init() throws Exception {
log.info("Initializing policy tests");
super.initializeServices();
initDatSource();
// System.setProperty("GetTenantIDForTest", "Super");
initiatePrivilegedCaronContext();

@ -46,6 +46,8 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest {
@BeforeClass
public void init() throws Exception {
log.info("Initializing policy tests");
super.initializeServices();
PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest();
PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint.getName(), evaluationPoint);
}

@ -89,6 +89,7 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest {
public void addPolicy() throws DeviceManagementException, GroupManagementException, PolicyManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
policyManagerService = new PolicyManagerServiceImpl();
PolicyManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService);
DeviceManagementService deviceManagementService = new TypeXDeviceManagementService(DEVICE_TYPE_A);
deviceMgtService.registerDeviceType(deviceManagementService);
operationManager = new OperationManagerImpl(DEVICE_TYPE_A, deviceManagementService);

@ -0,0 +1,134 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.ui.request.interceptor;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.entgra.ui.request.interceptor.beans.AuthData;
import io.entgra.ui.request.interceptor.util.HandlerConstants;
import io.entgra.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@MultipartConfig
@WebServlet("/default-credentials")
public class DefaultTokenHandler extends HttpServlet {
private static final Log log = LogFactory.getLog(DefaultTokenHandler.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
HttpSession httpSession = req.getSession(false);
if (httpSession != null) {
AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
if (authData == null) {
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
AuthData defaultAuthData = (AuthData) httpSession
.getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY);
if (defaultAuthData != null) {
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken()));
return;
}
String clientId = authData.getClientId();
String clientSecret = authData.getClientSecret();
String iotsCorePort = System.getProperty("iot.core.https.port");
if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())) {
iotsCorePort = System.getProperty("iot.core.http.port");
}
String tokenUrl =
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host")
+ HandlerConstants.COLON + iotsCorePort + "/api/device-mgt/v1.0/devices/" + clientId
+ "/" + clientSecret + "/default-token";
HttpGet defaultTokenRequest = new HttpGet(tokenUrl);
defaultTokenRequest
.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
defaultTokenRequest
.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest);
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API to get default token data.");
HandlerUtil.handleError(resp, tokenResultResponse);
return;
}
String tokenResult = tokenResultResponse.getData();
if (tokenResult == null) {
log.error("Invalid default token response is received.");
HandlerUtil.handleError(resp, tokenResultResponse);
return;
}
JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenResult);
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
AuthData newDefaultAuthData = new AuthData();
newDefaultAuthData.setClientId(clientId);
newDefaultAuthData.setClientSecret(clientSecret);
String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString();
newDefaultAuthData.setAccessToken(defaultToken);
newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString());
newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString());
httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData);
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken));
}
} else {
HandlerUtil.sendUnAuthorizeResponse(resp);
}
} catch (IOException e) {
log.error("Error occurred when processing GET request to get default token.", e);
}
}
/**
* Get Success Proxy Response
* @param responseString Response String
* @return {@link ProxyResponse}
*/
private ProxyResponse constructSuccessProxyResponse (String responseString) {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setData(responseString);
return proxyResponse;
}
}

@ -72,7 +72,6 @@ public class LoginHandler extends HttpServlet {
httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT));
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
JsonParser jsonParser = new JsonParser();
ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint);
String executorResponse = uiConfigResponse.getExecutorResponse();
if (!StringUtils.isEmpty(executorResponse) && executorResponse
@ -88,6 +87,7 @@ public class LoginHandler extends HttpServlet {
HandlerUtil.handleError(resp, null);
return;
}
JsonParser jsonParser = new JsonParser();
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData());
JsonObject uiConfigJsonObject = null;
if (uiConfigJsonElement.isJsonObject()) {

@ -18,7 +18,6 @@
package io.entgra.ui.request.interceptor;
import io.entgra.ui.request.interceptor.util.HandlerConstants;
import io.entgra.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@ -56,13 +56,13 @@ public class UserHandler extends HttpServlet {
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
HttpSession httpSession = req.getSession(false);
if (httpSession == null) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
if (authData == null) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
@ -91,7 +91,7 @@ public class UserHandler extends HttpServlet {
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
ProxyResponse proxyResponse = new ProxyResponse();
@ -106,18 +106,4 @@ public class UserHandler extends HttpServlet {
log.error("Error occurred while parsing the response. ", e);
}
}
/**
* Send UnAuthorized Response to the user
*
* @param resp HttpServletResponse object
*/
private void sendUnAuthorizeResponse(HttpServletResponse resp)
throws IOException {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
HandlerUtil.handleError(resp, proxyResponse);
}
}

@ -30,6 +30,7 @@ public class HandlerConstants {
public static final String TAGS_KEY = "tags";
public static final String APP_NAME_KEY = "applicationName";
public static final String SESSION_AUTH_DATA_KEY = "authInfo";
public static final String SESSION_DEFAULT_AUTH_DATA_KEY = "defaultAuthInfo";
public static final String UI_CONFIG_KEY = "ui-config";
public static final String PLATFORM = "platform";
public static final String USERNAME = "username";

@ -19,7 +19,6 @@
package io.entgra.ui.request.interceptor.util;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -35,9 +34,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@ -232,4 +229,17 @@ public class HandlerUtil {
}
}
/**
* Send UnAuthorized Response to the user
*
* @param resp HttpServletResponse object
*/
public static void sendUnAuthorizeResponse(HttpServletResponse resp)
throws IOException {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
handleError(resp, proxyResponse);
}
}

@ -36,6 +36,10 @@ import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthen
import org.wso2.carbon.webapp.authenticator.framework.authorizer.WebappTenantAuthorizer;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.regex.Pattern;
@ -43,12 +47,39 @@ import java.util.regex.Pattern;
public class WebappAuthenticationValve extends CarbonTomcatValve {
private static final Log log = LogFactory.getLog(WebappAuthenticationValve.class);
private static TreeMap<String, String> nonSecuredEndpoints = new TreeMap<>();
private static final TreeMap<String, String> nonSecuredEndpoints = new TreeMap<>();
private static final String PERMISSION_PREFIX = "/permission/admin";
public static final String AUTHORIZE_PERMISSION = "Authorize-Permission";
private static InetAddress inetAddress = null;
@Override
public void invoke(Request request, Response response, CompositeValve compositeValve) {
if (response != null) {
if (inetAddress == null) {
try {
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
if (!iface.isLoopback() && iface.isUp()) {
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
inetAddress = addresses.nextElement();
break;
}
}
break;
}
} catch (SocketException e) {
if (log.isDebugEnabled()) {
log.debug("Unable to get IP address of the node.", e);
}
}
}
if (inetAddress != null) {
response.setHeader("IoT-Node-IP", inetAddress.getHostAddress());
}
}
if ((this.isContextSkipped(request) || this.skipAuthentication(request))
&& (StringUtils.isEmpty(request.getHeader(AUTHORIZE_PERMISSION)))) {

@ -77,13 +77,13 @@
<IsAppUpdatable>true</IsAppUpdatable>
<IsInitialState>true</IsInitialState>
<IsDeletableState>true</IsDeletableState>
<Permission>/app-mgt/life-cycle/application/create</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/create</Permission>
<ProceedingStates>
<State>In-Review</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="In-Review">
<Permission>/app-mgt/life-cycle/application/review</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/review</Permission>
<ProceedingStates>
<State>Rejected</State>
<State>Approved</State>
@ -91,7 +91,7 @@
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Approved">
<Permission>/app-mgt/life-cycle/application/approve</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/approve</Permission>
<ProceedingStates>
<State>In-Review</State>
<State>Published</State>
@ -99,28 +99,28 @@
</LifecycleState>
<LifecycleState name="Rejected">
<IsDeletableState>true</IsDeletableState>
<Permission>/app-mgt/life-cycle/application/reject</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/reject</Permission>
<ProceedingStates>
<State>In-Review</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Published">
<IsAppInstallable>true</IsAppInstallable>
<Permission>/app-mgt/life-cycle/application/publish</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/publish</Permission>
<ProceedingStates>
<State>Blocked</State>
<State>Deprecated</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Blocked">
<Permission>/app-mgt/life-cycle/application/block</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/block</Permission>
<ProceedingStates>
<State>Published</State>
<State>Deprecated</State>
</ProceedingStates>
</LifecycleState>
<LifecycleState name="Deprecated">
<Permission>/app-mgt/life-cycle/application/deprecate</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/deprecate</Permission>
<ProceedingStates>
<State>Published</State>
<State>Retired</State>
@ -128,7 +128,7 @@
</LifecycleState>
<LifecycleState name="Retired">
<IsEndState>true</IsEndState>
<Permission>/app-mgt/life-cycle/application/retire</Permission>
<Permission>/permission/admin/app-mgt/life-cycle/application/retire</Permission>
</LifecycleState>
</LifecycleStates>

@ -159,5 +159,16 @@
<ExtensionClass>org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotifier</ExtensionClass>
<NotifyingInternalHost>http://localhost:8280</NotifyingInternalHost>
</EnrolmentNotificationConfiguration>
<DefaultRoles>
<Enabled>false</Enabled>
<Roles>
<Role>
<Name>test_role</Name>
<Permissions>
<Permission>/permission/admin/Login</Permission>
</Permissions>
</Role>
</Roles>
</DefaultRoles>
</DeviceMgtConfiguration>

@ -169,6 +169,7 @@
<Scope>perm:android:set-password-policy</Scope>
<Scope>perm:android:change-lock-code</Scope>
<Scope>perm:android:upgrade-firmware</Scope>
<Scope>perm:android:send-notification</Scope>
</Scopes>
<SSOConfiguration>
<Issuer>device-mgt</Issuer>

@ -572,6 +572,23 @@ CREATE TABLE IF NOT EXISTS DM_METADATA (
);
-- END OF METADATA TABLE --
-- DM_OTP_DATA TABLE --
CREATE TABLE IF NOT EXISTS DM_OTP_DATA (
ID INT AUTO_INCREMENT NOT NULL,
OTP_TOKEN VARCHAR(100) NOT NULL,
TENANT_DOMAIN VARCHAR(20) NOT NULL,
EMAIL VARCHAR(100) NOT NULL,
EMAIL_TYPE VARCHAR(20) NOT NULL,
META_INFO VARCHAR(20000) NOT NULL,
CREATED_AT TIMESTAMP NOT NULL,
EXPIRY_TIME INT NOT NULL DEFAULT 3600,
IS_EXPIRED BOOLEAN DEFAULT false,
TENANT_CREATED BOOLEAN DEFAULT false,
PRIMARY KEY (ID),
CONSTRAINT email_type_uk UNIQUE (EMAIL, EMAIL_TYPE)
);
-- END OF DM_OTP_DATA TABLE --
-- DASHBOARD RELATED VIEWS --
CREATE VIEW POLICY_COMPLIANCE_INFO AS
SELECT

@ -614,6 +614,23 @@ CREATE TABLE DM_METADATA (
);
-- END OF METADATA TABLE --
-- DM_OTP_DATA TABLE --
CREATE TABLE DM_OTP_DATA (
ID INT IDENTITY NOT NULL,
OTP_TOKEN VARCHAR(100) NOT NULL,
TENANT_DOMAIN VARCHAR(20) NOT NULL,
EMAIL VARCHAR(100) NOT NULL,
EMAIL_TYPE VARCHAR(20) NOT NULL,
META_INFO VARCHAR(20000) NOT NULL,
CREATED_AT DATETIME2(0) NOT NULL,
EXPIRY_TIME INT NOT NULL DEFAULT 3600,
IS_EXPIRED BIT DEFAULT false,
TENANT_CREATED BOOLEAN DEFAULT false,
PRIMARY KEY (ID),
CONSTRAINT email_type_uk UNIQUE (EMAIL, EMAIL_TYPE)
);
-- END OF DM_OTP_DATA TABLE --
-- DASHBOARD RELATED VIEWS --
IF NOT EXISTS (SELECT * FROM SYS.VIEWS WHERE NAME = 'POLICY_COMPLIANCE_INFO')

@ -630,6 +630,23 @@ CREATE TABLE IF NOT EXISTS DM_METADATA (
) ENGINE=InnoDB;
-- END OF METADATA TABLE --
-- DM_OTP_DATA TABLE --
CREATE TABLE IF NOT EXISTS DM_OTP_DATA (
ID INT AUTO_INCREMENT NOT NULL,
OTP_TOKEN VARCHAR(100) NOT NULL,
TENANT_DOMAIN VARCHAR(20) NOT NULL,
EMAIL VARCHAR(100) NOT NULL,
EMAIL_TYPE VARCHAR(20) NOT NULL,
META_INFO VARCHAR(20000) NOT NULL,
CREATED_AT TIMESTAMP NOT NULL,
EXPIRY_TIME INT NOT NULL DEFAULT 3600,
IS_EXPIRED BOOLEAN DEFAULT false,
TENANT_CREATED BOOLEAN DEFAULT false,
PRIMARY KEY (ID),
CONSTRAINT email_type_uk UNIQUE (EMAIL, EMAIL_TYPE)
);
-- END OF DM_OTP_DATA TABLE --
-- DASHBOARD RELATED VIEWS --
CREATE VIEW DEVICE_INFO_VIEW AS

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save