def get(self, id): try: id = int(id) sc = Screen.get(id) return self.render_page(sc) except (SQLObjectNotFound, ValueError): resp.seeother('/screens')
def post(self, channel_id): channel = Channel.get(int(channel_id)) form = self.form try: if form.action == 'add-channel-to-bundles': bundles_diff = json.loads(form.pop('diff', '{}')) for bundle_id, part_of in bundles_diff.items(): bundle = ChannelBundle.get(int(bundle_id)) if part_of: try: bundle.add_channel(channel) except ValueError: raise ImmediateFeedback(form.action, 'bundle_cycle', bundle.name) else: bundle.remove_channel(channel) add_feedback(form.action, 'ok') except ImmediateFeedback: pass form.was_bundle = type( channel ) == ChannelBundle # Hack to display the bundles tab instead form.data_edit = json.dumps([b.id for b in channel.bundles]) form.channel_id = channel_id form.name = channel.name store_form(form) resp.seeother('/channels')
def get(self, email): u = User.selectBy(email=email).getOne(None) if u is not None: self.session['user'] = u.to_dictionary(['id', 'fullname', 'email']) if 'sidebar' in self.session: self.session.pop('sidebar') resp.seeother('/')
def get(self, target_user): @PermissionGate.administrator def log_as(): u = User.selectBy(email=target_user).getOne() real_user_dict = self.session[ 'user'] if 'real_user' not in self.session else self.session[ 'real_user'] real_user = User.selectBy(email=real_user_dict['email']).getOne() if u is not None: if u.highest_permission_level in real_user.highest_permission_level: self.session['real_user'] = self.session[ 'user'] if 'real_user' not in self.session else self.session[ 'real_user'] self.session['user'] = u.to_dictionary( ['id', 'fullname', 'email']) self.logger.info( 'the super_administrator %s has been logged as %s', real_user.log_name, u.log_name) resp.seeother('/') else: resp.forbidden() if target_user == 'nobody': if 'real_user' in self.session: self.session['user'] = self.session['real_user'] self.session.pop('real_user') resp.seeother('/') log_as() return "the user " + target_user + " does not exist"
def get(self, mac): """ Redirects a screen with its given mac to its secret link. """ try: screen = ScreenMac.selectBy(mac=mac).getOne().screen except SQLObjectNotFound: resp.notfound() resp.seeother(screen.get_view_link())
def get(self, secret): user = User.selectBy(reset_secret=secret).getOne(None) if not user: logger.warning('IP %s tried to access password reset page with invalid secret', flask.request.remote_addr) if 'user' in self.session: logger.warning('User %s is currently connected', User.get(self.session['user']['id']).log_name) resp.seeother('/') return self.standalone_renderer.reset(user=user)
def post(self, channel_id, channel): """ Handles channel creation, editing, deletion, configuration and user permissions. """ form = self.form current_user = User.get(self.session['user']['id']) try: if form.action == 'reset-config': if form.all == "true": for param_id, param_attrs in channel.plugin.channels_params.items( ): read, write = channel.get_access_rights_for( param_id, current_user) if read and write: channel.plugin_config.pop(param_id, None) # Force SQLObject update channel.plugin_config = channel.plugin_config else: param_id = form["reset-param-id"] if param_id not in channel.plugin.channels_params.keys(): raise ImmediateFeedback(form.action, "invalid_param_id") read, write = channel.get_access_rights_for( param_id, current_user) if read and write: channel.plugin_config.pop(param_id, None) else: raise self.forbidden() # Force SQLObject update channel.plugin_config = channel.plugin_config channel.syncUpdate() logger.info('params of channel ' + channel.name + ' reset by ' + current_user.log_name) elif form.action == 'reset-cache-config': if not current_user.super_admin: raise self.forbidden() form.name = channel.name channel.cache_activated = None channel.cache_validity = None add_feedback('general', 'channel_cache_reset') logger.info( 'the cache configuration of channel %s has been reset by user %s', channel.name, current_user.log_name) elif form.action == 'reset-filtering-config': if not current_user.super_admin: raise self.forbidden() form.name = channel.name channel.keep_noncomplying_capsules = None add_feedback('general', 'channel_filtering_reset') logger.info( 'the capsule filtering configuration of channel %s has been reset by user %s', channel.name, current_user.log_name) add_feedback('general', 'channel_edited') add_feedback(form.action, 'ok') form.name = channel.name except ImmediateFeedback: if channel is not None and channel.enabled: form.enabled = 'on' store_form(form) resp.seeother('/channels/config/%d' % channel.id)
def post(self): """ Receive the POST binding request from IDP. - process the request - extract user attributes - create a new User if it doesn't exist - fill in the session - redirect to RelayState or / """ # SAML boiler plate code req = prepare_request() settings = build_settings(self.config['saml2']) # this is the object to interact with the shibboleth parameters auth = init_saml_auth(req, settings) errors = [] not_auth_warn = False success_slo = False input_data = flask.request.form if 'acs' in flask.request.args: auth.process_response() # decrypt and extract informations errors = auth.get_errors() not_auth_warn = not auth.is_authenticated() if len(errors) == 0: attrs = auth.get_attributes( ) # get attributes returned by the shibboleth idp for key in attrs.keys(): print("(" + key + ", " + str(attrs[key]) + ")") username = attrs[settings['sp']['attrs']['username']][0] realname = attrs[settings['sp']['attrs']['realname']][0] email = attrs[settings['sp']['attrs']['email']][0] u = User.selectBy(email=email).getOne(None) if not u: # The user does not exist in our DB u = User(username=username, email=email, fullname=realname, super_admin=False, disabled=True) self.session['user'] = u.to_dictionary( ['id', 'fullname', 'username', 'email']) self_url = OneLogin_Saml2_Utils.get_self_url(req) if 'RelayState' in input_data and self_url != input_data[ 'RelayState']: return resp.seeother( auth.redirect_to(input_data['RelayState'])) return resp.seeother('/')
def get(self, id): try: id = int(id) u = User.get(id) if id != self.session['user'][ 'id'] and UserPermissions.administrator not in User.get( self.session['user']['id']).highest_permission_level: resp.forbidden() return self.render_page(u) except (SQLObjectNotFound, ValueError): resp.seeother('/users')
def get(self, asset_id): """ Waits for the given asset to be downloaded. Redirects the user to the asset when done. """ try: asset_id = int(asset_id) if self.download_manager.has_pending_task_for_asset(asset_id): task = self.download_manager.get_pending_task_for_asset(asset_id) task.result() resp.seeother('/' + Asset.get(asset_id)._get_path(force=True)) # Task is complete but asset may be still marked as in flight except SQLObjectNotFound: resp.notfound() except KeyError: resp.seeother('/cache/' + str(asset_id))
def decorated_function(*args, **kwargs): app = flask.current_app if 'user' in app.session: u = User.get(app.session['user']['id']) if 'real_user' in app.session: real_user = User.get(app.session['real_user']['id']) # if the real user has at least the same right as the "logged as" user if u.highest_permission_level not in real_user.highest_permission_level: resp.seeother('/logas/nobody') if permission_level in u.highest_permission_level: return f(*args, **kwargs) resp.forbidden()
def post(self): if 'user' in self.session: resp.seeother('/') form = self.form try: user = User.selectBy(email=form.email, password=hash_password(form.password)).getOne(None) if not user: raise ImmediateFeedback('login', 'invalid_credentials') self.session['user'] = user.to_dictionary(['id', 'fullname', 'username', 'email']) except ImmediateFeedback: store_form(form) return self.render_page() resp.seeother('/')
def get(self): req = prepare_request() settings = build_settings(self.config['saml2']) auth = init_saml_auth(req, settings) errors = [] not_auth_warn = False success_slo = False input_data = flask.request.args if 'sso' in input_data: resp.seeother(auth.login()) return resp.seeother('/')
def get(self, id, user_id): channel_id = int(id) chan = Channel.get(channel_id) user_id = int(user_id) user = User.get(user_id) st = "You just receive a request of subscription for channel " + chan.name + ". Could you please subscribe " + str( user.fullname) + " (" + user.email + ") to this channel." for admin in chan.get_admins(): web.sendmail(web.config.smtp_sendername, admin.email, 'Request for subscription to a channel', st, headers={'Content-Type': 'text/html;charset=utf-8'}) resp.seeother('/channels')
def post(self, secret): user = User.selectBy(reset_secret=secret).getOne(None) form = self.form try: if form.get('password1') != form.get('password2'): raise ImmediateFeedback('reset', 'passwords_do_not_match') password = form.password1.strip() if len(password) <= 3: raise ImmediateFeedback('reset', 'password_insufficient') user.password = hash_password(form.password1) user.reset_secret = utils.generate_secret() # Make this token one time use logger.info('User %s has reset its password from IP %s', user.log_name, flask.g.ip) except ImmediateFeedback: return self.standalone_renderer.reset(user=user) add_feedback('reset', 'ok') resp.seeother(flask.url_for("LoginPage"))
def wrapper(*args, **kwargs): app = flask.current_app if len(flask.g.homepath)>0: # we are in a sub-app channelid = re.findall(r'\d+', flask.g.homepath)[0] else: channelid = re.findall(r'\d+', flask.request.path)[0] channel = PluginChannel.get(channelid) u = User.get(app.session['user']['id']) if 'real_user' in app.session: real_user = User.get(app.session['real_user']['id']) # if the real user has at least the same right as the "logged as" user if u.highest_permission_level not in real_user.highest_permission_level: resp.seeother('/logas/nobody') if UserPermissions.administrator in u.highest_permission_level or permission_level in channel.get_channel_permissions_of(u): kwargs['channel'] = channel return func(*args, **kwargs) else: resp.forbidden()
def log_as(): u = User.selectBy(email=target_user).getOne() real_user_dict = self.session[ 'user'] if 'real_user' not in self.session else self.session[ 'real_user'] real_user = User.selectBy(email=real_user_dict['email']).getOne() if u is not None: if u.highest_permission_level in real_user.highest_permission_level: self.session['real_user'] = self.session[ 'user'] if 'real_user' not in self.session else self.session[ 'real_user'] self.session['user'] = u.to_dictionary( ['id', 'fullname', 'email']) self.logger.info( 'the super_administrator %s has been logged as %s', real_user.log_name, u.log_name) resp.seeother('/') else: resp.forbidden()
def decorated_function(*args, **kwargs): app = flask.current_app app.session = flask.session if 'user' in app.session and 'sidebar' not in app.session: try: u = User.get(app.session['user']['id']) if 'real_user' in app.session: real_user = User.get(app.session['real_user']['id']) # if the real user has at least the same right as the "logged as" user if u.highest_permission_level not in real_user.highest_permission_level: resp.seeother('/logas/nobody') user_sidebar = {} for class_name in get_classes_from_user(u): e = sidebar_elements[class_name] user_sidebar[e['name']] = {'url': urls[urls.index(class_name) - 1], 'icon': e['icon']} app.session['sidebar'] = sorted(user_sidebar.items()) except SQLObjectNotFound: return f(*args, **kwargs) return f(*args, **kwargs)
def post(self): form = self.form subject = form['subject'] email_body = form['body'] to = form['to'] receivers = [] if to == "admins": receivers = [u for u in User.selectBy(admin=True, disabled=False)] elif to == "supadmins": receivers = [u for u in User.selectBy(super_admin=True).distinct()] elif to == 'contrib': id_channel = form['select_channel'] c = PluginChannel.get(id_channel) receivers = [u for u in c.get_contribs()] elif to == "channel_editor_users": pc = PluginChannel.select() for elem in pc: if elem.plugin.name == "editor": l1 = [u1 for u1 in elem.get_admins()] l2 = [u2 for u2 in elem.get_contribs()] list_users = l1 + l2 receivers = [u for u in list_users] else: for s in Screen.select(): receivers = [u for u in s.owners] try: mail = Mail(self.app) msg = Message( recipients=[u.email for u in receivers], subject=subject, body=email_body, extra_headers={'Content-Type': 'text/html;charset=utf-8'}) mail.send(msg) except smtplib.SMTPException: logger.error('An error occured when sending email ', exc_info=True) resp.seeother("/")
def local_authentication_processor(handler): if 'user' not in app.session and not flask.request.path.startswith( '/login') and not flask.request.path.startswith('/reset'): flask.abort(resp.seeother('/login')) handler()
def post(self, status): User.get(self.session['user']['id']).has_toured = status == 'ended' resp.seeother(flask.request.environ.get('HTTP_REFERER', '/'))
def post(self): self.session.clear() resp.seeother('/')
def post(self): """ Handles user creation, editing and deletion. """ form = self.form super_admin = form.get('super_admin', False) == 'on' admin = form.get('admin', False) == 'on' if super_admin: admin = False current_user = User.get(self.session['user']['id']) try: if form.action == 'create': username = form.username.strip() fullname = form.fullname.strip() form.email = form.email.strip() email = None if len(form.email) == 0 or not self.pattern.match( form.email) else form.email if email is None and len(form.email) != 0: raise ImmediateFeedback(form.action, 'invalid_email') if len(email) > User.sqlmeta.columns['email'].length: raise ImmediateFeedback(form.action, 'too_long_email') if len(username) > User.sqlmeta.columns['username'].length: raise ImmediateFeedback(form.action, 'too_long_username') if not username: username = None elif len(username) < 3: raise ImmediateFeedback(form.action, 'invalid_username') try: User(username=username, fullname=fullname, email=email, super_admin=super_admin, disabled=False) except DuplicateEntryError: u = User.selectBy(email=form.email).getOne(None) if u is not None: raise ImmediateFeedback(form.action, 'email_already_exists') u = User.selectBy(username=username).getOne(None) if u is not None: raise ImmediateFeedback(form.action, 'username_already_exists') elif form.action == 'edit': try: form.id = int(form.id) u = User.get(form.id) form.email = form.email.strip() email = None if len( form.email) == 0 or not self.pattern.match( form.email) else form.email form.username = u.username form.fullname = u.fullname if email is None and len(form.email) != 0: raise ImmediateFeedback(form.action, 'invalid_email') if email: try: u.email = email except DuplicateEntryError: raise ImmediateFeedback(form.action, 'email_already_exists') form.email = u.email if len(email) > User.sqlmeta.columns['email'].length: raise ImmediateFeedback(form.action, 'too_long_email') if not current_user.super_admin: if u.super_admin: resp.forbidden() else: if self.session['user']['id'] != form.id: u.set(super_admin=super_admin, admin=admin) except (SQLObjectNotFound, ValueError): raise ImmediateFeedback(form.action, 'invalid_id') elif form.action == 'toggle-activation': if not current_user.super_admin: resp.forbidden() try: form.id = int(form.id) u = User.get(form.id) form.email = u.email u.disabled = not u.disabled add_feedback( form.action, 'activated' if not u.disabled else 'deactivated') except (SQLObjectNotFound, ValueError): raise ImmediateFeedback(form.action, 'invalid_id') add_feedback(form.action, 'ok') except ImmediateFeedback: pass store_form(form) resp.seeother('/users')
def get(self): if 'user' in self.session: resp.seeother('/') return self.render_page()
def post(self, screen_id): def wrong_channel(channel, subscribe, user): """ returns True if the the user wants to subscribe to the channel while its plugin is not activated or if the user tries to subscribe to the channel without being in its authorized subscribers""" return subscribe and (type(channel) is PluginChannel and channel.plugin.activated != "yes" or (subscribe and not channel.can_subscribe(user))) form = self.form try: screen = Screen.get(screen_id) u = User.get(self.session['user']['id']) # Forbid if not admin or does not own this screen if not (UserPermissions.administrator in u.highest_permission_level or screen in u.screens): logger.warning('user %s tried change subscriptions of screen %d without having the rights to do this', u.log_name, screen.id) resp.forbidden() diff = json.loads(form.diff) if diff == {}: logger.info('user %s submitted empty diff for subscriptions of screen %s', u.log_name, screen.name) raise ImmediateFeedback("subscription", 'nothing_changed') # Do the subscription/unsubscription for every channel in the diff subscribed = [] unsubscribed = [] try: changes = [(Channel.get(channel_id), subscribe) for channel_id, subscribe in diff.items()] except SQLObjectNotFound: logger.warning('user %s tried to subscribe/unsubscribe screen %d to a channel which does not exist', u.log_name, screen.id) resp.forbidden() # if somebody tries to subscribe to a channel with a disabled plugin wrong_channels = [(channel, subscribe) for channel, subscribe in changes if wrong_channel(channel, subscribe, u)] if wrong_channels: channel, subscribe = wrong_channels[0] if channel.plugin.activated != "yes": logger.warning('user %s tried to %s screen %d to channel %d with disabled plugin', u.log_name, 'subscribe' if subscribe else "unsubscribe", screen.id, channel.id) raise ImmediateFeedback("subscription", "disabled_plugin") else: logger.warning('user %s tried to subscribe screen %d to channel %d without having the right to do this', u.log_name, screen.id, channel.id) resp.forbidden() for channel, subscribe in changes: if subscribe: screen.subscribe_to(u, channel) subscribed.append(str(channel.id)) else: screen.unsubscribe_from(u, channel) unsubscribed.append(str(channel.id)) if subscribed and unsubscribed: message = "user %s has subscribed screen %d to channel(s) %s and unsubscribed from channel(s) %s" % \ (u.log_name, screen.id, ', '.join(subscribed), ', '.join(unsubscribed)) else: message = "user %s has %s screen %d to channel(s) %s" % \ (u.log_name, "subscribed" if subscribed else "unsubscribed", screen.id, ', '.join(subscribed if subscribed else unsubscribed)) logger.info(message) add_feedback("subscription", 'ok') except SQLObjectNotFound: resp.notfound() except ImmediateFeedback: pass store_form(form) resp.seeother("/screens/%s/subscriptions" % screen.id)
def get(self): # TODO: Redirect if not using local authentication user = User.get(self.session['user']['id']) user.reset_secret = utils.generate_secret() logger.info('User %s requested a new password reset link', user.log_name) resp.seeother(flask.url_for("ResetPage", user.reset_secret))
def get(self, channel_id, channel): self.plugin_manager.invalidate_cache(channel.plugin.name, channel.id) resp.seeother('/channel/%d' % channel.id)
def post(self, channel_id): form = self.form u = User.get(self.session['user']['id']) subscribed = [] unsubscribed = [] if form.diff == 'diff': raise ImmediateFeedback(form.action, 'nothing_changed') try: diff = json.loads(form.diff) except (json.JSONDecodeError, ValueError): raise ImmediateFeedback(form.action, 'inconsistent_diff') try: channelid = int(channel_id) except ValueError: raise ImmediateFeedback(form.action, 'invalid_channel/screen_id') for k, v in diff.items(): try: sub = bool(v) except ValueError: raise ImmediateFeedback(form.action, 'invalid_channel/screen_id') try: screenid = int(k) except ValueError: raise ImmediateFeedback(form.action, 'invalid_channel/screen_id') try: channel = Channel.get(channelid) if not channel.can_subscribe(u): raise self.forbidden(message="You're not allow to do that") screen = Screen.get(screenid) if not u in screen.owners: raise self.forbidden(message="You're not allow to do that") #sub true -> New subscription #sub false -> Remove subscription if sub: screen.subscribe_to(u, channel) subscribed.append(str(channel.id)) else: screen.unsubscribe_from(u, channel) unsubscribed.append(str(channel.id)) if subscribed and unsubscribed: message = "user %s has subscribed screen %d to channel(s) %s and unsubscribed from channel(s) %s" % \ (u.log_name, screen.id, ', '.join(subscribed), ', '.join(unsubscribed)) else: message = "user %s has %s screen %d to channel(s) %s" % \ (u.log_name, "subscribed" if subscribed else "unsubscribed", screen.id, ', '.join(subscribed if subscribed else unsubscribed)) logger.info(message) add_feedback("subscription", 'ok') except SQLObjectNotFound: raise ImmediateFeedback(form.action, 'invalid_channel/screen_id') except DuplicateEntryError: # if the user has checked + unchecked the same checkbox, it will appear on the diff, # we just need to do nothing. pass except SQLObjectIntegrityError: # when there id more than one subscription matching the pair channel/screen pass resp.seeother("/channels/config/%s/subscriptions" % channel_id)
def post(self, bundle_id): def wrong_channel(channel, bundle, add): """ returns True if the channel to add is the bundle itself or if the channel is a PluginChannel with disabled plugin """ return bundle.id == channel.id or add and type(channel) is PluginChannel and channel.plugin.activated != "yes" form = self.form try: bundle = ChannelBundle.get(bundle_id) u = User.get(self.session['user']['id']) diff = json.loads(form.diff) if diff == {}: logger.info('user %s submitted empty diff for bundle management %s', u.log_name, bundle.name) raise ImmediateFeedback("manage_channels", 'nothing_changed') # Do the subscription/unsubscription for every channel in the diff contained = [] not_contained = [] try: changes = [(Channel.get(channel_id), add) for channel_id, add in diff.items()] except SQLObjectNotFound: logger.warning('user %s tried to add a channel which does not exist to bundle %d', u.log_name, bundle.id) resp.forbidden() # if somebody tries to add a channel with a disabled plugin or to add a bundle to itself wrong_channels = [(channel, add) for channel, add in changes if wrong_channel(channel, bundle, add)] if wrong_channels: channel, add = wrong_channels[0] if channel.id == bundle.id: logger.warning('user %s tried to %s bundle %d to itself', u.log_name, 'add' if add else "remove", bundle.id) raise ImmediateFeedback("manage_channels", "added_to_itself") else: logger.warning('user %s tried to %s channel %d with disabled plugin to bundle %d', u.log_name, 'add' if add else "remove", channel.id, bundle.id) raise ImmediateFeedback("manage_channels", "disabled_plugin") for channel, add in changes: if add: try: bundle.add_channel(channel) except ValueError: logger.warning("user %s has made changes in channels management of bundle %d that created a " "cycle of bundles by adding channel %d (%s)", u.log_name, bundle.id, channel.id, channel.name) form.channel_name = channel.name raise ImmediateFeedback("manage_channels", "bundle_cycle") contained.append(str(channel.id)) else: bundle.remove_channel(channel) not_contained.append(str(channel.id)) if contained and not_contained: message = "user %s has added to channel(s) %s and removed channel(s) %s to bundle %d" % \ (u.log_name, ', '.join(contained), ', '.join(not_contained), bundle.id) else: message = "user %s has %s channel(s) %s to bundle %d" % \ (u.log_name, "added" if contained else "removed", ', '.join(contained if contained else not_contained), bundle.id) logger.info(message) add_feedback("manage_channels", 'ok') except SQLObjectNotFound: resp.notfound() except ImmediateFeedback: pass store_form(form) resp.seeother("/channels/config/%s/manage_bundle" % bundle.id)
def saml_processor(handler): if 'user' not in app.session: flask.abort(resp.seeother('/shibboleth?sso')) handler()