Skip to content

Commit

Permalink
feat: front-end check the login plugin is enable
Browse files Browse the repository at this point in the history
- Check login plugin from config file of front-end
- Remove render `loginEnable` data of back-end
> move to front-end
- Change the config structure
> add login property
> move jwt into login property
- Use config file to toggle `login` button
- Remove unused code in `common.js`
- Log `Unauthorized` when token login failure
- Fix account size of user manager
> The size not minus 1 because currently the admin user not return
  • Loading branch information
Chinlinlee committed Jun 9, 2022
1 parent 848c613 commit 2f961ba
Show file tree
Hide file tree
Showing 12 changed files with 64 additions and 235 deletions.
4 changes: 1 addition & 3 deletions plugins/login/route/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ router.get("/dicom/UserManager", function (req, res) {
if (userType != "admin") res.redirect("/");
res.render("html/UserManager.html", {
user: user,
isAdmin: userType,
loginEnable: loginPlugin.enable
isAdmin: userType
});
});

Expand All @@ -33,7 +32,6 @@ router.get("/login", function (req, res) {
return res.render("html/login.html", {
user: user,
isAdmin: userType,
loginEnable: loginPlugin.enable,
messages: req.flash("error")[0]
});
}
Expand Down
2 changes: 1 addition & 1 deletion public/html/UploadDicom.html
Original file line number Diff line number Diff line change
Expand Up @@ -151,5 +151,5 @@ <h5 class="modal-title"><strong id="SystemInfoTitle"></strong></h5>
</script>
<script src="../scripts/external/formdata/formdata.min.js"></script>


<script src="../scripts/config.js"></script>
<script src="../scripts/dicom/UploadDicom.js"></script>
5 changes: 3 additions & 2 deletions public/html/UserManager.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
</div>
<div class="container-fluid" style="margin-top: 70px;">
<div style="float:right;width:130px"><label translate="userMS.LIST_TOTAL_COUNT" translate-values="{
DataListSize: DataListSize-1
DataListSize: DataListSize
}"></label></div>
<div dw-loading="DataList" dw-loading-options="{text: '載入清單...'}"
class="scrollable-area table-responsive scrollColor" style="float:left;width:100%;margin:5px">
Expand All @@ -36,7 +36,7 @@
</tr>
</thead>
<tbody>
<tr name="DataList" ng-repeat="DataItem in DataList | orderBy:orderColMtss:reverseList" ng-if="DataItem.account !=loggedUser">
<tr name="DataList" ng-repeat="DataItem in DataList | orderBy:orderColMtss:reverseList">
<td>{{($index)+"."}}</td>
<td>{{DataItem.account}}</td>
<td>{{DataItem.email}}</td>
Expand Down Expand Up @@ -69,6 +69,7 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-translate/2.19.0/angular-translate-loader-static-files/angular-translate-loader-static-files.js" integrity="sha512-zrJTB3VkziIateyhgLI0De3KBGrtK8uK9bR4K//Y0TxqcRXMZAP11m0U12YvGjAv+PlH4jPfVAZyYnao/ecnEQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="../scripts/external/angularjs/ui-bootstrap-tpls-3.0.6.min.js"></script>

