本文整理汇总了Python中pyotp.random_base32函数的典型用法代码示例。如果您正苦于以下问题:Python random_base32函数的具体用法?Python random_base32怎么用?Python random_base32使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了random_base32函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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"
开发者ID:unlondon,项目名称:bouncerd,代码行数:25,代码来源:server.py
示例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()})
开发者ID:rwongone,项目名称:django_tfa,代码行数:26,代码来源:views.py
示例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)
开发者ID:Syfaro,项目名称:weasyl,代码行数:26,代码来源:test_two_factor_auth.py
示例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
开发者ID:Conway,项目名称:anonpost,代码行数:7,代码来源:flask_app.py
示例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())
)
开发者ID:272789920,项目名称:augmented-traffic-control,代码行数:32,代码来源:access_manager.py
示例6: startup
def startup():
# db initializations
db.create_all()
settings = Settings(secret_key=pyotp.random_base32())
db.session.add(settings)
db.session.commit()
开发者ID:Conway,项目名称:anonpost,代码行数:7,代码来源:flask_app.py
示例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)
开发者ID:winster,项目名称:surcle,代码行数:26,代码来源:router.py
示例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'))
开发者ID:m85091081,项目名称:hakureshop,代码行数:27,代码来源:login.py
示例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
开发者ID:SergeyBondarenko,项目名称:openstack2FA,代码行数:7,代码来源:user.py
示例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))
开发者ID:OmarIbannez,项目名称:django_otp,代码行数:25,代码来源:views.py
示例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()
)
开发者ID:brolewis,项目名称:love_touches,代码行数:58,代码来源:signup.py
示例12: generate_secret
def generate_secret():
"""
Generate random OTP secret
:rtype: str
:returns: 16-character string
"""
return pyotp.random_base32()
开发者ID:node13h,项目名称:droll,代码行数:9,代码来源:otp.py
示例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
开发者ID:home-assistant,项目名称:home-assistant,代码行数:9,代码来源:totp.py
示例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
开发者ID:home-assistant,项目名称:home-assistant,代码行数:9,代码来源:totp.py
示例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)
开发者ID:aperezdc,项目名称:tacitum,代码行数:9,代码来源:models.py
示例16: __enable_otp
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("%[email protected]%s.gosa" % (user.uid, self.env.domain))
开发者ID:peuter,项目名称:gosa,代码行数:10,代码来源:main.py
示例17: main
def main():
parser = argparse.ArgumentParser(description='King Phisher TOTP Enrollment Utility', conflict_handler='resolve')
utilities.argp_add_args(parser)
config_group = parser.add_mutually_exclusive_group(required=True)
config_group.add_argument('-c', '--config', dest='server_config', type=argparse.FileType('r'), help='the server configuration file')
config_group.add_argument('-u', '--url', dest='database_url', help='the database connection url')
parser.add_argument('--otp', dest='otp_secret', help='a specific otp secret')
parser.add_argument('user', help='the user to mange')
parser.add_argument('action', choices=('remove', 'set', 'show'), help='the action to preform')
parser.epilog = PARSER_EPILOG
arguments = parser.parse_args()
utilities.configure_stream_logger(arguments.loglvl, arguments.logger)
if arguments.database_url:
database_connection_url = arguments.database_url
elif arguments.server_config:
server_config = yaml.load(arguments.server_config)
database_connection_url = server_config['server']['database']
else:
raise RuntimeError('no database connection was specified')
manager.init_database(database_connection_url)
session = manager.Session()
user = session.query(models.User).filter_by(id=arguments.user).first()
if not user:
color.print_error("invalid user id: {0}".format(arguments.user))
return
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.id, user.otp_secret))
totp = pyotp.TOTP(user.otp_secret)
uri = totp.provisioning_uri(user.id + '@king-phisher') + '&issuer=King%20Phisher'
color.print_status("provisioning uri: {0}".format(uri))
else:
color.print_status("user: {0} otp: N/A".format(user.id))
session.commit()
开发者ID:garyhak2009,项目名称:king-phisher,代码行数:55,代码来源:otp_enroll.py
示例18: signup
def signup(self, request):
username = request.username
result = USER.query(USER.username==username).fetch(1)
if len(result) > 0 :
return SignUpResponse(success=False,message='username ' + username + ' already exists')
else :
ssecret = pyotp.random_base32()
hotp = pyotp.HOTP(ssecret)
url = 'https://chart.googleapis.com/chart?chs=200x200&chld=M%7C0&cht=qr&chl=' + urllib.quote(hotp.provisioning_uri(username), safe='')
USER(username=username,secret=ssecret,lastcounter=-1).put()
return SignUpResponse(success=True, message=url)
开发者ID:MoSehsah,项目名称:wagdyapp-web,代码行数:11,代码来源:main.py
示例19: otp_secret
def otp_secret(self, msg, args):
"""Send a new secret to somebody"""
new_secret = pyotp.random_base32()
with self.lock:
with self.stored('secrets') as secrets:
secrets[args] = (new_secret, 0, BEGINNING_OF_TIMES)
totp = pyotp.TOTP(new_secret)
url = totp.provisioning_uri(args)
self.send(self.build_identifier(args), makeQRCodeMessage(url, self._bot.mode), None, 'chat')
return "New secret set for %s and message sent." % args
开发者ID:errbotio,项目名称:err-otp,代码行数:11,代码来源:otp.py
示例20: create
def create(plugin, user_metadata):
"""Creates a new user given the user_metadata dictionary, assigns a new random secret"""
user = User.get(plugin, user_metadata)
if not user:
token = pyotp.random_base32()
permissions = set()
if user_metadata['nick'] in getattr(settings, 'ADMIN_USERS', '').split(','):
permissions = set(['administer_twofactor', 'grant_permissions', 'revoke_permissions', 'view_permissions'])
return User(plugin, user_metadata, token, permissions)
else:
return None
开发者ID:shukla2112,项目名称:alton,代码行数:11,代码来源:user.py
注:本文中的pyotp.random_base32函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论