class DatabaseRelation(Object): """Standard database relation class.""" def __init__(self, charm): super().__init__(charm, DB_RELATION_NAME) self.charm = charm self.database = DatabaseProvides(self.charm, relation_name=DB_RELATION_NAME) self.framework.observe(self.database.on.database_requested, self._on_database_requested) self.framework.observe(self.charm.on[DB_RELATION_NAME].relation_broken, self._on_database_broken) def _get_or_set_password(self, relation) -> str: """Retrieve password from cache or generate a new one. Args: relation (str): The relation for each the password is cached. Returns: str: The password. """ if password := relation.data[self.charm.app].get("password"): return password password = generate_random_password(PASSWORD_LENGTH) relation.data[self.charm.app]["password"] = password return password
def activate_user(self, activation_key, site, password=None, send_email=True, message=None, no_profile_delete=False): """activate account with ``activation_key`` and ``password`` Activate account and email notification to the ``User``, returning activated ``User``, ``password`` and ``is_generated``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. An activation email will be generated by ``registration/activation_email.txt`` and ``registration/activation_email_subject.txt``. This method **DOES NOT** works if the account registration has not been accepted. You must accept the account registration before activate the account. Returning will be ``None`` if the account registration has not accepted or activation key has expired. if passed ``password`` is ``None`` then random password will be generated and set to the ``User``. If the password is generated, ``is_generated`` will be ``True`` Use returning value like:: activated = RegistrationProfile.objects.activate_user(activation_key) if activated: # Activation has success user, password, is_generated = activated # user -- a ``User`` instance of account # password -- a raw password of ``User`` # is_generated -- ``True`` if the password is generated When activation has success, the ``RegistrationProfile`` of the ``User`` will be deleted from database because the profile is no longer required. """ try: profile = self.get(_status='accepted', activation_key=activation_key) except self.model.DoesNotExist: return None if not profile.activation_key_expired(): is_generated = password is None password = password or generate_random_password(length=settings.REGISTRATION_DEFAULT_PASSWORD_LENGTH) user = profile.user user.set_password(password) user.is_active = True user.save() if send_email: profile.send_activation_email(site, password, is_generated, message=message) if not no_profile_delete: # the profile is no longer required profile.delete() return user, password, is_generated return None
def get_win_vm_password(self): if self.opts.win_minion_password is None: if self.win_minion_password is None: ssh_public_key = self._get_ssh_public_key( self.opts.ssh_public_key_path) self.win_minion_password = utils.generate_random_password( key=ssh_public_key) else: self.win_minion_password = self.opts.win_minion_password return self.win_minion_password
def generate_password(): password_len = request.args.get('password-len', '10') if not password_len.isdigit(): return "Error, password-len should be integer" password_len = int(password_len) if password_len > 100: return "Password should be less than 100" return generate_random_password(password_len)
def _on_leader_elected(self, _) -> None: """Handle the leader elected event.""" # Set MySQL config values in the peer relation databag peer_data = self._peers.data[self.app] required_passwords = [ "root-password", "server-config-password", "cluster-admin-password" ] for required_password in required_passwords: if not peer_data.get(required_password): password = generate_random_password(PASSWORD_LENGTH) peer_data[required_password] = password
def password_reset(request, pk): account = models.Account.objects.get(pk=pk) password = generate_random_password(length=8) u = User.objects.get(username=account.username) u.set_password(password) u.save() logger.info("Account %s has been reset password %s, done by %s", account.username, password, request.user) if settings.SENT_EMAIL: msg_txt = "Your password is reset to %s, please login and change your password." % password msg = string.join( ("From: %s" % settings.EMAIL_HOST_USER, "To: %s" % account.email, "Subject: Notification", "", msg_txt), "\r\n", ) send_mail("Notification", msg, settings.EMAIL_HOST_USER, [account.email], fail_silently=False) return redirect(reverse("admin-detail", kwargs={"pk": pk}))
def _get_or_set_password_in_peer_databag(self, username: str) -> str: """Get a user's password from the peer databag if it exists, else populate a password. Args: username: The mysql username Returns: a string representing the password for the mysql user """ peer_databag = self.charm._peers.data[self.charm.app] if peer_databag.get(f"{username}_password"): return peer_databag.get(f"{username}_password") password = generate_random_password(PASSWORD_LENGTH) peer_databag[f"{username}_password"] = password return password
def admin_add(request): username = request.POST["username"].strip() email = request.POST["email"].strip() account_type = request.POST["account_type"] try: account = models.Account.objects.get(Q(username__exact=username) | Q(email__exact=email)) if account.status == models.Account.STATUS_DISABLE: account.status = models.Account.STATUS_ENABLE account.save() messages.error( request, "Account %s already exists but is disabled, the status has been changed to enable" % username ) logger.info("Account %s has been activated by %s", username, request.user) else: messages.error(request, "Account %s already exists" % username) except models.Account.DoesNotExist: password = generate_random_password(length=8) models.Account.objects.create(username=username, email=email, password="", salt="", account_type=account_type) u = User.objects.get(username=username) u.set_password(password) u.save() logger.info("Account %s, %s, %s has been created by %s", username, password, account_type, request.user) if settings.SENT_EMAIL: msg_txt = ( "Your email is generated, please use %s as password to login. " "For your safety, please change your password once you login the system" % password ) msg = string.join( ("From: %s" % settings.EMAIL_HOST_USER, "To: %s" % u.email, "Subject: Notification", "", msg_txt), "\r\n", ) send_mail("Notification", msg, settings.EMAIL_HOST_USER, [u.email], fail_silently=False) return redirect("/admin")
class SharedDBRelation(Object): """Legacy `shared-db` relation implementation.""" def __init__(self, charm: CharmBase): super().__init__(charm, "shared-db-handler") self._charm = charm self.framework.observe( self._charm.on[LEGACY_DB_SHARED].relation_changed, self._on_shared_db_relation_changed) self.framework.observe( self._charm.on[LEGACY_DB_SHARED].relation_departed, self._on_shared_db_departed) self.framework.observe(self._charm.on.leader_elected, self._on_leader_elected) @property def _peers(self): return self.model.get_relation(PEER) def _get_or_set_password(self, username: str) -> str: """Retrieve password from cache or generate a new one. Args: username (str): The username. Returns: str: The password. """ if password := self._peers.data[self._charm.app].get( f"{username}_password"): return password password = generate_random_password(PASSWORD_LENGTH) self._peers.data[self._charm.app][f"{username}_password"] = password return password
def on_admin_created(self): self.merchant_code = generate_key(4) self.password = encrypt_password(generate_random_password(16)) self.confirmed_at = datetime.datetime.now() self.active = True
def activate_user(self, activation_key, site, password=None, send_email=True, message=None, no_profile_delete=False): """activate account with ``activation_key`` and ``password`` Activate account and email notification to the ``User``, returning activated ``User``, ``password`` and ``is_generated``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. An activation email will be generated by ``registration/activation_email.txt`` and ``registration/activation_email_subject.txt``. This method **DOES NOT** works if the account registration has not been accepted. You must accept the account registration before activate the account. Returning will be ``None`` if the account registration has not accepted or activation key has expired. if passed ``password`` is ``None`` then random password will be generated and set to the ``User``. If the password is generated, ``is_generated`` will be ``True`` Use returning value like:: activated = RegistrationProfile.objects.activate_user(activation_key) if activated: # Activation has success user, password, is_generated = activated # user -- a ``User`` instance of account # password -- a raw password of ``User`` # is_generated -- ``True`` if the password is generated When activation has success, the ``RegistrationProfile`` of the ``User`` will be deleted from database because the profile is no longer required. """ try: profile = self.get(_status='accepted', activation_key=activation_key) except self.model.DoesNotExist: return None if not profile.activation_key_expired(): is_generated = password is None password = password or generate_random_password( length=settings.REGISTRATION_DEFAULT_PASSWORD_LENGTH) user = profile.user user.set_password(password) user.is_active = True user.save() if send_email: profile.send_activation_email(site, password, is_generated, message=message) if not no_profile_delete: # the profile is no longer required profile.delete() return user, password, is_generated return None