本文整理汇总了Python中models.User.password方法的典型用法代码示例。如果您正苦于以下问题:Python User.password方法的具体用法?Python User.password怎么用?Python User.password使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.User
的用法示例。
在下文中一共展示了User.password方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sign_up
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def sign_up():
form = SignUpForm()
user = User()
if form.validate_on_submit():
user_name = request.form.get('user_name')
password = request.form.get('password')
user_email = request.form.get('user_email')
register_check = User.query.filter(db.or_(
User.nickname == user_name, User.email == user_email
)).first()
if register_check:
flash("error: the user's name or email already exists.")
return redirect('/sign-up')
if len(user_name) and len(user_email):
user.nickname = user_name
user.password = password
user.email = user_email
user.role = ROLE_USER
try:
db.session.add(user)
db.session.add(user.follow(user))
db.session.commit()
except:
flash('The Database error!')
return redirect('/sign-up')
flash('Sign up successful!')
return redirect('/index')
return render_template('sign_up.html', form = form)
示例2: init_db
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def init_db(self):
engine = self.session.get_bind(mapper=None, clause=None)
inspector = Inspector.from_engine(engine)
if 'ab_user' not in inspector.get_table_names():
print "Security DB not found Creating..."
Base.metadata.create_all(engine)
print "Security DB Created"
self.migrate_db()
if self.session.query(Role).filter_by(name = self.auth_role_admin).first() is None:
role = Role()
role.name = self.auth_role_admin
self.session.add(role)
self.session.commit()
print "Inserted Role for public access", self.auth_role_admin
if not self.session.query(Role).filter_by(name = self.auth_role_public).first():
role = Role()
role.name = self.auth_role_public
self.session.add(role)
self.session.commit()
print "Inserted Role for public access", self.auth_role_public
if not self.session.query(User).all():
user = User()
user.first_name = 'Admin'
user.last_name = 'User'
user.username = 'admin'
user.password = 'general'
user.active = True
user.role = self.session.query(Role).filter_by(name = self.auth_role_admin).first()
self.session.add(user)
self.session.commit()
print "Inserted initial Admin user"
print "Login using Admin/general"
示例3: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def register():
error = None
if request.method == 'POST':
uname =request.form['username']
passwd = request.form['password']
spasswd = request.form['spassword']
usercheck = db.GqlQuery("SELECT * FROM User WHERE username = :username", username=uname).get()
if len(uname.strip()) == 0 :
error = "Username field cannot be empty"
elif usercheck is not None:
error = "Username is already in use. Choose another"
elif len(passwd) == 0 | len(spasswd) == 0:
error = 'Password field cannot be empty'
elif spasswd != passwd:
error = 'Passwords do not match'
else :
u = User()
u.username = uname
u.password = get_hash(passwd)
u.put()
flash("Registration was successful")
return redirect(url_for("login"))
return render_template('register.html',error=error)
示例4: signin
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def signin():
form = SigninForm()
if form.validate_on_submit():
if len(User.query.filter_by(nickname=form.nickname.data).all()) > 0:
flash(gettext("Selected username already exists!"), category='alert-danger')
return redirect(url_for('signin'))
new_email = form.email.data
check_mail = User.query.filter_by(email=new_email).all()
#user mail already exists
if len(check_mail) > 0:
flash(gettext('Selected email is already in use!'), category='alert-danger')
return redirect(url_for('signin'))
user = User()
user.nickname = form.nickname.data
user.password = generate_password_hash(form.password.data)
user.email = new_email
user.language = form.language.data
# default role is user, not admin
user.role = USER_ROLES['ROLE_USER']
db.session.add(user)
db.session.commit()
flash(gettext('Thank you for joining us!'))
return redirect(url_for('index'))
return render_template('login/signin.html',
title=gettext('Sign In'),
form=form)
示例5: api_register_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def api_register_user(*, email, name, password):
if not name or not name.strip():
raise APIValueError('name')
if not email or not _RE_EMAIL.match(email):
raise APIValueError('email')
if not password or not _RE_SHA1.match(password):
raise APIValueError('password')
users = yield from User.findAll('email=?', [email])
if len(users) > 0:
raise APIError('register failed!', 'email', 'Email is already in use')
uid = next_id()
sha1_passwd = '%s:%s' % (uid, password)
admin = False
if email == '[email protected]':
admin = True
user = User(id=uid, name=name.strip(), password=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(),
image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest(),
admin=admin)
yield from user.save()
logging.info('save user ok.')
# 构建返回信息
r = web.Response()
r.set_cookie(_COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
# 把要返回的实例的密码改成‘******’,这样数据库中的密码是正确的,并保证真实的密码不会因返回而泄露
user.password = '******'
r.content_type = 'application/json;charset:utf-8'
r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
return r
示例6: insertUser
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def insertUser(request):
errors = []
u = User()
u.user = re.escape(request.POST.get('user'))
u.email = request.POST.get('email')
password = re.escape(request.POST.get('password'))
salt = uuid.uuid4().hex
hashed_password = hashlib.sha512(password + salt).hexdigest()
u.password = hashed_password
u.salt = salt
u.locked = False
u.activated = False
u.attempts = 0
num_users = u.query(User.user==u.user).count()
num_emails = u.query(User.email==u.email).count()
if num_users == 0 and num_emails == 0:
code = hashlib.sha512(u.user + salt).hexdigest()
u.code = re.escape(code)
u.put()
params = { 'user' : u.user, 'code': code}
sendEmail(u.email, "Account verification url: http://dsswkvn.appspot.com/validateaccount?" + urllib.urlencode(params))
return True
else:
message = "No se ha podido insertar el usuario"
if (num_users != 0):
errors.append("User already exists")
if (num_emails != 0):
errors.append("Email already exists")
template_values = {
'errors': errors
}
return template_values
示例7: api_register_user
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def api_register_user(*, email, name, password):
if not name or not name.strip():
raise APIValueError("name")
if not email or not _RE_EMAIL.match(email):
raise APIValueError("email")
if not password or not _RE_SHA1.match(password):
raise APIValueError("password")
users = yield from User.findAll("email=?", [email])
if len(users) > 0:
raise APIError("register:failed", "email", "Email is already in use.")
uid = next_id()
sha1_password = "%s:%s" % (uid, password)
user = User(
id=uid,
name=name.strip(),
email=email,
password=hashlib.sha1(sha1_password.encode("utf-8")).hexdigest(),
image="/static/img/user.png",
)
yield from user.save()
r = web.Response()
r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
user.password = "******"
r.content_type = "application/json"
r.body = json.dumps(user, ensure_ascii=False).encode("utf-8")
return r
示例8: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def register():
form = RegistrationForm(csrf_enabled=False)
if request.method == 'POST' and form.validate():
user = User()
user.id = form.id.data
user.first_name = form.first_name.data
user.last_name = form.last_name.data
user.password = form.password.data
user.email = form.email.data
user.contact_no = form.contact_no.data
user.branch = form.branch.data
user.profile_type = request.form['profile_type']
profile_pic = request.files['profile_pic']
if profile_pic:
profile_pic_extension = ctrl.get_extension_of_file(profile_pic.filename)
user.profile_pic_extension = profile_pic_extension
file_op.save_profile_pic(profile_pic, user.id)
if user.profile_type != 'P':
ctrl.mkdir_p(os.path.join(app.config['SOLUTION_FILES_DEST'], user.id))
user.is_active = 'Y'
db_session = get_db_session()
insert_to_db(db_session, user)
return render_template('forms/registration_success.html')
return render_template('forms/register.html', form=form)
示例9: sign_up
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def sign_up():
_name = request.form['inputName']
_user_name = request.form['inputUserName']
_password = request.form['inputPassword']
username_list = g.sql_session.query(User.username).all()
if (_user_name,) not in username_list:
user = User()
user.name = _name
user.username = _user_name
user.password = generate_password_hash(_password)
user.type = 1
g.sql_session.add(user)
try:
g.sql_session.commit()
except Exception as e:
flash(str(e))
g.sql_session.rollback()
return redirect(url_for('.show_sign_up'))
session['user'] = _user_name
session['name'] = _name
session['type'] = user.type
return redirect(url_for('.user_home'))
else:
flash("The duplicated username")
return redirect(url_for('.show_sign_up'))
示例10: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def post(self, **kwargs):
role = self.request.get('role', default_value=None)
tenantKey = self.request.get('tenant_key', default_value=None)
unitKey = self.request.get('unit_key', default_value=None)
locationKey = self.request.get('location_key', default_value = None)
username = self.request.get('username', default_value=None)
password = self.request.get('password', default_value=None)
if not all([role,locationKey,username,password]):
self.abort(400)
if role == 'tenant' and not tenantKey:
self.abort(400)
key = None
if role == 'tenant':
key = ndb.Key(Location, int(locationKey),
Unit, int(unitKey),
Tenant, int(tenantKey))
elif role == 'manager':
key = ndb.Key(Location, int(locationKey))
else:
self.response.status = 400
self.response.status_message = 'Role must be either tenant or manager.'
user = User()
try:
user.role = role
user.related_key = key
user.username = username
user.password = password
user.put()
except Exception as msg:
self.abort(500, details=msg)
return
self.response.write(json.dumps(user.to_dict()))
示例11: signup
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def signup():
"""For GET requests, display the login form. For POSTS, login the current user
by processing the form."""
form = SignupForm()
if form.validate_on_submit():
if form.password.data != form.retype_password.data:
flash('Invalid Password')
return render_template("signup.html", form=form)
user = User.query.get(form.email.data)
if user :
flash('User already exists')
return render_template("signup.html", form=form)
user = User()
user.email = form.email.data
user.password = bcrypt.generate_password_hash(form.password.data)
user.first_name = form.first_name.data
user.last_name = form.last_name.data
user.contact_no = form.contact_no.data
# Adding Zero Balance to user
user.balance = Balance()
user.balance.amount = 0.0
db.session.add(user)
db.session.commit()
return redirect(url_for("login"))
return render_template("signup.html", form=form)
示例12: login
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def login():
admin_user = User.query.filter_by(username='admin').first()
if not admin_user:
if request.method == 'POST':
if 'password' in request.form:
password_hash, salt = hash_and_salt(request.form['password'])
new_user = User()
new_user.username = 'admin'
new_user.password = password_hash
new_user.salt = salt
db.session.add(new_user)
db.session.commit()
flash('Password set successfully. Please log in.')
return redirect(url_for('webui.login'))
return render_template('create_password.html')
if request.method == 'POST':
if request.form['password']:
password_hash = hashlib.sha256()
password_hash.update(admin_user.salt + request.form['password'])
if admin_user.password == password_hash.hexdigest():
session['username'] = 'admin'
last_login_time = admin_user.last_login_time
last_login_ip = admin_user.last_login_ip
admin_user.last_login_time = datetime.now()
admin_user.last_login_ip = request.remote_addr
db.session.commit()
flash('Logged in successfully.')
if last_login_ip:
flash('Last login from ' + last_login_ip + ' on ' + last_login_time.strftime("%d/%m/%y %H:%M"))
return redirect(url_for('webui.index'))
else:
flash('Wrong passphrase')
return render_template('login.html')
示例13: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def register():
form = RegistrationForm()
if request.method == 'POST' and form.validate():
user = User()
form.populate_obj(user)
#Set paid explicitly to False
user.paid = False
#Create password hash
user.password = hashlib.md5(bytes(app.config['PASSWORD_SALT'] + user.password, 'utf-8')).hexdigest()
db_session.add(user)
user.create_missing_bets()
send_mail(Message('Hello',
recipients=[user.email]))
send_mail(Message('Neuer Schoselwetter',
body=str(user),
recipients=['[email protected]']))
return render_template('register_success.html')
return render_template('register.html', form=form)
示例14: post
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def post(self):
if self.user:
self.redirect(self.uri_for('www-dashboard-admin'))
return
if self.request.get('email') and self.request.get('first_name') and self.request.get('last_name') and self.request.get('password'):
email = self.request.get('email').strip().lower()
name = self.request.get('first_name') + " " + self.request.get('last_name')
phone = self.request.get('phone')
password = self.request.get('password')
user = User.get_by_id(email)
if user:
self.redirect(self.uri_for('www-register', error="User already exist. Please log in."))
return
user = User(id=email)
user.email = email
user.password = hash_password(email, password)
user.name = name
user.phone = phone
user.put()
self.login(user)
if self.request.get('goto'):
self.redirect(self.request.get('goto'))
else:
self.redirect(self.uri_for('www-dashboard-admin'))
return
else:
self.redirect(self.uri_for('www-register', Error="Please enter the all information required."))
示例15: register
# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import password [as 别名]
def register():
form = RegistrationForm()
if request.method == "GET":
return render_template("register.html", form=form)
elif request.method == "POST":
if form.validate_on_submit():
user = User()
form.populate_obj(user)
# overwrite the old password with a bcrypt-hash
user.password = hash_password(user.password)
try:
user.save()
app.logger.info("New user registered")
flash("User registered successfully", "success")
except IntegrityError as err:
app.logger.warning("Could not register user: {0}".format(err))
flash("User could not be registered, please try again", "error")
except OperationalError as err:
app.logger.warning("MySQL Error: {0!s}".format(err))
flash("{0!s}".format(err))
return redirect(url_for("show_index"))
else:
flash_errors(form)
return render_template("register.html", form=form)