def logout(): if not get_current_user_data(): return redirect_url('login') UserController.logout() return redirect('/', 302)
def logout(): if not get_current_user_data(): return redirect_url(url_for('login')) UserController.logout() return redirect(url_for('root'), 302)
def api_user_locale_set(lang): """ Sets the web interface locale. :param lang: The language as "en" or "nl", etc. :return: """ current_user = get_current_user_data() if get_current_user_data(): UserController.locale_set(locale=lang, user_id=current_user["id"]) return "locale set to %s" % lang UserController.locale_set(locale=lang) return "local set to %s" % lang
def api_browse_servers(): if UserController.is_admin(): resources = [resource.make_dict() for resource in Findex().get_resources()] return flask.jsonify(**{"status": True, "data": resources}) else: # do something with roles here return flask.jsonify(**{"a": 1})
def render(self, template_path, theme=None, status_code=200, **kwargs): if not theme: theme = self.get_active() # @TO-DO: use a context processor kwargs["env"] = {z: app.config[z] for z in app.config if z.islower()} kwargs["env"]["application_root"] = app.config["APPLICATION_ROOT"] user = UserController.get_current_user() user_context = get_current_user_data() if user_context: if not session.get("locale"): session["locale"] = user.locale elif session["locale"] != user.locale: session["locale"] = user.locale kwargs["user"] = user try: return render_template("%s/templates/%s.html" % (theme, template_path), url_for=url_for, **kwargs), status_code except TemplateNotFound as e: return "Template \"%s\" not found" % str(e) except Exception as ex: print(ex) if config("findex:findex:debug"): return "Jinja2 error!\n\n%s" % str(ex) return "Jinja2 error!"
def user_cp(): form = LocalizationForm(request.form) form.language.choices = locales.items() form.language.data = UserController.locale_get() return themes.render('main/user_cp', form=form)
def api_user_delete(username): """ Deletes an user. :param username: the username in question :return: """ user = UserController.user_delete(username=username) return "user '%s' deleted" % username
def add(content: str, title: str, current_user: User = None): if not isinstance(current_user, User): current_user = UserController.get_current_user() post = Post(content=content, title=title, created_by=current_user) db.session.add(post) db.session.commit() return post
def api_user_register(username, password): """ Register a new user :param username: the username in question :param password: super secure password :return: """ user = UserController.user_add(username=username, password=password) return "user '%s' registered" % username
def post(self): args = self.reqparse.parse_args() args = {k: v for k, v in args.items() if v is not None} user = UserController.user_delete(username=args['username']) if isinstance(user, Exception): return abort(404, message=str(user)) else: return flask.jsonify(**args)
def decorator(*args, **kwargs): data = get_current_user_data() if data is None: if request.authorization: if UserController.authenticate_basic(inject=True): return f(*args, **kwargs) return not_logged_in(_not_logged_in, *args, **kwargs) return f(*args, **kwargs)
def api_user_locale_set(): if 'lang' not in request.form: return flask.jsonify(**{'fail': 'parameter \'lang\' not given'}), 400 try: if request.authorization or get_current_user_data(): if request.authorization: user = UserController.authenticate_basic() else: user = User.query.filter( User.id == get_current_user_data()['id']).one() if user: UserController.locale_set( locale=request.form['lang'], user=user) return flask.jsonify(**{'success': True}), 201 UserController.locale_set(locale=request.form['lang']) return flask.jsonify(**{'success': True}), 201 except Exception as ex: return flask.jsonify(**{'fail': str(ex)}), 400
def login(): if get_current_user_data(): return redirect('/', 302) error = None if request.method == 'POST': username = request.form['username'] password = request.form['password'] if UserController.authenticate_and_session(username, password): flash(gettext('You were successfully logged in')) if request.referrer.endswith('/login'): return redirect(url_for('root')) return redirect(redirect_url()) else: error = gettext('Invalid credentials') return themes.render('main/login', error=error)
def remove_resource(resource_id, auto_remove_server=True, **kwargs): """ Removes a resource from the database. :param resource_id: The resource ID :param auto_remove_server: removes the server this resource has a relationship with, but only when that server does not have any other existing resource members/childs :param kwargs: :return: """ user = UserController.get_current_user() if not user.admin: resources = ResourceController.get_resources(by_owner=user.id) resource = [r for r in resources if r.id == resource_id] if not resource or isinstance(resource, Exception): raise FindexException("Could not fetch resource id \"%d\"" % resource_id) else: resource = resource[0] else: resource = db.session.query(Resource).filter( Resource.id == resource_id).first() if not resource: raise FindexException("Could not fetch resource id \"%d\"" % resource_id) if auto_remove_server: # check for other server resource members before trying to delete server = resource.server if [z for z in server.resources if z.id != resource_id]: # cant remove server, it still has one or more member(s) db.session.delete(resource) else: db.session.delete(resource) db.session.delete(server) else: db.session.delete(resource) db.session.commit() db.session.flush()
def check_role(requirements, **kwargs): """Raises exception on bad role""" from findex_gui.controllers.user.user import UserController if "skip_authorization" in kwargs: return def check_requirements(_user): for requirement in requirements: roles = [r.name for r in _user.roles] if requirement not in roles: raise RoleException("current user does not have the " "required role \"%s\"" % requirement) return _user try: user = UserController.get_current_user(apply_timeout=False) except RuntimeError: return if user: if user.admin: return user return check_requirements(user)
def add_resource(resource_port, resource_protocol, server_name=None, server_address=None, server_id=None, description="", display_url="/", basepath="/", recursive_sizes=True, auth_user=None, auth_pass=None, auth_type=None, user_agent=static_variables.user_agent, throttle_connections=-1, current_user=None, group="Default"): """ Adds a local or remote file resource :param server_name: Server name :param server_address: ipv4 'str' - clean hostname or IP :param server_id: server DB id :param resource_port: valid port number :param resource_protocol: valid protocol number 'int' - see `findex_common.static_variables.FileProtocols` :param description: resource description 'str' :param display_url: url prefix as it will be shown on the front-end 'str' :param basepath: the absolute crawl root path 'str' :param recursive_sizes: recursively calculate directory sizes (performance impact during crawl) :param auth_user: resource user authentication 'str' :param auth_pass: resource pass authentication 'str' :param auth_type: resource type authentication 'str' :param user_agent: The string to identify ourselves with against the service 'str' :param throttle_connections: Wait X millisecond(s) between each request/connection 'int' :return: resource """ if server_id: _server = db.session.query(Server).filter( Server.id == server_id).first() elif server_address: _server = db.session.query(Server).filter( Server.address == server_address).first() else: raise FindexException( "Either use server_id to refer to an existing Server " "object or supply a valid `server_name`, `server_port` " "and/or `server_address` parameters.") if not _server: if not isinstance(server_address, str) or not \ isinstance(resource_port, int) or not isinstance(resource_protocol, int): raise FindexException( "Could not auto-add server for resource - requires " "`resource_port`, `resource_protocol` and `server_address`" ) if resource_port > 65535 or resource_port < 1: raise FindexException("invalid port") _server = ResourceController.add_server(name=server_name, hostname=server_address) if not basepath: basepath = "/" elif not basepath.startswith("/") and len(basepath) > 1: basepath = "/%s" % basepath if _server.resources: for parent in _server.resources: if parent.port == resource_port and parent.protocol == resource_protocol \ and parent.basepath == basepath: raise FindexException( "Duplicate resource previously defined with resource id \"%d\"" % parent.id) resource = Resource(server=_server, protocol=resource_protocol, port=resource_port, display_url=display_url, basepath=basepath) resource.description = description resource.date_crawl_next = datetime.now() rm = ResourceMeta() if auth_user and auth_pass: rm.set_auth(auth_user, auth_pass, auth_type) rm.recursive_sizes = recursive_sizes rm.web_user_agent = user_agent rm.throttle_connections = throttle_connections resource.meta = rm if isinstance(current_user, int): current_user = db.session.query(User).filter( User.admin == True).first() elif current_user is None: current_user = UserController.get_current_user(apply_timeout=False) elif isinstance(current_user, User): pass else: raise Exception("bad type for parameter current_user") if not current_user: raise FindexException("Could not fetch the current user") resource.created_by = current_user db.session.add(resource) db.session.commit() resource.group = db.session.query(ResourceGroup).filter( ResourceGroup.name == group).first() db.session.commit() db.session.flush() return resource
def bootstrap(self): # check necessary postgres extensions self.create_extension( extension="pg_trgm", msg_on_activate_error="Postgres extension \"pg_trgm\" installed but " "could not be enabled, " "possibly missing administrator rights to enable " "pg_trgm: `CREATE EXTENSION pg_trgm;`") if config("findex:elasticsearch:enabled"): self.create_extension( extension="zombodb", msg_on_activate_error= "Postgres extension \"zombodb\" installed but " "could not be enabled.") # create the tables, types and indexes BASE.metadata.create_all(bind=self.engine) if config("findex:elasticsearch:enabled"): # check required types for es if not self.check_type(type_name="type_files"): raise DatabaseException( "Postgres type `type files` not found. " "Try the following SQL to rebuild the table:\n" "\tDROP TYPE type_files CASCADE;\n" "\tDROP TABLE files;\n") # check if the zombodb index is present if not self.check_index(table_name="files", index="idx_zdb_files"): raise DatabaseException( "Postgres index `idx_zdb_files` not found " "while ElasticSearch was enabled.\n" "Try the following SQL to rebuild the table:\n" "\tDROP TYPE type_files CASCADE;\n" "\tDROP TABLE files;\n") else: if self.check_index(table_name="files", index="idx_zdb_files"): raise DatabaseException( "Please remove the index `idx_zdb_files` before " "using findex without ES enabled:\n" "\tDROP INDEX idx_zdb_files\n" "\tcurl -XDELETE <es_host> db.schema.table.index") from findex_gui.controllers.user.user import UserController from findex_gui.controllers.user.roles import default_anon_roles from findex_gui.controllers.resources.resources import ResourceController # add some default users, groups and tasks to the database if not UserController.user_view(username="******"): UserController.user_add( username="******", password=config("findex:users:default_root_password"), removeable=False, admin=True, skip_authorization=True) if not UserController.user_view(username="******"): UserController.user_add( username="******", password=config("findex:users:default_anon_password"), privileges=default_anon_roles, removeable=False, skip_authorization=True) if not ResourceController.get_resource_group(name="Default"): ResourceController.add_resource_group( name="Default", description="Default group", removable=False, skip_authorization=True, log_error=False, ignore_constraint_conflict=True)
def decorator(*args, **kwargs): if not UserController.is_admin(): return not_logged_in(_not_admin, *args, **kwargs) return f(*args, **kwargs)
def user_cp(): form = LocalizationForm(request.form) form.language.choices = list(locales.items()) form.language.data = UserController.locale_get() return themes.render('main/user_cp/_misc', form=form)