How to use is_superuser method in autotest

Best Python code snippet using autotest_python

views.py

Source:views.py Github

copy

Full Screen

1import requests2from datetime import datetime3from django.http import HttpResponse, FileResponse4from django.shortcuts import render, redirect5from django.contrib.auth.models import User6from django.contrib.auth.decorators import login_required7from django.contrib import auth8from app import models9from app import function10def test(request):11 return HttpResponse("") # 返回字符串12 return render(request, "") # 返回一个网页13 return redirect('') # 重定向14# Create your views here.15#登录16def login(request):17 if request.method == "POST":18 username = request.POST.get("username")19 password = request.POST.get('password')20 user_obj = auth.authenticate(username=username, password=password)21 if not user_obj:22 return render(request, "login.html", {'error': '用户名或者密码错误'})23 else:24 auth.login(request, user_obj)25 rep = redirect('/app/index')26 if user_obj.is_superuser:27 # rep = redirect('/app/list_work_admin')28 rep.set_cookie("is_superuser", True)29 else:30 # rep = redirect('/app/list_work')31 rep.set_cookie("is_superuser", False)32 rep.set_cookie("username", username, max_age=60 * 60 * 24 * 14) #设置cookie保存14天33 return rep34 else:35 return render(request, "login.html")36@login_required37def logout(request):38 auth.logout(request)39 rep = redirect("/app/login")40 rep.delete_cookie("username")41 rep.delete_cookie("is_superuser")42 return rep43def register(request):44 if request.method == "POST":45 username = request.POST.get("username")46 firstname = request.POST.get("firstname")47 password = request.POST.get("password")48 try:49 user = User.objects.get(username=username) # get能且仅能返回一条数据。50 return render(request, "register.html", {'error': '该用户已经存在'})51 except User.DoesNotExist:52 User.objects.create_user(username=username, password=password, first_name=firstname)53 return redirect("/app/login/") # 重定向至登录界面54 pass55 else:56 username = request.COOKIES.get('username')57 return render(request, "register.html", {'username': username})58@login_required59# 初始界面60def index(request):61 username = request.COOKIES.get('username')62 is_superuser = request.COOKIES.get("is_superuser")63 if username == 'root':64 flag = True65 else:66 flag = False67 return render(request, "index.html", {'username': username, 'is_superuser': is_superuser, 'flag': flag})68@login_required69# 添加作业(管理员)70def add_work(request):71 is_superuser = request.COOKIES.get("is_superuser")72 if is_superuser == 'False':73 return redirect('/app/list_work')74 if request.method == 'POST':75 workname = request.POST.get('workname')76 deadline = request.POST.get('deadline')77 deadlinetime = request.POST.get('deadlinetime')78 email = request.POST.get('email')79 deadline = ' '.join([deadline, deadlinetime])80 t = models.Work.objects.create(name=workname, deadline=deadline, email=email)81 function.createDirectory('upload/' + str(t.id))82 return redirect("/app/list_work_admin") # 重定向至作业列表83 else:84 username = request.COOKIES.get('username')85 return render(request, "add_work.html", {'username': username, 'is_superuser': is_superuser})86@login_required87def add_userlist(request):88 is_superuser = request.COOKIES.get("is_superuser")89 if is_superuser == 'False':90 return redirect('/app/list_work')91 username = request.COOKIES.get("username")92 if username != 'root':93 return redirect('/app/index')94 if request.method == 'POST':95 path = 'upload/cache/名单.xlsx'96 obj = request.FILES.get('file')97 function.saveUploadedFile(obj, path)98 function.addUsers()99 return render(request, 'add_userlist.html', {'username': username, 'is_superuser': is_superuser, 'success': True})100 else:101 return render(request, 'add_userlist.html', {'username': username, 'is_superuser': is_superuser})102@login_required103# 上传作业104def upload_work(request):105 username = request.COOKIES.get('username')106 is_superuser = request.COOKIES.get("is_superuser")107 student = User.objects.get(username=username)108 id = request.GET.get("id")109 if request.method == 'GET':110 return render(request, "upload_work.html", {'id': id, 'username': username, 'is_superuser': is_superuser})111 else:112 path = 'upload/{}/{}'.format(id, student.username + '+' + student.first_name)113 upload, _ = models.Upload.objects.get_or_create(username=username, work_id=id)114 upload.time = datetime.now()115 upload.save()116 obj = request.FILES.get('file')117 path += '.' + obj.name.split('.')[1]118 function.saveUploadedFile(obj, path)119 return render(request, "upload_work.html",120 {'id': id, 'username': username, 'is_superuser': is_superuser, 'success': True})121@login_required122# 用户作业列表123def list_work(request):124 work_list = models.Work.objects.all()125 is_superuser = request.COOKIES.get("is_superuser")126 username = request.COOKIES.get('username')127 work = models.Upload.objects.filter(username=username)128 finish = []129 for i in work:130 finish.append(i.work_id)131 return render(request, "list_work.html",132 {'work_list': work_list, 'username': username, 'is_superuser': is_superuser, 'finish': finish})133@login_required134# 管理员作业列表135def list_work_admin(request):136 is_superuser = request.COOKIES.get("is_superuser")137 if is_superuser == 'False':138 return redirect('/app/list_work')139 work_list = models.Work.objects.all()140 username = request.COOKIES.get("username")141 work = models.Upload.objects.filter(username=username)142 finish = []143 for i in work:144 finish.append(i.work_id)145 return render(request, "list_work_admin.html",146 {'work_list': work_list, 'username': username, 'is_superuser': is_superuser, 'finish': finish})147@login_required148# 个人信息149def detail(request):150 is_superuser = request.COOKIES.get("is_superuser")151 if request.method == "POST":152 first_name = request.POST.get('first_name')153 password = request.POST.get('password')154 username = request.GET.get("username")155 _t = User.objects.get(username=username)156 _t.first_name = first_name157 if password:158 _t.set_password(password)159 _t.save()160 return render(request, "detail.html", {'student': _t, 'username': username, 'is_superuser': is_superuser})161 else:162 username = request.COOKIES.get("username")163 student = User.objects.get(username=username)164 return render(request, "detail.html", {'student': student, 'username': username, 'is_superuser': is_superuser})165@login_required166# 作业编辑(管理员)167def edit(request):168 is_superuser = request.COOKIES.get("is_superuser")169 if is_superuser == 'False':170 return redirect('/app/list_work')171 if request.method == "GET":172 id = request.GET.get("id")173 work = models.Work.objects.get(id=id)174 username = request.COOKIES.get('username')175 return render(request, "edit.html", {'work': work, 'username': username, 'is_superuser': is_superuser})176 else:177 id = request.GET.get("id")178 workname = request.POST.get('workname')179 deadline = request.POST.get('deadline')180 deadlinetime = request.POST.get('deadlinetime')181 email = request.POST.get('email')182 _t = models.Work.objects.get(id=id)183 _t.name = workname184 _t.deadline = deadline + ' ' + deadlinetime185 _t.email = email186 _t.save()187 return redirect('/app/list_work_admin/')188@login_required189# 作业删除(管理员)190def delete(request):191 is_superuser = request.COOKIES.get("is_superuser")192 if is_superuser == 'False':193 return redirect('/app/list_work')194 id = request.GET.get("id")195 models.Work.objects.get(id=id).delete()196 # 删除文件夹197 function.deleteDirectory('upload/' + str(id))198 # 删除与作业有关的记录199 models.Upload.objects.filter(work_id=id).delete()200 return redirect('/app/list_work_admin/')201@login_required202def download(request):203 is_superuser = request.COOKIES.get("is_superuser")204 if is_superuser == 'False':205 return redirect('/app/list_work')206 username = request.COOKIES.get('username')207 if request.method == 'POST':208 id = request.GET.get('id')209 work = models.Work.objects.get(id=id)210 obj = request.FILES.get('file')211 if obj is None:212 path = 'upload/cache/名单.xlsx'213 else:214 path = 'upload/cache/' + str(id)215 path += '.' + obj.name.split('.')[1]216 function.saveUploadedFile(obj, path) # 保存名单217 print(id)218 function.writeRecord(path, id) # 写入完成情况219 function.zipDirectory(id)220 new_path = 'upload/{}.zip'.format(id)221 file = open(new_path, 'rb')222 response = FileResponse(file)223 response['Content-Type'] = 'application/octet-stream'224 response['Content-Disposition'] = 'attachment;filename="{}.zip"'.format(work.name) # 不支持中文文件名225 return response226 else:227 id = request.GET.get('id')228 return render(request, "download.html", {'id': id, 'username': username, 'is_superuser': is_superuser})229@login_required230# 下载名单模板231def download_template(request):232 file = open('static/files/模板.xlsx', 'rb')233 response = FileResponse(file)234 response['Content-Type'] = 'application/octet-stream'235 response['Content-Disposition'] = 'attachment;filename="template.xlsx"' # 不支持中文文件名236 return response237@login_required238# 下载导入名单模板239def download_template1(request):240 file = open('static/files/导入模板.xlsx', 'rb')241 response = FileResponse(file)242 response['Content-Type'] = 'application/octet-stream'243 response['Content-Disposition'] = 'attachment;filename="template.xlsx"' # 不支持中文文件名244 return response245@login_required246def list_user(request):247 is_superuser = request.COOKIES.get("is_superuser")248 if is_superuser == 'False':249 return redirect('/app/list_work')250 username = request.COOKIES.get('username')251 if username != 'root':252 return redirect('/app/index')253 if request.method == "POST":254 pass255 else:256 user_list = User.objects.all()257 return render(request, 'list_user.html',258 {'user_list': user_list, 'username': username, 'is_superuser': is_superuser})259@login_required260def edit_user(request):261 is_superuser = request.COOKIES.get("is_superuser")262 if is_superuser == 'False':263 return redirect('/app/list_work')264 username = request.COOKIES.get('username')265 if username != 'root':266 return redirect('/app/index')267 id = request.GET.get("id")268 user = User.objects.get(id=id)269 if request.method == "POST":270 superuser = request.POST.get("superuser")271 name = request.POST.get("first_name")272 password = request.POST.get("password")273 user.first_name = name274 user.is_superuser = superuser275 if password:276 user.set_password(password)277 user.save()278 return render(request, 'edit_user.html',279 {'user': user, 'username': username, 'is_superuser': is_superuser, 'success': True})280 else:281 return render(request, 'edit_user.html',282 {'user': user, 'username': username, 'is_superuser': is_superuser})283@login_required284def delete_user(request):285 is_superuser = request.COOKIES.get("is_superuser")286 if is_superuser == 'False':287 return redirect('/app/list_work')288 username = request.COOKIES.get('username')289 if username != 'root':290 return redirect('/app/index')291 id = request.GET.get("id")292 user = User.objects.get(id=id)293 user.delete()294 return redirect("/app/list_user")295@login_required296def add_user(request):297 is_superuser = request.COOKIES.get("is_superuser")298 if is_superuser == 'False':299 return redirect('/app/list_work')300 username = request.COOKIES.get('username')301 if username != 'root':302 return redirect('/app/index')303 if request.method == "POST":304 username = request.POST.get("username")305 name = request.POST.get("first_name")306 password = request.POST.get("password")307 superuser = request.POST.get("superuser")308 if superuser:309 User.objects.create_user(username=username, password=password,first_name=name)310 else:311 User.objects.create(username=name, password=password,first_name=name)312 return redirect('/app/list_user')313 else:314 return render(request, 'add_user.html',315 {'username': username, 'is_superuser': is_superuser})316#定时任务317from apscheduler.schedulers.background import BackgroundScheduler318from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job319# 实例化调度器320scheduler = BackgroundScheduler()321# 调度器使用默认的DjangoJobStore()322scheduler.add_jobstore(DjangoJobStore(), 'default')323# 每天分钟执行这个任务324@register_job(scheduler, 'interval', id='test',seconds=60)325def test():326 # 具体要执行的代码327 function.checkDeadline()328# 注册定时任务并开始329register_events(scheduler)...

