How to clear all session variables without getting logged out - django

I am trying to clear all of the session variables but not logout the current user.
user = request.session.get('member_id', None)
request.session.flush()
request.session.modified = True
request.session['member_id'] = user
request.session.modified = True
Will this also affect other users of the site?

As of Django 1.8, any call to flush() will log out the user. From the docs:
Changed in Django 1.8: Deletion of the session cookie is a behavior
new in Django 1.8. Previously, the behavior was to regenerate the
session key value that was sent back to the user in the cookie.
If you want to be able to delete keys but keep the user logged in, you'll need to handle it manually:
for key in request.session.keys():
del request.session[key]
Or just delete the specific keys that are of concern:
del request.session['mykey']

In versions of django < 1.8, session.flush deletes the session data and regenerates the session key. It won't affect other users since session keys are unique.

As an improvement to shacker's1 in Python 2.x dict.keys() returns a list copy of the keys of a dictionary, in Python 3.x it instead returns an iterator. changing the size of an iterator is unwise. For an version safe implementation casting to list will prevent any size issues
for key in list(request.session.keys()):
del request.session[key]
My previous answer suggested the use of dict.viewkeys() but it will also return an iterator in python 3.x.

You can clear keys you have set in the django session, but to do so without logging the user out takes a little bit of trickiness; request.session.flush() logs the user out. And request.session = {} in deleting all keys in the session dictionary will also log the user out.
Thus, to clear out keys without logging the user out, you have to avoid keys that begin with an underscore character. The following code does the trick:
for key in list(request.session.keys()):
if not key.startswith("_"): # skip keys set by the django system
del request.session[key]

request.session internally uses cookies. And when a user requests some url of the site, only cookies present on that user's machine is sent to the server. So, request.session is always tied to the current user.
So, this in no way will affect other users of the site.
Also this will not log out the current user, because you are using flush() which will delete the old session and create a new session and this new session would be associated with the current user.
flush() internally uses clear(), delete() and create().
In the response this new session's key would be sent as a cookie and in subsequent requests this new session would continue working normally.

session_keys = list(request.session.keys())
for key in session_keys:
del request.session[key]

Related

Revoking tokens using Django rest-framework-jwt

I'm thinking of allowing a user to revoke previously issued tokens (yes, even though they are set to expire in 15 minutes), but did not find any way to do so using DRF-jwt.
Right now, I'm considering several options:
Hope someone on SO will show me how to do this out-of-the-box ;-)
Use the jti field as a counter, and, upon revocation, require jti > last jti.
Add user-level salt to the signing procedure, and change it upon revocation
Store live tokens in some Redis DB
Is any of the above the way to go?
We did it this way in our project:
Add jwt_issue_dt to User model.
Add original_iat to payload. So token refresh won't modify this field.
Compare original_iat from payload and user.jwt_issue_dt:
from calendar import timegm
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class CustomJSONWebTokenAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = super(CustomJSONWebTokenAuthentication, self).authenticate_credentials(payload)
iat_timestamp = timegm(user.jwt_issue_dt.utctimetuple())
if iat_timestamp != payload['iat']:
raise exceptions.AuthenticationFailed('Invalid payload')
return user
To revoke a token you just need to update the field user.jwt_issue_dt.

Odoo website, Creating a signup page for external users

How can I create a signup page in odoo website. The auth_signup module seems to do the job (according to their description). I don't know how to utilize it.
In the signup page there shouldn't be database selector
Where should I store the user data(including password); res.users or res.partner
you can turn off db listing w/ some params in in odoo.cfg conf
db_name = mydb
list_db = False
dbfilter = mydb
auth_signup takes care of the registration, you don't need to do anything. A res.user will be created as well as a partner related to it.
The pwd is stored in the user.
User Signup is a standard feature provided by Odoo, and it seems that you already found it.
The database selector shows because you have several PostgresSSQL databases.
The easiest way is to set a filter that limits it to the one you want:
start the server with the option --dbfilter=^MYDB$, where MYDBis the database name.
User data is stored both in res.userand res.partner: the user specific data, such as login and password, are stored in res.user. Other data, such as the Name is stored in a related res.partner record.

Allowing an anonymous person to post a value

