Django auth 自己编写装饰器

使用Django auth认证模块,但不适用起权限矩阵。自己编写基于本系统的权限模块,权限装饰器等

#!/usr/bin/env python

#encoding: utf-8

#author: xiaofangliu

importos

importsys

printos.getcwd()

reload(sys)

sys.setdefaultencoding('utf-8')

#os.environ.update({"DJANGO_SETTINGS_MODULE": "djapi.settings"})

#pro_dir = os.getcwd()  # 如果放在project目录,就不需要在配置绝对路径了

#sys.path.append('/Users/xiaofangl/Downloads/huasheng/hasan/djapi')

#

os.environ['DJANGO_SETTINGS_MODULE']='djapi.settings.settings'#项目的settings

importdjango

django.setup()

printsys.path

sys.path.append(os.path.dirname(__file__))

importjson

importuuid

importtime

importdatetime

fromlog.logging_confimport*

fromdjango.views.decorators.csrfimportcsrf_exempt

fromdjango.httpimportJsonResponse, HttpResponse, HttpResponseRedirect

fromdjango.shortcutsimportredirect

fromdjango.contrib.auth.modelsimportUser

fromdjango.contrib.auth.modelsimportGroup

frommodelsimportUser2Group

frommodelsimportGroupExtend

frommodelsimportModifyPermissionsLog

frompassport.modelsimportuserInfo

frompassport.modelsimportoperLog

fromdjango.appsimportAppConfig

fromdjango.confimportsettings

fromtools.send_mailimportMail

classPassportConfig(AppConfig):

name='passport'

"""

INSTALLED_APPS

给上面应用的每个应用创建四个组

admin, operate, guest, standby

"""

loger=logging.getLogger(__file__)

deflogin_required_hasan(func):

def_wrapper(request,*args,**kwargs):

#if login

ifrequest.META.get('HTTP_AUTHORIZATION',''):

returnfunc(request,*args,**kwargs)

#else:

#res = {'status': False, 'msg': '登录失败。。', 'user_id': '', 'userhashid': 'login_required_hasan', 'code': '2'}

#return res

return_wrapper

defrun_is_admin(username):

username=''ifnotusernameelseusername

user_id=userInfo.objects.filter(hashKey=username).values('user_id')

groups=User2Group.objects.filter(is_del=False,user_id=user_id).values('group__name')

foritemingroups:

if'admin'initem['group__name']:

returnTrue

else:

break

returnFalse

#访问用户是否在这个组

deflogin_required_permission(group):

defwrapped(func):

def_wrapper(request,*args,**kwargs):

username=request.META.get('HTTP_AUTHORIZATION','')

username=''ifnotusernameelseusername

user_id=userInfo.objects.filter(hashKey=username).values('user_id')

user_group=get_user_group(user_id)#用户已有权限组

_group=group.split('_')[:-1]

_group='_'.join(_group)

#print '_group', _group, type(_group)

_group=_group+'_admin'

#print _group

ifuser_group:

forminuser_group['data']:

ifgroupinm['group__name']:

returnfunc(request,*args,**kwargs)

elif_groupinm['group__name']:

returnfunc(request,*args,**kwargs)

print'not permission..'

res={'status':False,'msg':'权限不足,操作失败。请申请权限','user_id': username,'code':'21','data': group}

returnHttpResponse(json.dumps(res))

return_wrapper

returnwrapped

defget_user_group(user_id):

try:

groups=User2Group.objects.filter(is_del=False,user_id=user_id).values('group_id','group__name','group__groupextend__be_app')

group_name=[]

foritemingroups:

            group_name.append(item)

res={'status':True,'msg':'获取权限组成功。。','user_id': user_id,'code':'1','data': group_name}

exceptUser.groups:

res={'status':False,'msg':'没有权限。。','user_id': user_id,'code':'1','data': group_name}

    loger.warning(res)

ModifyPermissionsLog.objects.create(user=user_id,type='5',status=res['status'],desc=res['msg'],code=res['data'])

returnres

defget_admin_group(request):

