def create(grant_admin): """Creates a new user""" user_type = 'user' if not grant_admin else 'admin' while True: email = prompt_email() if email is None: return email = email.lower() if not User.query.filter(User.all_emails == email, ~User.is_deleted, ~User.is_pending).has_rows(): break print(cformat('%{red}Email already exists')) first_name = click.prompt("First name").strip() last_name = click.prompt("Last name").strip() affiliation = click.prompt("Affiliation", '').strip() print() while True: username = click.prompt("Enter username").lower().strip() if not Identity.find(provider='indico', identifier=username).count(): break print(cformat('%{red}Username already exists')) password = prompt_pass() if password is None: return identity = Identity(provider='indico', identifier=username, password=password) user = create_user(email, {'first_name': to_unicode(first_name), 'last_name': to_unicode(last_name), 'affiliation': to_unicode(affiliation)}, identity) user.is_admin = grant_admin _print_user_info(user) if click.confirm(cformat("%{yellow}Create the new {}?").format(user_type), default=True): db.session.add(user) db.session.commit() print(cformat("%{green}New {} created successfully with ID: %{green!}{}").format(user_type, user.id))
def create(grant_admin): """Create a new user.""" user_type = 'user' if not grant_admin else 'admin' while True: email = prompt_email() if email is None: return email = email.lower() if not User.query.filter(User.all_emails == email, ~User.is_deleted, ~User.is_pending).has_rows(): break click.secho('Email already exists', fg='red') first_name = click.prompt('First name').strip() last_name = click.prompt('Last name').strip() affiliation = click.prompt('Affiliation', '').strip() print() while True: username = click.prompt('Enter username').lower().strip() if not Identity.query.filter_by(provider='indico', identifier=username).has_rows(): break click.secho('Username already exists', fg='red') password = prompt_pass() if password is None: return identity = Identity(provider='indico', identifier=username, password=password) user = create_user(email, {'first_name': first_name, 'last_name': last_name, 'affiliation': affiliation}, identity) user.is_admin = grant_admin _print_user_info(user) if click.confirm(click.style(f'Create the new {user_type}?', fg='yellow'), default=True): db.session.add(user) db.session.commit() print(cformat('%{green}New {} created successfully with ID: %{green!}{}').format(user_type, user.id))
def user_create(grant_admin): """Creates new user""" update_session_options(db) user_type = 'user' if not grant_admin else 'admin' while True: email = prompt_email() if email is None: return email = email.lower() if not User.find(User.all_emails.contains(email), ~User.is_deleted, ~User.is_pending).count(): break error('Email already exists') first_name = prompt("First name") last_name = prompt("Last name") affiliation = prompt("Affiliation", '') print() while True: username = prompt("Enter username").lower() if not Identity.find(provider='indico', identifier=username).count(): break error('Username already exists') password = prompt_pass() if password is None: return identity = Identity(provider='indico', identifier=username, password=password) user = create_user(email, {'first_name': to_unicode(first_name), 'last_name': to_unicode(last_name), 'affiliation': to_unicode(affiliation)}, identity) user.is_admin = grant_admin print_user_info(user) if prompt_bool(cformat("%{yellow}Create the new {}?").format(user_type), default=True): db.session.add(user) db.session.commit() success("New {} created successfully with ID: {}".format(user_type, user.id))
def _process_POST(self): if User.query.has_rows(): return redirect(url_for_index()) setup_form = BootstrapForm(request.form) if not setup_form.validate(): flash(_("Some fields are invalid. Please, correct them and submit the form again."), 'error') return redirect(url_for('bootstrap.index')) # Creating new user user = User() user.first_name = to_unicode(setup_form.first_name.data) user.last_name = to_unicode(setup_form.last_name.data) user.affiliation = to_unicode(setup_form.affiliation.data) user.email = to_unicode(setup_form.email.data) user.is_admin = True identity = Identity(provider='indico', identifier=setup_form.username.data, password=setup_form.password.data) user.identities.add(identity) db.session.add(user) db.session.flush() user.settings.set('timezone', Config.getInstance().getDefaultTimezone()) user.settings.set('lang', session.lang or Config.getInstance().getDefaultLocale()) login_user(user, identity) full_name = user.full_name # needed after the session closes transaction.commit() # Configuring server's settings minfo = HelperMaKaCInfo.getMaKaCInfoInstance() minfo.setOrganisation(setup_form.affiliation.data) message = get_template_module('bootstrap/flash_messages.html').bootstrap_success(name=full_name) flash(Markup(message), 'success') # Activate instance tracking if setup_form.enable_tracking.data: contact_name = setup_form.contact_name.data contact_email = setup_form.contact_email.data try: register_instance(contact_name, contact_email) except (HTTPError, ValueError) as err: message = get_template_module('bootstrap/flash_messages.html').community_error(err=err) category = 'error' except Timeout: message = get_template_module('bootstrap/flash_messages.html').community_timeout() category = 'error' except RequestException as exc: message = get_template_module('bootstrap/flash_messages.html').community_exception(exc=exc) category = 'error' else: message = get_template_module('bootstrap/flash_messages.html').community_success() category = 'success' flash(Markup(message), category) return redirect(url_for_index())
def _handle_submit(self, setup_form): # Creating new user user = User() user.first_name = setup_form.first_name.data user.last_name = setup_form.last_name.data user.affiliation = setup_form.affiliation.data user.email = setup_form.email.data user.is_admin = True identity = Identity(provider='indico', identifier=setup_form.username.data, password=setup_form.password.data) user.identities.add(identity) db.session.add(user) db.session.flush() user.settings.set('timezone', config.DEFAULT_TIMEZONE) user.settings.set('lang', session.lang or config.DEFAULT_LOCALE) login_user(user, identity) full_name = user.full_name # needed after the session closes db.session.commit() # Configuring server's settings core_settings.set('site_organization', setup_form.affiliation.data) message = get_template_module( 'bootstrap/flash_messages.html').bootstrap_success(name=full_name) flash(Markup(message), 'success') # Activate instance tracking if setup_form.enable_tracking.data: contact_name = setup_form.contact_name.data contact_email = setup_form.contact_email.data try: register_instance(contact_name, contact_email) except (HTTPError, ValueError) as err: message = get_template_module('bootstrap/flash_messages.html' ).community_error(err=str(err)) category = 'error' except Timeout: message = get_template_module( 'bootstrap/flash_messages.html').community_timeout() category = 'error' except RequestException as exc: message = get_template_module( 'bootstrap/flash_messages.html').community_exception( err=str(exc)) category = 'error' else: message = get_template_module( 'bootstrap/flash_messages.html').community_success() category = 'success' flash(Markup(message), category) return redirect(url_for_index())
def _handle_add_local_account(self, form): identity = Identity(provider='indico', identifier=form.data['username'], password=form.data['password']) self.user.identities.add(identity) logger.info('User %s added a local account (%s)', self.user, identity.identifier) flash(_('Local account added successfully'), 'success')
def _create_identity(self): identity = Identity(user=self.user, provider=self.identity_info['provider'], identifier=self.identity_info['identifier'], data=self.identity_info['data'], multipass_data=self.identity_info['multipass_data']) logger.info('Created new identity for %s: %s', self.user, identity) del session['login_identity_info'] db.session.flush() login_user(self.user, identity) return multipass.redirect_success()
def register_user(email, extra_emails, user_data, identity_data, settings, from_moderation=False): """ Create a user based on the registration data provided during te user registration process (via `RHRegister` and `RegistrationHandler`). This method is not meant to be used for generic user creation, the only reason why this is here is that approving a registration request is handled by the `users` module. """ identity = Identity(**identity_data) user = create_user(email, user_data, identity=identity, settings=settings, other_emails=extra_emails, from_moderation=from_moderation) return user, identity
def _process(self): form = AdminAccountRegistrationForm() if form.validate_on_submit(): data = form.data identity = Identity(provider='indico', identifier=data.pop('username'), password=data.pop('password')) user = create_user(data.pop('email'), data, identity, from_moderation=True) msg = Markup('{} <a href="{}">{}</a>').format( escape(_('The account has been created.')), url_for('users.user_profile', user), escape(_('Show details')) ) flash(msg, 'success') return jsonify_data() return jsonify_template('users/users_admin_create.html', form=form)
def migrate_users(self): print cformat('%{white!}migrating users') seen_identities = set() for avatar in committing_iterator(self._iter_avatars(), 5000): if getattr(avatar, '_mergeTo', None): print cformat('%{red!}!!!%{reset} ' '%{yellow!}Skipping {} - merged into {}').format( avatar.id, avatar._mergeTo.id) continue elif avatar.status == 'Not confirmed': print cformat('%{yellow!}!!!%{reset} ' '%{yellow!}Skipping {} - not activated').format( avatar.id) continue elif not avatar.name.strip() and not avatar.surName.strip(): links = {(obj, role): list(objs) for obj, x in avatar.linkedTo.iteritems() for role, objs in x.iteritems() if objs} if not avatar.identities and not links: print cformat( '%{yellow!}!!!%{reset} ' '%{yellow!}Skipping {} - no names and no identities/links' ).format(avatar.id) continue user = self._user_from_avatar(avatar) self._fix_collisions(user, avatar) db.session.add(user) settings = self._settings_from_avatar(avatar) user_settings.set_multi(user, settings) # favorite users cannot be migrated here since the target user might not have been migrated yet # XXX: adapt to new categories for 2.0 user.favorite_categories = set( filter(None, avatar.linkedTo['category']['favorite'])) db.session.flush() print cformat( '%{green}+++%{reset} ' '%{white!}{:6d}%{reset} %{cyan}{}%{reset} [%{blue!}{}%{reset}] ' '{{%{cyan!}{}%{reset}}}').format( user.id, user.full_name, user.email, ', '.join(user.secondary_emails)) # migrate API keys self._migrate_api_keys(avatar, user) # migrate identities of non-deleted avatars if not user.is_deleted: for old_identity in avatar.identities: identity = None username = convert_to_unicode( old_identity.login).strip().lower() if not username: print cformat( "%{red!}!!!%{reset} " "%{yellow!}Empty username: {}. Skipping identity." ).format(old_identity) continue provider = { 'LocalIdentity': 'indico', 'LDAPIdentity': self.ldap_provider_name }.get(old_identity.__class__.__name__) if provider is None: print cformat( "%{red!}!!!%{reset} " "%{yellow!}Unsupported provider: {}. Skipping identity." ).format(old_identity.__class__.__name__) continue if (provider, username) in seen_identities: print cformat( "%{red!}!!!%{reset} " "%{yellow!}Duplicate identity: {}, {}. Skipping." ).format(provider, username) continue if provider == 'indico' and not self.ignore_local_accounts: identity = Identity(provider=provider, identifier=username) if not hasattr(old_identity, 'algorithm'): # plaintext password if not old_identity.password: # password is empty, skip identity print cformat( "%{red!}!!!%{reset} " "%{yellow!}Identity '{}' has empty password. Skipping identity." ).format(old_identity.login) continue identity.password = old_identity.password else: assert old_identity.algorithm == 'bcrypt' identity.password_hash = old_identity.password elif provider == self.ldap_provider_name: identity = Identity(provider=provider, identifier=username) if identity: print cformat( '%{blue!}<->%{reset} %{yellow}{}%{reset}').format( identity) user.identities.add(identity) seen_identities.add((provider, username)) for merged_avatar in getattr(avatar, '_mergeFrom', ()): if merged_avatar.id == avatar.id: continue merged = self._user_from_avatar(merged_avatar, is_deleted=True, merged_into_id=user.id) print cformat( '%{blue!}***%{reset} ' '%{white!}{:6d}%{reset} %{cyan}{}%{reset} [%{blue!}{}%{reset}] ' '{{%{cyan!}{}%{reset}}}').format( merged.id, merged.full_name, merged.email, ', '.join(merged.secondary_emails)) self._fix_collisions(merged, merged_avatar) db.session.add(merged) db.session.flush()
def _handle_add_local_account(self, form): identity = Identity(provider='indico', identifier=form.data['username'], password=form.data['password']) self.user.identities.add(identity) flash(_("Local account added successfully"), 'success')
def create_identity(self, data): del session['register_verified_email'] return Identity(provider='indico', identifier=data['username'], password=data['password'])
def create_identity(self, data): del session['login_identity_info'] return Identity(provider=self.identity_info['provider'], identifier=self.identity_info['identifier'], data=self.identity_info['data'], multipass_data=self.identity_info['multipass_data'])
def migrate_users(self): seen_identities = set() for avatar in committing_iterator(self._iter_avatars(), 5000): if getattr(avatar, '_mergeTo', None): self.print_warning('Skipping {} - merged into {}'.format(avatar.id, avatar._mergeTo.id)) merged_user = self.global_ns.avatar_merged_user.get(avatar._mergeTo.id) if merged_user: self.global_ns.avatar_merged_user[avatar.id] = merged_user else: # if the merge target hasn't yet been migrated, keep track of it self.unresolved_merge_targets[avatar._mergeTo.id].add(avatar.id) continue elif avatar.status == 'Not confirmed': self.print_warning('Skipping {} - not activated'.format(avatar.id)) continue elif not avatar.name.strip() and not avatar.surName.strip(): links = {(obj, role): list(objs) for obj, x in avatar.linkedTo.iteritems() for role, objs in x.iteritems() if objs} if not avatar.identities and not links: self.print_warning('Skipping {} - no names and no identities/links'.format(avatar.id)) continue user = self._user_from_avatar(avatar) self._fix_collisions(user, avatar) db.session.add(user) settings = self._settings_from_avatar(avatar) user_settings.set_multi(user, settings) # favorite users cannot be migrated here since the target user might not have been migrated yet for old_categ in avatar.linkedTo['category']['favorite']: if old_categ: self.global_ns.user_favorite_categories[old_categ.id].add(user) db.session.flush() self.print_success('%[white!]{:6d}%[reset] %[cyan]{}%[reset] [%[blue!]{}%[reset]] ' '{{%[cyan!]{}%[reset]}}'.format(user.id, user.full_name, user.email, ', '.join(user.secondary_emails))) # migrate API keys self._migrate_api_keys(avatar, user) # migrate identities of avatars for old_identity in avatar.identities: identity = None username = convert_to_unicode(old_identity.login).strip().lower() if not username: self.print_warning("Empty username: {}. Skipping identity.".format(old_identity)) continue provider = { 'LocalIdentity': 'indico', 'LDAPIdentity': self.ldap_provider_name }.get(old_identity.__class__.__name__) if provider is None: self.print_error("Unsupported provider: {}. Skipping identity.".format( old_identity.__class__.__name__)) continue if (provider, username) in seen_identities: self.print_error("Duplicate identity: {}, {}. Skipping.".format(provider, username)) continue if provider == 'indico' and not self.ignore_local_accounts: identity = Identity(provider=provider, identifier=username) if not hasattr(old_identity, 'algorithm'): # plaintext password if not old_identity.password: # password is empty, skip identity self.print_error("Identity '{}' has empty password. Skipping identity.".format( old_identity.login)) continue identity.password = old_identity.password else: assert old_identity.algorithm == 'bcrypt' identity.password_hash = old_identity.password elif provider == self.ldap_provider_name: identity = Identity(provider=provider, identifier=username) if identity: self.print_info('%[blue!]<->%[reset] %[yellow]{}%[reset]'.format(identity)) user.identities.add(identity) seen_identities.add((provider, username)) if hasattr(avatar, 'personalInfo') and avatar.personalInfo._basket._users: self.favorite_avatars[user.id] = avatar.personalInfo._basket._users # Map old merged identities (no longer in AvatarHolder) # to newly created user for merged_avatar in getattr(avatar, '_mergeFrom', ()): if merged_avatar.id != avatar.id: self.global_ns.avatar_merged_user[merged_avatar.id] = user self.global_ns.avatar_merged_user[avatar.id] = user if avatar.id in self.unresolved_merge_targets: del self.unresolved_merge_targets[avatar.id] self._resolve_merge_targets(avatar.id, user) db.session.flush()