本文整理汇总了Python中pyotp.random_base32函数的典型用法代码示例。如果您正苦于以下问题:Python random_base32函数的具体用法?Python random_base32怎么用?Python random_base32使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了random_base32函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: adduser
def adduser(request):
""" Method to insert new username, generate secret"""
messages = None
session = request.getSession()
user = IUser(session)
if not user.is_admin:
request.setResponseCode(403)
returnValue('Permission Denied')
if request.method == 'POST':
username = request.args.get("username", None)[0]
if username is not None:
# Generate Secret
secret = pyotp.random_base32()
# Insert user into db
try:
yield dbpool.runOperation('INSERT into users (username, secret) values (?, ?);', (username, secret))
# generate QRCODE
totp = pyotp.TOTP(secret)
img = qrcode.make(totp.provisioning_uri("Unlab:{}".format(username)))
page = webapp.templates.get_template('show_qrcode.html')
returnValue(page.render(username=username, img=make_datauri(img)))
except sqlite3.IntegrityError, e:
messages = "User {} already exists".format(username)
else:
messages = "Failed to create user"
示例2: register
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
seed = pyotp.TOTP(pyotp.random_base32())
# The parameter below is used as the label for the auth app interface.
uri = seed.provisioning_uri(username)
secret = urlparse.parse_qs(urlparse.urlparse(uri).query)['secret'][0]
# This can fail if username is not unique. TODO: wrap in try
newUser = User(username=username, password=password, tfaEnabled=True, tfaSecret=secret)
newUser.save()
request.session['username'] = username
request.session['password'] = password
request.session['tfaUri'] = uri
return redirect(reverse('tfaSetup'))
else:
return render(request, 'tfa/register.html', {'form': RegisterForm()})
else:
return render(request, 'tfa/register.html', {'form': RegisterForm()})
示例3: test_activate
def test_activate():
user_id = db_utils.create_user()
tfa_secret = pyotp.random_base32()
totp = pyotp.TOTP(tfa_secret)
# Failed validation between tfa_secret/tfa_response
assert not tfa.activate(user_id, tfa_secret, "000000")
# Verify 2FA is not active
assert not d.engine.scalar("""
SELECT twofa_secret
FROM login
WHERE userid = %(userid)s
""", userid=user_id)
# Validation successful, and tfa_secret written into user's `login` record
tfa_response = totp.now()
assert tfa.activate(user_id, tfa_secret, tfa_response)
# The stored twofa_secret must not be plaintext
stored_secret = d.engine.scalar("""
SELECT twofa_secret
FROM login
WHERE userid = %(userid)s
""", userid=user_id)
assert tfa_secret != stored_secret
# The stored secret must be decryptable to the generated tfa_secret
assert tfa_secret == tfa._decrypt_totp_secret(stored_secret)
示例4: new_google_authentication
def new_google_authentication():
new_token = pyotp.random_base32()
g.settings.secret_key = new_token
db.session.commit()
totp = pyotp.TOTP(g.settings.secret_key)
uri = totp.provisioning_uri("admin")
return uri
示例5: generate_token
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,
# valid_until returns time as a datetime.datetime object
# this converts it to a float time
valid_until=time.mktime(totp.valid_until(timestamp).timetuple())
)
示例6: startup
def startup():
# db initializations
db.create_all()
settings = Settings(secret_key=pyotp.random_base32())
db.session.add(settings)
db.session.commit()
示例7: otp_validate
def otp_validate():
print request.json
if request.json.get('mobile') is None or request.json.get('otp') is None :
abort(400)
else:
user_id = request.json.get('mobile')
otp = request.json.get('otp')
try:
act_rec = Account.query.filter_by(user_id=user_id).first()
if act_rec and act_rec.otp == otp:
time_difference = datetime.strptime(ctime(), "%a %b %d %H:%M:%S %Y") - act_rec.last_updated_on
if time_difference.seconds > 600:
return make_response(jsonify({'result': 'otp expired'}), 502)
access_token = pyotp.random_base32()
act_rec.access_token = access_token
act_rec.last_updated_on = ctime()
session_commit()
#map_products(user_id, request.json.get('products'))
products = Product.query.all()
res= {'products' : [product.as_dict() for product in products], 'access_token': access_token}
return make_response(jsonify(res), 200)
else:
return make_response(jsonify({'result': 'invalid otp'}), 501)
except Exception, e:
logging.error(str(e))
abort(404)
示例8: ologin
def ologin():
if request.method == 'GET':
if 'otpusername' not in session and 'username'in session :
if User.otpchk(str(session['username'])) == "0":
print("hellop")
import pyotp
key = pyotp.random_base32()
totp = pyotp.TOTP(key)
optsct = totp.provisioning_uri(session['username'])
User.optnew(str(session['username']),optsct,key)
return render_template('admin/otpset.html',otpurl=str(User.otpchk(str(session['username']))))
else:
return render_template('admin/otplogin.html',name=str(session['username']))
else:
return redirect(url_for('admin.index'))
else:
if 'username' in session:
import pyotp
passd = request.form['otppass']
otpkey = User.otpkeychk(str(session['username']))
totp = pyotp.TOTP(otpkey)
if totp.verify(passd) is True:
session['otpusername'] = str(session['username'])+str(passd)
return redirect(url_for('admin.index'))
else:
return redirect(url_for('login.ologin'))
示例9: create
def create(cls, email, key, password):
u = cls(email=email, key=key, password=password)
if u.key is None:
u.key = pyotp.random_base32()
return u
示例10: register_device
def register_device(request):
if request.method == 'POST':
secret_key = request.POST['secret_key']
otp = request.POST['otp']
totp = pyotp.TOTP(secret_key)
if totp.verify(otp) is False:
logout(request)
return HttpResponseRedirect('/login')
otpuser = OtpUser.objects.get(user__username=request.user.username)
otpuser.secret_key = secret_key
otpuser.save()
logout(request)
return HttpResponseRedirect('/login')
secret_key = pyotp.random_base32()
username = request.user.username
key_uri = 'otpauth://totp/appname:'+username+'?secret='+secret_key+'&issuer=appname'
qr = pyqrcode.create(key_uri)
qr_name = secret_key+'.svg'
qr_file = os.path.join(BASE_DIR, 'static')+'/'+qr_name
qr.svg(qr_file)
return render_to_response('register_device.html', {'qr_file':qr_name, 'secret_key': secret_key}, context_instance=RequestContext(request))
示例11: confirm
def confirm(action=None):
if flask_security.current_user.has_role("admin"):
return flask.redirect(flask.url_for("admin.index"))
if not flask_security.current_user.is_anonymous:
return flask.redirect(flask.url_for("manage.actions"))
if not (flask.session.get("email") or flask.session.get("phone")):
return flask.redirect(flask.url_for(".step_one"))
if not flask.session.get("actions"):
return flask.redirect(flask.url_for(".step_two"))
phone = utils.format_phone(flask.session)
if action == "submit":
user = None
query = models.User.query
email = flask.session.get("email", "")
if phone:
user = query.filter_by(phone=phone)
user = user.first()
if email and not user:
user = query.filter_by(email=email).first()
if not user:
user = models.User()
user.phone = phone
user.email = email
for action_id in flask.session["actions"]:
action = models.Action.query.get(action_id)
user.actions.append(action)
name = flask.session.get("method_name")
if name:
method = models.Method.query.filter_by(name=name).first()
user.method = method
utils.add_schedule(user, flask.session)
user.secret = pyotp.random_base32()
models.db.session.add(user)
models.db.session.commit()
redirect = "index"
if user.email and user.email_confirmed_at is None:
token = flask_security.confirmable.generate_confirmation_token(user)
link = flask.url_for(".confirm_signup", token=token, _external=True)
msg = flask_security.utils.get_message(
"CONFIRM_REGISTRATION", email=user.email
)
flask.flash(*msg)
subject = "Thank You for Signing Up for Love Touches!"
flask_security.utils.send_mail(
subject, user.email, "signup", user=user, confirmation_link=link
)
redirect = "index"
if user.phone and user.phone_confirmed_at is None:
utils.send_code(user)
flask.session["_user_id"] = user.id
redirect = "confirm_mobile"
for key in (x for x in list(flask.session.keys()) if not x.startswith("_")):
del flask.session[key]
return flask.redirect(flask.url_for(redirect))
actions = [models.Action.query.get(x) for x in flask.session["actions"]]
return flask.render_template(
"confirm.html", actions=actions, phone=phone, days_label=_days_label()
)
示例12: generate_secret
def generate_secret():
"""
Generate random OTP secret
:rtype: str
:returns: 16-character string
"""
return pyotp.random_base32()
示例13: _generate_secret_and_qr_code
def _generate_secret_and_qr_code(username: str) -> Tuple[str, str, str]:
"""Generate a secret, url, and QR code."""
import pyotp
ota_secret = pyotp.random_base32()
url = pyotp.totp.TOTP(ota_secret).provisioning_uri(
username, issuer_name="Home Assistant")
image = _generate_qr_code(url)
return ota_secret, url, image
示例14: _add_ota_secret
def _add_ota_secret(self, user_id: str,
secret: Optional[str] = None) -> str:
"""Create a ota_secret for user."""
import pyotp
ota_secret = secret or pyotp.random_base32() # type: str
self._users[user_id] = ota_secret # type: ignore
return ota_secret
示例15: __init__
def __init__(self, username, password=None, name=None, totp_key=None, groups=()):
if name is None:
name = username
if password is None:
password = passgen.passgen()
if totp_key is None:
totp_key = pyotp.random_base32()
super(User, self).__init__(username=username, password=password,
name=name, totp_key=totp_key, groups=groups)