Esempio n. 1
0
File: views.py Progetto: gluker/jaot
def showCourse(course_id):
    course = db_session.query(Course).get(course_id)
    if course is None:
        abort(404)
    psets = course.problemsets
    return render_template("showcourse.html", course=course, psets=psets,
                perm=check_permissions(course.id,session['user_id']))
Esempio n. 2
0
 def form_valid(self, form):
     if check_permissions(self.request.user, self.application) == HR_ADMIN:
         self.object = form.save(commit=False)
         self.object.event = AUDIT_EVENT_NOTE
         self.object.application = self.application
         self.object.user = self.request.user
         self.object.save()
     return HttpResponseRedirect(self.get_success_url())
Esempio n. 3
0
def test_check_permissions():
    """
    Confirm that permissions are correctly evaluated.

    Checks:
    * User not logged in (401)
    * User lacks permission (403)
    * User has permission indirectly (part of another permission) (200)
    * User has permission (200)
    """
    assert utils.check_permissions(["DATA_EDIT"], [], False) == 401
    permissions = ["DATA_EDIT"]
    user_permissions = {}
    assert utils.check_permissions(permissions, user_permissions, True) == 403
    user_permissions = ["DATA_MANAGEMENT"]
    assert utils.check_permissions(permissions, user_permissions, True) == 200
    user_permissions = ["DATA_EDIT"]
    assert utils.check_permissions(permissions, user_permissions, True) == 200
Esempio n. 4
0
 def get_context_data(self, **kwargs):
     context = super(HrViewApplication, self).get_context_data(**kwargs)
     perm = check_permissions(self.request.user, self.object)
     if perm == HR_VIEWONLY:
         context['audit'] = self.object.audit_set.filter(event__in=[AUDIT_EVENT_STATUSCHANGE, AUDIT_EVENT_REJECTION, AUDIT_EVENT_ACCEPTED, AUDIT_EVENT_MESSAGE])
     elif perm == HR_ADMIN:
         context['hrstaff'] = True
         context['audit'] = self.object.audit_set.all()
     else:
         raise Http404
     return context
Esempio n. 5
0
    async def whois(self,
                    ctx: utils.CustomContext,
                    user: discord.Member = None):
        """Gives you basic information on someone."""

        user = user or ctx.author
        colour = self._get_top_coloured_role(user)
        embed = self.bot.embed(ctx)
        embed.colour = colour
        embed.title = f"About {user.name}"
        embed.description = (
            f"**ID**: {user.id}\n"
            f"**Bot**: {user.bot}\n"
            f"{'**Is literally the bot owner**' if user.id in self.bot.owner_ids else ''}"
        )
        embed.set_thumbnail(url=user.avatar_url)

        created_at = (f"{utils.format_time(user.created_at)['date']} "
                      f"({humanize.naturaltime(user.created_at)})")

        joined_at = (f"{utils.format_time(user.joined_at)['date']} "
                     f"({humanize.naturaltime(user.joined_at)})")

        roles = user.roles[1:]
        roles.reverse()
        roles = [r.mention for r in roles][:30]

        def get_boost(u: discord.Member):
            """Quick function to check if a user is boosting."""

            if u.premium_since is None:
                return "No"
            else:
                return f"{utils.format_time(u.premium_since)['date']} ({humanize.naturaltime(u.premium_since)})"

        boost = get_boost(user)

        embed.add_field(name="Account created", value=f"{created_at}")

        embed.add_field(name="User joined date", value=f"{joined_at}")

        embed.add_field(name="Boosting", value=f"{boost}")

        embed.add_field(
            name=f"Roles [{len(roles) if len(roles) < 30 else '30*'}]",
            value=" ".join(roles) or "No roles.",
            inline=False)

        embed.add_field(name="Permissions",
                        value=utils.check_permissions(ctx, user),
                        inline=False)

        await ctx.send(embed=embed)
Esempio n. 6
0
 def render_to_response(self, context):
     status = self.kwargs.get('status', None)
     if status and int(status) in APPLICATION_STATUS_ROUTES[self.object.status]:
         perm = check_permissions(self.request.user, self.object)
         if perm == HR_ADMIN or (perm == HR_VIEWONLY and int(status) <= 1):
             if not self.object.status == status:
                 self.object.status = status
                 self.object.save(user=self.request.user)
                 self.object = self.model.objects.get(pk=self.object.pk)
                 messages.add_message(self.request, messages.INFO, "Application %s has been changed to %s" % (self.object.id, self.object.get_status_display()))
     else:
          messages.add_message(self.request, messages.ERROR, "Invalid status change request")
     return HttpResponseRedirect(reverse('hr-viewapplication', args=[self.object.id]))