Full Screen

Full Screen

social_auth.py

Source:social_auth.py Github

copy

Full Screen

1import requests2from django.conf import settings3from social_core.backends.azuread_tenant import AzureADTenantOAuth24from social_core.backends.github import GithubOAuth25from social_core.backends.okta import OktaOAuth26from social_core.backends.okta_openidconnect import OktaOpenIdConnect7# noinspection PyUnusedLocal8def fetch_github_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):9 org_name = getattr(settings, 'GITHUB_ADMIN_ORG_NAME', '')10 team_name = getattr(settings, 'GITHUB_ADMIN_TEAM_NAME', '')11 if not user or not isinstance(kwargs['backend'], GithubOAuth2) or not org_name or not team_name:12 return13 response = requests.post(14 url='https://api.github.com/graphql',15 headers={16 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),17 },18 json={19 'query': '''20 query($userName: String!, $orgName: String!, $teamName: String!) {21 organization(login: $orgName) {22 teams(query: $teamName, userLogins: [$userName], first: 1) {23 nodes {24 name25 }26 }27 }28 }29 ''',30 'variables': {31 'userName': details['username'],32 'orgName': org_name,33 'teamName': team_name,34 }35 }36 )37 response.raise_for_status()38 response = response.json()39 is_superuser = {'name': team_name} in response['data']['organization']['teams']['nodes']40 if user.is_superuser != is_superuser:41 user.is_superuser = is_superuser42 user.save()43# noinspection PyUnusedLocal44def fetch_azuread_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):45 group_id = getattr(settings, 'AZUREAD_ADMIN_GROUP_ID', '')46 if not user or not isinstance(kwargs['backend'], AzureADTenantOAuth2) or not group_id:47 return48 response = requests.post(49 url='https://graph.microsoft.com/v1.0/me/checkMemberGroups',50 headers={51 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),52 },53 json={54 'groupIds': [group_id]55 }56 )57 response.raise_for_status()58 response = response.json()59 is_superuser = group_id in response['value']60 if user.is_superuser != is_superuser:61 user.is_superuser = is_superuser62 user.save()63# noinspection PyUnusedLocal64def fetch_okta_oauth2_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):65 org_url = getattr(settings, 'SOCIAL_AUTH_OKTA_OAUTH2_API_URL', '')66 admin_group_name = getattr(settings, "OKTA_OAUTH2_ADMIN_GROUP_NAME", "")67 if not user or not isinstance(kwargs['backend'], OktaOAuth2):68 return69 # OktaOpenIdConnect inherits `OktaOAuth2`, so we have to explicitly skip OAuth2 trying70 # to fetch permissions when using OIDC backend.71 if isinstance(kwargs['backend'], OktaOpenIdConnect):72 return73 response = requests.post(74 url=f"{org_url}/v1/userinfo",75 headers={76 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),77 },78 )79 response.raise_for_status()80 response = response.json()81 is_superuser = admin_group_name in response.get("groups", [])82 is_staff = admin_group_name in response.get("groups", [])83 user_changed = False84 if user.is_superuser != is_superuser:85 user.is_superuser = is_superuser86 user_changed = user_changed or True87 if user.is_staff != is_staff:88 user.is_staff = is_staff89 user_changed = user_changed or True90 if user_changed:91 user.save()92# noinspection PyUnusedLocal93def fetch_okta_openidconnect_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):94 org_url = getattr(settings, 'SOCIAL_AUTH_OKTA_OPENIDCONNECT_API_URL', '')95 admin_group_name = getattr(settings, "OKTA_OPENIDCONNECT_ADMIN_GROUP_NAME", "")96 if not user or not isinstance(kwargs['backend'], OktaOpenIdConnect):97 return98 response = requests.post(99 url=f"{org_url}/v1/userinfo",100 headers={101 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),102 },103 )104 response.raise_for_status()105 response = response.json()106 is_superuser = admin_group_name in response.get("groups", [])107 is_staff = admin_group_name in response.get("groups", [])108 user_changed = False109 if user.is_superuser != is_superuser:110 user.is_superuser = is_superuser111 user_changed = user_changed or True112 if user.is_staff != is_staff:113 user.is_staff = is_staff114 user_changed = user_changed or True115 if user_changed:...

