How to use pyotp - 10 common examples

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 HenrikDK / youtube-xbmc-plugin / integrationtests / TestYouTubeLogin.py View on Github external
def test_plugin_should_perform_basic_2factor_login_correctly(self):
        import pyotp
        self.totp = pyotp.TOTP("fbfkkk27ffmaihzg")
        self.lastpin = False

        sys.modules["__main__"].settings.load_strings("./resources/2factor-login-settings.xml")
        tmp = sys.modules["__main__"].xbmcgui.Dialog()
        tmp.numeric.side_effect = self.generatePin

        assert(sys.modules["__main__"].settings.getSetting("auth") == "")

        print "username: " + sys.modules["__main__"].settings.getSetting("username")
        print "pass: " + sys.modules["__main__"].settings.getSetting("user_password")
        print "oauth2_access_token: " + sys.modules["__main__"].settings.getSetting("oauth2_access_token")

        self.navigation.executeAction({"action": "settings"})

        oauth2_access_token = sys.modules["__main__"].settings.getSetting("oauth2_access_token") 
        print "username: " + sys.modules["__main__"].settings.getSetting("username")
github sbezboro / standard-web-flask / standardweb / views / settings.py View on Github external
form = RemoveMFAForm()

        if form.validate_on_submit():
            session['mfa_stage'] = None
            user.mfa_login = False
            user.save(commit=True)

            flash('Disabled two-factor authentication', 'success')

            return redirect(url_for('mfa_settings'))
    else:
        form = AddMFAForm()

        if form.validate_on_submit():
            token = request.form['token']
            totp = pyotp.TOTP(user.mfa_secret)

            if totp.verify(token):
                session['mfa_stage'] = 'mfa-verified'
                user.mfa_login = True
                user.save(commit=True)

                flash('Successfully enabled two-factor authentication', 'success')

                return redirect(url_for('mfa_settings'))
            else:
                form.token.errors = ['Invalid code']

    template_vars = {
        'form': form,
        'active_option': 'mfa'
    }
github securestate / king-phisher / king_phisher / server / server_rpc.py View on Github external
user = session.query(db_models.User).filter_by(name=username).first()
	if not user:
		logger.info('creating new user object with name: ' + username)
		user = db_models.User(name=username)
	elif user.has_expired:
		logger.warning("failed login request from {0} for user {1}, (user has expired)".format(handler.client_address[0], username))
		return fail_default
	elif user.otp_secret:
		if otp is None:
			logger.debug("failed login request from {0} for user {1}, (missing otp)".format(handler.client_address[0], username))
			return fail_otp
		if not (isinstance(otp, str) and len(otp) == 6 and otp.isdigit()):
			logger.warning("failed login request from {0} for user {1}, (invalid otp)".format(handler.client_address[0], username))
			return fail_otp
		totp = pyotp.TOTP(user.otp_secret)
		now = datetime.datetime.now()
		if otp not in (totp.at(now + datetime.timedelta(seconds=offset)) for offset in (0, -30, 30)):
			logger.warning("failed login request from {0} for user {1}, (invalid otp)".format(handler.client_address[0], username))
			return fail_otp
	user.last_login = db_models.current_timestamp()
	session.add(user)
	session.commit()
	session_id = handler.server.session_manager.put(user)
	logger.info("successful login request from {0} for user {1} (id: {2})".format(handler.client_address[0], username, user.id))
	signals.send_safe('rpc-user-logged-in', logger, handler, session=session_id, name=username)
	return True, ConnectionErrorReason.SUCCESS, session_id
github Truth0906 / PTTOTP / PTTOTP / systemtray.py View on Github external
self.console.config.load()
        if self.console.config.get(config.key_otp_key) is None:

            self.system_alert(f'{self.console.ptt_id} 歡迎使用 Ptt OTP')
            rule_form = rule_window.Form(self.console)
            rule_form.show()
            rule_form.exec_()

            if not rule_form.ok:
                self.system_alert('Ptt OTP 感謝您的試用')
                time.sleep(3)
                self.exit_func()

            otp_key = pyotp.random_base32()

            otp_url = pyotp.totp.TOTP(otp_key).provisioning_uri(self.console.ptt_id, issuer_name="Ptt OTP")
            img = qrcode.make(otp_url)
            img.save('./temp.png')

            show_verify_form = show_verify.Form(self.console, otp_key)
            show_verify_form.show()
            show_verify_form.exec_()

            os.remove('./temp.png')

            if not show_verify_form.ok:
                self.system_alert('Ptt OTP 感謝您的試用')
                time.sleep(3)
                self.exit_func()

            self.console.config.set(config.key_otp_key, otp_key)
github seleniumbase / SeleniumBase / seleniumbase / fixtures / base_case.py View on Github external
if not totp_key:
            totp_key = settings.TOTP_KEY

        epoch_interval = time.time() / 30.0
        cycle_lifespan = float(epoch_interval) - int(epoch_interval)
        if float(cycle_lifespan) > 0.95:
            # Password expires in the next 1.5 seconds. Wait for a new one.
            for i in range(30):
                time.sleep(0.05)
                epoch_interval = time.time() / 30.0
                cycle_lifespan = float(epoch_interval) - int(epoch_interval)
                if not float(cycle_lifespan) > 0.95:
                    # The new password cycle has begun
                    break

        totp = pyotp.TOTP(totp_key)
        return str(totp.now())
github mubix / ctf / 2018-hacktober.org / Programming / files / picksomemorenumbers.py View on Github external
import pyotp
import requests

url = "https://picksomemorenumbers.h4110w33n.com/"
requests.packages.urllib3.disable_warnings()

key = pyotp.TOTP('YSH45EYF35IRJHVV').now()
r = requests.post(url, data={"number1":key[0:3]}, verify=False)
r = requests.post(url+r.history[0].headers['location'], data={"number2":key[3:]}, verify=False)
print(r.text)
github OmniLayer / omniapi / api / user_service.py View on Github external
else:
        print_debug(("DEBUG: USER_SERVICE: VERIFY_MFA: Error decrypting secret for",uuid,"got error:",encsec[1]),8)
        return False,True
    else:
      print_debug(("DEBUG: USER_SERVICE: VERIFY_MFA: Error verifying mfa, secret already setup for",uuid),8)
      return False,True

  if secret in ['None',None]:
    if token == 'null':
      print_debug(("DEBUG: USER_SERVICE: VERIFY_MFA: MFA Secret not setup/provided, no token provided, login allowed",uuid),9)
      return True,False
    else:
      print_debug(("DEBUG: USER_SERVICE: VERIFY_MFA: MFA Secret not setup/provided, no token provided, login abort",uuid),9)
      return False,False
  else:
    totp = pyotp.TOTP(secret)
    test=totp.verify(token,None,1)
    print_debug(("DEBUG: USER_SERVICE: VERIFY_MFA: MFA Secret setup/provided, token provided, token validation",test,"for",uuid),9)
    return test,True
github sentialabs / coto / coto / clients / signin_aws / __init__.py View on Github external
email: Account email address.
            password: Account password.
            mfa_secret: Account mfa secret. The Base32 seed defined as specified
                in RFC3548. The Base32StringSeed is Base64-encoded.

        Returns:
            bool: Signin successful
        """
        data = {
            'email': email,
            'password': password,
            'client_id': 'arn:aws:iam::015428540659:user/homepage',
        }

        if mfa_secret is not None:
            data['mfa1'] = TOTP(mfa_secret).now()

        # an exception is thrown if authentication was unsuccessful
        self._action('authenticateRoot', data, captcha_guess=captcha_guess)
        self.session().authenticated = True
        self.session().root = True
        return True
github alexandremendoncaalvaro / face-access / temp_access.py View on Github external
def __init__(self):
        self.totp = pyotp.TOTP(ConfigTempAccess.BASE_32_KEY)
github jx-sec / jxotp / single-user / auth.py View on Github external
def  otp_auth(code):
        totp = pyotp.TOTP(OTP_SECRET)
        if totp.now() == code:
                return True
        else:
                return False

pyotp

Python One Time Password Library

MIT
Latest version published 1 year ago

Package Health Score

84 / 100
Full package analysis