Esempio n. 7
0
def main():
    """The entrypoint for osg-incommon-cert-request
    """
    global args
    try:
        args = parse_cli()

        config_parser = ConfigParser.ConfigParser()
        config_parser.readfp(StringIO(CONFIG_TEXT))
        CONFIG = dict(config_parser.items('InCommon'))

        if args.orgcode:
            codes = [code.strip() for code in args.orgcode.split(',')]
            CONFIG['organization'] = codes[0]
            CONFIG['department'] = codes[1]

        print("Using organization code of %s and department code of %s" %
              (CONFIG['organization'], CONFIG['department']))

        utils.check_permissions(args.write_directory)

        if args.test:
            print("Beginning testing mode: ignoring optional parameters.")
            print("=" * 60)

        # Creating SSLContext with cert and key provided
        # usercert and userprivkey are already validated by utils.findusercred
        ssl_context = cert_utils.get_ssl_context(usercert=args.usercert,
                                                 userkey=args.userprivkey)

        restclient = InCommonApiClient(CONFIG['apiurl'], ssl_context)

        if args.test:
            test_incommon_connection(CONFIG, restclient)
            restclient.close_connection()
            sys.exit(0)

        print("Beginning certificate request")
        print("=" * 60)

        #Create tuple(s) either with a single hostname and altnames or with a set of hostnames and altnames from the hostfile
        if args.hostname:
            hosts = [tuple([args.hostname.strip()] + args.altnames)]
        else:
            with open(args.hostfile, 'rb') as hosts_file:
                host_lines = hosts_file.readlines()
            hosts = [
                tuple(line.split()) for line in host_lines if line.strip()
            ]

        requests = list()
        csrs = list()

        print(
            "The following Common Name (CN) and Subject Alternative Names (SANS) have been specified: "
        )
        # Building the lists with certificates --> utils.Csr(object)
        for host in set(hosts):
            common_name = host[0]
            sans = host[1:]

            print("CN: %s, SANS: %s" % (common_name, sans))
            csr_obj = cert_utils.Csr(common_name,
                                     output_dir=args.write_directory,
                                     altnames=sans)

            logger.debug(csr_obj.x509request.as_text())
            csrs.append(csr_obj)

        print("=" * 60)

        for csr in csrs:
            subj = str(csr.x509request.get_subject())
            print("Requesting certificate for %s: " % subj)
            response_request = submit_request(CONFIG,
                                              restclient,
                                              subj,
                                              csr.base64_csr(),
                                              sans=csr.altnames)

            # response_request stores the sslId for the certificate request
            if response_request:
                requests.append(tuple([response_request, subj]))
                print("Request successful. Writing key file at: %s" %
                      csr.keypath)
                csr.write_pkey()
            else:
                print("Request failed for %s" % subj)

            print("-" * 60)

        # Closing the restclient connection before going idle waiting for approval
        restclient.close_connection()

        print("%s certificate(s) was(were) requested successfully." %
              len(requests))
        print("Waiting %s seconds for requests approval..." % WAIT_APPROVAL)
        time.sleep(WAIT_APPROVAL)

        print("\nStarting certificate retrieval")
        print("=" * 60)
        # Certificate retrieval has to retry until it gets the certificate
        # A restclient (InCommonApiClient) needs to be created for each retrieval attempt
        for request in requests:
            subj = request[1]
            print("Retrieving certificate for %s: " % subj)
            response_retrieve = retrieve_cert(CONFIG, ssl_context, request[0])

            if response_retrieve is not None:
                cert_path = os.path.join(args.write_directory,
                                         subj.split("=")[1] + '-cert.pem')
                print("Retrieval successful. Writing certificate file at: %s" %
                      cert_path)
                utils.safe_rename(cert_path)
                utils.atomic_write(cert_path, response_retrieve)
                os.chmod(cert_path, 0644)
            else:
                print("Retrieval failure for %s" % subj)
                print(
                    "The certificate can be retrieved directly from the InCommon Cert Manager interface."
                )
                print("CN %s, Self-enrollment Certificate ID (sslId): %s" %
                      (subj, request[0]))

            print("-" * 60)

    except SystemExit:
        raise
    except ValueError as exc:
        sys.exit(exc)
    except KeyboardInterrupt as exc:
        print(str(exc))
        sys.exit('''Interrupted by user\n''')
    except KeyError as exc:
        print(prog + ": error: " + "Key %s not found in dictionary" % exc)
        sys.exit(1)
    except FileNotFoundException as exc:
        print(prog + ": error: " + str(exc) + ':' + exc.filename)
        sys.exit(1)
    except SSLError as exc:
        print(prog + ": " + str(exc))
        sys.exit('Please check for valid certificate.\n')
    except (IOError, FileWriteException, BadPassphraseException,
            AttributeError, EnvironmentError, ValueError, EOFError, SSLError,
            AuthenticationFailureException) as exc:
        print(prog + ": error: " + str(exc))
        sys.exit(1)
    except httplib.HTTPException as exc:
        print(str(exc))
        sys.exit(1)
    except Exception:
        traceback.print_exc()
        sys.exit(1)
    sys.exit(0)
Esempio n. 8
0
 def get_context_data(self, **kwargs):
     context = super(HrIndexView, self).get_context_data(**kwargs)
     context['is_hr_staff'] = check_permissions(self.request.user)
     context['can_recommend'] = len(blacklist_values(self.request.user, BLACKLIST_LEVEL_ADVISORY)) == 0
     return context
Esempio n. 9
0
 def dispatch(self, request, *args, **kwargs):
     self.application = get_object_or_404(Application, pk=kwargs.get('applicationid'))
     if not (check_permissions(request.user) == HR_ADMIN and request.user.has_perm('hr.can_accept')):
         return HttpResponseRedirect(reverse('hr-index'))
     return super(HrRejectApplication, self).dispatch(request, *args, **kwargs)
Esempio n. 10
0
 def dispatch(self, request, *args, **kwargs):
     self.application = Application.objects.get(pk=kwargs.get('applicationid'))
     self.perm = check_permissions(request.user, self.application)
     if self.perm == HR_NONE:
         return HttpResponseRedirect(reverse('hr-index'))
     return CreateView.dispatch(self, request, *args, **kwargs)
Esempio n. 11
0
 def dispatch(self, request, *args, **kwargs):
     if not check_permissions(request.user) == HR_ADMIN:
         return HttpResponseRedirect(reverse('hr-index'))
     self.application = Application.objects.get(pk=kwargs.get('applicationid'))
     return super(HrAddNote, self).dispatch(request, *args, **kwargs)