Orchard CMS — Authenticated User — Layout Snippet
Snippets are Layout Elements that you can drag n drop into the layout canvas. You add them to the Views/Elements folder of your theme and they have to end with Snippet.cshtml. Layout Snippets it’s one of my favourites features of Orchard.
In this Blog Post, I will show you how to make a Page only accessible for authenticated users. There are plenty of ways to do it but I will use the Layout Snippet way.
If a user is not logged in the WorkContext.CurrentUser will be null.
We will a create a cshtml file in the Views/Elements folder of our theme, with the name AuthenticatedUserSnippet.
@{
string redirectUrl = Model.URL;
if (WorkContext.CurrentUser == null)
{
if(String.IsNullOrEmpty(redirectUrl)) {
Response.Redirect("~/Users/Account/LogOn");
} else {
Response.Redirect("~/" + redirectUrl);
}
}
}
We will create a manifest for the Snippet in order to add a description, an icon and a custom field.
The manifest name must be the same as the cshtml. The file name will be AuthenticatedUserSnippet.txt.
DisplayName: Authenticated User
ToolboxIcon: "\uf007"
Description: Authenticated User Snippet
Category: Snippets
Fields:
- Name: URL
DisplayName: URL
Description: If the user is not authenticated will be redirected to this url. Leave empty for default.
Type: Text
You have to add the AuthenticatedUserSnippet.cshtml
and the AuthenticatedUserSnippet.txt
files to your Views/Elements
folder of your theme.
After this you can drag the AuthenticatedUser snippet wherever you want and if the user is not logged in will be redirected to a custom url or to login page.
You can download the AuthenticatedUserSnippet.cshtml
and the AuthenticatedUserSnippet.txt
files from here.
This feature is already installed in this head start Orchard CMS theme.
Originally published at https://orchardtricks.dotnest.com.