How to extend OrchardCMS to show/hide navigation and content from intranet vs internet users - orchardcms

I have certain pages that I want accessible only to users that are accessing the site from within a given IP range. For all other users, these pages should be inaccessible, and their respective links not visible in the menu/navigation.
I'm new to OrchardCMS, can someone provide some general guidance and point me in the right direction?

There two aspects to answer your question.
1. To check access to orchard content items and menu item relative to it:
To achieve this, you can implement new IAuthorizationServiceEventHandler to replace the default roles based authorization service, the best sample for you is ContentMenuItemAuthorizationEventHandler which you can find under Orchard.ContentPicker module, I included a sample code to explain the usage of this handler:
public class CustomAuthorizationEventHandler :
IAuthorizationServiceEventHandler{
public ContentMenuItemAuthorizationEventHandler() {
}
public void Checking(CheckAccessContext context) { }
public void Adjust(CheckAccessContext context) {
//Here you can put your business to grant user or not
context.Granted = true; //Roles service will look to this value to grant access to the user
context.Adjusted = true;
}
public void Complete(CheckAccessContext context) {}
}
2. To check access to some actions.
To achieve this, you can implement new IAuthorizationFilter to check access to some actions in your system:
public class CustomAuthorizationFilter : FilterProvider, IAuthorizationFilter {
public void OnAuthorization(AuthorizationContext filterContext) {
if (!Granted) {
filterContext.Result = new HttpUnauthorizedResult();
}
}
}

The solutions mentioned by #mdameer are ok, but you will run into difficulties when using containers, lists, projections and stuff.
I had a similar task but with date time ranges. See my question and answer to the task to get an idea how to tackle this via a custom part:
How to skip displaying a content item in Orchard CMS?

Related

Workflow extension that doesn't run

In an Acumatica code extension, I am attempting to create a workflow extension for BusinessAccountWorkflow. It adds a few actions that I want to suppress. My extension’s Configure method override basically doesn’t do anything, so that the base method doesn’t create actions. My override method doesn’t seem to be running, though, because the actions still appear, and my breakpoint isn’t hit. Below is the extension. What could I be missing to get this override to run?
public class BusinessAccountWorkflowExt : PXGraphExtension<BusinessAccountWorkflow,
BusinessAccountMaint>
{
public static bool IsActive() => false;
public override void Configure(PXScreenConfiguration configuration)
{
var context = configuration
.GetScreenConfigurationContext<BusinessAccountMaint, BAccount>();
context.AddScreenConfigurationFor(screen =>
{
return screen;
});
//context.RemoveScreenConfigurationFor();
}
}
Tony, your code sample sets IsActive to false which should disable the graph extension. This doesn't exactly seem to behave the same on workflows as it does normal graph extensions, so I'm not sure if it causes any harm.
Next, I think you really want to use UpdateScreenConfigurationFor instead of AddScreenConfigurationFor. This lets you tap into the defined workflow and add actions or alter conditions. For instance, you can update an action to be .IsHiddenAlways() if you don't want it to show in any condition. (Alternatively, you can hide it via permissions and never have to code for that!)
Take a look at standard workflow source code that ends _ApprovalWorkflow.cs for examples of how Acumatica updates an existing workflow to insert Approve and Reject functionality as well as altering transitions to inject the Pending approval state.
To be able to add your own actions, it's pretty simple code. Below is an example of how I injected my own actions into the menu for the Sales Order Entry screen, which honestly has a crazy complex workflow overall. However, always adding my buttons to the menu doesn't require touching any of that standard complexity.
using PX.Data;
using PX.Data.WorkflowAPI;
using SSCS;
namespace PX.Objects.SO.Workflow.SalesOrder
{
public class SOOrderEntry_Workflow_SSCS : PXGraphExtension<SOOrderEntry>
{
public static bool IsActive() => true; // Insert your own logic here
#region Initialization
public override void Configure(PXScreenConfiguration config)
{
Configure(config.GetScreenConfigurationContext<SOOrderEntry, SOOrder>());
}
protected virtual void Configure(WorkflowContext<SOOrderEntry, SOOrder> context)
{
context.UpdateScreenConfigurationFor(screen =>
{
return screen
.WithActions(actions =>
{
actions.Add<SOOrderEntry_Extension>(g => g.RecordOutage, a => a.WithCategory(PredefinedCategory.Actions));
});
});
}
#endregion
}
}
Where I added actions in the above sample using actions.Add, you would want to use actions.Update to alter the definition of the action. This is where you would put .IsHiddenWhen(condition) or .IsHiddenAlways().

How to customize the approval button on the Expense Claim screen

