1.github中的项目clone到本地(路径在最后),然后将arya文件夹复制到你的django工程中作为一个独立的app,该app实现了RBAC(基于角色的权限访问控制Role-Based Access Control)和CRM(客户关系管理).
完成效果:
2.setting中注册arya和配置rbac相关设置
INSTALLED_APPS = [
.....
'arya.apps.AryaConfig',
] ....
# ############################## RBAC权限相关配置开始 ##############################
# session中保存权限信息的Key
RBAC_PERMISSION_URL_SESSION_KEY = "rbac_permission_url_session_key" # Session中保存菜单和权限信息的Key
RBAC_MENU_PERMISSION_SESSION_KEY = "rbac_menu_permission_session_key"
RBAC_MENU_KEY = "rbac_menu_key"
RBAC_MENU_PERMISSION_KEY = "rbac_menu_permission_key" # 匹配URL时指定规则
RBAC_MATCH_PARTTERN = "^{0}$" # 无需权限控制的URL
RBAC_NO_AUTH_URL = [
'/login/',
'/logout/',
"/index/",
"/test/",
] # 无权访问时,页面提示信息
RBAC_PERMISSION_MSG = "无权限访问" #菜单图标
MENU_ICONS = ["icon-book", "icon-book", "icon-book", "icon-book", "icon-book"]
# ############################## RBAC权限相关配置结束 ##############################
3.在你的用户表(用来作登录验证)中添加一行roles
from django.db import models
from arya.models import Role class Account(models.Model):
username = models.CharField("用户名", max_length=64, unique=True)
password = models.CharField("密码", max_length=128)
roles = models.ManyToManyField(to=Role, verbose_name="角色")
4.在你需要arya来管理的app中,新建arya.py,注册你的model
from arya.service import sites
from . import models sites.site.register(models.Account)
5.在主url中加入arya的路由:
from django.conf.urls import url
# from django.contrib import admin
from arya.service import sites urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^admin/', sites.site.urls),
]
6.在你的登录视图函数中书写如下逻辑,可以根据实际情况自己做修改
请注意:我默认你的url配置中是有如下配置的.
login.html和index.html可以暂时使用本demo中的.
from app01 import views
urlpatterns = [
url(r'^login/$', views.login),
url(r'^logout/$', views.logout),
url(r'^index/$', views.index),
]
from django.shortcuts import render,redirect from arya.service.rbac import initial_permission
from . import models
def login(request):
if request.method == "GET":
return render(request, "login.html")
elif request.method == "POST":
username = request.POST.get("username")
pwd = request.POST.get("pwd")
# print("___cookie",request.COOKIES)
obj = models.Account.objects.filter(username=username, password=pwd).first()
if obj:
# 初始化权限
request.session["user_info"] = {"nid": obj.id}
print(request.session["user_info"])
initial_permission(request, obj) return redirect('/index/')
else:
return render(request, "login.html") def logout(request):
request.session["user_info"] = None
return redirect("/login/") def index(request):
return render(request, "index.html")
7.做数据库迁移
python manage.py makemigrations
python manage.py migrate
8.启动程序,登录
1.可以先在你的用于登录的model中加入测试用的账号密码,如usernme:tom password:123
2.如无错误的话,可以看到如下界面
9.添加一个权限:url为: http://127.0.0.1:8000/admin/arya/permission/
10.添加一个角色:url为:http://127.0.0.1:8000/admin/arya/role/
11.为你的account添加一个角色,url为:http://127.0.0.1:8000/admin/app01/account/
12.修改角色权限或者为用户添加角色后,需要重新登录,session信息刷新后才能看到菜单,我们重新登录,即可看到如下菜单.
13.然后你就可以为所欲为了,然后有啥问题可以联系我.
Github地址:https://github.com/jackChen8850/arya