python group/user management packages

2024/9/23 17:23:29

I was looking for python user/group management package.(Creation of user group and adding/removing members to that group) I found flask_dashed.

     https://github.com/jeanphix/Flask-Dashed/ 

It more or less what I was looking for. But It supports only one user to add/remove groups. Does any one know what are the other such similar packages available in python-flask world?

Answer

I literally just did this myself yesterday. I did it with a combination of

Flask-Login
Flask-Principal
Flask-SQLAlchemy

Basically the way it works is like this. Flask-Login is used for user authentication. On successful login, a signal is sent that you can intercept / use to add permissions

@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):# Set the identity user objectcurrent_user = session.get('user', False)if not current_user:return Falseidentity.user = current_user# Add the UserNeed to the identityif hasattr(current_user, 'id'):identity.provides.add(UserNeed(current_user.id))# Assuming the User model has a list of groups, update the# identity with the groups that the user providesif hasattr(current_user, 'groups'):groups = user.Group.query.filter(user.Group.users.any(id=current_user.id)).all()for group in groups:identity.provides.add(RoleNeed(group.name))

The models for the user and group look like this:

groups = db.Table('groups',db.Column('user_id', db.Integer, db.ForeignKey('user.id')),db.Column('group_id', db.Integer, db.ForeignKey('group.id'))
)group_to_group = db.Table('group_to_group',db.Column('parent_id', db.Integer, db.ForeignKey('group.id'), primary_key=True),db.Column('child_id', db.Integer, db.ForeignKey('group.id'), primary_key=True)
)class User(db.Model):id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String(64), unique=True)email = db.Column(db.String(120), unique=True)display_name = db.Column(db.String(120))created_at = db.Column(db.DateTime)last_login = db.Column(db.DateTime, default=db.func.now())def __init__(self, name, email, display_name):self.name = nameself.email = emailself.display_name = display_nameself.created_at = datetime.datetime.now()self.order_by = User.display_namedef is_authenticated(self):return Truedef is_active(self):return Truedef is_anonymous(self):return Falsedef get_id(self):return unicode(self.id)def __repr__(self):return self.display_nameclass Group(db.Model):id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String(64))users = db.relationship('User', secondary=groups,backref=db.backref('groups',lazy='dynamic',order_by=name))parents = db.relationship('Group',secondary=group_to_group, primaryjoin=id==group_to_group.c.parent_id,  secondaryjoin=id==group_to_group.c.child_id, backref="children",remote_side=[group_to_group.c.parent_id])def __repr__(self):return self.name

Then, it is just a matter of rolling some CRUD pages to take care of administering the groups.

I then set up some logic to create Principal Roles based on my group names so each new group is available.

When you want to restrict access to something, you just do it like...

@NameOfYourRole.require(http_exception=403)
@route("/something/special/people/can/do")
def super_cool(...):
https://en.xdnf.cn/q/71799.html

Related Q&A

Resize NumPy array to smaller size without copy

When I shrink a numpy array using the resize method (i.e. the array gets smaller due to the resize), is it guaranteed that no copy is made?Example:a = np.arange(10) # array([0, 1, 2, 3, 4, …

TensorFlow FileWriter not writing to file

I am training a simple TensorFlow model. The training aspect works fine, but no logs are being written to /tmp/tensorflow_logs and Im not sure why. Could anyone provide some insight? Thank you# import…

python time.strftime %z is always zero instead of timezone offset

>>> import time >>> t=1440935442 >>> time.strftime("%Y/%m/%d-%H:%M:%S %z",time.gmtime(t)) 2015/08/30-11:50:42 +0000 >>> time.strftime("%Y/%m/%d-%H:%M:…

Python: Nested for loops or next statement

Im a rookie hobbyist and I nest for loops when I write python, like so:dict = {key1: {subkey/value1: value2} ... keyn: {subkeyn/valuen: valuen+1}}for key in dict:for subkey/value in key:do it to itIm a…

How to install cython an Anaconda 64 bits with Windows 10?

Its all in the title, does someone have a step by step method to install cython and run it on Anaconda 64 bits on Windows 10? I search for hours and there are a lot of tutorials... For things that I w…

Using DictWriter to write a CSV when the fields are not known beforehand

I am parsing a large piece of text into dictionaries, with the end objective of creating a CSV file with the keys as column headers. csv.DictWriter(csvfile, fieldnames, restval=, extrasaction=raise, di…

How to Save io.BytesIO pdfrw PDF into Django FileField

What I am trying to do is basically:Get PDF from URL Modify it via pdfrw Store it in memory as a BytesIO obj Upload it into a Django FileField via Model.objects.create(form=pdf_file, name="Some n…

Which python static checker can catch forgotten await problems?

Code: from typing import AsyncIterableimport asyncioasync def agen() -> AsyncIterable[str]:print(agen start)yield 1yield 2async def agenmaker() -> AsyncIterable[str]:print(agenmaker start)return …

Tkinter : Syntax highlighting for Text widget

Can anyone explain how to add syntax highlighting to a Tkinter Text widget ?Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word tkinter in pi…

how to use pkgutils.get_data with csv.reader in python?

I have a python module that has a variety of data files, (a set of csv files representing curves) that need to be loaded at runtime. The csv module works very well # curvefile = "ntc.10k.csv"…