简体   繁体   中英

Remove or hide html links based on user permission when viewing the page

I have a webpage with 100's of links to control a piece of hardware, I would like certain (guest) users to be able to see the entire page but basically render/serve this same page without any of the a href=" links.

I already have the login mechanism and session/cookie set based on the user, I'm just wondering if there is a more efficient way to hide/remove all the a href=" links other than encapsulating each in a IF ELSE statement.

For example, this is what I have today...

    <% If Session("adminuser") = "true" Then %><a target="hidden" href="/trigger.asp?cmd=ext-access&data=on">External Access is off</a>
    <% Else %>External Access is off
    <% End If %>

A fast solution may be the following. Each link is encapsulated in somthing like this:

<span class="admin-action" data-action="/trigger.asp?cmd=ext-access&data=on">External Access is off</span>
<span class="guest-action" data-action="/trigger.asp?cmd=hello-world&data=on">Hello World</span>

The following JavaScript will insert the link dynamically if allowed:

<script>
<% If Session("adminuser") = "true" Then %>
document.querySelectorAll('.admin-action').forEach(function (e) {
   var action = e.getAttribute('data-action');
   e.innerHTML = '<a target="hidden" href="' + action + '">' + e.innerHTML + '</a>';
});
<% End If %>

<% If Session("guestuser") = "true" Then %>
document.querySelectorAll('.guest-action').forEach(function (e) {
   var action = e.getAttribute('data-action');
   e.innerHTML = '<a target="hidden" href="' + action + '">' + e.innerHTML + '</a>';
});
<% End If %>
<script>

Wrap the linking in a function:

function adminLink( linkTarget, linkText ) {
    if( Session("adminuser") = "true" ) Then
        adminLink = "<a target='hidden' href='" & linkTarget & "'>" & linkText & "</a>"
    else
        adminLink = linkText
    end if
end function

Then for each link just do:

<%=adminLink( "/trigger.asp?cmd=ext-access&data=on", "External Access is off" )%>

You could probably generalize the function so you could use it sitewide in similar situations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM