Django Login/Logout Logger - python-3.x

I have a django project where I need to know how much time each user spends on the site.
The first thing that came to my mind was that since I have a CustomUser I can create my own login/logout view and populate a table with login and logout and the user's identifier. However, I wanted to know if there is a callback function for django.contrib.auth.urls. So I can use the default login form?

You can use Django Signals. Django has several built-in Signals that trigger when various events occur. For example, post_save and post_delete. You can write handlers that listen for these signals to trigger whenever the session (or token, JWT, so on, depending on your authentication backend) is created or destroyed. You can then perform actions (like updating a database table) whenever these events occur.

Related

How to secure Firebase account etc. from user actions?

I am developing a hobby project using Firebase and some Node.JS running on Google App Engine as backend. I am a real newbie in this area, and also just hear about Firebase a month ago.
My question relates to how various "things" can be secured from user actions, even though Firebase is running as JS on client-side.
I am aware that the DB and Storage can be secured using logical rules - that is in place.
My question rather concerns the actions an user can perform with firebase.auth() and similar, such as:
firebase.auth().createUserWithEmailAndPassword()
firebase.auth().currentUser.delete()
firebase.auth().currentUser.link()
As I have understood it from the question linked below, there is no solution - user will always be able to call these functions, and it is considered low-risk since they cannot touch other user accounts. "prevent firebase user from deleting himself"
My concern with not being able to block users from these actions is that I cannot perform the relevant changes to the DB. For some basic use cases I assume it is easy to set up a nightly batch-job to clean up, but I am afraid of future more complex issues.
My current solution for making atomic actions, e.g. delete user account and delete user data in DB, is to send a request to my back-end Node.JS server. That works fine, but a user could, as I understand, by pass this and request e.g. currentUser.delete() by himself/herself. Another case is when a user unlinks a google account. I would like the user to be logged out by, but with the premises the user can unlink with the follow up action.
Question: Have I misunderstood anything? Can this be easily prevented, or is it so that all the available actions are consider harmless and it is up to me to perform clever clean-up etc.? If it cannot be prevented, do you have any more suggestions more clever than nightly batch jobs?
With Cloud functions for firebase you could for example trigger a function on user deletion. That way every time a user is deleted, you can run your code to do the clean up. No matter how the user deletion is invoked.
exports.removeUserFromDatabase = functions.auth.user().onDelete(function(event) {
// Get the uid of the deleted user.
var uid = event.data.uid;
// Remove the user from your Realtime Database's /users node.
return admin.database().ref("/users/" + uid).remove();
});
The same goes for "onCreate". Check out their documentation
https://firebase.google.com/docs/auth/extend-with-functions

A way to track "logged in" users on Google App Engine

I want to implement logging in for users, and regard them as "logged in" during their surfing (using sessions). I do it on Google App Engine with webapp2 framework. But the platform is not important, I'm sure you will point out the general rules to do it.
I have written the class Authorization with authorize method, and every handler inherits from this class. When some handler is triggered I first run self.authorize() and it checks whether the user has the session variable holding his login. Then I check the internal datastore to find out whether the user's session is expired (so I don't depend only on the info from the client's side).
How can I improve or simplify this approach? Do I have to do the authorization routine from every handler or I can keep it in one place?
Also the way webapp2 implements sessions look strange to me. I have to make a class with dispatch and session methods that do some magic. And if a handler inherits from this class I can use sessions inside it:self.sessions['login'] = 'Joe'; self.sessions.get('login').

Node.js user system

I'm currently working on a web application which deals with multiple users. Whilst it currently works, it relies on some real bad practises which I'll outline in a minute.
We're using MySQL as the database system, since we're updating our current application, we want to ensure everything is backwards compatible. Otherwise I'd look at MongoDB etc.
Our users are stored in a table aptly named login. This contains their username, email, hashed password etc and a field which contains a JSON encoded object of their preferences. There is no real reason for doing this over using a meta table.
So the bad practises:
We're storing the entire users login row, excluding their password (although this is an internal-only app) in a cookie. It's JSON encoded.
Once the user logs in we have a secure HTTP cookie, readable only via Node.js for their username and their password so that we can continue to keep the user logged in automatically.
We have a app.get('*') route which constantly ensures that the user has their three cookies and updates their acc cookie with new preferences. This means that every time the user switches page or accesses a new AJAX item (all under the same routes) they have an updated cookie.
Every time a user performs an action we do this to get their user id: JSON.parse(res.cookies.acc).agent_id yuck!
Now, each user is able to perform actions to certain elements on the page, this effects everyone as the application is internal and anybody can work on the data inside of it.
I know what I want to achieve and how it should be done in say PHP, but I can't figure out the most effective way in Node.js.
I've started creating a User module which would allow us to get the user who performed the action and neatly update their preferences etc. You can see this here bearing in mind that it's a WIP. The issue I'm having with the module is that it doesn't have access to the users cookies, since it's not "a part of" Express. Which explains the last bad practise.
What would be the best way to handle such a system and remain bad-practise free?
I doubt it meets all of your requirements but its worth checking out out Drywall; A website and user system for Node.js
Hopefully it (or parts of it) could be helpful to you.
http://jedireza.github.io/drywall/

