我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用model.User()。
def user_list(): args = parser.parse({ 'email': wf.Str(missing=None), 'permissions': wf.DelimitedList(wf.Str(), delimiter=',', missing=[]), }) user_dbs, cursors = model.User.get_dbs( email=args['email'], prev_cursor=True, ) permissions = list(UserUpdateForm._permission_choices) permissions += args['permissions'] return flask.render_template( 'user/user_list.html', html_class='user-list', title='User List', user_dbs=user_dbs, next_url=util.generate_next_url(cursors['next']), prev_url=util.generate_next_url(cursors['prev']), api_url=flask.url_for('api.admin.user.list'), permissions=sorted(set(permissions)), ) ############################################################################### # User Update ###############################################################################
def user_profile(user_id): """Show user profile""" user_info = User.query.filter_by(user_id=user_id).first() account_created = user_info.account_created account_created = str(account_created)[:11] system_info = UserSystem.query.filter_by(user_id=user_id).all() rating_info = (db.session.query(Game.name, Rating.score, Game.game_id) .join(Rating).filter(Rating.user_id==user_id) .all()) num_games = (db.session.query(func.count(Rating.user_id)) .filter(Rating.user_id == user_id) .first()) num_games = int(num_games[0]) return render_template("user_profile.html", user_info=user_info, system_info=system_info, rating_info=rating_info, account_created=account_created, user_id=user_id, num_games=num_games)
def login(): """Attempt to log the user in""" email = request.form.get("email") password = request.form.get("password") existing_email = User.query.filter_by(email=email).first() if existing_email is not None and existing_email.password == password: # add user to session session["user_id"] = existing_email.user_id flash("Successfully logged in!") return redirect('/homepage') elif existing_email is None: flash("Incorrect email.") return redirect('/') else: flash("Incorrect password.") return redirect('/')
def before_request(self,*args): """Verfies that the API is Vaild for the correct user and the IP address hasn't changed since log in""" signer = TimestampSigner(SECRET_KEY) api_key = request.headers['API_KEY'] Client_id = request.headers['Client_ID'] ip_address = request.remote_addr user = User.query.filter_by(Client_id=Client_id).first() if user == None: return make_response(jsonify({'Failure': 'Invaild User'}), 400) if api_key != user.api_key: return make_response(jsonify({'Failure': 'Incorrect API Key'}), 400) if ip_address != user.current_login_ip: return make_response(jsonify({'Failure': 'Incorrect IP for Client, Please Re-login in'}), 400) try: signer.unsign(api_key, max_age=86164) except: return make_response(jsonify({'Failure': 'Invaild API Key, please request new API Key'}), 400)
def login_processed(): """Processes old users.""" email = request.form["email"] password = request.form["password"] user = User.query.filter_by(email=email).first() if not user: flash("Oops, you don't exist yet! Please sign up.") return redirect('/enter_phone') if user.password != password: flash("The password you have given is incorrect.") return redirect('/login') session['id'] = user.user_id flash("Welcome back, %s. You have successfully logged in." % user.first_name) return redirect("/")
def sumbit_login(): """checks for login info to log in and if not present, creates user""" username = request.form.get("username") password = request.form.get("password") user = User.query.filter_by(email=username).first() # if user already exists, checks password and logs them in if correct. If not, prompts # for password again if user: if user.password == password: session['user'] = user.user_id flash("You are now logged in") return redirect('/users/' + str(user.user_id)) else: flash("Password incorrect") return redirect('/login') else: #instantiates new user and passes user_id to session user = User(email=username, password=password) db.session.add(user) db.session.commit() session['user'] = user.user_id flash("Your account has been created") return redirect('/')
def submit_login(): """Logs in user or directs to sign up form if no email""" email = request.form.get("email") password = request.form.get("password") user = User.query.filter_by(email=email).first() # if user already exists, checks password and logs them in if correct. If not, prompts # for password again if user: if user.verify_password(password): session['user'] = user.user_id flash("You are now logged in") return redirect('/') else: flash("Password incorrect") return redirect('/') else: return render_template('sign_up_form.html', email=email, password=password)
def invite_user(): """Allows user to invite other member to group by email""" email = request.form.get('invite') user = User.query.filter_by(email=email).first() group_id = request.form.get('group_id') group = Group.query.filter_by(group_id=group_id).first() if user: user_search = UserGroup.query.filter_by(user_id=user.user_id, group_id=group_id).first() if user_search: flash("User is already in this group") else: new_user = UserGroup(user_id=user.user_id, group_id=group_id) db.session.add(new_user) db.session.commit() flash("Added new user " + email + " to " + group.group_name) else: flash("No such user") return redirect('/')
def get_user_info(user_id): """Retrieves user data based on the user ID.""" user = User.query.get(user_id) user = user.__dict__ if '_sa_instance_state' in user: del user['_sa_instance_state'] user_plants = get_user_plants(user_id) user['plants'] = user_plants # adds a key to dictionary that has a value of true/false depending on # whether reminder was set for plant in user['plants']: user['plants'][plant]['reminder_status'] = str(get_reminder_status(user['user_id'], user['plants'][plant]['plant_id'])) return jsonify(user)
def process_login(): """Processes user input and either logs user in if input is in database""" # gets the user input from the username field and looks it up in the database username = request.form.get('username') user = User.query.filter_by(username=username).first() # if username entered exists in db, gets the password entered and compares # it to the one in the database if user: # if password is correct, adds user to the current session and redirects to home page if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user.password.encode('utf-8')).decode() == user.password: session['logged_in'] = user.user_id print 'logged in' return jsonify(session) # if password is incorrect, redirects to login page else: return 'error' # if username is not in the database, redirects to the registration form else: return 'error'
def update_user(): """Saves updated user info.""" user_id = request.form.get('id') user_to_update = User.query.get(int(user_id)) if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user_to_update.password.encode('utf-8')).decode() == user_to_update.password: if request.form.get('email'): user_to_update.email = request.form.get('email') if request.form.get('phone'): user_to_update.phone = request.form.get('phone') else: return "bad password" db.session.commit() return "ok" # PlantUser Routes *********************************
def add_reminder(): """Adds a watering reminder for a particular PlantUser""" user_id = int(request.form.getlist('user_id')[0].encode('utf-8')) if User.query.get(user_id).phone: plant_id = int(request.form.getlist('plant_id')[0].encode('utf-8')) days = request.form.getlist('days')[0].encode('utf-8') plant_user = PlantUser.query.filter(PlantUser.user_id == user_id, PlantUser.plant_id == plant_id).first() plant_user.watering_schedule = days db.session.commit() return 'ok' else: return 'phone number missing'
def create_user_db(auth_id, name, username, email='', verified=False, password='', **props): """Saves new user into datastore""" if password: password = util.password_hash(password) email = email.lower() user_db = model.User( name=name, email=email, username=username, auth_ids=[auth_id] if auth_id else [], verified=verified, token=util.uuid(), password_hash=password, **props ) user_db.put() task.new_user_notification(user_db) return user_db
def create_or_get_user_db(auth_id, name, username, email='', **kwargs): """This function will first lookup if user with given email already exists. If yes then it will append auth_id for his record and saves it. If not we'll make sure to find unique username for this user (for the case of signing up via social account) and then store it into datastore""" user_db = model.User.get_by('email', email.lower()) if user_db: user_db.auth_ids.append(auth_id) user_db.put() return user_db if isinstance(username, str): username = username.decode('utf-8') username = unidecode.unidecode(username.split('@')[0].lower()).strip() username = re.sub(r'[\W_]+', '.', username) new_username = username suffix = 1 while not model.User.is_username_available(new_username): new_username = '%s%d' % (username, suffix) suffix += 1 return create_user_db(auth_id, name, new_username, email=email, **kwargs)
def seed_user(profile, user_id): first_name = profile['names'][0].get("givenName") last_name = profile['names'][0].get("familyName") user_exists = User.query.get(user_id) if user_exists is None: user = User(user_id=user_id, first_name=first_name, last_name=last_name) db.session.add(user) db.session.commit() return user_id
def get_master_recoverinfo(): username = request.form.get("username",None) if username is None: return json.dumps({'success':'false', 'message':'username field is required.'}) else: user = User.query.filter_by(username=username).first() return json.dumps({'success':'true', 'uid':user.id, 'groupname':user.user_group})
def billing_beans(): logger.info("handle request: /billing/beans/") form = request.form owner_name = form.get("owner_name",None) billing = int(form.get("billing",None)) if owner_name is None or billing is None: return json.dumps({'success':'false', 'message':'owner_name and beans fields are required.'}) # update users' tables in database owner = User.query.filter_by(username=owner_name).first() if owner is None: logger.warning("Error!!! Billing User %s doesn't exist!" % (owner_name)) else: #logger.info("Billing User:"+str(owner)) oldbeans = owner.beans owner.beans -= billing #logger.info(str(oldbeans) + " " + str(owner.beans)) if oldbeans > 0 and owner.beans <= 0 or oldbeans >= 100 and owner.beans < 100 or oldbeans >= 500 and owner.beans < 500 or oldbeans >= 1000 and owner.beans < 1000: # send mail to remind users of their beans if their beans decrease to 0,100,500 and 1000 data = {"to_address":owner.e_mail,"username":owner.username,"beans":owner.beans} # request_master("/beans/mail/",data) beansapplicationmgr.send_beans_email(owner.e_mail,owner.username,int(owner.beans)) try: db.session.commit() except Exception as err: db.session.rollback() logger.warning(traceback.format_exc()) logger.warning(err) return json.dumps({'success':'false', 'message':'Fail to wirte to databases.'}) #logger.info("Billing User:"+str(owner)) if owner.beans <= 0: # stop all vcluster of the user if his beans are equal to or lower than 0. logger.info("The beans of User(" + str(owner) + ") are less than or equal to zero, all his or her vclusters will be stopped.") auth_key = env.getenv('AUTH_KEY') form = {'username':owner.username, 'auth_key':auth_key} request_master("/cluster/stopall/",form) return json.dumps({'success':'true'})
def signup(): next_url = util.get_next_url() form = None if config.CONFIG_DB.has_email_authentication: form = form_with_recaptcha(SignUpForm()) save_request_params() if form.validate_on_submit(): user_db = model.User.get_by('email', form.email.data) if user_db: form.email.errors.append('This email is already taken.') if not form.errors: user_db = create_user_db( None, util.create_name_from_email(form.email.data), form.email.data, form.email.data, ) user_db.put() task.activate_user_notification(user_db) cache.bump_auth_attempt() return flask.redirect(flask.url_for('welcome')) if form and form.errors: cache.bump_auth_attempt() title = 'Sign up' if config.CONFIG_DB.has_email_authentication else 'Sign in' return flask.render_template( 'auth/auth.html', title=title, html_class='auth', next_url=next_url, form=form, **urls_for_oauth(next_url) ) ############################################################################### # Sign out stuff ###############################################################################
def form_with_recaptcha(form): should_have_recaptcha = cache.get_auth_attempt() >= config.RECAPTCHA_LIMIT if not (should_have_recaptcha and config.CONFIG_DB.has_recaptcha): del form.recaptcha return form ############################################################################### # User related stuff ###############################################################################
def create_user_db(auth_id, name, username, email='', verified=False, **props): email = email.lower() if email else '' if verified and email: user_dbs, cursors = model.User.get_dbs(email=email, verified=True, limit=2) if len(user_dbs) == 1: user_db = user_dbs[0] user_db.auth_ids.append(auth_id) user_db.put() task.new_user_notification(user_db) return user_db if isinstance(username, str): username = username.decode('utf-8') username = unidecode.unidecode(username.split('@')[0].lower()).strip() username = re.sub(r'[\W_]+', '.', username) new_username = username n = 1 while not model.User.is_username_available(new_username): new_username = '%s%d' % (username, n) n += 1 user_db = model.User( name=name, email=email, username=new_username, auth_ids=[auth_id] if auth_id else [], verified=verified, token=util.uuid(), **props ) user_db.put() task.new_user_notification(user_db) return user_db
def get_user_db_from_email(email, password): user_dbs, cursors = model.User.get_dbs(email=email, active=True, limit=2) if not user_dbs: return None if len(user_dbs) > 1: flask.flash('''We are sorry but it looks like there is a conflict with your account. Our support team is already informed and we will get back to you as soon as possible.''', category='danger') task.email_conflict_notification(email) return False user_db = user_dbs[0] if user_db.password_hash == util.password_hash(user_db, password): return user_db return None
def user_verify(token): user_db = auth.current_user_db() if user_db.token != token: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('profile')) user_db.verified = True user_db.token = util.uuid() user_db.put() flask.flash('Hooray! Your email is now verified.', category='success') return flask.redirect(flask.url_for('profile')) ############################################################################### # User Forgot ###############################################################################
def user_forgot(token=None): if not config.CONFIG_DB.has_email_authentication: flask.abort(418) form = auth.form_with_recaptcha(UserForgotForm(obj=auth.current_user_db())) if form.validate_on_submit(): cache.bump_auth_attempt() email = form.email.data user_dbs, cursors = util.get_dbs( model.User.query(), email=email, active=True, limit=2, ) count = len(user_dbs) if count == 1: task.reset_password_notification(user_dbs[0]) return flask.redirect(flask.url_for('welcome')) elif count == 0: form.email.errors.append('This email was not found') elif count == 2: task.email_conflict_notification(email) form.email.errors.append( '''We are sorry but it looks like there is a conflict with your account. Our support team is already informed and we will get back to you as soon as possible.''' ) if form.errors: cache.bump_auth_attempt() return flask.render_template( 'user/user_forgot.html', title='Forgot Password?', html_class='user-forgot', form=form, ) ############################################################################### # User Reset ###############################################################################
def user_reset(token=None): user_db = model.User.get_by('token', token) if not user_db: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('welcome')) if auth.is_logged_in(): login.logout_user() return flask.redirect(flask.request.path) form = UserResetForm() if form.validate_on_submit(): user_db.password_hash = util.password_hash(user_db, form.new_password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() flask.flash('Your password was changed succesfully.', category='success') return auth.signin_user_db(user_db) return flask.render_template( 'user/user_reset.html', title='Reset Password', html_class='user-reset', form=form, user_db=user_db, ) ############################################################################### # User Activate ###############################################################################
def user_activate(token): if auth.is_logged_in(): login.logout_user() return flask.redirect(flask.request.path) user_db = model.User.get_by('token', token) if not user_db: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('welcome')) form = UserActivateForm(obj=user_db) if form.validate_on_submit(): form.populate_obj(user_db) user_db.password_hash = util.password_hash(user_db, form.password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() return auth.signin_user_db(user_db) return flask.render_template( 'user/user_activate.html', title='Activate Account', html_class='user-activate', user_db=user_db, form=form, ) ############################################################################### # User Merge ###############################################################################
def register_process(): """Get information from registration form.""" username = request.form.get("username") email = request.form.get("email") password = request.form.get("password") systems = request.form.getlist("systems") account_created = datetime.now() existing_username = User.query.filter_by(username=username).first() existing_email = User.query.filter_by(email=email).first() # check if the username is in use if existing_username is None and existing_email is None: #check if the email is in use new_user = User(username=username, email=email, password=password, account_created=account_created) db.session.add(new_user) db.session.commit() get_user_rating(games) for system in systems: # add each system to the database for the specific user system_id = db.session.query(System.system_id).filter(System.name==system).first() new_user_system = UserSystem(user_id=new_user.user_id, system_id=system_id) db.session.add(new_user_system) db.session.commit() flash("Successfully registered " + username + "!") return redirect("/") else: flash("Username or email already in use") # TODO probably handle this in AJAX on the form and be more specific # as to whether it was the username or email that failed return redirect("/")
def get_user_db_from_email(email, password): user_dbs, cursors = model.User.get_dbs(email=email, active=True, limit=2) if not user_dbs: return None if len(user_dbs) > 1: flask.flash('''We are sorry but it looks like there is a conflict with your account. Our support team has been informed and we will get back to you as soon as possible.''', category='danger') task.email_conflict_notification(email) return False user_db = user_dbs[0] if user_db.password_hash == util.password_hash(user_db, password): return user_db return None
def user_reset(token=None): user_db = model.User.get_by('token', token) if not user_db: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('welcome')) if auth.is_logged_in(): flask_login.logout_user() return flask.redirect(flask.request.path) form = UserResetForm() if form.validate_on_submit(): user_db.password_hash = util.password_hash(user_db, form.new_password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() flask.flash('Your password was changed succesfully.', category='success') return auth.signin_user_db(user_db) return flask.render_template( 'user/user_reset.html', title='Reset Password', html_class='user-reset', form=form, user_db=user_db, ) ############################################################################### # User Activate ###############################################################################
def user_activate(token): if auth.is_logged_in(): flask_login.logout_user() return flask.redirect(flask.request.path) user_db = model.User.get_by('token', token) if not user_db: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('welcome')) form = UserActivateForm(obj=user_db) if form.validate_on_submit(): form.populate_obj(user_db) user_db.password_hash = util.password_hash(user_db, form.password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() return auth.signin_user_db(user_db) return flask.render_template( 'user/user_activate.html', title='Activate Account', html_class='user-activate', user_db=user_db, form=form, ) ############################################################################### # User Merge ###############################################################################
def signup_processed(): """Processes new users.""" user_id = request.form["user_id"] phone_number = request.form["phone_number"] first_name = request.form["first_name"] last_name = request.form["last_name"] email = request.form["email"] password = request.form["password"] # checking to see if the email already exists in the db. If not, a new account is created. user = User.query.filter_by(email=email).first() if user: flash("Oops, your email already exists! Please log in.") return redirect("/login") else: new_user = User(user_id=user_id, first_name=first_name, last_name=last_name, email=email, password=password) # used in test to update phone number Phone.query.filter_by(id=user_id).update({"phone": phone_number}) db.session.add(new_user) db.session.commit() session['id'] = new_user.user_id user = get_specific_user(email) flash("Welcome to Fork&Spoon, %s. You have successfully logged in." % user.first_name) return render_template("welcomepage.html")
def profile(id): """Displays/saves user's profile""" user = User.query.filter_by(user_id=session['id']).first() return render_template("profile.html", user=user)
def edit_profile(): """Displays/saves user's profile""" description = request.form.get("description") User.query.filter_by(user_id=session['id']).update({"description": description}) db.session.commit() return "You have successfully updated your profile."
def event_confirmed(): """Confirmation page after creating an event.""" # instantiating event and single attendees into our tables date = request.form['date'] start_time = request.form['start_time'] end_time = request.form['end_time'] date_start_time = date + " " + start_time date_end_time = date + " " + end_time start_datetime = datetime.strptime(date_start_time, "%m/%d/%Y %H:%M") end_datetime = datetime.strptime(date_end_time, "%m/%d/%Y %H:%M") business_url = request.form['business_url'] business = get_specific_business(business_url) # getting category id and business id to instantiate event category_id = request.form['category_id'] business_id = business.id # grabbing the current user info to instantiate our event. user = User.query.filter_by(user_id=session['id']).first() event = Event(start_time=start_datetime, end_time=end_datetime, category_id=category_id, business_id=business_id, user_id=user.user_id) db.session.add(event) db.session.commit() event = get_specific_event(business_id) event_id = event.id # instantiating an attendee row so that it shows the creater is the owner/is attending. If there is a match, we can query through it later and two rows will show up by filtering the specific event_id. If not, only one attendee will appear and show the event is not matched. attendee = Attendee(user_id=user.user_id, event_id=event_id, is_owner=True) db.session.add(attendee) db.session.commit() return render_template("confirmation.html", event=event)
def available_events(): """Displaying all events that are available, not including the current user's created events.""" pacific = timezone('US/Pacific') time_now = datetime.now(tz=pacific) user = User.query.filter_by(user_id=session['id']).first() # The past is 'less' than the present, and we want to show all future (greater) events. events = Event.query.filter(Event.is_matched == False, Event.user_id != user.user_id, Event.end_time > time_now).all() return render_template("find_events.html", events=events)