username=request.META.get('HTTP_AUTHORIZATION','')

username=''ifnotusernameelseusername

user_id=userInfo.objects.filter(hashKey=username).values('user_id')

user_group=get_user_group(user_id)#用户已有权限组

#print 'user_group', user_group

apps=[]

forminuser_group['data']:

if'admin'inm['group__name']:

apps.append(m['group__groupextend__be_app'])

app_list=set(apps)

list_group=[]

printapp_list

foriteminapp_list:

tmp=GroupExtend.objects.filter(is_del=False,be_app=item).values('group_id','group__name','be_app')

fornintmp:

            list_group.append(n)

#print 'get_admin_group', list_group

returnlist_group

#

@login_required_hasan

defadd_group(request):

username=request.META.get('HTTP_AUTHORIZATION','')

username=''ifnotusernameelseusername

print'add_group_username', username

#第一次,

apps=settings.__getattr__('INSTALLED_APPS')

#每创建一个APP

#apps = settings.__getattr__('ADD_APP')

#groups = settings.APP_DEFAULT_GROUP.get().keys()

group_list=['admin','operate','guest','standby']

#print 'add_group', settings.APP_DEFAULT_GROUP.get('admin')

app_list=[]

foriteminapps:

#print item

if'django'notinitem:

            app_list.append(item)

else:

continue

print'applist', app_list, group_list

all_data=[]

forappinapp_list:

name_row=[]

row_data={'group_id':''}

forgroupingroup_list:

name_row.append(app+'_'+group)

row_data['be_app']=app

row_data['created']=datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')

row_data['name']=name_row

        all_data.append(row_data)

#print 'all_data', all_data

for_ninall_data:

for_namein_n['name']:

try:

group=Group.objects.get(name=_name)

is_extend=GroupExtend.objects.filter(group_id=group.id)

ifnotis_extend:

is_extend=GroupExtend.objects.create(be_app=_n['be_app'],group_id=group.id,created=_n['created'])

res={'status':False,'msg':'group 已经存在。。','user_id': username,'code':'1','is_extend': is_extend}

exceptGroup.DoesNotExist:

group=Group.objects.create(name=_name)

is_extend=GroupExtend.objects.create(be_app=_n['be_app'],group_id=group.id,created=_n['created'])

res={'status':True,'msg':'group 创建成功。。','user_id': username,'code':'0','is_extend': is_extend}

operLog.objects.create(user=username,type='add_group',status=res['status'],desc=res['msg'],code=res['is_extend'])

print'add_group', res

returnHttpResponse(res)

"""

# group => PERMISSIONS(super)

# @get_group_user('passport_operate')

def group_add_permissions(request):

    username = request.META.get('HTTP_AUTHORIZATION', '')

    username = '' if not username else username

# (super)

# @get_group_user('passport_operate')

def group_del_permissions(request):

    username = request.META.get('HTTP_AUTHORIZATION', '')

    username = '' if not username else username

"""

#@login_required_hasan

defget_users(request,*args,**kwargs):

username=request.META.get('HTTP_AUTHORIZATION','')

username=''ifnotusernameelseusername

try:

data=[]

user=User.objects.filter(is_active=True).values('id','username','email')

#print type(user)

foriteminuser:

            data.append(item)

exceptUser.DoesNotExist:

res={'status':False,'msg':'get_groups failed..'}

ModifyPermissionsLog.objects.create(user=username,type='get_users',status=res['status'],desc=res['msg'],code='')

#print type(data)

returndata

defget_groups(request,*args,**kwargs):

username=request.META.get('HTTP_AUTHORIZATION','')

username=''ifnotusernameelseusername

try:

data=[]

group=Group.objects.filter(groupextend__is_del=False).values('id','groupextend__be_app','name')

#print 'data', data

foritemingroup:

            data.append(item)

exceptGroup.DoesNotExist:

res={'status':False,'msg':'get_groups failed..'}

ModifyPermissionsLog.objects.create(user=username,type='get_groups',status=res['status'],desc=res['msg'],code='')

printtype(data)

returndata

#(admin)