An anonymous user (no login) gets directed to a landing page where there is a button and text field to post information.
I want the act posting of data to be tied to the person landing on the page. ie knowing the target url of the post shouldn't allow you to post stuff, it should be tied to a very short duration session.
I am using Django.
What is the simplest or built in method to use?
Sessions
You can store this information in the anonymous user's session if you have a session store configured. To start the session:
request.session["allow_post_until"] = datetime.datetime.now() + datetime.timedelta(...)
And to check it:
if not (request.session["allow_post_until"] and request.session["allow_post_until"] < datetime.datetime.now()):
raise PermissionDenied
Signed Cookies
If you are using django 1.4 and don't want to configure a session store you can use signed cookies for this. When you want to enable a session for the user, set a cookie with an appropriate max_age. When a user posts, check for the signed cookie and check its validity. To set:
response.set_signed_cookie("mysession", "sessiondata", max_age=<session period in seconds>)
To check:
request.get_signed_cookie("mysession", max_age=<session period in seconds>)

ASP.NET MVC4 Remember login password using cookies - Secure way?

I would like the feature for the sign in box to have the username and password automatically filled in if the user has previously been on the site and logged in successfully before. I see this implemented on many sites so I figured theres a way to do this without creating a security risk.
EDIT: According to a post this is a browser feature and should not be implemented in code because its never safe to store password anywhere.
Edited the code to reflect a new direction where Im only storing the username. However, Im not sure what to look for to see if its working. I tried to login then logout, then go to login screen again but username box still blank when the view loads in. Not sure if its the code or Im testing it the wrong way.
Login POST:
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return Json(new { ok = true, message = "Login successful." });
}
}
return Json(new { ok = false, message = "The username or password you entered is invalid. Please try again." });
}
Login GET:
[HttpGet]
public ActionResult Login(string path)
{
LoginModel model = new LoginModel();
HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName.ToString()];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null & !authTicket.Expired)
{
model.UserName = authTicket.UserData;
}
}
return PartialView(path, model);
}
There are couple of issues with your code. The first one is that you are adding the cookie to the Request object instead of adding it to the Response => Response.Cookies.Add(authCookie);.
The second issue is that you are creating a non-persistent cookie meaning that it will only live through the browser session. Once the user closes the browser it will be gone forever because it was never stored on the client computer. In order to create a persistent cookie you need to specify an expiration date for it which will obviously correspond for how long this cookie will be persisted on the client computer. For example if you wanted to remember for 5 days:
HttpCookie authCookie = new HttpCookie("authCookie", "cookieValue")
{
Expires = DateTime.Now.AddDays(5)
};
Another issue is that you are storing only the MD5 hash of the password inside the cookie and you expect to be able to decrypt it later with FormsAuthentication.Decrypt which is not possible. This method can decrypt values that were encrypted with the Encrypt method.
And the biggest problem of them all is the security: you should never be storing any password related stuff anywhere. The username should suffice. Browsers offer the possibility to remember passwords for given site. I would recommend you using this functionality instead of doing what you are doing.
Another possibility is to emit a persistent authentication cookie when the user logs in, so that even if he closes the browser he will be remembered as authenticated for the validity period you specified in this authentication cookie.
you don't need the actual password for the user to make sure he logged in previously. You shouldn't even save the actual password in the database. You usually only save a salted hash of that password. When the user logs in, you create a hash for that password and compare it with the hash stored in the database. If they match, he entered the correct password.
As for storing login information in a cookie, i'd then store a salted hash of that password hash in the cookie. Upon GET, you just create a salted hash of the stored password hash and compare it with the one from the cookie. If they match, the login cookie is valid. That way you never actually store any user password anywhere.
To make this more secure, the login page should be secured by SSL, otherwise the password would at least once be transmitted unencrypted.
If you're using SQL, you can generate a random number when the user first logs on. Store this number in the Users table, and also as a cookie on the user's machine. The user can then authenticate by comparing the random number with that stored on the server.
It's a good idea to timestamp the login though, so it expires after a set period of time.

Flash + pyAMF + Django session cookie security

