class RegistrationConfirmController(controller.Controller): """ Create the CWUser when user confirm the account creation by clicking the link of the confirmation mail. """ __regid__ = "registration_confirm" def publish(self, rset=None): req = self._cw try: data = crypto.decrypt(req.form["key"], self._cw.vreg.config._secret) login = data["login"] password = data.pop("upassword") except: msg = req._( u"Invalid registration data. Please try registering again.") raise Redirect(req.build_url("register", _message=msg)) if self._cw.user.login == login: # already logged in (e.g. regstration link replayed twice in the browser) raise Redirect(self.success_redirect_url(self._cw.user.name())) # Check the user has not been created yet with self.appli.repo.internal_cnx() as cnx: msg = req._(u"Account already validated. Please try to login.") rset = cnx.execute( "Any U Where U is CWUser, U login '{0}'".format(login)) if rset.rowcount != 0: raise Redirect(req.build_url("register", _message=msg)) req.form = data # hijack for proper validation error handling err_raised = False try: with self.appli.repo.internal_cnx() as cnx: cnx.call_service("register_user", login=unicode(login), password=password, email=unicode(data.get("mail")), firstname=unicode(data.get("firstname")), surname=unicode(data.get("surname"))) cnx.commit() except ValidationError, err: err_raised = True # XXX TEMPORARY HACK to allow registration links to work more than # once. This is required because some email clients (e.g. kmail) # start by downloading the url to find the mimetype of the resource # and then execute the appropriate action (e.g. open the url in the # default browser) based on the mimetype. if err.errors.keys() != ["login"]: raise # Try to connect using the provided credentials try: from cubicweb import repoapi cnx = repoapi.connect(self.appli.repo, login, password=password) with cnx: name = cnx.user.name() raise Redirect(self.success_redirect_url(name)) except: if err_raised: # Both registration and login failed, re-raise the previous # ValidationError raise err raise
def test_connect(self): """check that repoapi.connect works and returns a usable connection""" cnx = connect(self.repo, login='******', password='******') self.assertEqual('admin', cnx.user.login) with cnx: rset = cnx.execute('Any X WHERE X is CWUser') self.assertTrue(rset)
def get_cnx(self): """return Connection object on the current repository""" from cubicweb.repoapi import connect repo = self.get_repo() sources = self.config.read_sources_file() login = sources['admin']['login'] password = sources['admin']['password'] or 'xxx' cnx = connect(repo, login, password=password) return cnx
def admincnx(appid): from cubicweb import repoapi from cubicweb.cwconfig import CubicWebConfiguration from cubicweb.server.repository import Repository config = CubicWebConfiguration.config_for(appid) login = config.default_admin_config['login'] password = config.default_admin_config['password'] repo = Repository(config) repo.bootstrap() return repoapi.connect(repo, login, password=password)
def repo_cnx(config): """return a in-memory repository and a repoapi connection to it""" from cubicweb import repoapi from cubicweb.server.utils import manager_userpasswd try: login = config.default_admin_config['login'] pwd = config.default_admin_config['password'] except KeyError: login, pwd = manager_userpasswd() while True: try: repo = repoapi.get_repository(config=config) cnx = repoapi.connect(repo, login, password=pwd) return repo, cnx except AuthenticationError: print('-> Error: wrong user/password.') # reset cubes else we'll have an assertion error on next retry config._cubes = None login, pwd = manager_userpasswd()
def run(args): """run the command line tool""" try: opts, args = getopt.getopt(args, 'hn:t:u:p:P:o:', [ 'help', 'user='******'password='******'nb-times=', 'nb-threads=', 'profile', 'report-output=', ]) except Exception as ex: print(ex) usage(1) repeat = 100 threads = 1 user = os.environ.get('USER', os.environ.get('LOGNAME')) password = None report_output = sys.stdout prof_file = None for opt, val in opts: if opt in ('-h', '--help'): usage() if opt in ('-u', '--user'): user = val elif opt in ('-p', '--password'): password = val elif opt in ('-n', '--nb-times'): repeat = int(val) elif opt in ('-t', '--nb-threads'): threads = int(val) elif opt in ('-P', '--profile'): prof_file = val elif opt in ('-o', '--report-output'): report_output = open(val, 'w') if len(args) != 2: usage(1) queries = [query for query in lines(args[1]) if not query.startswith('#')] if user is None: user = raw_input('login: '******'password: '******'times' else: QueryExecutor(cnx, repeat, queries, reporter=reporter).run() reporter.dump_report(report_output)
def init_repository(config, interactive=True, drop=False, vreg=None, init_config=None): """Initialise a repository database by creating tables and filling them with the minimal set of entities (ie at least the schema, base groups and a initial user) """ from cubicweb.repoapi import get_repository, connect from cubicweb.server.repository import Repository from cubicweb.server.utils import manager_userpasswd from cubicweb.server.sqlutils import sqlexec, sqlschema, sql_drop_all_user_tables from cubicweb.server.sqlutils import _SQL_DROP_ALL_USER_TABLES_FILTER_FUNCTION as drop_filter # configuration to avoid db schema loading and user'state checking # on connection config.creating = True config.consider_user_state = False config.cubicweb_appobject_path = set(('hooks', 'entities')) config.cube_appobject_path = set(('hooks', 'entities')) # only enable the system source at initialization time repo = Repository(config, vreg=vreg) repo.bootstrap() if init_config is not None: # further config initialization once it has been bootstrapped init_config(config) schema = repo.schema sourcescfg = config.read_sources_file() source = sourcescfg['system'] driver = source['db-driver'] with repo.internal_cnx() as cnx: sqlcnx = cnx.cnxset.cnx sqlcursor = cnx.cnxset.cu execute = sqlcursor.execute if drop: helper = database.get_db_helper(driver) dropsql = sql_drop_all_user_tables(helper, sqlcursor) # We may fail dropping some tables because of table dependencies, in a first pass. # So, we try a second drop sequence to drop remaining tables if needed. # Note that 2 passes is an arbitrary choice as it seems enough for our usecases # (looping may induce infinite recursion when user have no rights for example). # Here we try to keep code simple and backend independent. That's why we don't try to # distinguish remaining tables (missing privileges, dependencies, ...). failed = sqlexec(dropsql, execute, cnx=sqlcnx, pbtitle='-> dropping tables (first pass)') if failed: failed = sqlexec(failed, execute, cnx=sqlcnx, pbtitle='-> dropping tables (second pass)') remainings = list( filter(drop_filter, helper.list_tables(sqlcursor))) assert not remainings, 'Remaining tables: %s' % ', '.join( remainings) handler = config.migration_handler(schema, interactive=False, repo=repo, cnx=cnx) # install additional driver specific sql files handler.cmd_install_custom_sql_scripts() for cube in reversed(config.cubes()): handler.cmd_install_custom_sql_scripts(cube) _title = '-> creating tables ' print(_title, end=' ') # schema entities and relations tables # can't skip entities table even if system source doesn't support them, # they are used sometimes by generated sql. Keeping them empty is much # simpler than fixing this... schemasql = sqlschema(schema, driver) failed = sqlexec(schemasql, execute, pbtitle=_title) if failed: print( 'The following SQL statements failed. You should check your schema.' ) print(failed) raise Exception( 'execution of the sql schema failed, you should check your schema' ) sqlcursor.close() sqlcnx.commit() with repo.internal_cnx() as cnx: # insert entity representing the system source ssource = cnx.create_entity('CWSource', type=u'native', name=u'system') repo.system_source.eid = ssource.eid cnx.execute('SET X cw_source X WHERE X eid %(x)s', {'x': ssource.eid}) # insert base groups and default admin print('-> inserting default user and default groups.') try: login = sourcescfg['admin']['login'] pwd = sourcescfg['admin']['password'] except KeyError: if interactive: msg = 'enter login and password of the initial manager account' login, pwd = manager_userpasswd(msg=msg, confirm=True) else: login, pwd = source['db-user'], source['db-password'] # sort for eid predicatability as expected in some server tests for group in sorted(BASE_GROUPS): cnx.create_entity('CWGroup', name=group) admin = create_user(cnx, login, pwd, u'managers') cnx.execute( 'SET X owned_by U WHERE X is IN (CWGroup,CWSource), U eid %(u)s', {'u': admin.eid}) cnx.commit() repo.shutdown() # re-login using the admin user config._cubes = None # avoid assertion error repo = get_repository(config=config) # replace previous schema by the new repo's one. This is necessary so that we give the proper # schema to `initialize_schema` above since it will initialize .eid attribute of schema elements schema = repo.schema with connect(repo, login, password=pwd) as cnx: with cnx.security_enabled(False, False): repo.system_source.eid = ssource.eid # redo this manually handler = config.migration_handler(schema, interactive=False, cnx=cnx, repo=repo) # serialize the schema initialize_schema(config, schema, handler) # yoo ! cnx.commit() repo.system_source.init_creating() cnx.commit() repo.shutdown() # restore initial configuration config.creating = False config.consider_user_state = True # (drop instance attribute to get back to class attribute) del config.cubicweb_appobject_path del config.cube_appobject_path print('-> database for instance %s initialized.' % config.appid)