#@get_group_user('admin')

defrun_add_group(request,user_list,group):

username=request.META.get('HTTP_AUTHORIZATION','')

username=''ifnotusernameelseusername

res={'status':True,'msg':'','data':''}

print'receive', user_list, group

foriteminuser_list:

is_exist=User2Group.objects.filter(is_del=False,group_id=group,user_id=item)

ifnotis_exist:

try:

obj=User2Group.objects.create(group_id=group,user_id=item)

res={'status':True,'msg':'user added group success..','data': obj.id}

exceptUser2Group.DoesNotExistase:

res={'status':False,'msg':'user added group failed..','data': e}

ModifyPermissionsLog.objects.create(user=username,type='run_add_group',status=res['status'],desc=res['msg'],

code=res['data'])

else:

continue

returnres

#(admin)

#@get_group_user('admin')

defrun_del_group(request,group_list,user):

username=request.META.get('HTTP_AUTHORIZATION','')

username=''ifnotusernameelseusername

res={'status':True,'msg':'','data':''}

print'receive', group_list, user

foritemingroup_list:

is_exist=User2Group.objects.filter(is_del=False,group_id=item,user_id=user)

ifis_exist:

try:

is_exist.update(is_del=True)

res={'status':True,'msg':'user deleted group success..','data':''}

exceptUser2Group.DoesNotExistase:

res={'status':False,'msg':'user deleted group failed..','data': e}

ModifyPermissionsLog.objects.create(user=username,type='run_add_group',status=res['status'],

desc=res['msg'],

code=res['data'])

else:

continue

returnres

@csrf_exempt

defrun_pwd_mail(title,sender,addressee,content,source_ip):

print'this run_send_mail'

#写一个urls 专用来 重置密码的

title='Reset Password'ifnottitleelsetitle

sender='Hasan(哈桑)'ifnotsenderelsesender

#urls = "http://hasan.huashenghaoche.work"

reset="/reset_pwd"

urls="http://"+source_ip+reset

#urls = "http://www.baidu.com"

content="""


          请重置密码


Hi!%s

              请点击链接重置密码.

链接地址为 点我


           

You Dear Shawna..



"""%(addressee, urls, urls)

addressee=addressee+'@huashenghaoche.com'

mail=Mail(title, sender, addressee, content)

res=mail._send()

returnres

defrun_apply_permission(apply_user,app,text,source_ip):

#print type(apply_user), type(app), type(text)

title='APPLY PERMISSION'

#app_group_id = GroupExtend.objects.filter(is_del=False, be_app=app).values('group__name', 'group_id')

##print 'app_group_id', app_group_id

#for item in app_group_id:

#if 'admin' in item['group__name']:

#admin_group = item['group_id']

#print 'admin_group', admin_group

#addressees = User2Group.objects.filter(is_del=False, group_id=admin_group).values('user__username')

#print 'addressees', addressees

#for c in addressees:

#print type(c['user__username']), c['user__username']

addressee='ops'+'@huashenghaoche.com'

urls="http://"+source_ip

content="""


              申请权限


Hi!%s

因访问%s:

%s


链接地址为 去往Hasan

               

You Dear Shawna..



"""%(addressee, app, text, urls, urls)

#print content

mail=Mail(title, apply_user, addressee, content)

res=mail._send()

returnres

defrun_apply_dbmain(apply_user,text,source_ip):

#print type(apply_user), type(app), type(text)

title='APPLY DBMAIN'

addressee=settings.DB_MAIN.get('addressee')

addressee='[email protected]'ifnotaddresseeelseaddressee

source_ip='http://dbmain.huashenghaoche.work/accounts/login/?next=/'ifnotsource_ipelsesource_ip

urls=source_ip

content="""


              申请dbmain账号


Hi!%s

%s


去往dbmain

               

You Dear Shawna..



"""%(addressee, text, urls, urls)

#print content

mail=Mail(title, apply_user, addressee, content)

res=mail._send()

returnres

if__name__=='__main__':

get_groups('')

你可能感兴趣的:(Django auth 自己编写装饰器)