First off, if there is a true, official way of having flash/flex's NetConnections usurp the session/cookie state of the surrounding web page, so that if the user has already logged in, they don't need to provide credentials again just to set up an AMF connection, please stop me now and post the official answer.
Barring that, I'm assuming there is not, as I have searched and it seems to not exist. I've concocted a means of doing this, but want some feedback as to whether it is secure.
Accessing a wrapper-page for a flash object will always go to secure https due to django middleware
When the page view is loaded in Django, it creates a "session alias" object with a unique key that points to the current session in play (in which someone ostensibly logged in)
That session alias model is saved, and that key is placed into a cookie whose key is another random string, call it randomcookie
That randomcookie key name is passed as a context variable and written into the html as a flashvar to the swf
The swf is also loaded only via https
The flash application uses ExternalInterface to call java to grab the value at that randomcookie location, and also deletes the cookie
It then creates a NetConnection to a secure server https location, passing that randomcookie as an argument (data, not in the url) to a login-using-cookie rpc
At the gateway side, pyamf looks up the session alias and gets the session it points to, and logs in the user based on that (and deletes the alias, so it can't be reused)
(And the gateway request could also set the session cookie and session.session_key to the known session ID, but I could let it make a whole new session key... I'm assuming that doing so should affect the response properly so that it contains the correct session key)
At this point, the returned cookie values on the flash side should stick to the NetConnection so that further calls are authenticated (if a connection is authenticated using username and password the normal way, this definitely works, so I think this is a safe bet, testing will soon prove or disprove this)
So, is this unsafe, or will this work properly? As far as I know, since the html page is guaranteed to be over ssl, the key and cookie data should be encrypted and not steal-able. Then, the info therein should be safe to use one-time as basically a temporary password, sent again over ssl because the gateway is also https. After that, it's using the normal pyAMF system over https and not doing anything out of the ordinary.
No responses on this so far, so the best I can do is confirm that it does in fact physically work. For details on how to set up Flex Builder to write html-wrappers that communicate with Django pages templates, see my other post. The above was accomplished using a combination of the aforementioned, plus:
Made a SessionAlias model:
class SessionAlias(models.Model):
alias = models.CharField( max_length=40, primary_key=True )
session = models.ForeignKey( Session )
created = models.DateTimeField( auto_now_add=True )
Flex points to a Django page that loads via a view containing:
s = SessionAlias()
s.alias = SessionStore().session_key // generates new 40-char random
s.session = Session.objects.get( session_key=request.session.session_key )
s.save();
randomcookie = SessionStore().session_key // generates new 40-char random
kwargs['extra_context']['randomcookie'] = randomcookie
response = direct_to_template( request, **kwargs )
response.set_cookie( randomcookie, value=alias )
In the flex html-wrapper, where randomcookie is the location to look for the alias:
<param name="flashVars" value="randomcookie={{randomcookie}}" />
In applicationComplete, where we get randomcookie and find the alias, and log on using that:
var randomcookie:String = this.parameters["randomcookie"];
// randomcookie is something like "abc123"
var js:String = "function get_cookie(){return document.cookie;}";
var cookies:String = ExternalInterface.call(js).toString();
// cookies looks like "abc123=def456; sessionid=ghi789; ..."
var alias:String = // strip out the "def456"
mynetconnection.call( "loginByAlias", alias, successFunc, failureFunc );
Which in turn access this pyamf gateway rpc:
from django.contrib.auth import SESSION_KEY, load_backend
from django.contrib.auth.models import User
from django.contrib import auth
from django.conf import settings
def loginByAlias( request, alias ):
a = SessionAlias.objects.get( alias=alias )
session_engine = __import__( settings.SESSION_ENGINE, {}, {}, [''] )
session_wrapper = session_engine.SessionStore( a.session.session_key )
user_id = session_wrapper.get( SESSION_KEY )
user = User.objects.get( id=user_id )
user.backend='django.contrib.auth.backends.ModelBackend'
auth.login( request, user )
a.delete()
return whateverToFlash
And at that point, on the flash/flex side, that particular mynetconnection retains the session cookie state that can make future calls such that, inside the gateway, request.user is the properly-authenticated user that logged onto the webpage in the first place.
Note again that the run/debug settings for flex must use https, as well as the gateway settings for NetConnection. And when releasing this, I have to make sure that authenticated users stay on https.
Any further info from people would be appreciated, especially if there's real feedback on the security aspects of this...
IE doesn't give access to cookies in local development but if you publish the SWF and put on a domain, it should pickup the session just like ever other browser. Use Firefox 3.6 to build your flex apps locally.
Tested in IE8, Firefox using a pyamf gateway on Flex 3 with NetConnection. The gateway function was decorated with #login_required