How to use the pyotp.random_base32 function in pyotp

To help you get started, we’ve selected a few pyotp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github IntuitiveWebSolutions / PyWebRunner / PyWebRunner / WebRunner.py View on Github external
def generate_otp_hash(self):
        try:
            import pyotp
            return pyotp.random_base32()
        except ImportError:
            print("You must install pyotp to use `generate_otp_hash`.")
            print("pip install pyotp")
            return None
github zatosource / zato / code / zato-cli / src / zato / cli / web_admin_auth.py View on Github external
def execute(self, args):

        # If there was a key given on input, we need to validate it,
        # this report an erorr if the key cannot be used.
        if args.key:
            totp = pyotp.TOTP(args.key)
            totp.now()

            # If we are here, it means that the key was valid
            key = args.key
        else:
            key = pyotp.random_base32()

        from zato.admin.web.models import User
        from zato.admin.web.util import get_user_profile
        from zato.admin.zato_settings import zato_secret_key
        self.reset_logger(args, True)

        try:
            user = User.objects.get(username=args.username)
        except User.DoesNotExist:
            self.logger.warn('No such user `%s` found in `%s`', args.username, args.path)
            return

        # Here we know we have the user and key for sure, now we need to get the person's profile
        user_profile = get_user_profile(user)

        # Everything is ready, we can reset the key ..
github AUCR / AUCR / aucr_app / plugins / auth / models.py View on Github external
def set_otp_secret(self):
        """Set two factor token for user."""
        if self.otp_secret is None:
            # generate a random secret
            self.otp_secret = pyotp.random_base32()
github securestate / king-phisher / tools / otp_enroll.py View on Github external
user = models.User(name=arguments.user)
		session.add(user)
		color.print_status('the specified user was created')

	for case in utilities.switch(arguments.action):
		if case('remove'):
			user.otp_secret = None
			break
		if case('set'):
			if user.otp_secret:
				color.print_error("the specified user already has an otp secret set")
				return
			if arguments.otp_secret:
				new_otp = arguments.otp_secret
			else:
				new_otp = pyotp.random_base32()
			if len(new_otp) != 16:
				color.print_error("invalid otp secret length, must be 16")
				return
			user.otp_secret = new_otp
			break

	if user.otp_secret:
		color.print_status("user: {0} otp: {1}".format(user.name, user.otp_secret))
		totp = pyotp.TOTP(user.otp_secret)
		uri = totp.provisioning_uri(user.name + '@king-phisher') + '&issuer=King%20Phisher'
		color.print_status("provisioning uri: {0}".format(uri))
		if has_qrcode and arguments.qrcode_filename:
			img = qrcode.make(uri)
			img.save(arguments.qrcode_filename)
			color.print_status("wrote qrcode image to: " + arguments.qrcode_filename)
	else:
github home-assistant / home-assistant / homeassistant / auth / mfa_modules / notify.py View on Github external
def _generate_random() -> int:
    """Generate a 8 digit number."""
    import pyotp

    return int(pyotp.random_base32(length=8, chars=list("1234567890")))
github YoLoveLife / DevOps / apps / authority / api / user.py View on Github external
def get_qrcode(user):
    if not user.qrcode:
        user.qrcode = pyotp.random_base32()
        user.save()
    file_name = str(aes.encrypt(user.qrcode), encoding='utf-8')
    file = settings.QCODE_ROOT+'/'+file_name+'.png'
    if not os.path.exists(file):
        data = pyotp.totp.TOTP(user.qrcode).provisioning_uri(user.username, issuer_name="devEops")
        qr = QRCode(
            version=1,
            error_correction=constants.ERROR_CORRECT_L,
            box_size=6,
            border=4,)
        try:
            qr.add_data(data)
            qr.make(fit=True)
            img = qr.make_image()
            img.save(file)
            return '/media/qrcode/' + file_name + '.png'
github gonicus / gosa / backend / src / gosa / backend / plugins / two_factor / main.py View on Github external
def __enable_otp(self, user):
        if user.uuid not in self.__settings:
            self.__settings[user.uuid] = {}

        user_settings = self.__settings[user.uuid]
        secret = random_base32()
        totp = TOTP(secret)
        user_settings['otp_secret'] = secret
        self.__save_settings()
        return totp.provisioning_uri("%s@%s.gosa" % (user.uid, self.env.domain))
github psono / psono-server / psono / restapi / views / user_ga.py View on Github external
:type request:
        :param args:
        :type args:
        :param kwargs:
        :type kwargs:
        :return: 201 / 400
        :rtype:
        """

        serializer = self.get_serializer(data=request.data)

        if not serializer.is_valid():

            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        secret = pyotp.random_base32()

        new_ga = Google_Authenticator.objects.create(
            user=request.user,
            title= serializer.validated_data.get('title'),
            secret = encrypt_with_db_secret(str(secret)),
            active=False
        )

        return Response({
            "id": new_ga.id,
            "secret": str(secret)
        },
            status=status.HTTP_201_CREATED)
github facebookarchive / augmented-traffic-control / atc / atcd / atcd / access_manager.py View on Github external
def generate_token(self, ip, duration):
        """
        takes an ip to generate an AccessToken for and a duration that the
        remote device will be granted control of the ip once the token is used
        """
        totp_dict = self._ip_to_totp_map.get(ip)
        if totp_dict is None:
            # Timeout changed to 60 seconds from the default 30 as it may take
            # more than 30 sec to get the code, go to other client and enter it
            totp = AtcdTOTP(
                interval=self.ACCESS_TOKEN_INTERVAL,
                s=pyotp.random_base32()
            )
            self._ip_to_totp_map[ip] = {
                'totp': totp,
                'duration': duration
            }
        else:
            totp = totp_dict.get('totp')
            if duration != totp_dict.get('duration'):
                totp_dict['duration'] = duration
                self._ip_to_totp_map[ip] = totp_dict

        timestamp = datetime.datetime.now()

        return AccessToken(
            token=totp.at(timestamp),
            interval=self.ACCESS_TOKEN_INTERVAL,

pyotp

Python One Time Password Library

MIT
Latest version published 1 year ago

Package Health Score

84 / 100
Full package analysis