log user out from template file in django - django-templates

I want to add a logout href in my admin.html like:
Log out
What can I do to destroy the session when a user is redirected to /panel/ by clicking that 'Log out' link? What are the session variables to use in template files?
thank you

In your view do something like this
#views.py
from django.contrib.auth import logout as auth_logout
def logout(request):
response = auth_logout(request)
return HttpResponseRedirect('http://yourdomain.com')
#urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^panel/$', 'views.logout', name='logout'),
)

Related

After a successful login, I want to be redirected to the screen I was on before I logged in. getLoginRedirect() does not work

Suppose you were in the user list screen. From there you will go to the login screen to log in. There, you will enter your email and password and enter the submit button.
You have successfully logged in.
If the login is successful, we want to be redirected to the user list screen.
If you were in the user details screen, you will be redirected to the user details screen by
If the user was on the edit screen, the user editing screen
I have read the AuthenticationPlugin documentation at book.cakephp.org.
There I learned to use getLoginRedirect() to achieve this functionality.
I am aware that what I want to do will happen once I set up in the steps below.
However, getLoginRedirect() returns null.
What do I need to do?
What am I missing?
What's wrong?
// in Application.php
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$path = $request->getPath();
$authenticationService = new AuthenticationService([
'unauthenticatedRedirect' => '/',
'queryParam' => 'redirect', // <- I believe this is the only one that matters.
]);
// Abbreviated below....
}
// in UsersController
public function login()
{
$this->request->allowMethod(['get', 'post']);
if ($this->request->is('post')) {
$result = $this->Authentication->getResult();
$requestData = $this->request->getData();
if ($result->isValid()) {
// I want to get the original url. But null is passed.
$redirect = $this->Authentication->getLoginRedirect() ?? '/';
return $this->redirect($redirect);
}
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->error(__('メールアドレス、またはパスワードが間違っています。'));
}
}
}
I think I've disclosed everything related to getLoginRedirect(). If there is something missing or something you are curious about, please feel free to let me know.
Please help me. Please help me...
The login redirect functionality provided by the plugin only works automatically when you are being redirected to the login URL after accessing a URL that requires authentication while not being logged in. In that case the authentication middleware will set the redirect query string variable with the current URL, so that the component can pick it up after the redirect to the login URL.
If you manually visit the login URL, then you'd also need to manually set the redirect query string variable, ie in your menu where you build the link that takes you to the login, add the current URL to the query string, something along the lines of this:
$service = $this->request->getAttribute('authentication');
// here `$queryParam` would by default be `redirect`
$queryParam = $service->getConfig('queryParam');
echo $this->Html->link('Login', [
'plugin' => null,
'prefix' => false,
'controller' => 'Users',
'action' => 'login',
'?' => [
$queryParam => $this->request->getRequestTarget(),
],
]);
So if you're on /users/show, the login link's URL would look something like:
/login?redirect=/users/show
and the form helper that builds your login form should pick up that exact URL, so that after submitting the form, the authentication component can read the redirect URL from the current URL accordingly.
See also
Cookbook > Views > Helpers > Html > Creating Links

Login page rendering value even when the user in not logged in

I am working on an angular app and implementing registration and logging functionality in it using Firebase. Both functionalties are working fine.
Now the trouble that I am having is in onAuthStateChanged() function. What I want is once a user is logged in, he/she must be able to see a message saying that they are logged in. I am even able to see "Hi {{currentUser.firstname}}" that I have mentioned in the code once I log in but as soon as I refresh the page and try to log in again, I see that "Hi {{currentUser.firstname}}" even when I do not click the login button. I don't know how my login page is rendering $rootScope.currentUser value even when I haven't logged in. I have written the following code for it
JS
auth.onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var data = firebase.database().ref('users/' + user.uid);
data.on('value', function(snapshot) {
var userobj=snapshot.val();
$rootScope.currentUser=userobj;
})} else {
// No user is signed in.
$rootScope.currentUser=' ';
}
});
html
<div class="userinfo" ng-show="currentUser">
<span class="userinfo">Hi {{currentUser.firstname}}</span>
</div>
The behaviour is by-design. From the docs:
The Firebase Auth instance persists the user's state, so that refreshing the page (in a browser) or restarting the application doesn't lose the user's information.
If you do not want the users's auth state to be persisted, you will need to sign out the user.

single page application deep linking with login page

