def save(self, *args, **kwargs): request = CrequestMiddleware.get_request() if self.user is None: request = CrequestMiddleware.get_request() if request: if request.user.is_authenticated: self.user = request.user if self.user is None: # IF IT IS STILL NONE self.user = User.objects.first() super(NotificationRequest, self).save(*args, **kwargs)
def create_user_profile(sender, instance, created, **kwargs): if created: print ('instance is: {}'.format(instance)) for entry in reversed(inspect.stack()): #print (entry[0].f_locals['request'].user) try: current_request = CrequestMiddleware.get_request() #user = None user = current_request.user #user = entry[0].f_locals['request'].user except: user = None break print ('user: {}'.format(user)) if user: try: #print ('yay') UserProfile.objects.create(scout_username=instance, troop=user.userprofile.troop, troop_details=user.userprofile.troop_details) except (AttributeError): UserProfile.objects.create(scout_username=instance) #do not create now #then create in views pass else: UserProfile.objects.create(scout_username=instance) instance.userprofile.save()
def CatPresensiView(request, cats): # https://stackoverflow.com/questions/37104604/adding-a-django-model-instance-without-a-form-button-only current_request = CrequestMiddleware.get_request() user = current_request.user.id userr = str(current_request.user.username) profiles = Profile.objects.get(user_id=user) # presensi = MasterPresensi.objects.get(namaa_id=user) category_posts = MenuPresensi.objects.filter(name=cats) categor = MenuPresensi.objects.get(slug__iexact=cats) linkk = MenuPresensi.objects.values("slug").distinct() masterPresensi = MasterPresensi.objects.filter(namaa_id=user) # createPresensi = MasterPresensi.objects.create() # createPresensi.save() now = datetime.datetime.now().strftime('%H:%M:%S') now1 = datetime.datetime.now().date() if request.method == 'POST': exis = MasterPresensi.objects.filter(namaa_id=request.user, tanggal=f'{now1}').exists() if exis: nul = MasterPresensi.objects.filter(namaa_id=request.user, tanggal=f'{now1}', jam_pulang=None) if nul: obj = MasterPresensi.objects.filter( namaa_id=request.user, tanggal=f'{now1}').update(jam_pulang=f'{now}') return HttpResponseRedirect('/presensi/data-kehadiran/') else: obj = MasterPresensi.objects.create(namaa_id=request.user, tanggal=f'{now1}') obj.save() return HttpResponseRedirect('/presensi/data-kehadiran/') p = Paginator(MasterPresensi.objects.filter(namaa_id=request.user), 5) page = request.GET.get('page') presensi_list = p.get_page(page) nums = "a" * presensi_list.paginator.num_pages context = { 'heading': '', 'cats': cats.title(), 'category_posts': category_posts, 'linkk': linkk, 'categor': categor, 'presensi': masterPresensi, 'presensi_list': presensi_list, 'nums': nums } if request.method == 'POST': context['heading'] = 'ABSEN BERHASIL' if cats == 'data-kehadiran': return render(request, 'presensi/data_kehadiran.html', context) else: return render(request, 'presensi/absen_hadir.html', context)
def get_raz_client(raz_url, username, auth='kerberos', service='s3', service_name='cm_s3', cluster_name='myCluster'): if not username: from crequest.middleware import CrequestMiddleware request = CrequestMiddleware.get_request() username = request.user.username if request and hasattr( request, 'user') and request.user.is_authenticated else None if not username: raise PopupException('No username set.') if auth == 'kerberos' or True: # True until JWT option auth_handler = requests_kerberos.HTTPKerberosAuth( mutual_authentication=requests_kerberos.OPTIONAL) raz = RazToken(raz_url, auth_handler) raz_token = raz.get_delegation_token(user=username) return RazClient(raz_url, raz_token, username, service=service, service_name=service_name, cluster_name=cluster_name)
def comment_send_mail(sender, instance, **kwargs): current_request = CrequestMiddleware.get_request() # Send email only if comment comes from someone else if instance.author.email != instance.harvest.pick_leader.email: # Building email content pick_leader_email = list() pick_leader_email.append(instance.harvest.pick_leader.email) pick_leader_name = instance.harvest.pick_leader.person.first_name mail_subject = u"New comment from %s" % instance.author message = u'Hi %s, \n\n' \ u'On %s %s left the following comment\n' \ u'in the harvest "%s":\n\n' \ u'%s\n\n' \ u'You can see all comments related to this ' \ u'harvest at\n' \ u'http://saskatoon.lesfruitsdefendus.org/harvest/%s.' \ u'\n\n' \ u'Yours,\n' \ u'--\n' \ u'Saskatoon Harvest System' % \ ( pick_leader_name, instance.created_date.strftime('%b %d at %H:%M'), instance.author, instance.harvest.property.publishable_location, instance.content, instance.harvest.id ) # Sending email to pick leader _send_mail(mail_subject, message, pick_leader_email)
def get_score(self, student_answers): def make_cmap(status = 'incorrect', points = 0, msg = ''): return CorrectMap(self.answer_id, status, npoints = points, msg = msg) log.info('\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>') log.info(student_answers) log.info(self.answer_id) # Get stat for current user from crequest.middleware import CrequestMiddleware current_request = CrequestMiddleware.get_request() user = current_request.user ext_responce = self.do_external_request(user.username) # If any arror occured -- we are done if (isinstance(ext_responce, dict) and ext_responce.error is not None): return make_cmap(msg = ext_responce.error) # Find course we are checking for el in ext_responce: # FIXME Pretty brave assumption, make it error-prone if (int(self.course.text) == el['course_id']): points_earned = float(el['tasks_completed']) / el['tasks_total'] * self.get_max_score() # Ew, grosse! points_earned = round(points_earned * 100) / float(100) return make_cmap(status = 'correct', points = points_earned) return make_cmap()
def _save_timeseries_data(self): request = CrequestMiddleware.get_request() # Create a hard link to the temporary uploaded file with the data # so that it's not automatically deleted and can be used by the celery # worker tmpfilename = self.cleaned_data["data"].temporary_file_path() datafilename = tmpfilename + ".1" os.link(tmpfilename, datafilename) tasks.save_timeseries_data.delay( id=self.instance.id, replace_or_append=self.cleaned_data["replace_or_append"], datafilename=datafilename, username=request.user.username, ) messages.add_message( request, messages.INFO, _('The data for the time series "{} - {} - {}" will be imported ' "soon. You will be notified by email when the importing finishes." ).format( self.instance.timeseries_group.gentity.name, str(self.instance.timeseries_group), str(self.instance), ), )
def addtopology(sender, instance=None, created=False, **kwargs): current_request = CrequestMiddleware.get_request() if created: url = str(instance.url) img = url.rsplit('/', 1)[1] action = '添加拓扑图' + img createlogs(username=current_request.user.username, action=action)
def __init__(self): h = HTMLParser() request = CrequestMiddleware.get_request() if request is None: self.AuthMemCookie = None self.SimpleSAML = None self.SimpleSAMLAuthToken = None self.OUNetID = None self.FirstName = None self.LastName = None self.Email = None self.MemberOf = None else: self.AuthMemCookie = request.COOKIES["AuthMemCookie"] self.SimpleSAML = request.COOKIES["SimpleSAML"] self.SimpleSAMLAuthToken = request.COOKIES["SimpleSAMLAuthToken"] self.OUNetID = urllib.unquote(request.COOKIES["OUNetID"]) if ( "OUNetID" in request.COOKIES) else "" self.FirstName = urllib.unquote(request.COOKIES["FirstName"]) if ( "FirstName" in request.COOKIES) else "" self.LastName = urllib.unquote(request.COOKIES["LastName"]) if ( "LastName" in request.COOKIES) else "" self.Email = urllib.unquote(request.COOKIES["Email"]) if ( "Email" in request.COOKIES) else "" groups = urllib.unquote(request.COOKIES["MemberOf"]) self.MemberOf = groups.split(":")
def addnetwork(sender, instance=None, created=False, **kwargs): current_request = CrequestMiddleware.get_request() if created: action = '添加网络设备:' + instance.eq_ip else: action = '编辑网络设备:' + instance.eq_ip createlogs(username=current_request.user.username, action=action)
def __get_role(self): request = CrequestMiddleware.get_request() if request is not None and hasattr(request, "user") and request.user is not None and\ not request.user.is_anonymous(): return request.session.get("active_role") else: return None
def rfp_send_mail(sender, instance, **kwargs): current_request = CrequestMiddleware.get_request() # First check if pick_leader is set if instance.harvest.pick_leader: # Send email only if request comes from someone else if instance.picker.email != instance.harvest.pick_leader.email: # Building email content pick_leader_email = list() pick_leader_email.append(instance.harvest.pick_leader.email) pick_leader_name = instance.harvest.pick_leader.person.first_name mail_subject = u"New request for participation from %s" % instance.picker message = u'Hi %s, \n\n' \ u'On %s %s requested to participate\n' \ u'in the harvest at "%s %s":\n\n' \ u'You can see all information related to this ' \ u'harvest at\n' \ u'http://saskatoon.lesfruitsdefendus.org/harvest/%s.' \ u'\n\n' \ u'Yours,\n' \ u'--\n' \ u'Saskatoon Harvest System' % \ ( pick_leader_name, instance.creation_date.strftime('%b %d at %H:%M'), instance.picker, instance.harvest.property.street_number, instance.harvest.property.street, instance.harvest.id ) # Sending email to pick leader _send_mail(mail_subject, message, pick_leader_email)
def __get_auth(self): request = CrequestMiddleware.get_request() if request is not None and hasattr(request, "user") and request.user is not None and\ not request.user.is_anonymous(): return request.user.username, request.session.get("password") else: return None
def __init__(self, target_object, data=None, initial=None, parent=None, **kwargs): self.user = kwargs.pop('user', None) self.parent = parent if initial is None: initial = {} initial.update({'parent': self.parent}) super(MPTTCommentForm, self).__init__(target_object, data=data, initial=initial, **kwargs) if self.user is not None: if self.user.is_authenticated: self.fields['email'].required = False self.fields['name'].required = False else: self.fields['captcha'] = CaptchaField() else: current_request = CrequestMiddleware.get_request() if current_request.user.is_authenticated: self.fields['email'].required = False self.fields['name'].required = False else: self.fields['captcha'] = CaptchaField()
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Custom save, it assign the user As owner and the last modifed it sets the doc_type make sure that dlc_date has correct timezone ?! :param force_insert: :param force_update: :param using: :param update_fields: :return: """ from ra.base.helpers import get_next_serial request = CrequestMiddleware.get_request() self.doc_type = self.get_doc_type() if not self.slug: self.slug = get_next_serial(self.__class__) # self.slug = slugify(self.slug) if not self.pk: if not self.lastmod_user_id: self.lastmod_user_id = request.user.pk if not self.owner_id: self.owner_id = self.lastmod_user_id self.lastmod = now() # if self.doc_date: # if self.doc_date.tzinfo is None: # self.doc_date = pytz.utc.localize(self.doc_date) super(EntityModel, self).save(force_insert, force_update, using, update_fields)
def save(self, *args, **kwargs): current_request = CrequestMiddleware.get_request() if current_request and (not self.created_by or not self.pk): user = current_request.user self.created_by = user super(ProgramUpdate, self).save(*args, **kwargs)
def addpc(sender, instance=None, created=False, **kwargs): current_request = CrequestMiddleware.get_request() if created: action = '添加PC:' + instance.ip createlogs(username=current_request.user.username, action=action) else: action = '编辑PC:' + instance.ip createlogs(username=current_request.user.username, action=action)
def get_current_request(default=None): """ Returns the current request. You can optonally pass in a dummy request object to act as the default if there is no current request, e.g. when get_current_request() is called during a manage.py command. 2017-07-24: This function now uses django-crequest instead of GlobalRequestMiddleware, and accepts a default arg. """ return CrequestMiddleware.get_request(default)
def __get_bp_auth(self): request = CrequestMiddleware.get_request() if request is not None and hasattr(request, "bp") and request.bp is not None: return requests.auth._basic_auth_str(request.bp.username, request.bp.password) else: return None
def addgroup(sender, instance=None, created=False, **kwargs): current_request = CrequestMiddleware.get_request() if created: action = "添加组:" + instance.name createlogs(username=current_request.user.username, action=action) else: action = "编辑组:" + instance.name createlogs(username=current_request.user.username, action=action)
def get_url(self): request = CrequestMiddleware.get_request() if self.protocol in ('ws', 'wss'): url = request.build_absolute_uri(f'/w/{self.client_id}') url = re.sub(r'^https?://', f'{self.protocol}://', url) else: raise ValueError(f'Unsupported protocol {self.protocol}') return url
def render_owned(self, value): current_request = CrequestMiddleware.get_request() user = current_request.user if user == value: return "yes" return "no"
def last_comments(number_of_comments=10): current_request = CrequestMiddleware.get_request() current_user = current_request.user if hasattr(current_user, "member"): last_comments_ = CardComment.objects.filter(board__members=current_user.member, card__is_closed=False).\ order_by("-creation_datetime") return last_comments_[:number_of_comments] return CardComment.objects.none()
def changed_by(sender, instance, **kwargs): current_request = CrequestMiddleware.get_request() if current_request: # If property is created by the owner not authenticated: if current_request.user.is_anonymous is False: instance.changed_by = current_request.user else: instance.changed_by = None
def save(self, *args, **kwargs): current_request = CrequestMiddleware.get_request() super(Company, self).save(*args, **kwargs) offices = self.office_set.count() if offices == 0: current_user = current_request.user central = self.office_set.create(name='central') self.companyuserrole_set.create(user=current_user, company_role_id=1)
def save(self, *args, **kwargs): request = CrequestMiddleware.get_request() if not self.id: if request: v = RequestLog() v.from_http_request(request, None) self.request = v self.internel_name = str(self.log_name).replace(' ', '_').lower() super(UserLog, self).save(*args, **kwargs)
def add_author_forms(sender, instance, created, **kwargs): if created: current_request = CrequestMiddleware.get_request() if current_request: author = current_request.user.username or PUBLIC_USER else: author = PUBLIC_USER instance.author = author instance.public_id = f'{instance.pk}-' + salt()
def render_name(self, record): from crequest.middleware import CrequestMiddleware current_request = CrequestMiddleware.get_request() user = current_request.user if (user.username == Constants.USER_ANONYMOUS): return record.name; if (user.username == record.owner.username and record.project.all().filter(is_deleted=False).count() == 0): ## it can't be in any active project return mark_safe('<a href="#modal_remove_reference" id="id_remove_reference_modal" data-toggle="modal"' +\ ' ref_name="' + record.name + '" pk="' + str(record.pk) + '"><i class="fa fa-trash"></i></span> </a>' + record.name) return record.name;
def render_name(self, record): from crequest.middleware import CrequestMiddleware current_request = CrequestMiddleware.get_request() user = current_request.user if (user.username == Constants.USER_ANONYMOUS): return record.name; if (user.username == record.owner.username): return mark_safe('<a href="#id_remove_modal" id="id_remove_reference_modal" data-toggle="modal"' +\ ' ref_name="' + record.name + '" pk="' + str(record.pk) + '"><i class="fa fa-trash"></i></span> </a>' + record.name) return record.name;
def is_liked_by_me(self): status = False try: request = CrequestMiddleware.get_request() user = request.user if self.like_set.filter(user_id=user.id).exists(): status = True except Exception: pass return status
def group_required(group_names): """Requires user membership in at least one of the groups passed in.""" try: user = CrequestMiddleware.get_request().user if user.is_authenticated(): test = user.groups.filter(name=group_names).exists() except (AttributeError): test = False return user_passes_test(test)
def save(self, *args, **kwargs): if self.name == '': self.name = None if self.slug == '': if self.parent: self.slug = self.parent.slug crequest = CrequestMiddleware.get_request() self.created_by = crequest.user super(Product, self).save(*args, **kwargs)
def handle_oidc_token_save(sender, instance, **kwargs): request = CrequestMiddleware.get_request() if not request: return try: service = Service.objects.get(client=instance.client) except Service.DoesNotExist: return UserLoginEntry.objects.create_from_request(request, service, user=instance.user)
def handle_oauth2_access_token_save(sender, instance, **kwargs): request = CrequestMiddleware.get_request() if not (request and instance.application): return try: service = Service.objects.get(application=instance.application) except Service.DoesNotExist: return UserLoginEntry.objects.create_from_request(request, service, user=instance.user)
def add_info_log(sender, instance, **kwargs): current_request = CrequestMiddleware.get_request() if current_request: instance.changed_by = current_request.user else: instance.changed_by = None from models import AdditionalInfoLog, AdditionalInfo if instance.created_on.strftime("%Y%d%H%M%S") != timezone.now().strftime("%Y%d%H%M%S"): # Do not log if same people + same event + same day infos_for_this_event = AdditionalInfoLog.objects.filter(info__event=instance.event) for i in infos_for_this_event: if i.changed_on.strftime("%d%m%y") == timezone.now().strftime("%d%m%y") and i.changed_by == instance.changed_by: i.delete() a = AdditionalInfoLog.objects.create(changed_by=instance.changed_by, info=instance)
def get_authorization_grant(token, sessionid, host): """ Get the authorization code for this user, for use in allowing edx to be an oauth2 provider to sifu. """ cr = CrequestMiddleware.get_request() headers = { "Host":host, # Get base url from env variable "X-CSRFToken":token, "Connection": 'keep-alive', "Referer":"http://%s" % host, "Cookie": cr.META['HTTP_COOKIE'] } sifu_id = get_sifu_id() if sifu_id is None: return None # will need to update sifu with the secret details somehow state = "3835662" # randomly generate this base_url = "http://%s" % host location = "%s/oauth2/authorize/?client_id=%s&state=%s&redirect_uri=%s&response_type=code" % (base_url,sifu_id,state,base_url) authorization_grant = None try: while location is not None: resp = requests.request("GET", location, headers=headers, allow_redirects=False) resp.raise_for_status() try: location = resp.headers['location'] authorization_grant = parse_auth_code(resp.headers['location']) if authorization_grant is None else authorization_grant except KeyError, e: # client might not be trusted # session id might be incorrect location = None # "GET /oauth2/authorize/confirm" # "GET /oauth2/redirect "" #"GET /?state=3835662&code=48dbd69c8028c61d35df319d04f9d827cfe4c51c HTTP/1.1" 302 0 " return authorization_grant
def student_view(self, context=None, request=None): cr = CrequestMiddleware.get_request() if not self.runtime.user_is_staff and cr is not None: user_service = self.runtime.service(self, 'user') xb_user = user_service.get_current_user() username = xb_user.opt_attrs.get('edx-platform.username') if username is None: log.debug(u'[JupyterNotebook Xblock] : User not found in student_view') # get the course details course_unit_name = str(self.course_unit) resource = str(self.file_noteBook) token = csrf.get_token(cr) sessionid = cr.session.session_key cookie_data_string = cr.COOKIES.get(settings.SESSION_COOKIE_NAME) host = cr.META['HTTP_HOST'] authorization_grant = get_authorization_grant(token, sessionid, host) # Get a token from Sifu sifu_domain = self.get_config('sifu_domain') sifu_token = None # it looks like these might be single use tokens cr.session['sifu_token'] = None try: sifu_token = cr.session['sifu_token'] except: cr.session['sifu_token'] = None if sifu_token is None: sifu_token = get_auth_token(authorization_grant, username, sifu_domain) cr.session['sifu_token'] = sifu_token cr.session.save() cr.session.modified = True #check if user notebook & base notebook exists if not self.user_notebook_exists(username, course_unit_name, resource, sifu_token, sifu_domain): log.debug(u'[JupyterNotebook Xblock] : User notebook does not exist.') # check the base file exists if not self.base_file_exists(course_unit_name, resource, sifu_token, sifu_domain): log.debug(u'[JupyterNotebook Xblock] : The course unit base notebook does not exist.') # create the base file self.create_base_file(course_unit_name, resource, sifu_token, sifu_domain, host) # create user notebook assuming the base file exists if not self.create_user_notebook(username, course_unit_name, resource, sifu_token, sifu_domain): log.debug(u'[JupyterNotebook Xblock] : Could create {}\'s notebook'.format(username)) context = { "sifu_token": sifu_token, 'sifu_url': 'http://%s:3334/v1/api/set-cookie/' % sifu_domain, 'self': self, 'user_is_staff': self.runtime.user_is_staff, 'current_url_resource': self.get_current_url_resource(username, course_unit_name, resource, sifu_token, sifu_domain, host), } else: context = { 'self': self, 'user_is_staff': self.runtime.user_is_staff, 'current_url_resource': None, } template = self.render_template("static/html/jupyternotebook_xblock.html", context) frag = Fragment(template) frag.add_css(self.resource_string("static/css/jupyternotebook_xblock.css")) frag.add_javascript(self.resource_string("static/js/src/jupyternotebook_xblock.js")) frag.initialize_js('JupyterNotebookXBlock') return frag
def get_current_request(): """ Retain current request. """ return CrequestMiddleware.get_request()
def function_without_request(): cr = CrequestMiddleware.get_request() print type(cr)