Python pyotp.random_base32() Examples

The following are 19 code examples of pyotp.random_base32(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyotp , or try the search function .
Example #1
Source File: conftest.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def test_two_factor_auth_user(app):
    with app.app_context():
        user = User(username="TEST_FACTOR_USER", password="TEST_USER_PASSWORD")
        ug = Group(name="TEST_FACTOR_USER", user_group=True, members=[user])
        secret = pyotp.random_base32()
        auth = TwoFactorAuth(user=user, enabled=True)
        auth.secret_key = secret
        otp_generator = partial(get_two_factor_code, secret)
        db.session.add(user)
        db.session.add(auth)
        db.session.add(ug)
        db.session.commit()
        backup_codes = generate_backup_codes()
        for code in backup_codes:
            backup = TwoFactorBackup(auth_id=auth.user_id)
            backup.backup_code = code
            db.session.add(backup)
        db.session.commit()
        return TestTwoFactorUser(
            user.id, user.username, "TEST_USER_PASSWORD", otp_generator, backup_codes
        ) 
Example #2
Source File: libmfa.py    From vulpy with MIT License 6 votes vote down vote up
def mfa_get_secret(username):

    #secret=pyotp.random_base32()

    conn = sqlite3.connect('db_users.sqlite')
    conn.set_trace_callback(print)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    #c.execute("UPDATE users SET mfa = ? WHERE username = ?", (secret, username,))
    user = c.execute("SELECT * FROM users WHERE username = ?", (username, )).fetchone()

    if user:
        return user['mfa_secret'] #True
    else:
        return False 
Example #3
Source File: libmfa.py    From vulpy with MIT License 6 votes vote down vote up
def mfa_reset_secret(username):

    secret=pyotp.random_base32()

    conn = sqlite3.connect('db_users.sqlite')
    conn.set_trace_callback(print)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    #c.execute("UPDATE users SET mfa = ? WHERE username = ?", (secret, username,))
    #user = c.execute("SELECT * FROM users WHERE username = ?", (username, )).fetchone()
    c.execute("UPDATE users SET mfa_secret = ? WHERE username = ?", (secret, username))
    conn.commit()

    #if user:
    #    return user['mfa_secret'] #True
    #else:
    return False 
Example #4
Source File: libmfa.py    From vulpy with MIT License 6 votes vote down vote up
def mfa_get_secret(username):

    #secret=pyotp.random_base32()

    conn = sqlite3.connect('db_users.sqlite')
    conn.set_trace_callback(print)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    #c.execute("UPDATE users SET mfa = ? WHERE username = ?", (secret, username,))
    user = c.execute("SELECT * FROM users WHERE username = ?", (username, )).fetchone()

    if user:
        return user['mfa_secret'] #True
    else:
        return False 
Example #5
Source File: otp.py    From platypush with MIT License 6 votes vote down vote up
def refresh_secret(self, secret_path: Optional[str] = None) -> Response:
        """
        Refresh the secret token for key generation given a secret path.

        :param secret_path: Secret path to refresh (default: default configured path).
        """

        secret_path = secret_path or self.secret_path
        assert secret_path, 'No secret_path configured'

        os.makedirs(os.path.dirname(os.path.abspath(os.path.expanduser(secret_path))), exist_ok=True)
        secret = pyotp.random_base32()
        with open(secret_path, 'w') as f:
            f.writelines([secret])
        os.chmod(secret_path, 0o600)
        return secret 
Example #6
Source File: user.py    From DevOps with GNU General Public License v2.0 6 votes vote down vote up
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'
        except Exception as e:
            return '/media/qrcode/' + file_name + '.png'
    else:
        return '/media/qrcode/' + file_name + '.png' 
Example #7
Source File: two_factor.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        profile = self.profile
        if not profile.totp_key:
            profile.totp_key = pyotp.random_base32(length=32)
            profile.save(update_fields=['totp_key'])
        if not profile.scratch_codes:
            profile.generate_scratch_codes()
        return self.render_to_response(self.get_context_data()) 
Example #8
Source File: views.py    From SOMS with GNU General Public License v3.0 5 votes vote down vote up
def index(request):
    user = request.user
    skey = ''

    if request.method == 'POST':
        skey = request.POST.get('security_key', None)
        user.mfa = skey
        user.save()
        return redirect('logout')
    if not user.mfa:
        skey = pyotp.random_base32(32)
        get_qrcode(skey, user.username, user.pk)
    return render(request, 'index.html', {'security_key': skey}) 
Example #9
Source File: user_settings.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def enable_two_factor():
    """
    Switch two factor auth on for the currently logged in user.
    """
    secret = pyotp.random_base32()
    provisioning_url = pyotp.totp.TOTP(secret).provisioning_uri(
        current_user.username,
        issuer_name=current_app.config["FLOWAUTH_TWO_FACTOR_ISSUER"],
    )
    signed_secret = TimestampSigner(current_app.config["SECRET_KEY"]).sign(secret)
    backup_codes = generate_backup_codes()
    serialised_codes = TimedSerializer(current_app.config["SECRET_KEY"]).dumps(
        backup_codes
    )
    return (
        jsonify(
            {
                "provisioning_url": provisioning_url,
                "secret": signed_secret.decode(),
                "issuer": current_app.config["FLOWAUTH_TWO_FACTOR_ISSUER"],
                "backup_codes": backup_codes,
                "backup_codes_signature": serialised_codes,
            }
        ),
        200,
    ) 
Example #10
Source File: models.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def post_create(cls, sender, instance, created, *args, **kwargs):  # pylint: disable=unused-argument
        if created:
            instance.secret = pyotp.random_base32()
            instance.save() 
Example #11
Source File: forms.py    From zentral with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user")
        super().__init__(*args, **kwargs)
        self.initial_secret = pyotp.random_base32()
        self.fields["secret"].initial = self.initial_secret 
Example #12
Source File: WebRunner.py    From PyWebRunner with MIT License 5 votes vote down vote up
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 
Example #13
Source File: profile.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_scratch_codes(self):
        codes = [pyotp.random_base32(length=16) for i in range(settings.DMOJ_SCRATCH_CODES_COUNT)]
        self.scratch_codes = json.dumps(codes)
        self.save(update_fields=['scratch_codes'])
        return codes 
Example #14
Source File: mfa_setup.py    From app with MIT License 5 votes vote down vote up
def mfa_setup():
    if current_user.enable_otp:
        flash("you have already enabled MFA", "warning")
        return redirect(url_for("dashboard.index"))

    otp_token_form = OtpTokenForm()

    if not current_user.otp_secret:
        LOG.d("Generate otp_secret for user %s", current_user)
        current_user.otp_secret = pyotp.random_base32()
        db.session.commit()

    totp = pyotp.TOTP(current_user.otp_secret)

    if otp_token_form.validate_on_submit():
        token = otp_token_form.token.data.replace(" ", "")

        if totp.verify(token) and current_user.last_otp != token:
            current_user.enable_otp = True
            current_user.last_otp = token
            db.session.commit()
            flash("MFA has been activated", "success")

            return redirect(url_for("dashboard.recovery_code_route"))
        else:
            flash("Incorrect token", "warning")

    otp_uri = pyotp.totp.TOTP(current_user.otp_secret).provisioning_uri(
        name=current_user.email, issuer_name="SimpleLogin"
    )

    return render_template(
        "dashboard/mfa_setup.html", otp_token_form=otp_token_form, otp_uri=otp_uri
    ) 
Example #15
Source File: libmfa.py    From vulpy with MIT License 5 votes vote down vote up
def mfa_enable(username):

    #secret=pyotp.random_base32()

    conn = sqlite3.connect('db_users.sqlite')
    conn.set_trace_callback(print)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    #c.execute("UPDATE users SET mfa = ? WHERE username = ?", (secret, username,))
    c.execute("UPDATE users SET mfa_enabled = 1 WHERE username = ?", (username,))
    conn.commit()

    return True 
Example #16
Source File: libmfa.py    From vulpy with MIT License 5 votes vote down vote up
def mfa_enable(username):

    #secret=pyotp.random_base32()

    conn = sqlite3.connect('db_users.sqlite')
    conn.set_trace_callback(print)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    #c.execute("UPDATE users SET mfa = ? WHERE username = ?", (secret, username,))
    c.execute("UPDATE users SET mfa_enabled = 1 WHERE username = ?", (username,))
    conn.commit()

    return True 
Example #17
Source File: models.py    From AUCR with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #18
Source File: routes.py    From AUCR with GNU General Public License v3.0 5 votes vote down vote up
def edit_profile():
    """Edit profile function allows the user to modify their about me section."""
    form = EditProfileForm(current_user.username)
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        user_name = User.query.filter_by(username=current_user.username).first()
        if user_name is None:
            render_error_page_template(404)
        if form.otp_token_checkbox.data:
            if user_name.otp_secret:
                current_user.otp_secret = user_name.otp_secret
            else:
                current_user.otp_secret = pyotp.random_base32()
            db.session.commit()
            url = pyqrcode.create(user_name.get_totp_uri())
            stream = BytesIO()
            url.svg(stream, scale=3)
            return render_template('two-factor-setup.html'), 200, {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'}
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me
        if form.otp_token_checkbox:
            if form.otp_token_checkbox.data:
                form.otp_token.data = current_user.otp_token
        else:
            form.otp_token_checkbox = current_user.otp_token_checkbox
    else:
        for error in form.errors:
            flash(str(form.errors[error][0]), 'error')
    return render_template('edit_profile.html', title=_('Edit Profile'), form=form) 
Example #19
Source File: user.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def set_TFA_secret(self):
        secret = pyotp.random_base32()
        self._TFA_secret = encrypt_string(secret)