I have a link on the main page that is only accessible if they are logged in. However, if this link is clicked, I want to show a custom error message on the login page (a custom 'Message.auth').
i.e. I want (pseudo code)
if (referer == '/users/reserve'){
Message.auth = 'Please log in to reserve tickets';
}
else {
Message.auth = 'Please log in to access that page';
}
Where would I put this bit of code?
Provided you have auth flash messages being output in the login view, this should work:
// login action of users_controller.ctp
if ($this->Session->check('Auth.redirect')
&& $this->Session->read('Auth.redirect') == '/users/reserve') {
$this->Session->write('Message.auth', 'Please log in to reserve tickets');
}
to get referer you can call $this->referer() to get the referring URL then pass that value to your view.
see: referer
Related
I am quite new to MEAN and I am learning a lot. At the moment I am trying to show an error message on my page when an user is not allowed into the website. The page contains a button which redirects you to the steam login. After you login the steam API sends your steamid which I will then check in the mongodb database:
app.get('/auth/steam/return',
passport.authenticate('steam', { failureRedirect: '/' }),https://stackoverflow.com/users/5333805/luud-van-keulen
function(req, res) {
UserModel.findOne({ steamid : req.user.id }, function (err, user) {
if(!user) {
console.log('does not exist');
//Probably have to set the error message here
} else {
req.session.userid = req.user.id; //Setting the session
}
});
res.redirect('/');
});
The only thing that I can't get working is how to show a message when the user is not allowed (he is not in the database). I want to use AngularJS for the HTML (so no Jade).
I do know that I have to set a variable somewhere in the response header and then with AngularJS I need to check if this variable exists or not. When It exist it should show the div which contains the error message.
The problem is that I can't use res.render because I need to redirect.
So in the block where user is not found, you should have something like:
res.status(401).send("Login failed.");
And then on the client side you can check the response status and display the mesage.
Edit: if you need help on the client side as well, please provide your client code.
I ended up using express-flash.
I want that users have to login before seeing other pages. If they try to access some other page, they have to login first.
I tried using the following, but it keeps giving me an HTTP Status 401 - Access Denied error.
http.csrf().disable().exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler).and()
.formLogin().loginPage("/login").successHandler(authSuccess)
.failureHandler(authFailure).and().authorizeRequests()
.antMatchers("/login", "/#/login", "/login.html", "/login.jsp", "login", "/login")
.permitAll().anyRequest().authenticated();
Since I am using angularjs, it might have to be something with that. I however still tried to add the /#/login part, but still without any good result.
You can achieve this using routing. Have a look at the below code.
app.run(function($rootScope, $location,cacheLogOut) {
// register listener to watch route changes
$rootScope.$on("$routeChangeStart", function(event, next, current) {
if ($rootScope.loggedUser == null) {
// no logged user, we should be going to #login
if (next.templateUrl == "login.html") {
// already going to #login, no redirect needed
} else {
// not going to #login, we should redirect now
$location.path("/login");
}
}
});
});
This is borrowed from Redirecting to a certain route based on condition. I am using it for redirecting to the login page if the user is not logged in. The $rootScope.loggedUser value is set once the user is logged in.
I am writing a android and windows native app. The native app stores the login details as reated for mulitple other web apps, and logs them into this when browsing to them from the native app.
one of the buttons in my app open a prestashop site for a authenticated user. How can i set the username and password and log that user in to the site programmitcally, giving the illusion and user experience that he has been seemlessly authenticated and accessed to his shop.
I know this is an old question, but theres another way which i find better for the purpose.
You include the AuthController from the controllers folder, set your post-parameters and execute the postProcess() method. After this, you can check the "$authController->errors" array for errors. If it's empty - the login was successful.
Example:
public function hookDisplayHeader()
{
if ($this->context->cookie->isLogged())
{
return;
} else {
$acceptLogin = false;
if( isset( $_POST["email"] ) && isset( $_POST["passwd"] ) )
{
$acceptLogin = $this->attemptLogin($_POST["email"],$_POST["passwd"]);
}
if( $acceptLogin )
return;
die( $this->display(__FILE__, 'logintemplate.tpl') );
}
}
protected function attemptLogin($email, $password)
{
include _PS_FRONT_CONTROLLER_DIR_ . "AuthController.php";
$auth = new AuthController();
$auth->isAjax = true;
$_POST["email"] = $email;
$_POST["passwd"] = $password;
$_POST["SubmitLogin"] = true;
$auth->postProcess();
if( count($auth->errors) > 0 )
{
$this->context->smarty->assign( "errors", $auth->errors );
return false;
} else {
return true;
}
}
Edit: This no longer works with Prestashop 1.6. As of PS 1.6 $auth->postProcess() either redirects or sends the ajaxs response immediately. There is no way to circumvent this. If you want to do something after login, you have to make two ajax calls.
Basically do the same as the PrestaShop login form does, which is (for v1.5 at least):
Sending a POST request to http(s)://yourshop.com/index.php?controller=authentication with the following parameters:
email: your customer's email address
passwd: your customer's password
back: name of the controller you want to be redirected to after success (ex: my-account)
SubmitLogin: put anything there, it just needs to be true, so that the controller knows it's a login action
If it doesn't work, your version may work differently and you will have to check the network tab of your favourite developer tool, to see what kind of request is sent with which parameters.
Let me explain the situation before I ask the question. I have a site, domain.com. the page sub.domain.com requires a user to be logged in to access. If I allow access to sub.domain.com/login which provides a form whose action is domain.com/login, it sends the data to domain.com/login and redirects back to sub.domain.com/login like it should. However, if I try to access sub.domain.com (which requires authentication) it redirects to domain.com/login correctly, but doesn't redirect back to sub.domain.com after logging in. I found the error to be that the redirect when not logged in wasn't sending the referrer header. Is there a way to make it so that if a user tries to access a page on a subdomain that requires authentication, that it will redirect him to domain.com/login, then back to where he originally was?
Does redirect always need to redirect back to sub.domain.com? If so, i'd suggest setting the AuthComponents loginRedirect attribute to the location you want the user to be redirected to. See this page: http://book.cakephp.org/1.3/en/view/1270/loginRedirect
Also, that page says that CakePHP automatically stores the controller-action pair you were accessing before the login in your session. So maybe you should also check whether your session is shared between the domain.com and sub.domain.com.
One final comment: what does happen after login? Are you redirected to the controller/action on domain.com or aren't you redirected at all?
NOTE: I'm assuming you're using CakePHP 1.3 and use the AuthComponent for logging users in.
Ok, it all had to do with routes. I finally was able to get it working by setting up a switch statement in my routes.php file:
switch(Configure::read('subdomain'))
{
case 'subdomain':
Router::connect('/login', array('controller'=>'users', 'action'=>'login'));
}
And set up my bootstrap like so:
preg_match('/^(?:www\.)?(?:(.+)\.)?(.+\..+)$/i', env('HTTP_HOST'), $matches);
$subdomain = empty($matches[1]) ? false : $matches[1];
if( strlen($subdomain) > 0 && $subdomain != "www" )
{
if($subdomain == 'api')
$_GET["url"] = $subdomain . "/" . (isset($_GET["url"]) ? $_GET["url"] : "");
Configure::write('subdomain', $subdomain);
}
I have an application added to several fan pages.
Ideally, the application should work custom depending on the referring page.
How can I detect which page referred to the app.
Developing a Facebook Iframe app, Using PHP.
(Question posted on Facebook's dev forum as well:
http://forum.developers.facebook.net/viewtopic.php?id=108409)
Thx,
Oren.
As explained in the Page Tab Tutorial
When a user selects your Page Tab, you will received the signed_request parameter with one additional parameter, page. This parameter contains a JSON object with an id (the page id of the current page), admin (if the user is a admin of the page), and liked (if the user has liked the page). As with a Canvas Page, you will not receive all the user information accessible to your app in the signed_request until the user authorizes your app.
With the http referer, you will have the the Facebook proxy url.
In your case, I think you have to use the id of the page (passed in the signed request).
The following PHP snippet will output the signed_request received on the page tab. You will find the page ID needed in your case.
<?php
$appsecret = 'Your App Secret';
$signed_request = $_REQUEST['signed_request'];
$request = $_REQUEST;
$signed_request = parse_signed_request($signed_request, $appsecret);
print_r($signed_request);
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
?>
Using the new php-sdk, there is a quicker way to find out the referring page. $facebook->getSignedRequest() will return an array with the signed request, authorization token, page and user basic info.