本文整理汇总了Python中pyotp.TOTP属性的典型用法代码示例。如果您正苦于以下问题:Python pyotp.TOTP属性的具体用法?Python pyotp.TOTP怎么用?Python pyotp.TOTP使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类pyotp
的用法示例。
在下文中一共展示了pyotp.TOTP属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_request_tfa_token
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def test_request_tfa_token(test_client, authed_sempo_admin_user, otp_generator, status_code):
"""
GIVEN a Flask Application
WHEN '/api/auth/tfa/' is requested (POST)
THEN check a tfa token is only returned when OTP is valid
"""
auth_token = authed_sempo_admin_user.encode_auth_token().decode()
tfa_url = authed_sempo_admin_user.tfa_url
tfa_secret = tfa_url.split("secret=")[1].split('&')[0]
func = pyotp.TOTP(tfa_secret)
otp = otp_generator(func)
otp_expiry_interval = 1
response = test_client.post('/api/v1/auth/tfa/',
headers=dict(Authorization=auth_token, Accept='application/json'),
json=dict(
otp=otp,
otp_expiry_interval=otp_expiry_interval
),
content_type='application/json', follow_redirects=True)
assert response.status_code == status_code
示例2: test_auth_mfa_success
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def test_auth_mfa_success(flask_client):
user = User.create(
email="a@b.c",
password="password",
name="Test User",
activated=True,
enable_otp=True,
otp_secret="base32secret3232",
)
db.session.commit()
totp = pyotp.TOTP(user.otp_secret)
s = Signer(FLASK_SECRET)
mfa_key = s.sign(str(user.id))
r = flask_client.post(
url_for("api.auth_mfa"),
json={"mfa_token": totp.now(), "mfa_key": mfa_key, "device": "Test Device"},
)
assert r.status_code == 200
assert r.json["api_key"]
assert r.json["email"]
assert r.json["name"] == "Test User"
示例3: test_auth_wrong_mfa_key
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def test_auth_wrong_mfa_key(flask_client):
user = User.create(
email="a@b.c",
password="password",
name="Test User",
activated=True,
enable_otp=True,
otp_secret="base32secret3232",
)
db.session.commit()
totp = pyotp.TOTP(user.otp_secret)
r = flask_client.post(
url_for("api.auth_mfa"),
json={
"mfa_token": totp.now(),
"mfa_key": "wrong mfa key",
"device": "Test Device",
},
)
assert r.status_code == 400
assert r.json["error"]
示例4: generate_code
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def generate_code(self, secret):
"""
Generate two-factor authentication code.
Args:
secret (str): one time password authentication secret string.
Returns:
str: 6 digit two-factor authentication code.
Examples:
>>> secret = balena.twofactor_auth.get_otpauth_secret()
>>> balena.twofactor_auth.generate_code(secret)
'259975'
"""
totp = pyotp.TOTP(secret)
return totp.now()
示例5: do_mfa_view
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def do_mfa_view():
if 'username' not in g.session:
return redirect('/user/login')
if libmfa.mfa_is_enabled(g.session['username']):
return render_template('mfa.disable.html')
else:
libmfa.mfa_reset_secret(g.session['username'])
secret = libmfa.mfa_get_secret(g.session['username'])
secret_url = pyotp.totp.TOTP(secret).provisioning_uri(g.session['username'], issuer_name="Vulpy")
img = qrcode.make(secret_url)
buffered = BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()
return render_template('mfa.enable.html', secret_url=secret_url, img_str=img_str)
示例6: do_mfa_enable
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def do_mfa_enable():
if 'username' not in g.session:
return redirect('/user/login')
secret = libmfa.mfa_get_secret(g.session['username'])
otp = request.form.get('otp')
totp = pyotp.TOTP(secret)
if totp.verify(otp):
libmfa.mfa_enable(g.session['username'])
return redirect('/mfa/')
else:
flash("The OTP was incorrect")
return redirect('/mfa/')
return render_template('mfa.enable.html')
示例7: set_otp
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def set_otp(self, hash, selector=None, elem=None, otp_type='time', otp_index=1):
try:
import pyotp
except ImportError:
print("You must install pyotp to use `set_otp`.")
print("pip install pyotp")
return
if not elem:
elem = self.get_element(selector)
if otp_type == 'time':
otp = pyotp.TOTP(hash)
response = otp.now()
else:
otp = pyotp.HOTP(hash)
response = otp.at(otp_index)
self.set_value(selector, response, elem=elem)
示例8: check_totp
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def check_totp(self, _, window, entry, new_otp, this_user):
if not new_otp.verify(entry.get_text().strip()):
gui_utilities.show_dialog_warning(
'Incorrect TOTP',
self.application.get_active_window(),
'The specified TOTP code is invalid. Make sure your time\n'\
+ 'is correct, rescan the QR code and try again.'
)
return
self.application.rpc.remote_table_row_set('users', this_user['id'], {'otp_secret': new_otp.secret})
gui_utilities.show_dialog_info(
'TOTP Enrollment',
self.application.get_active_window(),
'Successfully set the TOTP secret. Your account is now enrolled\n'\
+ 'in two factor authentication. You will be prompted to enter the\n'
+ 'value the next time you login.'
)
window.destroy()
示例9: claim_secret
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def claim_secret(self, request, pk):
"""Claim and try to get an achievement with its secret."""
# Get object
offer = get_object_or_404(self.queryset, id=pk)
# Check if secret is valid
secret = request.data['secret']
if offer.secret and (secret == offer.secret or secret == pyotp.TOTP(offer.secret).now()):
if request.user.profile.achievements.filter(offer=offer).exists():
return Response({'message': 'You already have this achievement!'})
# Create the achievement
Achievement.objects.create(
title=offer.title, description=offer.description, admin_note='SECRET',
body=offer.body, event=offer.event, verified=True, dismissed=True,
user=request.user.profile, offer=offer)
return Response({'message': 'Achievement unlocked successfully!'}, 201)
return forbidden_no_privileges()
示例10: get_qrcode
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def get_qrcode(skey, username, uid):
filepath = os.path.join(BASE_DIR, 'media/qrcode/{}/'.format(uid))
if not os.path.exists(filepath):
os.makedirs(filepath)
data = pyotp.totp.TOTP(skey).provisioning_uri(username, issuer_name=u'SOMS')
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(filepath + username + '.png')
return True
except Exception, e:
print e
return False
示例11: validate_OTP
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def validate_OTP(self, input_otp):
secret = self.get_TFA_secret()
server_otp = pyotp.TOTP(secret)
ret = server_otp.verify(input_otp, valid_window=2)
return ret
示例12: mfa_setup
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
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
)
示例13: mfa_cancel
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def mfa_cancel():
if not current_user.enable_otp:
flash("you don't have MFA enabled", "warning")
return redirect(url_for("dashboard.index"))
otp_token_form = OtpTokenForm()
totp = pyotp.TOTP(current_user.otp_secret)
if otp_token_form.validate_on_submit():
token = otp_token_form.token.data
if totp.verify(token):
current_user.enable_otp = False
current_user.otp_secret = None
db.session.commit()
# user does not have any 2FA enabled left, delete all recovery codes
if not current_user.two_factor_authentication_enabled():
RecoveryCode.empty(current_user)
flash("MFA is now disabled", "warning")
return redirect(url_for("dashboard.index"))
else:
flash("Incorrect token", "warning")
return render_template("dashboard/mfa_cancel.html", otp_token_form=otp_token_form)
示例14: rpc_login
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def rpc_login(handler, session, username, password, otp=None):
logger = logging.getLogger('KingPhisher.Server.Authentication')
if not ipaddress.ip_address(handler.client_address[0]).is_loopback:
logger.warning("failed login request from {0} for user {1}, (invalid source address)".format(handler.client_address[0], username))
raise ValueError('invalid source address for login')
fail_default = (False, ConnectionErrorReason.ERROR_INVALID_CREDENTIALS, None)
fail_otp = (False, ConnectionErrorReason.ERROR_INVALID_OTP, None)
if not (username and password):
logger.warning("failed login request from {0} for user {1}, (missing username or password)".format(handler.client_address[0], username))
return fail_default
if not handler.server.forked_authenticator.authenticate(username, password):
logger.warning("failed login request from {0} for user {1}, (authentication failed)".format(handler.client_address[0], username))
return fail_default
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
示例15: tfa_url
# 需要导入模块: import pyotp [as 别名]
# 或者: from pyotp import TOTP [as 别名]
def tfa_url(self):
if not self._TFA_secret:
self.set_TFA_secret()
db.session.flush()
secret_key = self.get_TFA_secret()
return pyotp.totp.TOTP(secret_key).provisioning_uri(
self.email,
issuer_name='Sempo: {}'.format(
current_app.config.get('DEPLOYMENT_NAME'))
)