Symfony 2 - how to disable querying user at every page load?

I'm using my own User class as and entity provider for security system in symfony 2.0.
I noticed that on each reload of the page symfony is fetching user from db:
SELECT t0.id AS id1, t0.username AS username2, t0.salt AS salt3,
t0.password AS password4, t0.email AS email5, t0.is_active AS
is_active6, t0.credentials AS credentials7 FROM w9_users t0 WHERE
t0.id = ? Parameters: ['23'] Time: 4.43 ms
Is there any easy way to disable this behaviour? Maybe serialize user data in session variables or cache them some way?
You can change this behavior in the refreshUser method of your UserProvider.
You should be careful when doing this with doctrine: There is an issue at FosUserBundle github, explaining the pitfalls:
Storing it in the session would lead to several issues, which is why it is not done by default:
if an admin change the permissions of a user, the changes will have an effect only the next time you retrieve the user from the database. So caching the user must be done carefully to avoid security issues
if you simply reuse the user which was serialized in the session, it will not be managed by Doctrine anymore. This means that as soon as you want to modify the user or to use the user in a relation, you will have to merge it back into the UnitOfWork (which will return a different object than the one used by the firewall). Merging will trigger a DB query too. And requiring such logic will break some of the built-in controller which are expecting to be able to use the user object for updates.

CouchDB - Figuring out database security

CouchDB offers validation prior to allowing an object/row to be inserted into the database. This make sure that if you have a public facing couch application, you're database won't be filled with junk by just anyone.
User <-> CouchDB
However, I'm tring to figure out what that looks like comming from the standard application design process where you have a trusted middle layer that does much of the auth work. For example, most apps place Ruby or PHP between the database and user agent which allows the application to figure out information about the user agent before allowing something like a post to be saved to the database.
User -> Ruby -> MySQL
User <- Ruby <- MySQL
How do you trust the user to do administrative tasks when the user can't be trusted?
For example, how would you do something like "email verification" prior to inserting a user row using just couchDB? You can't let the user agent insert the row - because they would fill the system with spam accounts. On the other hand, there is no middle layer either that can insert the row after they click the link in the email.
How about this, I would assume that you would allow anyone to enter their email by creating a new record in a public table like email_verify. This is something that a public user agent could do as the table would not do anything in the application - it would just be a holding tank.
Then node.js could track the _changes feed and send an activation email while creating a new entry in a private table (like email_confirm) (node.js would serve as a trusted middle layer). If the user clicks that link and comes back then... [unknown] ... and node.js could finally create a record in the private user table (user).
At this point we could then rely on couchdb validation for the rest of the application since we got a confirmed user account created.
As more background lets imagine a discussion built on couchdb that anyone can register for. We don't want to allow just anyone to directly submit content without some kind of verification - yet the user agents all directly run the system. (Tables would be Thread, Comment, & User). How would this work?
I would think about adding roles to existing users in this issue.
Using couchdb's validation and changing _design/_auth can be a good idea to add email, email_verified and randomly generated email_verification_code in _users database when the user firsts registers.
To send mail, get confirmation, resend confirmation you can use external processes. (for an example usage of external process you can check couchdb-lucene).
And at last you can again do a quick check in _design/_auth in user update process if verification code matches and add verified_user role for that user.
This way all your requests would pass over couchdb, you would use external process only when you need to send mail and get confirmation.
Edit : Forgot to add (since it was pretty obvious), I would add verified_user role to database readers.
Couldn't you just make use of CouchDb's Validation ?
Users could be flagged. Upon registration, a User is added to the Users database. He gets his mail and then is flagged "valid:true" or something like this upon answering to that mail or clicking a link.
With validation users could not only be "logged in/out" but also access authorization can be implemented with more granular access rights. E.g.: Only mark threads solved if one is the author, admin, whatever...
Or does this seem impracticable?
After talking with some people on #couchdb IRC, it seems that they can't figure out out a way to do something administrative (like activation users that click on a email link) with out using a "backend" process like a node.js server which keeps track of the _changes feed.
I was hoping for a pure couchdb app - but it seems like couchdb still has a little ways to go.
Still, the good news is that you can hand off 80% of your applications logic/processing to your users. The other 20% will be 1) a node.js instance for things like sending emails or checking recaptcha and 2) record validation functions running in your couchdb, and 3) map/reduce (query) functions. These three things cannot be offloaded to something "untrusted" like a user-agent.

Resources