Full Screen

Full Screen

policys.py

Source:policys.py Github

copy

Full Screen

...37 "condition": ["is_superuser"],38 "effect": "allow",39 },40 ]41 def is_superuser(self, request, view, action):42 return request.user.is_superuser43class CommentViewSetPolicy(AccessPolicy):44 statements = [45 {46 "principal": ["authenticated"],47 "action": ["create", "<safe_methods>"],48 "effect": "allow",49 },50 {51 "principal": ["authenticated"],52 "action": ["update", "partial_update", "destroy"],53 "condition": ["is_writer_or_superuser"],54 "effect": "allow",55 },56 ]57 def is_writer_or_superuser(self, request, view, action):58 writer = request.user59 comment = view.get_object()60 is_writer = comment.user is writer61 is_superuser = writer.is_superuser62 return is_writer or is_superuser63class CommentReportViewSetPolicy(AccessPolicy):64 statements = [65 {66 "principal": ["authenticated"],67 "action": ["create"],68 "effect": "allow",69 },70 {71 "principal": ["authenticated"],72 "action": ["list", "retrieve", "update", "partial_update", "delete"],73 "condition": ["is_superuser"],74 "effect": "allow",75 },76 ]77 def is_superuser(self, request, view, action):78 return request.user.is_superuser79class WorldcupViewSetPolicy(AccessPolicy):80 statements = [81 {82 "principal": ["*"],83 "action": ["<safe_methods>"],84 "effect": "allow",85 },86 {87 "principal": ["authenticated"],88 "action": ["create"],89 "effect": "allow",90 },91 {...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful