def frontend_top_nav():
        navbar = ExtendedNavbar(
            View(current_app.config['SITE_TITLE'], 'frontend.index'),
            root_class='navbar navbar-inverse navbar-fixed-top',
            items = (
                View('Home', 'frontend.index'),
                View('Members', 'frontend.members'),
            )
        )
        if current_user.is_active:
            navbar.right_items = (
                View('Logout {}'.format(current_user.email), 'security.logout'),
                View('Change password', 'security.change_password'),
            )
            if current_user.has_role('admin'):
                navbar.right_items = \
                    (View('User admin', 'useradmin.index'),)\
                        +navbar.right_items
            if current_user.has_role('editor'):
                navbar.right_items = \
                    (View('Site editor', 'backend.index'),)\
                        +navbar.right_items
                
        else:
            navbar.right_items = ( View('Login', 'security.login'), )
        return navbar
 def get_query(self):
     allowed_locations = [location.id for location in current_user.locations]
     if current_user.has_role('Administrator'):
         return self.session.query(self.model)
     elif current_user.has_role('Standard'):
         return self.session.query(self.model).filter(
             self.model.id.in_(allowed_locations))
Beispiel #3
0
def application_comment_action(application_id, comment_id, action):
    form_comment = HrApplicationCommentForm()

    if current_user.has_role("recruiter") or current_user.has_role("admin"):
        if HrApplication.query.filter_by(id=int(application_id)).first():
            if HrApplicationComment.query.filter_by(id=comment_id).first():

                comment = HrApplicationComment.query.filter_by(id=comment_id).first()

                if comment.user_id == current_user.get_id() or current_user.has_role("admin"):

                    if request.method == 'POST':
                        if action == "edit":
                            if form_comment.validate_on_submit():
                                flash("comment valid", category="message")
                                HrManager.edit_comment(comment, form_comment.comment.data)

                        elif action == "delete":
                            print "wat"
                            comment.delete()

                    elif action == "delete":
                        print "wat"
                        comment.delete()
            return redirect(url_for('recruit.application_view', application_id=application_id))

    return redirect(url_for('recruit.applications'))
 def get_count_query(self):
     allowed_locations = [location.id for location in current_user.locations]
     if current_user.has_role('Administrator'):
         return super(StandardFilteredView, self).get_count_query()
     elif current_user.has_role('Standard'):
         return super(StandardFilteredView, self).get_count_query().filter(
             self.model.id.in_(allowed_locations))
def frontend_top_nav():
        navbar = ExtendedNavbar(
            LocalizedView(babel_config('SITE_TITLE'), 'frontend.index'),
            root_class='navbar navbar-inverse navbar-fixed-top',
            items = (
                LocalizedView(_('Home'), 'frontend.index'),
                LocalizedView(_('Members'), 'frontend.members'),
            )
        )
        if current_user.is_active:
            navbar.right_items = (
                Text('{}:'.format(current_user.email)),
                LocalizedView(_('Logout'), 'security.logout'),
                LocalizedView(_('Change password'), 'security.change_password'),
            )
            if current_user.has_role('editor'):
                navbar.right_items += \
                    (LocalizedView(_('Site editor'), 'backend.index'),)
            if current_user.has_role('admin'):
                navbar.right_items += \
                    (LocalizedView(_('User admin'), 'useradmin.index'),)
        else:
            navbar.right_items = ( View(_('Login'), 'security.login'), )

        if get_language_code()=='en':
            navbar.right_items += (
                LocalizedView(u'עברית', 'frontend.index', 'he'), )
        else:
            navbar.right_items += (
                LocalizedView('English', 'frontend.index', 'en'), )
        return navbar
Beispiel #6
0
    def is_accessible(self):
        #set defaults..
        self.can_export = False

        # set accessibility...
        if not current_user.is_active or not current_user.is_authenticated:
            return False
        # roles not tied to assending permissions...
        if current_user.has_role('export'):
            self.can_export = True
        # roles with assending permissions...
        if current_user.has_role('superuser'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = True
            self.can_export = True
            return True
        if current_user.has_role('user'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = False
            return True
        if current_user.has_role('create'):
            self.can_create = True
            self.can_edit = False
            self.can_delete = False
            return True
        if current_user.has_role('read'):
            self.can_create = False
            self.can_edit = False
            self.can_delete = False
            #self.can_export = False
            return True
        return False
Beispiel #7
0
def list_receivers():
    """List receivers that only have rights to see."""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 3, type=int)

    classes = current_user.classes
    role_ids = []
    if current_user.has_role(u'辅导员'):
        # 如果当前的角色是辅导员,则可以看到所有的本班的人,除了自己。
        student_role = api_role.first(name=u'学生')
        role_ids = [student_role.id]
    elif current_user.has_role(u'学生'):
        # 如果当前的角色是学生,则只可以看到学生以外的角色
        teacher_role = api_role.first(name=u'辅导员')
        role_ids = [teacher_role.id]

    users = api_user.get_user_from_classes(class_ids=[cls.id for cls in classes], role_ids=role_ids)

    #需要把users<pagenate对象>的相关属性提出来
    userdict = [{'id': u.id, 'text': str(u)} for u in users.items]
    return jsonify(dict(data=userdict,
                        pageinfo=dict(has_next=users.has_next, has_prev=users.has_prev,
                                      next_num=users.next_num, pages=users.pages,
                                      per_page=users.per_page, prev_num=users.prev_num,
                                      total=users.total)))
Beispiel #8
0
    def put(self, customer_id):
        moteur_id = None
        if current_user.has_role('admin'):
            parser = reqparse.RequestParser()
            parser.add_argument('moteur_id', location='values')
            moteur_id = parser.parse_args().get('moteur_id', None)
            if not moteur_id and not current_user.has_role('moteur'):
                abort(400, message='You need moteur_id argument')
        if not moteur_id:
            moteur_id = current_user.id

        customer = CustomerModel.query.filter_by(id=customer_id,
                moteur_id=current_user.id).first()
        if not customer:
            abort(404, message="Unable to find customer: {}".format(customer_id))

        json = request.json
        if not 'data' in json:
            abort(400, message="data is needed in json")
        if len(json['data']) == 0:
            return {"data": [customer]}
        if len(json['data']) > 1:
            abort(400, message="length of data must be one")
        customer_json = json['data'][0]
        for arg in ['reprieve_begin', 'reprieve_end', 'ban_begin', 'ban_end']:
            if not arg in customer_json:
                continue
            value = json.get(arg, None)
            setattr(customer, arg, value)
        db.session.add(customer)
        db.session.commit()
        return {"data":[customer]}
Beispiel #9
0
def application_view(application_id):
    comments = []
    characters = []

    form_app = HrApplicationForm()
    form_comment = HrApplicationCommentForm()

    application = HrApplication.query.filter_by(id=application_id).first()
    if application:
        if current_user.has_role("recruiter") or current_user.has_role("admin"):
            characters = EveCharacter.query.filter_by(user_id=application.user_id).all()

            comments = HrApplicationComment.query.filter_by(application_id=application_id).all()

            return render_template('recruit/application.html',
                                   application=application,
                                   characters=characters,
                                   comments=comments,
                                   form_comment=form_comment,
                                   form_app=form_app)

        elif int(application.user_id) == int(current_user.get_id()):

            return render_template('recruit/application.html',
                                   application=application,
                                   characters=characters,
                                   comments=comments,
                                   form_comment=form_comment,
                                   form_app=form_app)

    return redirect(url_for('recruit.applications'))
Beispiel #10
0
def application_interact(application_id, action):
    application_status = None

    auth_info = AuthInfoManager.get_or_create(current_user)

    if auth_info.main_character_id == None:
        return redirect(url_for('user.eve_characters'))

    application = HrApplication.query.filter_by(id=application_id).first()
    if application:
        # alter_application takes one of 4 actions
        if current_user.has_role("admin") or current_user.has_role("recruiter"):
            if current_user.has_role("admin") or action != "delete":
                application_status = HrManager.alter_application(application, action, current_user)

                flash("%s's application %s" % (application.main_character_name,
                                               application_status),
                      category='message')

        elif application.user_id == current_user.get_id():
            if action == "delete" and application.approve_deny == "Pending":
                application_status = HrManager.alter_application(application, action, current_user)
                flash("%s's application %s" % (application.main_character,
                                               application_status),
                      category='message')

        if application_status and application_status != "deleted":
            return redirect(url_for('recruit.application_view',
                                    application_id=application.id))

    return redirect(url_for('recruit.applications'))
Beispiel #11
0
def user(id):
    user = models.User.get(id) if id else None
    roles = models.Role.query.filter(models.Role.id >= current_user.roles[0].id).all()

    class UserForm(barrel.forms.Form):
        email = wtforms.StringField("email", [
            wtforms.validators.Required()
        ])
        role = wtforms.SelectField(choices=[(r.id, r.name) for r in roles],
                                   default=user.roles[0].id if user else 0)
        active = wtforms.BooleanField(default=True)
        new_password = wtforms.PasswordField()
        confirm_password = wtforms.PasswordField(None, [
            wtforms.validators.EqualTo('new_password',
                                       message='Passwords must match')
        ])
    if current_user.has_role('admin'):
        if user:
            UserForm.group_id = SelectField(models.Group, label='group', default=user.group_id)
        else:
            UserForm.group_id = SelectField(models.Group, label='group')
    elif id:
        UserForm.password = wtforms.PasswordField('Huidig wachtwoord',
                                                  [wtforms.validators.Required()])
    if request.method == 'POST':
        form = request.form
        if user and not current_user.has_role('admin'):
            if not security.verify_password(form.get('current_password'), user.password):
                app.logger.flash("Password incorrect", 'error')

        kwargs = {kw: form.get(kw) for kw in 'email active'.split()}
        if form.get('new_password'):
            kwargs['password'] = form.get('new_password')
        if form.get('role'):
            kwargs['roles'] = [models.Role.get(int(form.get('role')))]
        if form.get('group_id'):
            kwargs['group_id'] = int(form.get('group_id'))
        else:
            kwargs['group_id'] = current_user.group_id

        if user:
            user.update(**kwargs)
        else:
            user = models.User.create(**kwargs)
        return redirect(url_for('user', id=user.id))
    else:
        columns = 'email role active'
        users = models.User.query
        if current_user.has_role('admin'):
            columns += ' group'
        else:
            users = users.filter_by(group_id=current_user.group_id)
        return app.forms.render_page(
            id,
            models.User,
            template='lists/base.jinja2',
            columns=columns,
            form_class=UserForm,
            rows=users)
Beispiel #12
0
	def is_accessible(self):
		if not current_user.is_active or not current_user.is_authenticated:
			return False
		if (current_user.has_role("admin")
				or current_user.has_role("draw_approval")
				or current_user.has_role("site_manager")
				or current_user.has_role("budget_manager")):
			return True
		return False
Beispiel #13
0
def home():
    if current_user.has_role('admin'):
        user_list = [u for u in User.query.all() if u.has_role('operateur')]
    elif current_user.has_role('operateur'):
        user_list = [current_user]
    else:
        user_list = []
    return render_template('index.html',
                          user_name_list=[u.email for u in user_list],
                          is_admin=current_user.has_role('admin'),
                          apikey=current_user.apikey)
Beispiel #14
0
def ads_list():
    if not taxis_models.ADS.can_be_listed_by(current_user):
        if current_user.has_role('stats'):
            return self.metadata()
        abort(403, message="You're not allowed to see this page")
    q = taxis_models.ADS.query
    if not current_user.has_role('admin') and not current_user.has_role('prefecture'):
        q = q.filter_by(added_by=current_user.id)
    page = int(request.args.get('page')) if 'page' in request.args else 1
    return render_template('lists/ads.html',
        ads_list=q.paginate(page) if q else None)
Beispiel #15
0
def drivers_view(self):
    if not taxis_models.Driver.can_be_listed_by(current_user):
        if current_user.has_role('stats'):
            return self.metadata()
        abort(403, message="You can't list drivers")
    page = int(request.args.get('page')) if 'page' in request.args else 1
    q = taxis_models.Driver.query
    if not current_user.has_role('admin') and not current_user.has_role('prefecture'):
        q = q.filter_by(added_by=current_user.id)
    return render_template('lists/drivers.html',
        driver_list=q.paginate(page))
Beispiel #16
0
def list_hails(dep):
    if not current_user.has_role('admin') and\
       not current_user.has_role('operateur') and not current_user.has_role('moteur'):
        return defaultdict(dict)

    depattern = '{0:02d}%'.format(dep) if dep else '%'
    hails = []

    last_year = datetime.now() + relativedelta(months=-12)

    hails = db.session.query(Hail.operateur_id, Hail.added_by,
                             Hail.creation_datetime, Hail.id,
                             ADS.insee, ADS.numero, Hail._status) \
                 .join(Hail.taxi_relation) \
                 .join(Taxi.ads) \
                 .filter(ADS.insee.like(depattern)) \
                 .filter(Hail.creation_datetime >= last_year)

    if current_user.has_role('operateur'):
        hails = hails.filter(Hail.operateur_id == current_user.id)
    elif current_user.has_role('moteur'):
        hails = hails.filter(Hail.added_by == current_user.id)
    hidden_operator = User.query.filter_by(
        email=current_app.config.get('HIDDEN_OPERATOR', 'testing_operator')
    ).first()
    hidden_moteur = User.query.filter_by(
        email=current_app.config.get('HIDDEN_MOTEUR', 'testing_moteur')
    ).first()

    if hidden_operator:
        hails = hails.filter(Hail.operateur_id != hidden_operator.id)
    if hidden_moteur:
        hails = hails.filter(Hail.added_by != hidden_moteur.id)
    hails = hails.order_by(Hail.creation_datetime.desc()).limit(100).all()

    tab_hails = defaultdict(dict)
    for hail in hails:
        tab_hails[hail.id]['creation_datetime'] = hail.creation_datetime
        # tab_hails[hail.id]['added_by'] = user_datastore.get_user(hail.added_by).commercial_name
        tab_hails[hail.id]['added_by'] = user_datastore.get_user(hail.added_by).email
        tab_hails[hail.id]['operator'] = user_datastore.get_user(hail.operateur_id).commercial_name
        tab_hails[hail.id]['ads.insee'] = hail.insee
        zupc = None
        zupc = ZUPC.query.filter_by(insee=hail.insee).order_by(ZUPC.id.desc()).first()
        if zupc:
            tab_hails[hail.id]['zupc.nom'] = zupc.nom
        else:
            tab_hails[hail.id]['zupc.nom'] = ''
        tab_hails[hail.id]['ads.numero'] = hail.numero
        tab_hails[hail.id]['last_status'] = hail._status

    return tab_hails
Beispiel #17
0
def hails_map_list():
    if 'id' in request.args:
        return hails_log(request.args['id'])
    operateurs = []
    moteurs = []
    for u in User.query.all():
        if u.has_role('operateur') and current_user.has_role('admin'):
            operateurs.append(str(u.email))
        if u.has_role('moteur') and current_user.has_role('admin'):
            moteurs.append(str(u.email))
    return render_template('hails_list_map.html', apikey=current_user.apikey,
                          statuses=status_enum_list, operateurs=operateurs,
                          moteurs=moteurs)
Beispiel #18
0
 def get_count_query(self):
     if not current_user.has_role('package_admin'):
         return super(VersionView, self).get_count_query().\
             join(self.model.package).\
             join(Package.maintainers).\
             filter(User.id == current_user.id)
     return super(VersionView, self).get_count_query()
Beispiel #19
0
 def post(self):
     db = current_app.extensions['sqlalchemy'].db
     hj = request.json
     taxi_json = hj['data'][0]
     departement = administrative_models.Departement.filter_by_or_404(
         numero=str(taxi_json['driver']['departement']))
     driver = taxis_models.Driver.filter_by_or_404(
             professional_licence=taxi_json['driver']['professional_licence'],
                        departement_id=departement.id)
     vehicle = taxis_models.Vehicle.filter_by_or_404(
             licence_plate=taxi_json['vehicle']['licence_plate'])
     ads = taxis_models.ADS.filter_by_or_404(
           numero=taxi_json['ads']['numero'],insee=taxi_json['ads']['insee'])
     taxi = taxis_models.Taxi.query.filter_by(driver_id=driver.id,
             vehicle_id=vehicle.id, ads_id=ads.id).first()
     if taxi_json.get('id', None):
         if current_user.has_role('admin'):
             taxi = taxis_models.Taxi.query.get(taxi_json['id'])
         else:
             del taxi_json['id']
     if not taxi:
         taxi = taxis_models.Taxi(driver=driver, vehicle=vehicle, ads=ads,
                 id=taxi_json.get('id', None))
     #This can happen if this is posted with a admin user
     if 'status' in taxi_json and taxi.vehicle.description:
         try:
             taxi.status = taxi_json['status']
         except AssertionError:
             abort(400, message='Invalid status')
     db.session.add(taxi)
     db.session.commit()
     return {'data':[taxi]}, 201
Beispiel #20
0
    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False

        if current_user.has_role('superuser'):
            return True

        return False
Beispiel #21
0
    def is_accessible(self):
        if not current_user.is_active() or not current_user.is_authenticated():
            return False

        if current_user.has_role('admin'):
            return True

        return False
Beispiel #22
0
    def validate(self):
        if not super(GenerateApiKeyForm, self).validate():  # pragma: no cover
            return False

        if not current_user.has_role('developer'):
            return False

        return True
Beispiel #23
0
 def index(self):
     if login.current_user.is_authenticated:
         if current_user.has_role('admin'):
             return super(AdminIndexView, self).index()
         else:
             return make_response("Unauthorized User")
     else:
         return redirect(url_for('.login_view'))
Beispiel #24
0
def check_if_admin():
    if current_user:
        if current_user.has_role("admin"):
            return True
        else:
            return False
    else:
        return False
Beispiel #25
0
def TestLogin():
    if current_user.is_authenticated:
        if current_user.has_role('privileged_user'):
            context = {'user_name': get_current_user_first_name()}
            return render_template('testroles.html', **context)
        else:
            return  make_response("Unauthorized User")
    else:
        return redirect('/login')
Beispiel #26
0
 def is_accessible(self):
     if not current_user.is_active or not current_user.is_authenticated:
         return False
     if current_user.has_role('read'):
         self.can_create = False
         self.can_edit = False
         self.can_delete = False
         return True
     if current_user.has_role('create'):
         self.can_create = False
         self.can_edit = False
         self.can_delete = False
         return True
     if current_user.has_role('user'):
         self.can_create = False
         self.can_edit = False
         self.can_delete = False
         return True
     return False
Beispiel #27
0
 def is_accessible(self):
     if not current_user.is_active or not current_user.is_authenticated:
         return False
     if current_user.has_role('adminrole'):
         self.can_create = True
         self.can_edit = True
         self.can_delete = True
         #self.can_export = True
         return True
     return False
Beispiel #28
0
def script():
    """render own javascript"""
    return Response(
        response=render_template(
            "user_management/js/user_management.js", _=_,
            is_admin=current_user.has_role("Administrator"),
            user_id=current_user.id
        ),
        status=200,
        mimetype="application/javascript"
    )
    def _handle_view(self, name, **kwargs):
        """Redirect users when a view is not accessible"""
        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

        self.can_create = self.can_delete = current_user.has_role('Administrator')  # noqa
Beispiel #30
0
def send_mail_from_service():
    data = request.get_json()
    if current_user.is_authenticated() and not current_user.has_role('blocked'):
        service=Service.query.filter(Service.slug==data['service']).first()
        data['service'] = service.name
        data['user'] = current_user.email
        data['date'] = datetime.datetime.now()

        mail_template = render_template('service-mail.jinja', **data)

        msg = Message('new service',
                      sender="*****@*****.**",
                      recipients=["*****@*****.**"])
        msg.body = mail_template
        mail.send(msg)
        return jsonify(**{'status':'ok', 'notification': render_template('_notification.html', text="We have recived your service offer. We will contact you soon.")})
    else:
        if not current_user.is_authenticated():
            return jsonify(**{'status':'fail', 'notification': render_template('_notification.html', text="Sorry, you are not authenticated!")})
        elif current_user.has_role('blocked'):
            return jsonify(**{'status':'fail', 'notification': render_template('_notification.html', text="Sorry, you are in the blacklist!")})
Beispiel #31
0
    def post(self, id: str):
        """POST to /assets/<id>, where id can be 'create' (and thus a new asset is made from POST data)
        Most of the code deals with creating a user for the asset if no existing is chosen.
        """

        asset: Asset = None
        error_msg = ""

        if id == "create":
            asset_form = with_options(NewAssetForm())

            # We make our own auth check here because set_owner might alter the DB;
            # otherwise we trust the API is handling auth.
            if not current_user.has_role("admin"):
                return unauthorized_handler(None, [])
            owner, owner_error = set_owner(asset_form,
                                           create_if_not_exists=True)
            market, market_error = set_market(asset_form)

            if asset_form.asset_type_name.data == "none chosen":
                asset_form.asset_type_name.data = ""

            form_valid = asset_form.validate_on_submit()

            # Fill up the form with useful errors for the user
            if owner_error is not None:
                form_valid = False
                asset_form.owner.errors.append(owner_error)
            if market_error is not None:
                form_valid = False
                asset_form.market_id.errors.append(market_error)

            # Create new asset or return the form for new assets with a message
            if form_valid and owner is not None and market is not None:
                post_asset_response = InternalApi().post(
                    url_for("flexmeasures_api_v2_0.post_assets"),
                    args=asset_form.to_json(),
                    do_not_raise_for=[400],
                )

                if post_asset_response.status_code in (200, 201):
                    asset_dict = post_asset_response.json()
                    asset = process_internal_api_response(
                        asset_dict, int(asset_dict["id"]), make_obj=True)
                    msg = "Creation was successful."
                else:
                    current_app.logger.error(
                        f"Internal asset API call unsuccessful [{post_asset_response.status_code}]: {post_asset_response.text}"
                    )
                    asset_form.process_api_validation_errors(
                        post_asset_response.json())
                    if "message" in post_asset_response.json():
                        error_msg = post_asset_response.json()["message"]
            if asset is None:
                msg = "Cannot create asset. " + error_msg
                return render_flexmeasures_template(
                    "crud/asset_new.html",
                    asset_form=asset_form,
                    msg=msg,
                    map_center=get_center_location(db, user=current_user),
                    mapboxAccessToken=current_app.config.get(
                        "MAPBOX_ACCESS_TOKEN", ""),
                )

        else:
            asset_form = with_options(AssetForm())
            if not asset_form.validate_on_submit():
                return render_flexmeasures_template(
                    "crud/asset_new.html",
                    asset_form=asset_form,
                    msg="Cannot edit asset.",
                    map_center=get_center_location(db, user=current_user),
                    mapboxAccessToken=current_app.config.get(
                        "MAPBOX_ACCESS_TOKEN", ""),
                )
            patch_asset_response = InternalApi().patch(
                url_for("flexmeasures_api_v2_0.patch_asset", id=id),
                args=asset_form.to_json(),
                do_not_raise_for=[400],
            )
            asset_dict = patch_asset_response.json()
            if patch_asset_response.status_code in (200, 201):
                asset = process_internal_api_response(asset_dict,
                                                      int(id),
                                                      make_obj=True)
                msg = "Editing was successful."
            else:
                current_app.logger.error(
                    f"Internal asset API call unsuccessful [{patch_asset_response.status_code}]: {patch_asset_response.text}"
                )
                asset_form.process_api_validation_errors(
                    patch_asset_response.json())
                asset = Asset.query.get(id)

        latest_measurement_time_str, asset_plot_html = get_latest_power_as_plot(
            asset)
        return render_flexmeasures_template(
            "crud/asset.html",
            asset=asset,
            asset_form=asset_form,
            msg=msg,
            latest_measurement_time_str=latest_measurement_time_str,
            asset_plot_html=asset_plot_html,
            mapboxAccessToken=current_app.config.get("MAPBOX_ACCESS_TOKEN",
                                                     ""),
        )
Beispiel #32
0
 def is_accessible(self):
     # 目前仅允许超级管理员访问该页面
     return current_user.has_role(SuperAdmin)
Beispiel #33
0
    def edit_form_rules(self):
       
        if not has_app_context() or current_user.has_role('reviewer1'):
         edit_form_rules = [        
            #rules.Header('Personal Info'),
            rules.Header('Project Info'),
            rules.Field('project_name'),
            rules.Field('version'), 
            rules.Field('SVN'),
            CustomizableField('notes', field_args={
                 'readonly': True
            }),
            #rules.Field('project_name'),
            #rules.Field('version'),
            #rules.Field('SVN'),
            #rules.Field('notes'),
            rules.Header('Reviewers'),
            rules.Field('comment1'),
            CustomizableField('review1', field_args={
                 'readonly': True
            }),
            CustomizableField('comment2', field_args={
                 'readonly': True
            }),
            CustomizableField('comment3', field_args={
                 'readonly': True
            }),
          ]
         
        if not has_app_context() or current_user.has_role('reviewer2'):
         edit_form_rules = [        
            #rules.Header('Personal Info'),
            rules.Header('Project Info'),
            rules.Field('project_name'),
            rules.Field('version'),
            rules.Field('SVN'),
            CustomizableField('notes', field_args={
                 'readonly': True
            }),
            rules.Header('Reviewers'),
            CustomizableField('comment1', field_args={
                 'readonly': True
            }),
            rules.Field('comment2'),
            CustomizableField('review2', field_args={
                 'readonly': True
            }),
            CustomizableField('comment3', field_args={
                 'readonly': True
            }),
         ]
 
        if not has_app_context() or current_user.has_role('developer'):
         edit_form_rules = [        
            #rules.Header('Personal Info'),
            rules.Header('Project Info'),
            CustomizableField('project_name', field_args={
                 'readonly': True
            }),
            CustomizableField('version', field_args={
                 'readonly': True
            }),
            CustomizableField('SVN', field_args={
                 'readonly': True
            }),
            #rules.Container('wrap', rules.Field('notes')),
            rules.Field('notes'),
            rules.Header('Reviewers'),           
            CustomizableField('comment1', field_args={
                 'readonly': True
            }),
            CustomizableField('comment2', field_args={
                 'readonly': True
            }),
            CustomizableField('comment3', field_args={
                 'readonly': True
            }),
         ]
       
        if not has_app_context() or current_user.has_role('superuser') or current_user.has_role('administrator'):
         edit_form_rules = [        
            #rules.Header('Personal Info'),
            rules.Header('Project Info'),
            rules.Field('project_name'),
            rules.Field('version'),
            rules.Field('SVN'),
            rules.Field('notes'),
            rules.Header('Reviewers'),
            rules.Field('comment1'),
            rules.Field('review1'),
            rules.Field('comment2'),
            rules.Field('review2'),
            rules.Field('comment3'),
            rules.Field('approve'), 
         ]
        return edit_form_rules
Beispiel #34
0
 def can_unsign(self):
     return current_user.has_role('admin')
Beispiel #35
0
 def is_accessible(self):
     return current_user.has_role('admin')
	def is_accessible(self):
		if ((current_user is None)
		or not (current_user.has_role('admin'))):
			return False
		else:
			return True
 def is_accessible(self):
     return (
         current_user.is_superadmin
         or current_user.has_role("dataprovider")
         or current_user.writable_teams.count()
     )
Beispiel #38
0
 def can_delete(self):
     return current_user.has_role('admin')
Beispiel #39
0
 def can_create(self):
     return current_user.has_role('package_admin')
Beispiel #40
0
def can_do_stuff_with_job(current_user, owner):
    return current_user.has_role('admin') or current_user.email == owner.email
Beispiel #41
0
def admin():
    # "管理员界面"
    print('管理员界面')
    print(current_user.has_role('admin'))
    return 'admin view'
Beispiel #42
0
def upload_submitter_attachment(sid):
    # sid is a SubmissionRecord id
    record = SubmissionRecord.query.get_or_404(sid)

    # check is convenor for the project's class, or has suitable admin/root privileges
    config = record.owner.config
    pclass = config.project_class
    if not is_uploadable(record, message=True, allow_student=True, allow_faculty=True):
        return redirect(redirect_url())

    url = request.args.get('url', None)
    text = request.args.get('text', None)

    has_admin_rights = is_admin(current_user)
    UploadSubmitterAttachmentForm = UploadSubmitterAttachmentFormFactory(admin=has_admin_rights)
    form = UploadSubmitterAttachmentForm(request.form)

    if form.validate_on_submit():
        if 'attachment' in request.files:
            attachment_file = request.files['attachment']

            # generate unique filename for upload
            incoming_filename = Path(attachment_file.filename)
            extension = incoming_filename.suffix.lower()

            root_subfolder = current_app.config.get('ASSETS_ATTACHMENTS_SUBFOLDER') or 'attachments'

            year_string = str(config.year)
            pclass_string = pclass.abbreviation

            subfolder = Path(root_subfolder) / Path(pclass_string) / Path(year_string)

            filename, abs_path = make_submitted_asset_filename(ext=extension, subpath=subfolder)
            submitted_files.save(attachment_file, folder=str(subfolder), name=str(filename))

            # generate asset record
            asset = SubmittedAsset(timestamp=datetime.now(),
                                   uploaded_id=current_user.id,
                                   expiry=None,
                                   filename=str(subfolder/filename),
                                   target_name=form.target_name.data,
                                   mimetype=str(attachment_file.content_type),
                                   license=form.license.data)

            try:
                db.session.add(asset)
                db.session.flush()
            except SQLAlchemyError as e:
                flash('Could not upload attachment due to a database issue. Please contact an administrator.', 'error')
                current_app.logger.exception("SQLAlchemyError exception", exc_info=e)
                return redirect(url_for('documents.submitter_documents', sid=sid, url=url, text=text))

            # generate attachment record
            attachment = SubmissionAttachment(parent_id=record.id,
                                              attachment_id=asset.id,
                                              description=form.description.data)

            if has_admin_rights:
                attachment.type = form.type.data
                attachment.publish_to_students = form.publish_to_students.data
                attachment.include_supervisor_emails = form.include_supervisor_emails.data
                attachment.include_marker_emails = form.include_marker_emails.data

            else:
                attachment.include_marker_emails = False
                attachment.include_supervisor_emails = False
                attachment.type = SubmissionAttachment.ATTACHMENT_OTHER

                if current_user.has_role('student'):
                    attachment.publish_to_students = True

                else:
                    attachment.publish_to_students = False

            # uploading user has access
            asset.grant_user(current_user)

            # project supervisor has access
            if record.project is not None and record.project.owner is not None:
                asset.grant_user(record.project.owner.user)

            # project examiner has access
            if record.marker is not None:
                asset.grant_user(record.marker.user)

            # students can't ordinarily download attachments unless permission is given

            # set up list of roles that should have access, if they exist
            asset.grant_roles(['office', 'convenor', 'moderator', 'exam_board', 'external_examiner'])

            try:
                db.session.add(attachment)
                db.session.commit()
            except SQLAlchemyError as e:
                flash('Could not upload attachment due to a database issue. '
                      'Please contact an administrator.', 'error')
                current_app.logger.exception("SQLAlchemyError exception", exc_info=e)
            else:
                flash('Attachment "{file}" was successfully uploaded.'.format(file=incoming_filename), 'info')

            return redirect(url_for('documents.submitter_documents', sid=sid, url=url, text=text))

    else:
        if request.method == 'GET':
            form.license.data = current_user.default_license

    return render_template('documents/upload_attachment.html', record=record, form=form, url=url, text=text,
                           has_admin_rights=has_admin_rights)
Beispiel #43
0
 def is_accessible(self):
     return (current_user.is_active and current_user.is_authenticated
             and current_user.has_role('superuser'))
 def is_accessible(self):
     return current_user.is_active and current_user.is_authenticated and \
            (not self.role_required or current_user.has_role(self.role_required))
Beispiel #45
0
 def is_accessible(self):
     if not current_user.is_active or not current_user.is_authenticated:
         return False
     if current_user.has_role('superuser'):
         return True
     return False
Beispiel #46
0
 def is_accessible(self):
     return current_user.has_role(Role.admin().name)
Beispiel #47
0
 def has_one_accepted_role(self, user):
     return any([current_user.has_role(r) for r in self.roles_accepted])
Beispiel #48
0
def timeline(student_id):
    """
    Show student timeline
    :return:
    """

    if current_user.has_role('student') and student_id != current_user.id:
        flash(
            'It is only possible to view the project timeline for your own account.',
            'info')
        return redirect(redirect_url())

    user = User.query.get_or_404(student_id)

    if not user.has_role('student'):
        flash(
            'It is only possible to view project timelines for a student account.',
            'info')
        return redirect(redirect_url())

    if user.student_data is None:
        flash(
            'Cannot display project timeline for this student account because the corresponding '
            'StudentData record is missing.', 'error')
        return redirect(redirect_url())

    data = user.student_data

    if not data.has_timeline:
        if current_user.has_role('student'):
            flash(
                'You do not yet have a timeline because you have not completed any projects. '
                'This option will become available once you have one or more completed '
                'submissions in the database.', 'info')

        else:
            flash(
                'This student does not yet have any completed submissions. The timeline option '
                'will become available once one or more retired submissions have been entered '
                'in the database.', 'info')

        return redirect(redirect_url())

    url = request.args.get('url', None)
    text = request.args.get('text', None)

    # collate retired selector and submitter records for this student
    years, selector_records, submitter_records = data.collect_student_records()

    # check roles for logged-in user, to determine whether they are permitted to view the student's feedback
    roles = {}
    for year in submitter_records:
        submissions = submitter_records[year]
        for sub in submissions:
            for record in sub.ordered_assignments:
                if validate_is_convenor(sub.config.project_class,
                                        message=False):
                    roles[record.id] = 'convenor'
                elif validate_submission_viewable(record, message=False):
                    roles[record.id] = 'faculty'
                elif user.id == current_user.id and current_user.has_role(
                        'student'):
                    roles[record.id] = 'student'

    student_text = 'my timeline'
    generic_text = 'student timeline'.format(name=user.name)
    return_url = url_for('student.timeline',
                         student_id=data.id,
                         text=text,
                         url=url)

    return render_template('student/timeline.html',
                           data=data,
                           years=years,
                           user=user,
                           student=data,
                           selector_records=selector_records,
                           submitter_records=submitter_records,
                           roles=roles,
                           text=text,
                           url=url,
                           student_text=student_text,
                           generic_text=generic_text,
                           return_url=return_url)
Beispiel #49
0
 def inaccessible_callback(self, name, **kwargs):
     if not current_user.has_role('admin'):
         return redirect(url_for('security.login', next=request.url))
Beispiel #50
0
def view_vid_page(videoID):
    sysSettings = settings.settings.query.first()
    videos_root = globalvars.videoRoot + 'videos/'

    recordedVid = RecordedVideo.RecordedVideo.query.filter_by(
        id=videoID).first()

    if recordedVid is not None:

        if recordedVid.published is False:
            if current_user.is_authenticated:
                if current_user != recordedVid.owningUser and current_user.has_role(
                        'Admin') is False:
                    flash("No Such Video at URL", "error")
                    return redirect(url_for("root.main_page"))
            else:
                flash("No Such Video at URL", "error")
                return redirect(url_for("root.main_page"))

        if recordedVid.channel.protected and sysSettings.protectionEnabled:
            if not securityFunc.check_isValidChannelViewer(
                    recordedVid.channel.id):
                return render_template(
                    themes.checkOverride('channelProtectionAuth.html'))

        recordedVid.views = recordedVid.views + 1
        recordedVid.channel.views = recordedVid.channel.views + 1

        if recordedVid.length is None:
            fullVidPath = videos_root + recordedVid.videoLocation
            duration = None
            try:
                duration = videoFunc.getVidLength(fullVidPath)
            except:
                return render_template(themes.checkOverride('notready.html'),
                                       video=recordedVid)
            recordedVid.length = duration
        db.session.commit()

        topicList = topics.topics.query.all()

        streamURL = '/videos/' + recordedVid.videoLocation

        isEmbedded = request.args.get("embedded")

        newView = views.views(1, recordedVid.id)
        db.session.add(newView)
        db.session.commit()

        # Function to allow custom start time on Video
        startTime = None
        if 'startTime' in request.args:
            startTime = request.args.get("startTime")
        try:
            startTime = float(startTime)
        except:
            startTime = None

        if isEmbedded is None or isEmbedded == "False":

            randomRecorded = RecordedVideo.RecordedVideo.query.filter(
                RecordedVideo.RecordedVideo.pending == False,
                RecordedVideo.RecordedVideo.id != recordedVid.id,
                RecordedVideo.RecordedVideo.published == True).order_by(
                    func.random()).limit(12)

            subState = False
            if current_user.is_authenticated:
                chanSubQuery = subscriptions.channelSubs.query.filter_by(
                    channelID=recordedVid.channel.id,
                    userID=current_user.id).first()
                if chanSubQuery is not None:
                    subState = True

            return render_template(themes.checkOverride('vidplayer.html'),
                                   video=recordedVid,
                                   streamURL=streamURL,
                                   topics=topicList,
                                   randomRecorded=randomRecorded,
                                   subState=subState,
                                   startTime=startTime)
        else:
            isAutoPlay = request.args.get("autoplay")
            if isAutoPlay is None:
                isAutoPlay = False
            elif isAutoPlay.lower() == 'true':
                isAutoPlay = True
            else:
                isAutoPlay = False
            return render_template(
                themes.checkOverride('vidplayer_embed.html'),
                video=recordedVid,
                streamURL=streamURL,
                topics=topicList,
                isAutoPlay=isAutoPlay,
                startTime=startTime)
    else:
        flash("No Such Video at URL", "error")
        return redirect(url_for("root.main_page"))
Beispiel #51
0
 def is_accessible(self):
     """Make sure only admins can see this"""
     return current_user.has_role('admin')
Beispiel #52
0
def comments_vid_page(videoID):
    sysSettings = settings.settings.query.first()

    recordedVid = RecordedVideo.RecordedVideo.query.filter_by(
        id=videoID).first()

    if recordedVid is not None:

        if request.method == 'POST':

            comment = system.strip_html(request.form['commentText'])
            currentUser = current_user.id

            newComment = comments.videoComments(currentUser, comment,
                                                recordedVid.id)
            db.session.add(newComment)
            db.session.commit()

            if recordedVid.channel.imageLocation is None:
                channelImage = (sysSettings.siteProtocol +
                                sysSettings.siteAddress +
                                "/static/img/video-placeholder.jpg")
            else:
                channelImage = (sysSettings.siteProtocol +
                                sysSettings.siteAddress + "/images/" +
                                recordedVid.channel.imageLocation)

            pictureLocation = ""
            if current_user.pictureLocation is None:
                pictureLocation = '/static/img/user2.png'
            else:
                pictureLocation = '/images/' + pictureLocation

            newNotification = notifications.userNotification(
                templateFilters.get_userName(current_user.id) +
                " commented on your video - " + recordedVid.channelName,
                '/play/' + str(recordedVid.id),
                "/images/" + str(current_user.pictureLocation),
                recordedVid.owningUser)
            db.session.add(newNotification)
            db.session.commit()

            webhookFunc.runWebhook(
                recordedVid.channel.id,
                7,
                channelname=recordedVid.channel.channelName,
                channelurl=(sysSettings.siteProtocol +
                            sysSettings.siteAddress + "/channel/" +
                            str(recordedVid.channel.id)),
                channeltopic=templateFilters.get_topicName(
                    recordedVid.channel.topic),
                channelimage=channelImage,
                streamer=templateFilters.get_userName(
                    recordedVid.channel.owningUser),
                channeldescription=str(recordedVid.channel.description),
                videoname=recordedVid.channelName,
                videodate=recordedVid.videoDate,
                videodescription=recordedVid.description,
                videotopic=templateFilters.get_topicName(recordedVid.topic),
                videourl=(sysSettings.siteProtocol + sysSettings.siteAddress +
                          '/videos/' + recordedVid.videoLocation),
                videothumbnail=(sysSettings.siteProtocol +
                                sysSettings.siteAddress + '/videos/' +
                                recordedVid.thumbnailLocation),
                user=current_user.username,
                userpicture=(sysSettings.siteProtocol +
                             sysSettings.siteAddress + str(pictureLocation)),
                comment=comment)
            flash('Comment Added', "success")
            system.newLog(
                4, "Video Comment Added by " + current_user.username +
                "to Video ID #" + str(recordedVid.id))

        elif request.method == 'GET':
            if request.args.get('action') == "delete":
                commentID = int(request.args.get('commentID'))
                commentQuery = comments.videoComments.query.filter_by(
                    id=commentID).first()
                if commentQuery is not None:
                    if current_user.has_role(
                            'Admin'
                    ) or recordedVid.owningUser == current_user.id or commentQuery.userID == current_user.id:
                        upvoteQuery = upvotes.commentUpvotes.query.filter_by(
                            commentID=commentQuery.id).all()
                        for vote in upvoteQuery:
                            db.session.delete(vote)
                        db.session.delete(commentQuery)
                        db.session.commit()
                        system.newLog(
                            4, "Video Comment Deleted by " +
                            current_user.username + "to Video ID #" +
                            str(recordedVid.id))
                        flash('Comment Deleted', "success")
                    else:
                        flash("Not Authorized to Remove Comment", "error")

    else:
        flash('Invalid Video ID', 'error')
        return redirect(url_for('root.main_page'))

    return redirect(url_for('.view_vid_page', videoID=videoID))
Beispiel #53
0
def authorize(role):
    if not current_user.is_authenticated:
        return _unauthenticated_response
    if not current_user.has_role(role):
        return _forbidden_response
    return None
Beispiel #54
0
 def is_accessible(self):
     return current_user.has_role('Superuser') or current_user.has_role(
         'Admin')
Beispiel #55
0
 def can_edit(self):
     return current_user.has_role('package_admin')
Beispiel #56
0
 def is_accessible(self):
     """
     Only allow admins to see other users
     """
     return current_user.has_role('admin')
Beispiel #57
0
def index():
    if not current_user.is_authenticated:
        return redirect("/login")
    if current_user.has_role(data_store.find_role("pending")):
        return redirect("/pending")
    return redirect("/overview")
Beispiel #58
0
    def index(self):
        if not current_user.is_authenticated:
            return redirect(url_for('security.login'))

        if current_user.has_role('master'):
            print('i am a master')
            current_week = len(
                Profile.query.filter(
                    Profile.propertys.any(Property.name == 'Лид')).filter(
                        Profile.user == current_user.id).filter(
                            func.strftime('%W', User.created_at) == (
                                '0' + str(datetime.now().isocalendar()[1])
                            )).filter(Profile.city == Profile.city).filter(
                                Profile.contacted.any(
                                    Profile.user == current_user.id)).all())
            print(current_week)
            previous_week = len(
                Profile.query.filter(
                    Profile.propertys.any(Property.name == 'Лид')).filter(
                        Profile.user == current_user.id).filter(
                            func.strftime('%W', User.created_at) == (
                                '0' + str(datetime.now().isocalendar()[1] - 1)
                            )).filter(Profile.city == Profile.city).filter(
                                Profile.contacted.any(
                                    Profile.user == current_user.id)).all())
            print(previous_week)

            if previous_week == 0 and current_week == 0:
                delta = 0
            elif previous_week == 0:
                delta = round(
                    (((float(previous_week) / float(current_week)) + 1) * 100),
                    2)
            else:
                delta = round(
                    (((float(current_week) / float(previous_week)) - 1) * 100),
                    2)

        elif current_user.has_role('superadmin'):
            arg1 = 'Hello'
            asd = User.query.get(1)
            year = '2018'
            month = '1'
            day = '1'
            time = '23:59:59'
            data = '{}-{}-{} {}'.format(year, month, day, time)
            newdata = '{}-{}-{} {}'.format((str(int(year) - 25)), month, day,
                                           time)
            #print(newdata)
            print(asd.created_at.isocalendar()[1])
            print(str(int(datetime.now().isocalendar()[1])))
            if asd.created_at.strftime('%V') == (
                    '0' + str(int(datetime.now().isocalendar()[1]))):
                print('yeah!')

            print(asd.created_at.strftime('%V'))
            print('0' + str(int(datetime.now().isocalendar()[1])))
            weekly_contacts = User.query.filter(
                db.func.date(User.created_at) <= data,
                db.func.date(User.created_at) >= newdata).count()
            current_week = len(
                User.query.filter(
                    func.strftime('%W', User.created_at) == (
                        '0' + str(datetime.now().isocalendar()[1]))).all())
            previous_week = len(
                User.query.filter(
                    func.strftime('%W', User.created_at) == (
                        '0' + str(datetime.now().isocalendar()[1] - 1))).all())

            #print(newquery)
            print(current_week)
            print(previous_week)
            if previous_week == 0 and current_week == 0:
                delta = 0
            elif previous_week == 0:
                delta = round(
                    (((float(previous_week) / float(current_week)) + 1) * 100),
                    2)
            else:
                delta = round(
                    (((float(current_week) / float(previous_week)) - 1) * 100),
                    2)

            #fromto_contacts = len(User.query.filter(User.created_at.between(newdata, data)).all())
            #print(fromto_contacts)
            #print(weekly_contacts)

        return self.render(
            'admin/roles/superadmin.html',
            current_week='123',  #current_week,
            previous_week='123',  #previous_week,
            delta='123')  #delta)
Beispiel #59
0
 def is_accessible(self):
     return current_user.is_authenticated and current_user.has_role('admin')
Beispiel #60
0
def index_redirect():
    if current_user.has_role('Greinir'):
        return redirect(url_for('verification.verify_index'))
    return redirect(url_for('collection.collection_list'))