How do I block access to any page in cakePHP. With page, I'm referring to actual views lying in the Page folder.
When I remove this line in, it works, but it also stops users from logging in. It would create a direct loop:
$this->Auth->allow('display');
Basically, when a user wants to view any page, and they are not logged in, they will be redirected to the login (app/users/login) page. After they've logged in, they will be directed to the page they last tried to access.
How would I go about this?
The problem in your situation is that all pages shown by the pagesController are the same action (display()), only using a different parameter (the page to display). You can therefore not block access to the display action, because that will block access to all pages.
If the number of pages is limited, then the easiest way to implement this is ControllerAuthorize. Read the documentation here; Using ControllerAuthorize
class AppController extends Controller {
public $components = array(
'Auth' => array('authorize' => 'Controller'),
);
public function isAuthorized($user = null) {
// Make all actions public
return true;
}
}
Then, inside your pages controller;
class PagesController extends AppController {
public function isAuthorized($user = null) {
if ('display' !== $this->request->action) {
// other actions; let he AppController handle access
return parent::isAuthorized($user);
}
if (!empty($user)) {
// Logged-in users have access to any page
return true;
}
$page = empty($this->request->params['pass'][0]) ? null : $this->request->params['pass'][0];
switch($page) {
case 'home':
case 'about':
// etc
return true;
}
// all other pages are 'private'
return false;
}
}
Just an example, of course, modify to fit your needs
use
$this->Auth->allow('\','display');
it allow all after '\' pages..
or
if you not allow except display page you do nothing.
Related
Somehow I find this hard to describe, but here I go:
I have a div in my SelectClasses Razor view page with an id="id152".
In order for me to show that div on the page at reload, I have to add the suffix #id152 to my page url.
<div id="id152">blabla</div>
...
..
Section 7
Now my question: Is there a way to add/pass this suffix to a 'RedirectToAction()'?
public ActionResult Index()
{
//All we want to do is redirect to the class selection page and add a suffix
return RedirectToAction("SelectClasses", "Registration", new { id = 99 })); //add suffix here somewhere
}
So when my SelectClasses view is shown, the url looks something like this:
'[url]/SelectClasses/99#id152'
The RedirectToActionResult (among the rest of RedirectTo* results) is meant to be used for generation of URLs based on registered routing data.
In your case, you wish to concatenate a hash parameter value (#id152) that is not being sent to the server and only used by the browser. That's why said methods don't bother dealing with it.
I suggest you do this instead:
var redirUrl = Url.Action("SelectClasses", "Registration", new { id = 99 });
redirUrl = String.Concat(redirUrl, "#id152");
return Redirect(redirUrl);
I'm trying to cache a page without the navbar of the page.
When i cache the page its all works fine but I get unwanted behavior.
Explanation:
When I cache the index page for example, the navbar is also cached so if the user press the log-in button and log-on, the user redirect to the same page (Index) and the log-in doesn't take affect (the user name and the log out button doesn't appear), the log-in and register buttons still shows, its a problem.
This is my code:
Home Controller:
public class HomeController : Controller
{
[OutputCache(Duration=(60*60))]
public ActionResult Index()
{
return View();
}
// ...
}
Can I do Vary by something to prevent it ?
I manage to find the solution using "haim770" guidelines.
The solution using the "Donut-Caching" (https://github.com/moonpyk/mvcdonutcaching)
1.first I get the "Donut Caching from the NuGet Packages.
2.I switched in the _layout.cshtml page the line : #Html.Partial("_LoginPartial") with #Html.Action("partialView", true)
3.Than I build an Action inside the Account controller called "partialView" that return the view I wanted, like this :
public ActionResult partialView()
{
return PartialView("_LoginPartial");
}
4.After it I decorated the Action that return the index page with
[DonutOutputCache(Duration=(60*60))]
like this:
[DonutOutputCache(Duration=(60*60))]
public ActionResult Index()
{
return View();
}
And you done, Thanks again to Haim(Chaim).
I've been testing the example code here http://mywsat.codeplex.com/
In their example they have different buttons to login to either the admin pages or members page using seperate links
However, I'm trying to use a single link to a landing page and after the user logs in redirect to the relevant page using codebehind. The landingpage requires login but all roles can view this page set in the rules.
landingpage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string redirectPath;
string pagePath = Request.AppRelativeCurrentExecutionFilePath;
if (Page.User.IsInRole("Administrator"))
{
//Admin
redirectPath = "~/admin/Default.aspx";
if (redirectPath != pagePath)
{
Response.Redirect(redirectPath);
}
}
else if (Page.User.IsInRole("Member"))
{
//Members
redirectPath = "~/members/Default.aspx";
if (redirectPath != pagePath)
{
Response.Redirect(redirectPath);
}
}
else if (Page.User.IsInRole("Trial"))
{
//Trial
redirectPath = "~/trial/Default.aspx";
if (redirectPath != pagePath)
{
Response.Redirect(redirectPath);
}
}
else
{
//Non member
redirectPath = "~/Default.aspx";
if (redirectPath != pagePath)
{
Response.Redirect(redirectPath);
}
}
}
The problem is the Page_Load event fires straight away and then launches login-with-captcha.ascx after the event has fired.
So then I moved the code to the login form login-with-captcha.ascx.cs to redirect after e.Authenticated = true; but it just redirects back to login-with-captcha.ascx in an endless loop
login-with-captcha.ascx.cs:
// Next, determine if the user's username/password are valid
if (Membership.ValidateUser(loginUsername, loginPassword))
{
e.Authenticated = true;
//tried redirecting from here based on role!
}
else
//............
How can I redirect from the landing page after the user is validated? I suspect it may have something to do with postback but need some help
Can you try adding the following as the first line within your Page_Load to see if it helps? This will likely prevent the endless loop issue if it's being caused by something that triggers a postback event, like a button click.
if (IsPostBack) return;
I am trying to access the CurrentUser property of the NancyContext. How do I do this from within the html of a Razor view?
I would be grateful for a code snippet if possible.
Thanks
Edit
I now extend Nancy.ViewEngines.Razor.HtmlHelpers to give me cross-view data with syntactic sugar that keeps the view code terse and readable.
Here are a few examples:
public static bool IsRegistered<T>(this HtmlHelpers<T> html)
{
var user = GetUser(html);
return user != null && user.IsRegistered;
}
public static bool IsAuthenticated<T>(this HtmlHelpers<T> html)
{
return GetUser(html) != null;
}
public static User GetUser<T>(this HtmlHelpers<T> html)
{
return (User)html.RenderContext.Context.CurrentUser;
}
And some razor code from a view. Here I am deciding to include the html for a Sign In popup (Foundation Reveal) only if the user is not currently authenticated - makes sense.
#if (!Html.IsAuthenticated())
{
Html.Partial("Reveals/SignInReveal");
}
You can access the NancyContext through the Html property's RenderContext property.
A sample usage:
#inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
<p>Current User: #Html.RenderContext.Context.CurrentUser </p>
However if your are using the SuperSimpleViewEngine (thanks the comment to #Sean) then you can do similar using the
#Context.CurrentUser.UserName
I want to limit access to certain elements of a user's profile so that only the user can see them and not other logged in users. So far the is_logged_in function (see below) works fine, now I need to refine it so that it is limited to a specific user that is logged in.
I'm already including a user_id variable in my session data, so that's available for use.
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if($is_logged_in)
{
$this->index();
}
else
{
redirect('fooview');
}
}
you will need to know the user_id of the profile you are viewing, lets assume in your controller you have it as $user_id.
in your controller you can do $is_owner = $this->session->userdata('user_id') == $user_id ? true : false;
then pass it to your view as e.g. $is_owner.
then in your view simply have
if($is_owner){
//show stuff
} else {
//message saying stuff is private!
}