<script src="../scripts/config.js"></script>
<script src="../scripts/common.js"></script>
<script src="../scripts/ngCommon.js"></script>
<script src="../scripts/user/manager.js"></script>
Expand Down
17 changes: 14 additions & 3 deletions public/navbar.html
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,14 @@
aria-haspopup="true"
aria-expanded="false"
></a>
<div class="dropdown-menu" aria-labelledby="dropdownLang">
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownLang">
<a class="dropdown-item" href="#" onclick="raccoon.setLang('en_US')">English</a>
<a class="dropdown-item" href="#" onclick="raccoon.setLang('zh_TW')">繁體中文</a>
</div>
</div>
</li>
</ul>
<% if (user) { %>
<% if (user) { %>
<ul class="nav navbar-nav navbar-right">
<li class="nav-item active">
<div class="dropdown show">
Expand All @@ -105,11 +105,22 @@
</ul>
<% } %>
<% if (!user) { %>
<ul class="nav navbar-nav navbar-right" ng-if="!$parent.loggedUser">
<ul class="nav navbar-nav navbar-right nav-login">
<li class="nav-item active">
<a class="nav-link" href="/login">LOGIN</a>
</li>
</ul>
<% } %>
</div>
</nav>
<script src="/scripts/config.js"></script>
<script>
if (envConfig) {
let navLogin = document.querySelector(".nav-login");
if (envConfig.login.enable) {
navLogin.style.display = "block";
} else {
navLogin.style.display = "none";
}
}
</script>
5 changes: 4 additions & 1 deletion public/scripts/ImageMS/ImageMS.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ imageMSApp.config([

imageMSApp.controller("imageMSCtrl",
function ($scope, $translate, imageMSService, commonService) {
if (envConfig.login.jwt) raccoon.tokenLogin();

$scope.loggedUser = "";
// commonService.user.init($scope);
$scope.dataList = [];
$scope.openSeries = { studyID: "", seriesList: [] };
$scope.parentStudy = 0;
Expand Down Expand Up @@ -425,4 +426,6 @@ $(function () {
$("#deletionInstanceModal").on("show.bs.modal", function () {
$("#deleteInstanceConfirmInput").val("");
});

raccoon.tokenLogin();
});
222 changes: 23 additions & 199 deletions public/scripts/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,205 +123,29 @@ async function sleep(ms = 1) {
},
setLang: (lang) => {
angular.element(document.body).scope().setLang(lang);
}
};
window.raccoon = raccoon;
})();

(function () {
let Micala = {
check_Date: (i_Date) => {
let flag = moment(i_Date, 'YYYYMMDD').isValid();
if (i_Date.length > 8) {
flag = false;
}
return flag;
},
get_StudyUID: (i_Item) => {
if (i_Item.identifier.value.includes('urn:oid:')) {
return i_Item.identifier.value.substring(8);
}
return i_Item.identifier.value;
},
get_Series: (i_Item) => {
let result = [];
for (let i = 0; i < i_Item.series.length; i++) {
result.push(i_Item.series[i]);
}
return result;
},
get_Date_Query: (from_Date, end_Date) => {
if (from_Date != "" && end_Date != "") {
return `${from_Date}-${end_Date}`;
} else if (from_Date != "") {
return `${from_Date}-`;
} else if (end_Date != "") {
return `-${end_Date}`;
}
},
getQIDOViewerUri: (i_Item) => {
let StudyDate = moment(i_Item.started).format('YYYYMMDD').toString() + '-';
let PatientName = i_Item.patient[0].name[0].text;
let PatientID = i_Item.subject.identifier.value;
let StudyInstanceUID = get_StudyUID(i_Item);
let qido_uri = `${envConfig.QIDO.http}://${envConfig.QIDO.hostName}/cornerstonetest309/html/start.html?StudyDate=${StudyDate}&PatientName=${PatientName}&PatientID=${PatientID}&StudyInstanceUID=${StudyInstanceUID}`;
return qido_uri;
},
createMyAutoComplete: (commonService) => {
const myAucomplete = new autoComplete({
data: { // Data src [Array, Function, Async] | (REQUIRED)
src: async () => {
return new Promise((resolve) => {
// User search query
const query = document.querySelector("#txtSearch").value
// Fetch External Data Source
let dataset = [];
commonService.es.getReportSuggestion(query).then(function (res) {
dataset = res.data;
console.log(dataset);
return resolve(dataset);
});
// Return Fetched data
});
// API key token
},
key: ["key"],
cache: false
},
selector: "#txtSearch", // Input field selector | (Optional)
// Post duration for engine to start | (Optional)
searchEngine: (query, record) => {
const select = {
highlight: "autoComplete_highlighted",
};
const highlight = value => `<span class=${select.highlight}>${value}</span>`;
// Loose mode
// Search query string sanitized & normalized
query = query.replace(/ /g, "");
// Array of matching characters
let regex = new RegExp(`[${query}]`, "gi");
return record.replace(regex, highlight('$&'));
}, // Search Engine type/mode | (Optional)

resultsList: { // Rendered results list object | (Optional)
render: true,
container: source => {
source.setAttribute("id", "txtAutoComplete_list");
source.setAttribute("style", "padding-top:10px;position: relative;z-index:1000");
source.setAttribute("class", "list-inline");
},
destination: document.querySelector("#txtSearch"),
position: "afterend",
element: "ul",
navigation: (event, input, resListElement, onSelection, resListData) => {
const select = {
result: "autoComplete_result",
highlight: "autoComplete_highlighted",
selectedResult: "autoComplete_selected"
};
const keys = {
ENTER: 13,
ARROW_UP: 38,
ARROW_DOWN: 40
};
const li = resListElement.childNodes,
liLength = li.length - 1;
let liSelected = undefined,
next;
// Remove selection class
const removeSelection = direction => {
liSelected.classList.remove("autoComplete_selected");
if (direction === 1) {
next = liSelected.nextSibling;
} else {
next = liSelected.previousSibling;
}
};
// Add selection class
const highlightSelection = current => {
liSelected = current;
liSelected.classList.add(select.selectedResult);
};
// Keyboard action
input.onkeydown = event => {
if (li.length > 0) {
switch (event.keyCode) {
// Arrow Up
case keys.ARROW_UP:
// Prevent cursor relocation
event.preventDefault();
if (liSelected) {
removeSelection(0);
if (next) {
highlightSelection(next);
let id = next.getAttribute("data-id");
onSelection(resListData.list[id]);
} else {
highlightSelection(li[liLength]);
onSelection(resListData.list[liLength]);
}
} else {
highlightSelection(li[liLength]);
onSelection(resListData.list[liLength]);
}
break;
// Arrow Down
case keys.ARROW_DOWN:
if (liSelected) {
removeSelection(1);
if (next) {
highlightSelection(next);
let id = next.getAttribute("data-id");
onSelection(resListData.list[id]);
} else {
highlightSelection(li[0]);
onSelection(resListData.list[0]);
}
} else {
highlightSelection(li[0]);
onSelection(resListData.list[0]);
}
break;
case keys.ENTER:
if (liSelected) {
let id = liSelected.getAttribute("data-id");
console.log(resListData.list[id]);
onSelection(resListData.list[id]);
}
break;
}
}
};
// Mouse action
li.forEach(selection => {
let id = selection.getAttribute("data-id");
selection.onmousedown = (event) => {
onSelection(resListData.list[id]);
const qs = $("#txtSearch").val();
const mode = $("#viewAndSearchMode").val();
window.location.href = `/search?txtSearch=${qs}&viewAndSearchMode=${mode}`
};
});
}
},
maxResults: 5, // Max. number of rendered results | (Optional)
highlight: true, // Highlight matching results | (Optional)
resultItem: {
content: (data, source) => {
source.innerHTML = data.match;
}
},
noResults: () => { // Action script on noResults | (Optional)

},
onSelection: feedback => { // Action script onSelection event | (Optional)

const selection = feedback.value.key;
$("#txtSearch").val(selection);
tokenLogin: () => {
let token = localStorage.getItem("raccoon_token");
let tokenLoginUrlObj = new URL(
"/login/token",
envConfig.backend.baseUrl
);

let xhr = new XMLHttpRequest();
xhr.open("POST", tokenLoginUrlObj.href, true);
xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.send();

xhr.onreadystatechange = function() {
if (
this.readyState === XMLHttpRequest.DONE &&
this.status !== 200
) {
console.error("Unauthorized");
console.error(xhr.response);
}
});
}
}
}
window.Micala = Micala
return Micala;
})()
};
window.raccoon = raccoon;
})();
8 changes: 4 additions & 4 deletions public/scripts/config.template.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ var envConfig = {
api: "api/fhir",
http: "http"
},
/**
* *If true, get token from localStorage and add headers for every requests
*/
jwt: false,
login: {
enable: true,
jwt: true //*If true, get token from localStorage and add headers for every requests
},
backend: {
baseUrl: "http://localhost:8081"
}
Expand Down
3 changes: 3 additions & 0 deletions public/scripts/dicom/UploadDicom.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ uploadApp.controller("UploadCtrl",
$scope.systemInfo = "";
$scope.uploadResult = "";

if (envConfig.login.jwt) raccoon.tokenLogin();


$scope.setLang = function(lang) {
$translate.use(lang);
}
Expand Down
12 changes: 1 addition & 11 deletions public/scripts/user/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,30 +22,20 @@ homePageApp.controller("HomePageCtrl",
async function (
$scope,
$translate,
$window,
HomePageService,
commonService
) {
$scope.setLang = function (lang) {
$translate.use(lang);
};

$scope.loggedUser = "";
await commonService.user.init($scope);
console.log($scope.loggedUser == "");
}
);

homePageApp.service("HomePageService", function ($http, $q, $location) {
return {
getProfile: getProfile
};
function getProfile() {
let request = $http({
method: "get",
url: "/api/profile"
});
return request.then(handleSuccess, handleError);
}

function handleSuccess(response) {
console.log(response);
Expand Down
Loading

0 comments on commit 2f961ba

Please sign in to comment.