My team is going to build a single-page-application for our future project. At the moment, I have a problem with designing the app with login page. There are 2 approaches:
Create the login page as a separate page, the rest of the app is another single page.
The app has only 1 page and the login page will be a view in the app which is switched back and forth using javascript.
I don't know which approach I should take. I have read some discussions on the internet, it seems like it's more popular to create the login page as a separate page, the reason for this is we can use normal cookie-based authentication with session on server, redirect users to default page (main page) after successful login, and so on. Therefore, I'm thinking about creating the login page as a separate page, but I have a problem with deep linking.
For example, let's say I have 2 pages: login.html, index.html (main page). When an unauthenticated user requests a page like this index.html#product=1, the user will be redirected to the login.html, after successfully loging in, redirect the user back to index.html#product=1. But at this point, the #product=1 is lost.
Please advice me on how to keep the deep link or should I take the second approach?
Thank you
If you are building a single page app, it would be 'nicer' from the users point of view to have it all on one page, so I would suggest option 2.
Not sure if you need javascript to switch it though - you could use something like the following (PHP code)
At the start of the application saves what view the user is looking at and checks if the user pressed 'submit' on the login form
$selected_menu = $_GET['menu'] ;
//check to see if they've submitted the login form
if(isset($_POST['submit-login'])) {
If the login is successful, redirect them back to the same page with the appropriate view as a parameter
Then in the main page of the app when you are about to display data you would check to see if the user is validated, and if not then present the login form as part of the page.
$usr = CheckLogon();
if ( $usr == "" ) { // check for correct test to make sure user is logged on
ShowLoginForm();
....
I decided to go with approach 2: The app has only 1 page and the login page will be a view in the app which is switched back and forth using javascript.. I found out that it's not difficult to do and I can still use normal cookie-based authentication with session on server, redirect users to default page (main page) after successful login, and so on. Here is a sample code how I do it with angularjs.
Routing:
var App = angular.module('App', ["ui.state"]);
App.config(function ($stateProvider, $routeProvider) {
$stateProvider.
.state('login', {
url: "/login?returnUrl",
templateUrl: '/Home/Login',
controller:"LoginController"
})
.state('main', {
url: "/main",
abstract:true,
templateUrl: '/Home/Main',
controller: "MainController"
})
})
.run(function ($rootScope, $state, $stateParams, $location) {
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
if (error.status == 401) {
$state.transitionTo("login", { returnUrl: $location.url() });
}
})
});
The point here is when there is a route change error with status 401 (from the server) indicating that the user is not logged in, I will transition to login state with the return url.
After the user successfully logging in using ajax, I will transition the state back to my main view. Something like this:
$http.post("/Login", JSON.stringify({UserName:username,Password:password}))
.success(function (data, status, headers, config) {
var returnUrl = $stateParams.returnUrl ? $stateParams.returnUrl : "mydefaulturl";
$location.url(returnUrl);
})
With this approach, now I'm able to create deep-link to jump to a specific state in my app with login page and return url.

Rails 3: Rendering actions with named anchors/fragments after failed form submission

The edit view for one of my models contains tabs that utilize anchors in the url to switch between settings such as model/1/edit#tab1 and model/1/edit#tab2. Is there a way to redirect to these anchors after submitting the edit form but failing to save due to errors? My current code is below:
def update
#user = Product.new(params[:user])
if #user.save
flash[:success] = "Your user has been created"
redirect_to #user
else
render 'edit' //want to render here with an anchor
end
end
I would like to store the url containing the anchor before form submit and then re-render the form with the same anchor while rendering error messages. Any ideas?
Best way was to use jquery cookie to save last opened tab and then set default tab using saved cookie.

How do I get a link for a protected page and redirect the user to the login page?

In my Sitecore site I need a page viewable only to authorized users. I have allowed read and inheritance for the role I want and denied read and inheritance for extranet\anonymous. The item is part of a group where the other items are not protected. This list of items is databound and rendered as navigation links on the site.
var id = new Sitecore.Data.ID("<guid here>");
var item = Sitecore.Context.Database.GetItem(id);
// protected item is not part of Children collection when user is anon.
this.navrepeater.DataSource = item.Children;
this.navrepeater.DataBind();
When I'm logged in, a link to the protected item is shown and I can view the page. When I'm not logged in (operating as extranet\anonymous), the link is not shown at all. When I go the url directly I get a 403 error. In my web.config I have set the loginPage attribute on the site node but I don't get redirected.
<site name="mysite" ... loginpage="/login.aspx" />
So,
How do I display the link to the protected page for anonymous users
How do get sitecore to redirect the user to the login page when needed
1) You can wrap the code that retrieves the items for the nav links in the SecurityDisabler to show the link even if they can't view the page:
using(new SecurityDisabler()) { // this bypasses any security
this.navrepeater.DataSource = item.GetChildren(); // note that the Children property is deprecated, use the GetChildren() method instead
}
2) If you make your page's code behind class inherit from Sitecore.Shell.Web.UI.SecurePage it will handle the check and redirect to the login page for you. No coding needed.