def upd(name): try: mo=get_model(name, db_id) dbn= mo._meta.db_table \ if not hasattr(mo._meta, 'verbose_name') \ else mo._meta.verbose_name mv= mo\ .objects \ .filter(**ol_d)#location=ol) if 'confirmed' in get: nc= mo \ .objects \ .filter(**ol_d).count() #location=ol).count() mv.update(**nl_d) #{'location':nl}) if not 'moved' in out: out.update({'moved':[]}) out['moved'].append([ dbn, nc ]) else: mvn=get_model(name,db_id) \ .objects \ .filter(**nl_d) #location=nl) if not 'move' in out: out.update({'move':[]}) out['move'].append([ dbn, mv.count(), mvn.count()]) except Exception as e: print(name+': '+e)
def process_request(self, request): if request.path in ("/login","/loginpsw","/logout","/b"): return None loginurl = "https://%s/login" % request.get_host() msg = 'Sisselogimiseks minge <a href="%s">siia</a>' % loginurl try: user_id = request.session['sarvuser_id'] except KeyError: if request.is_ajax(): response = {"type": "event", "name": "sessionexpiry", "url": "%s" % loginurl} return HttpResponse(json.dumps(response), mimetype = "application/javascript") else: return render_to_response("login.html", { 'MEDIA_URL': settings.MEDIA_URL, 'loginurl': loginurl, 'login_as': True if request.path.replace('/','') == 'login_as' else False, 'PUBLIC_STATIC_URL': settings.PUBLIC_STATIC_URL }) from sarv.utils import get_model SarvUser = get_model("User") try: sarvuser = SarvUser.objects.get(pk=user_id) except: return HttpResponse(msg) request.__class__.user = AnonymousUser() request.__class__.sarvuser = sarvuser return None
def insert_page_user_right(self, given): """ given={destination,group,id,permission,userlevel} """ if not "destination" in given: return False actor_type = "group" if "group" in given else "user" if not given["destination"][0].isupper(): try: given["destination"] = AclDestination.objects.get( keyword=given["destination"]).model except AclDestination.DoesNotExist: return False if actor_type == "group": try: actor_qs = AclUserGroup.objects.get( group__keyword=given["group"], user__username=given["user"]) except AclUserGroup.DoesNotExist: new_group = AclUserGroup( **{ "group": AclGroup.objects.get(keyword=given["group"]), "user": User.objects.get(username=given["user"]) }) new_group.save() actor_qs = new_group else: try: actor_qs = User.objects.get(username=given["user"]) except User.DoesNotExist: return False dest_model = Menu if given["destination"] == "Menu" else \ get_model(given["destination"]) arguments = { "id_tested": actor_qs.pk, "type": actor_type, "content_type": ContentType.objects.get_for_model(dest_model), } if not "save_all" in given: arguments.update({"object_id": given["id"]}) self.remove_page_user_right(arguments) arguments.update({ "permission_id": 1, "rights_group":AclRightsGroup.objects.get(name="%s"% given["userlevel"] \ if "userlevel" in given else 1), }) if "save_all" in given: new_items = [] for item in dest_model.objects.all(): arguments.update({"object_id": item.pk}) new_items.append(mAcl(**arguments)) mAcl.objects.bulk_create(new_items) else: new_item = mAcl(**arguments) new_item.save() return False
def insert_page_user_right (self, given): """ given={destination,group,id,permission,userlevel} """ if not "destination" in given: return False actor_type = "group" if "group" in given else "user" if not given["destination"][0].isupper(): try: given["destination"] = AclDestination.objects.get(keyword=given["destination"]).model except AclDestination.DoesNotExist: return False if actor_type == "group": try: actor_qs = AclUserGroup.objects.get(group__keyword=given["group"],user__username=given["user"]) except AclUserGroup.DoesNotExist: new_group = AclUserGroup(**{ "group":AclGroup.objects.get(keyword=given["group"]), "user":User.objects.get(username=given["user"])}) new_group.save() actor_qs = new_group else: try: actor_qs = User.objects.get(username=given["user"]) except User.DoesNotExist: return False dest_model = Menu if given["destination"] == "Menu" else \ get_model(given["destination"]) arguments = { "id_tested": actor_qs.pk, "type": actor_type, "content_type": ContentType.objects.get_for_model(dest_model), } if not "save_all" in given: arguments.update({"object_id":given["id"]}) self.remove_page_user_right(arguments) arguments.update({ "permission_id": 1, "rights_group":AclRightsGroup.objects.get(name="%s"% given["userlevel"] \ if "userlevel" in given else 1), }) if "save_all" in given: new_items = [] for item in dest_model.objects.all(): arguments.update({"object_id":item.pk}) new_items.append(mAcl(**arguments)) mAcl.objects.bulk_create(new_items) else: new_item = mAcl(**arguments) new_item.save() return False
def process_request(self, request): if request.path in ("/login", "/loginpsw", "/logout", "/b"): return None loginurl = "https://%s/login" % request.get_host() msg = 'Sisselogimiseks minge <a href="%s">siia</a>' % loginurl try: user_id = request.session['sarvuser_id'] except KeyError: if request.is_ajax(): response = { "type": "event", "name": "sessionexpiry", "url": "%s" % loginurl } return HttpResponse(json.dumps(response), mimetype="application/javascript") else: return render_to_response( "login.html", { 'MEDIA_URL': settings.MEDIA_URL, 'loginurl': loginurl, 'login_as': True if request.path.replace('/', '') == 'login_as' else False, 'PUBLIC_STATIC_URL': settings.PUBLIC_STATIC_URL }) from sarv.utils import get_model SarvUser = get_model("User") try: sarvuser = SarvUser.objects.get(pk=user_id) except: return HttpResponse(msg) request.__class__.user = AnonymousUser() request.__class__.sarvuser = sarvuser return None
def get_model (self, mname = None): """ Get model instance by name and include database parameter. @param mname: Model name @type mname: str """ if not 'request' in self.input: print('fatal error in NextifyUtils.get_model') if not mname: pass from sarv.utils import get_model m = get_model(mname) s = self.input['request'].session if 'database_id' in s \ and isinstance(s['database_id'], int) \ and hasattr(m, 'session_db'): m.session_db = s['database_id'] return m
def get_model(self, mname=None): """ Get model instance by name and include database parameter. @param mname: Model name @type mname: str """ if not 'request' in self.input: print('fatal error in NextifyUtils.get_model') if not mname: pass from sarv.utils import get_model m = get_model(mname) s = self.input['request'].session if 'database_id' in s \ and isinstance(s['database_id'], int) \ and hasattr(m, 'session_db'): m.session_db = s['database_id'] return m
from django import template from django.db.models import Q from sarv.utils import get_model Menu = get_model("SarvMenu") register = template.Library() def main_menu(context): # context - dict, with {sarvuser:<User:User object>,'database':'git'} allowed_urls = [] if context["acl"]: allowed_urls = [url.replace("+", "/") for url in context["acl"].keys() if context["acl"][url][0] is True] menu = Menu.objects.filter(Q(page__url__in=allowed_urls) | Q(row=0)).order_by("column", "row") output = {} for v in menu: if v.column not in output: output.update({v.column: []}) if v.page and v.page.url and v.page.url[-4:] == ".php" and not v.page.url.startswith("sarv_php"): v.page.url = "sarv_php/%s" % v.page.url.replace("sarv_intra/", "") output[v.column].append(v) outp = {} for k in output.keys(): if len(output[k]) > 1: outp[k] = output[k] return {"content": outp} register.inclusion_tag("menu/menu-tag.html", takes_context=True)(main_menu)
# -*- coding: utf-8 -*- import json from django.contrib import admin from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from apps.acl.models import AclRightsGroup, AclGroup from apps.acl.views import Acl as vAcl from sarv.settings import PROJECT_ADMINS from sarv.utils import get_model User, Page, Menu = get_model(["User", "SarvPage", "SarvMenu"]) class AclAdmin(object): def __init__(self): pass def index(self, request): rightsgroups = AclRightsGroup.objects.all() pagerights, users, column_names = self.get_page_data(request) print([pagerights, users, column_names]) return render_to_response( "admin/acl_index.html", { "data": json.dumps({ "pages": pagerights, "users": users }), "users": users, "rightsgroups": rightsgroups,
import json from django.http import HttpResponse from sarv.utils import get_model SarvIssue, SarvUser = get_model(["SarvIssue", "User"]) def read(request): msg_l = SarvIssue.objects \ .filter( reported_to = request.sarvuser, resolved = False ) \ .order_by("-date_added") \ .values_list( "title", "pk", "date_added", "reported_by__username", "description", "response", "issue_type__issue_type" ) o_l=[] for i in msg_l: u_l=[] for j in i: u_l.append(str(j)) o_l.append(u_l) return HttpResponse(json.dumps(o_l), content_type = "application/json") def add(request):
import json from datetime import datetime, timedelta from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django.shortcuts import render_to_response from django.conf import settings from sarv.settings import PROJECT_ADMINS from django.contrib.auth.models import User from sarv.middleware import get_database from sarv.utils import get_model Database, SarvIssue, Session, SarvUser = get_model(["Database", "SarvIssue", "SarvSession", "User"]) def index(request): user = request.sarvuser if user is None: return HttpResponse("") database = user.db request.session["database"] = user.db user_o = SarvUser.objects.get(username=user) # Get all messages to user msg_n=SarvIssue.objects \ .filter(reported_to=user_o, resolved=False) \ .count() return render_to_response("index.html", {
def get_model (modelname, db_id): from sarv.utils import get_model m = get_model(modelname) if hasattr(m, "session_db"): m.session_db=db_id return m
def relocate_location(request): get=request.GET.dict() out={'get':get} db_id=request.session['database_id'] m=get_model('Location', db_id) #update if 'location_old' in get \ and 'location_new' in get: ol=get['location_old'] nl=get['location_new'] #mn=m.objects.filter(location=nl) ol_d={'storage':int(ol)} \ if ol.isdigit() \ else {'location':ol} nl_d={'storage':int(nl)} \ if nl.isdigit() \ else {'location':nl} def upd(name): try: mo=get_model(name, db_id) dbn= mo._meta.db_table \ if not hasattr(mo._meta, 'verbose_name') \ else mo._meta.verbose_name mv= mo\ .objects \ .filter(**ol_d)#location=ol) if 'confirmed' in get: nc= mo \ .objects \ .filter(**ol_d).count() #location=ol).count() mv.update(**nl_d) #{'location':nl}) if not 'moved' in out: out.update({'moved':[]}) out['moved'].append([ dbn, nc ]) else: mvn=get_model(name,db_id) \ .objects \ .filter(**nl_d) #location=nl) if not 'move' in out: out.update({'move':[]}) out['move'].append([ dbn, mv.count(), mvn.count()]) except Exception as e: print(name+': '+e) upd('Specimen') upd('Sample') upd('Analysis') upd('Preparation') #upd('SamplePaleontology') # todo: check if model is missing qs=m.objects.all().values_list('location',flat=True) out.update({ 'locations': list([j for j in qs if j]) }) return render_to_response( 'relocate_location.html', out, context_instance=RequestContext(request))
# -*- coding: utf-8 -*- from django.template import RequestContext from django.shortcuts import render_to_response from django.http import HttpResponse import json from django.db.models import Q from django.contrib.contenttypes.models import ContentType from django.conf import settings from apps.acl.models import AclUserGroup,AclGroup,Acl as mAcl from apps.acl.views import Acl from sarv.utils import get_model Menu, Page = get_model(["SarvMenu","SarvPage"]) institutions = ("git","elm","tug") class MenuAdmin(object): def is_active(self,request): #print (request.acl) pass def router(self, request, action=False): ''' Route url requests from urls.py to match views.py Acl class methods s''' response = False if hasattr(self, action): response = getattr(self, action)(request) else: print ('no attr') return HttpResponse(response)
# -*- coding: utf-8 -*- from apps.acl.models import Acl as mAcl, AclDestination, AclGroup, AclRightsGroup, AclUserGroup from django.db.models import Q from django.contrib.contenttypes.models import ContentType from sarv.local_settings import ACL_USERRIGHTS from sarv.utils import get_model User, Menu, Page = get_model(["User", "SarvMenu", "SarvPage"]) class Acl(object): def __init__(self, **kwargs): pass def get_all_user_rights(self, request): output = {} uid = request.session["sarvuser_id"] u_gs = AclUserGroup.objects.filter(user_id=uid) ct = ContentType.objects.get_for_model(Page) qs = mAcl.objects.filter(Q(id_tested__in=u_gs) & Q(type="group") & Q(content_type=ct)) \ .order_by("object_id") pages = {item.pk:item.url.replace("[generic]","").replace("[extify]","") \ for item in Page.objects.all() if item.url is not None \ and not len(item.url) < 1 and item.visibility == "acl"} ri = {} for item in qs: rights = ACL_USERRIGHTS[int(item.rights_group_id) - 1] ri.update({item.object_id: rights})
# -*- coding: utf-8 -*- from apps.acl.models import Acl as mAcl, AclDestination, AclGroup, AclRightsGroup, AclUserGroup from django.db.models import Q from django.contrib.contenttypes.models import ContentType from sarv.local_settings import ACL_USERRIGHTS from sarv.utils import get_model User, Menu, Page = get_model(["User", "SarvMenu", "SarvPage"]) class Acl(object): def __init__(self, **kwargs): pass def get_all_user_rights (self, request): output = {} uid = request.session["sarvuser_id"] u_gs = AclUserGroup.objects.filter(user_id=uid) ct = ContentType.objects.get_for_model(Page) qs = mAcl.objects.filter(Q(id_tested__in=u_gs) & Q(type="group") & Q(content_type=ct)) \ .order_by("object_id") pages = {item.pk:item.url.replace("[generic]","").replace("[extify]","") \ for item in Page.objects.all() if item.url is not None \ and not len(item.url) < 1 and item.visibility == "acl"} ri = {} for item in qs: rights = ACL_USERRIGHTS[int(item.rights_group_id)-1] ri.update({item.object_id:rights})
import json from django.http import HttpResponse from sarv.utils import get_model SarvIssue, SarvUser = get_model(["SarvIssue", "User"]) def read(request): msg_l = SarvIssue.objects \ .filter( reported_to = request.sarvuser, resolved = False ) \ .order_by("-date_added") \ .values_list( "title", "pk", "date_added", "reported_by__username", "description", "response", "issue_type__issue_type" ) o_l = [] for i in msg_l: u_l = [] for j in i: u_l.append(str(j)) o_l.append(u_l) return HttpResponse(json.dumps(o_l), content_type="application/json")
from django import template from django.db.models import Q from sarv.utils import get_model Menu = get_model("SarvMenu") register = template.Library() def main_menu(context): # context - dict, with {sarvuser:<User:User object>,'database':'git'} allowed_urls = [] if context['acl']: allowed_urls = [url.replace('+','/') \ for url in context['acl'].keys() \ if context['acl'][url][0] is True] menu = Menu.objects \ .filter(Q(page__url__in=allowed_urls)|Q(row=0)) \ .order_by('column','row') output = {} for v in menu: if v.column not in output: output.update({v.column: []}) if v.page \ and v.page.url \ and v.page.url[-4:] == '.php' \ and not v.page.url.startswith('sarv_php'): v.page.url = 'sarv_php/%s' % v.page.url.replace('sarv_intra/', '') output[v.column].append(v) outp = {} for k in output.keys(): if len(output[k]) > 1:
# -*- coding: utf-8 -*- import json from django.contrib import admin from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from apps.acl.models import AclRightsGroup, AclGroup from apps.acl.views import Acl as vAcl from sarv.settings import PROJECT_ADMINS from sarv.utils import get_model User, Page, Menu = get_model(["User", "SarvPage", "SarvMenu"]) class AclAdmin(object): def __init__(self): pass def index(self, request): rightsgroups = AclRightsGroup.objects.all() pagerights, users, column_names = self.get_page_data(request) print([pagerights, users, column_names]) return render_to_response("admin/acl_index.html", {"data": json.dumps({ "pages": pagerights, "users": users}), "users": users, "rightsgroups": rightsgroups, "col_names": column_names },
import json from datetime import datetime, timedelta from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django.shortcuts import render_to_response from django.conf import settings from sarv.settings import PROJECT_ADMINS from django.contrib.auth.models import User from sarv.middleware import get_database from sarv.utils import get_model Database, SarvIssue, Session, SarvUser = get_model( ["Database", "SarvIssue", "SarvSession", "User"]) def index(request): user = request.sarvuser if user is None: return HttpResponse("") database = user.db request.session["database"] = user.db user_o = SarvUser.objects.get(username=user) # Get all messages to user msg_n=SarvIssue.objects \ .filter(reported_to=user_o, resolved=False) \ .count()