I am trying to customize the approve button and I can't find the right method to do it.
Could you tell me how I can manipulate that event.
Thanks in advance.
button to customize
Method
I looked around at the ExpenseClaimEntry, and the approval is added from the class ExpenceClaimApproval. You can browse the code through the Code Library in an extension Library under the folder App_Data\CodeRepository\PX.Objects\EP\ExpenseClaimEntry.cs. The derived type is declared in the Descriptor\Attribute.cs file. There is a StatusHandler you can set that is executed upon approval/denial.
I built this test graph and was able to break in the middle of the approval process:
public class ExpenseClaimEntry_Extension : PXGraphExtension<ExpenseClaimEntry>
{
public void CustomApprovalAction(EPExpenseClaim item)
{
//do something
}
public override void Initialize()
{
base.Initialize();
Base.Approval.StatusHandler += CustomApprovalAction;
}
}

Using Catel with Repository Pattern, EF6 and View Models

I cannot find any documentation on connecting a view model to a repository using Catel.
I have set up the Repository Pattern and my Models with EF6 Code First (all extending from ModelBase) but need to know how to use it with a ViewModel.
Do I need to create a service for the UnitOfWork? And if so, how? How will I use this in a ViewModel?
I am currently using the repository as a model in my viewmodel, but i do not think this is the correct way to do it? See my CompaniesViewModel below:
IUnitOfWork uow;
public CompaniesViewModel()
{
uow = new UnitOfWork<SoftwareSolutionsContext>();
CompanyRepository = uow.GetRepository<ICompanyRepository>();
}
public override string Title { get { return "Companies"; } }
protected override async Task Close()
{
uow.Dispose();
await base.Close();
}
protected override async Task Initialize()
{
Companies = new ObservableCollection<Company>(CompanyRepository.GetAll());
await base.Initialize();
}
public ObservableCollection<Company> Companies
{
get { return GetValue<ObservableCollection<Company>>(CompaniesProperty); }
set { SetValue(CompaniesProperty, value); }
}
public static readonly PropertyData CompaniesProperty = RegisterProperty("Companies", typeof(ObservableCollection<Company>), null);
[Model]
public ICompanyRepository CompanyRepository
{
get { return GetValue<ICompanyRepository>(CompanyRepositoryProperty); }
private set { SetValue(CompanyRepositoryProperty, value); }
}
public static readonly PropertyData CompanyRepositoryProperty = RegisterProperty("CompanyRepository", typeof(ICompanyRepository));
Essentially, I have 2 scenarios for working on the data:
getting all the data to display on a datagrid
selecting a record on the datagrid to open another view for editing a single record
Any guidance would be appreciated.
This is a very difficult subject, because there are basically a few options here:
Create abstractions in services (so the VM's only work with services, the services are your API into the db). The services work with the UoW
There are some people thinking that 1 is overcomplicated. In that case, you can simply use the UoW inside your VM's
Both have their pros and cons, just pick what you believe in most.

Get user details in liferay layout listener

I'm creating a listener for liferay Layout model. I want to get the page creating/updating user details to the log. Here is a snippet from my code.
public class LayoutListener extends BaseModelListener<Layout> {
private final static Logger log = Logger.getLogger(LayoutListener.class);
#Override
public void onAfterRemove(Layout layout) throws ModelListenerException {
// Need to find user deatils here.
if (log.isInfoEnabled()) {
log.info("Page -- " + layout.getName() + " -- removed.");
}
super.onAfterRemove(layout);
}
}
How can I get the relevant user who is deleting the page inside this method?
PS - I was able to get user from accessing the current thread. But I need to know a proper way to do this.
Well here is how liferay fetches it for listeners in its Audit EE plugin:
if(PrincipalThreadLocal.getName() != null) {
userId = GetterUtil.getLong(PrincipalThreadLocal.getName());
}
And we are also using the same thing in our custom listeners for Blogs and Documents.

Access Orchard Content Part Buttons (Save and Publish Now)

I want to disable Orchard Content Part buttons (Save and Publish Now) in the EDITOR template (when Content Item is created) based on some conditions. Can I do that ? How do I access the buttons in the EDITOR view.
Here are come examples,
To build a content fully from a Controller example, taken from the Blog Module
public ActionResult Create() {
if (!Services.Authorizer.Authorize(Permissions.ManageBlogs, T("Not allowed to create blogs")))
return new HttpUnauthorizedResult();
BlogPart blog = Services.ContentManager.New<BlogPart>("Blog");
if (blog == null)
return HttpNotFound();
dynamic model = Services.ContentManager.BuildEditor(blog);
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)model);
}
[HttpPost, ActionName("Create")]
public ActionResult CreatePOST() {
if (!Services.Authorizer.Authorize(Permissions.ManageBlogs, T("Couldn't create blog")))
return new HttpUnauthorizedResult();
var blog = Services.ContentManager.New<BlogPart>("Blog");
_contentManager.Create(blog, VersionOptions.Draft);
dynamic model = _contentManager.UpdateEditor(blog, this);
if (!ModelState.IsValid) {
_transactionManager.Cancel();
// Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
return View((object)model);
}
_contentManager.Publish(blog.ContentItem);
return Redirect(Url.BlogForAdmin(blog));
}
BuidEditor does the work for you.
And you should use a alternative version of this template, but remove the edit link and publish link.
Note, you need a route for you custom create action, and a menu link on the dashboard may come in handy.

Resources