def review(): """Provide the review page.""" form = ReviewForm() if form.validate_on_submit(): review_doc = { getattr(form, key).label.text: value for key, value in form.data.items() if key != 'csrf_token' and value } name, locality = review_doc['Course'].rsplit(', ', 3)[:2] course_id = APP.config['COURSES_COLLECTION'].find_one({ 'Name': name, 'addressLocality': locality })['Course Id'] review_doc['User Id'] = current_user.user_id review_doc['Course Id'] = course_id review_doc['Course Name'] = name review_doc.pop('Course', None) result, error = do_review(review_doc) if not result: return render_template('review.html', form=form, error=error) current_user.update() return redirect(url_for('account')) else: flash_errors(form) return render_template('review.html', form=form)
def follow(user): friend = User.objects(username=user).first() if friend is None: flash("Unable to follow! D:") return redirect(url_for('users.profile', user=user)) current_user.update(add_to_set__following=friend) return redirect(url_for('users.profile', user=user))
def update_profile(): """Provide the update profile page.""" form = UpdateProfileForm() atts = { getattr(form, key).label.text: value for key, value in form.data.items() if key != 'csrf_token' and value } if 'Country' in atts and 'City' not in atts: atts['City'] = form.state.data if form.validate_on_submit(): filled = any([value for value in atts.values()]) if not filled: error = 'Please fill out at least one field before updating.' return render_template('update_profile.html', form=form, error=error) check_location(form) message = 'You have successfully updated your profile.' result, error = do_update(atts) if not result: return render_template('update_profile.html', error=error) current_user.update() return redirect(url_for('account', message=message)) else: error = form.errors return render_template('update_profile.html', form=form, error=error)
def change_username(): um = current_app.kuser_manager form = um.change_username_form(request.form) if form.validate_on_submit(): current_user.username = form.username.data current_user.update() return redirect(url_for(um.after_change_username_endpoint))
def change_password(): """ On GET: display change password page On POST: accepting old and new password and display the flash message. :return: """ if request.method == 'GET': return render_template('profile/change_password.html') else: old_passwd = request.form['old_pwd'] new_passwd = request.form['new_pwd'] retype_passwd = request.form['retype_pwd'] if old_passwd == new_passwd: flash('Old and New password can not same', category="error") elif new_passwd != retype_passwd: flash('New and Retype password must be same', category="error") elif old_passwd != new_passwd and new_passwd == retype_passwd: if check_password(current_user.password, old_passwd): hash_new_pwd = generate_password(new_passwd) current_user.update(commit=True, password=hash_new_pwd) flash('your password change successfully') return redirect( request.args.get('next') or url_for('dashboard.dashboard')) else: flash('Old password is not correct', category="error") else: flash('Please contact administrator', category="error") return render_template('profile/change_password.html')
def unfollow(user): enemy = User.objects(username=user).first() if enemy is None: flash("Unable to unfollow! D:") return redirect(url_for('users.profile', user=user)) current_user.update(pull__following=enemy) return redirect(url_for('users.profile', user=user))
def index(): account_form = AccountForm() if account_form.validate_on_submit(): email_changed = account_form.email.data != current_user.email current_user.update({ "name": account_form.name.data, "email": account_form.email.data, "email_verified_at": None if email_changed else current_user.email_verified_at, "confirmation_token": generate_random_str(40) if email_changed else None }) flash("Votre compte a été mis à jour avec succès", "success") if email_changed: flash( "Your account has been disabled, you must validate your email", "warning") send_validation_email(current_user) return redirect(url_for("settings.index")) account_form.name.data = current_user.name account_form.email.data = current_user.email return render_template("settings/index.html", form=account_form)
def change_info(): info_form = ChangeinfoForm() passwd_form = EditPasswordForm() summary_form = SummaryForm() pay_form = PayForm() if request.method == 'POST': if info_form.validate_on_submit(): old_email = current_user.email current_user.update(username=info_form.username.data, email=info_form.email.data, phone=info_form.phone.data, unit=info_form.unit.data) if info_form.email.data != old_email: token = current_user.generate_confirmation_token() send_mail(info_form.email.data, 'Confirm Your Account', 'auth/confirm', user=current_user, token=token) flash(u'似乎您已经改变邮箱地址,一封新的确认邮件已经发送到您的新邮箱地址请注意查收.', 'success') flash('hi {}, 已经更新邮箱地址.'.format(info_form.username.data), 'success') return redirect(url_for('users.members')) flash_errors(info_form) return render_template('user/update.html', info_form=info_form, passwd_form=passwd_form, summary_form=summary_form, pay_form=pay_form)
def change_to_fav(): if current_user.is_authenticated: print(f"User is authenticated\n", file=sys.stdout) if request.method == "POST": response_text = "subscribed" snack_id = request.form["snack_id"] try: if snack_id not in current_user.wish_list: current_user.update(add_to_set__wish_list=snack_id) else: current_user.update(pull__wish_list=snack_id) response_text = "unsubscribed" except Exception as e: raise Exception( f"Error {e}. \n Couldn't change {snack_id} in wishlist ") print(f"Changed this snack in favourites/watchlist: {snack_id}\n", file=sys.stdout) response = make_response(json.dumps(response_text)) response.status_code = 200 print(f"{response}\n", file=sys.stdout) return response else: return redirect(url_for('index')) else: return redirect(url_for('index'))
def setting(path): form = None if path == "profile": form = UserInfoForm() elif path == "message": pass elif path == "account": form = UserPassEditForm() elif path == "delete": form = DeleteUserForm() else: abort(404) if form and form.validate_on_submit(): if path == "profile": current_user.email = form.email.data current_user.update() elif path == "message": pass elif path == "account": current_user.update_password(form.new_password.data) logout_user() return redirect(url_for("view.login")) elif path == "delete": current_user.delete() return redirect(url_for("view.home")) if path == "profile": form.username.data = current_user.username form.email.data = current_user.email return render_template("setting/{}.html".format(path), form=form)
def edit_profile(): """View function that renders the page to allow a user to update their contact information""" admin_route = False upload_image_form = UploadImageForm() upload_image_form.image.errors = session.pop("image_form_errors", []) remove_image_form = RemoveImageForm() profile_form = EditProfileForm(current_user) if profile_form.validate_on_submit(): current_user.update(**profile_form.data) db.session.add(current_user._get_current_object()) db.session.commit() flash("Your profile information has been successfully updated.", "success") return redirect(url_for("users.edit_profile")) profile_form.populate(**current_user.to_dict()) return render_template( "users/edit_profile.html", profile_form=profile_form, upload_image_form=upload_image_form, remove_image_form=remove_image_form, user=current_user, admin_route=admin_route, profile_photo=current_user.profile_photo, )
def user_get_patch_delete_by_id(id): if current_user is None: db.session.close() abort(404, description="This user does not exist") #Returns the specific User if request.method == 'GET': returnValue = jsonify(current_user.to_dict()) db.session.close() return returnValue, 200 #Updates the user password elif request.method == 'PATCH': obj = request.get_json() if not v.validate(obj): abort(400, description=v.errors) # Note that this update function is specified in models.py if "password" in obj: myPassword = obj.pop('password', None) current_user.set_password(myPassword) current_user.update(obj) db.session.commit() returnValue = jsonify(current_user.to_dict()) db.session.close() return returnValue, 200 #Removes the user and its devices from the database elif request.method == 'DELETE': user = User.query.filter_by(id = current_user.get_id()) for o in user: db.session.delete(o) db.session.flush() db.session.delete(current_user) db.session.commit() db.session.close() return '', 204
def account_github_auth_callback(): state = session.get('github_state') if state is None: flash('Error in authorization process. Try again.') return redirect(url_for('settings.account_details')) session.pop('github_state') received_code = request.args.get('code') received_state = request.args.get('state') if received_state != state: flash('Error in authorization process. Try again.') return redirect(url_for('settings.account_details')) data = { 'client_id': current_app.config['GITHUB_CLIENT_ID'], 'client_secret': current_app.config['GITHUB_CLIENT_SECRET'], 'code': received_code, 'state': state } res = requests.post('https://github.com/login/oauth/access_token', data=data, headers={'Accept': 'application/json'}) gh = Github(res.json()['access_token']) gh_id = gh.get_user().id u = User.query.filter_by(github_id=gh_id).first() if u is not None: flash('GitHub account already associated with a user') return redirect(url_for('settings.account_details')) current_user.update(github_id=gh_id) return redirect(url_for('settings.account_details'))
def perfil(): """Pagina do Perfil do Usuario.""" formulario = UserForm() if request.method == 'GET': formulario.nome.data = current_user.nome formulario.cpf.data = current_user.cpf formulario.email.data = current_user.email formulario.telefone.data = current_user.telefone return render_template('perfil.html', form=formulario), 200 else: if formulario.validate_on_submit(): if current_user.verify_password('senha', formulario.senha.data): try: current_user.nome = formulario.nome.data current_user.email = formulario.email.data current_user.telefone = formulario.telefone.data if formulario.novaSenha.data == formulario\ .confNovaSenha.data: if (not (formulario.novaSenha.data == '')): current_user.senha = formulario.novaSenha.data current_user.criptografar_senha('senha') else: return jsonify({'msg': 'Senhas Diferentes!'}) current_user.update('id', current_user.id) return jsonify({ 'status': 'ok', 'msg': 'Atualizado Com Sucesso!' }) except Exception: return jsonify({'msg': 'Erro ao Atualizao'}) else: return jsonify({'msg': 'Senha Errada!'}) else: return jsonify({'msg': 'Erro!'})
def vote(): now = datetime.now() """Present vote page.""" form = VotationForm(request.form) print(current_user.id) if form.validate_on_submit(): if form.deacons.data: for deacon in form.deacons.data: print(current_user.id, deacon, now) Vote.create( voter_id = current_user.id, type = "deacon", name = deacon, #check how to access id of deacon date = now ) if form.elders.data: for elder in form.elders.data: print(current_user.id, elder, now) Vote.create( voter_id = current_user.id, type = "elder", name = elder, #check how to access id of elder date = now ) if (form.deacons.data) or (form.elders.data): current_user.update(voted = True) flash("Thank you for voting.", "success") return redirect(url_for("election.submit")) else: flash_errors(form) return render_template("elections/vote.html", form=form)
def account(): form = AccountUpdateForm() if form.validate_on_submit(): if form.picture.data: if current_user.img_id != 1: UserImage().delete(img_id=current_user.img_id) current_user.img_id = create_new_image(form.picture.data, "User") current_user.username = form.username.data current_user.name = form.name.data current_user.email = form.email.data current_user.birthdate = form.birthdate.data current_user.update() flash(f'Account updated!', 'alert alert-success alert-dismissible fade show') return redirect(url_for('account')) elif request.method == 'GET': form.username.data = current_user.username form.name.data = current_user.name form.email.data = current_user.email form.birthdate.data = current_user.birthdate image_path = url_for('get_user_image', img_id=current_user.img_id) return render_template('account.html', title='Account', image_path=image_path, form=form)
def register_set_role(): if current_user.roles: flash('您已经设置过角色信息,请勿在设置。') return redirect(url_for('public.home')) form = RegisterRoleForm() if request.method=='GET': return dict(form=form) else: if not form.validate_on_submit(): flash_errors(form) return dict(form=form) role = Role.query.filter_by(name='Others').first() current_user.update( name = form.name.data, phone = form.phone.data, id_number = form.id_number.data, address = form.address.data, car_number = form.car_number.data, q_number = "Q"+str(current_user.id), roles=role ) flash('您的信息已提交') return redirect(url_for('public.home'))
def upload_summary(): info_form = ChangeinfoForm() passwd_form = EditPasswordForm() summary_form = SummaryForm() pay_form = PayForm() if request.method == 'POST': if 'summary' not in request.files or request.files[ 'summary'].filename == '': flash(u'当前没有选取到您上传的摘要', 'danger') return redirect(url_for('users.update')) file = request.files['summary'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) saveFilename = '_'.join([current_user.username, filename]) current_user.update(filename=saveFilename) file.save(os.path.join(Config.UPLOAD_FOLDER, saveFilename)) flash(u'摘要上传成功', 'success') redirect(url_for('users.members')) else: flash(u'上传文件格式不正确', 'danger') redirect(url_for('users.update')) return render_template('user/update.html', info_form=info_form, passwd_form=passwd_form, summary_form=summary_form, pay_form=pay_form)
def create_brand(): if current_user.is_authenticated and hasattr(current_user, 'company_name'): print(f"User is authenticated", file=sys.stdout) create_brand_form = CreateBrandForm(request.form) if request.method == "POST": snack_brand = create_brand_form.add_snack_brand.data try: current_user.update( add_to_set__company_snackbrands=snack_brand) except Exception as e: raise Exception( f"Error {e}. \n Couldn't add {snack_brand},\n with following creation form: {create_brand_form}" ) return redirect(url_for('account')) else: # For frontend purposes context_dict = { "title": "Add Brand", "form": create_brand_form, "user": current_user } return render_template("create_brand.html", **context_dict) else: # Go back to index if not authenticated or if user is not company user return redirect(url_for('index'))
def unsubscribe(course_id): course = LightCourse.query.get(course_id) flash(notify_warning('Unsubscribed from {}!'.format(course.name))) current_user.light_courses.remove(course) current_user.update() return redirect(url_for('course.mycourses'))
def profile_settings(category: str) -> Union[str, Response]: if category not in ['profile', 'display'] and not is_authorized('contributor'): abort(403) # pragma: no cover form = getattr( importlib.import_module('openatlas.forms.setting'), uc_first(category) + 'Form')() if form.validate_on_submit(): for field in form: if field.type in ['CSRFTokenField', 'HiddenField', 'SubmitField']: continue if field.name == 'name': current_user.real_name = field.data elif field.name == 'email': current_user.email = field.data else: current_user.settings[field.name] = field.data Transaction.begin() try: current_user.update() current_user.update_settings(form) Transaction.commit() session['language'] = current_user.settings['language'] flash(_('info update'), 'info') except Exception as e: # pragma: no cover Transaction.rollback() logger.log('error', 'database', 'transaction failed', e) flash(_('error transaction'), 'error') return redirect(url_for('profile_index') + '#tab-' + category) set_form_settings(form, True) return render_template( 'display_form.html', form=form, manual_page='profile', title=_('profile'), crumbs=[[_('profile'), url_for('profile_index') + '#tab-' + category], _(category)])
def export_worklogs(self): """ Exports worklogs to target resource """ target_name = self.target.connector_type.name target_connector = ConnectorManager.create_connector( target_name, server=self.target.server, api_token=self.target.api_token, login=self.target.login, password=self.target.password) # Get all valid worklogs from this synchronization worklogs_to_upload = Worklog.query \ .filter( Worklog.synchronization_id == self.get_id(), Worklog.is_valid, Worklog.parent_id == None # NOQA ) try: target_connector.export_worklogs(worklogs_to_upload) except ExportException as err: # just delete worklogs # TODO: implement better solution worklogs_to_delete = worklogs_to_upload[err.index:] for w in worklogs_to_delete: Worklog.delete(w.get_id()) db.session.commit() raise err current_user.update(date_last_sync=datetime.utcnow()) self.complete()
def record_interest(event_id): event = Event.objects.get(id=event_id) if event in current_user.events: current_user.update(pull_all__events=[event]) else: current_user.update(add_to_set__events=[event]) return redirect(request.referrer)
def preferences(): if request.method == 'GET': all_categories = Category.objects category_ids = [ str(category.id) for category in current_user.categories ] return render_template( 'preferences.html', name=current_user.email, categories=[category.to_json() for category in all_categories], user_category_ids=category_ids) form_string = request.form['categories'] if form_string != '': raw_category_ids = form_string.split(',') category_ids = [ ObjectId(category_id) for category_id in raw_category_ids ] current_user.update(categories=category_ids) else: current_user.update(categories=None) # user = User.objects(id=current_user.id).first() # recommender.set_recommended_events(user.id) return redirect(url_for('web.dashboard'))
def add_todolist(): form = TodoListForm(todo=request.form.get('title')) if form.validate(): todolist = Models.TodoList(title=form.title.data, creator=current_user.id).save() current_user.update(push__todolists=todolist) return redirect(url_for('todo.todolist', id=todolist.id)) return redirect(url_for('todo.index'))
def edit_user_event(event_id): event_id = ObjectId(event_id) if request.method == 'POST': current_user.update(add_to_set__events=event_id) else: current_user.update(pull__events=event_id) return jsonify({})
def address_del(addr_id): address = Models.Address.objects(id=addr_id).first_or_404() if address not in current_user.addresses: return jsonify(message='Failed', error=_('invalid address id for current user')) current_user.update(pull__addresses=address) address.delete() return jsonify(message='OK')
def set_password(): form = ChangePasswordForm(request.form) if form.validate_on_submit(): current_user.update(password=form.password.data) flash(lazy_gettext("You have changed password."), "success") else: flash_errors(form) return redirect(url_for("account.index"))
def resend_activation_email(): if current_user.is_verified(): flash("This account has already been activated.", 'warning') else: current_user.update(activate_token=generate_random_token()) send_activation(current_user) flash('Activation email sent! Please check your inbox', 'info') return redirect(url_for('public.index'))
def update_user(): form = {k: request.form[k].strip() for k in request.form} current_user.update( username=(None if 'username' not in form else form['username']), password=(None if 'password' not in form else form['password']), name=(None if 'name' not in form else form['name']), info=(None if 'info' not in form else form['info'])) db.session.commit() return Validity(True).get_resp()
def change_fraternity(frat_id): """Change the user's fraternity, but only if they're an admin.""" if not current_user.is_admin: raise Forbidden() frat = Fraternity.find_or_404(frat_id) current_user.update(fraternity=frat) redirect_url = request.referrer if request.referrer else \ url_for('parties.parties') return redirect(redirect_url)
def profile_password(): form = PasswordForm() if form.validate_on_submit(): current_user.password = bcrypt.hashpw(form.password.data.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') current_user.update() flash(_('info password updated'), 'info') return redirect(url_for('profile_index')) return render_template('profile/password.html', form=form)
def account_settings(self): self.meta_tags(title="Account Settings") if request.method == "POST": action = request.form.get("action") try: action = action.lower() # if action == "info": first_name = request.form.get("first_name").strip() last_name = request.form.get("last_name", "").strip() data = { "first_name": first_name, "last_name": last_name } current_user.update(**data) flash("Account info updated successfully!", "success") # elif action == "login": confirm_password = request.form.get("confirm-password").strip() if current_user.password_matched(confirm_password): self.change_login_handler() flash("Login Info updated successfully!", "success") else: flash("Invalid password", "error") # elif action == "password": confirm_password = request.form.get("confirm-password").strip() if current_user.password_matched(confirm_password): self.change_password_handler() flash("Password updated successfully!", "success") else: flash("Invalid password", "error") elif action == "profile-photo": file = request.files.get("file") if file: prefix = "profile-photos/%s/" % current_user.id extensions = ["jpg", "jpeg", "png", "gif"] my_photo = storage.upload(file, prefix=prefix, allowed_extensions=extensions) if my_photo: url = my_photo.url current_user.update(profile_image_url=url) flash("Profile Image updated successfully!", "success") else: raise UserError("Invalid action") except Exception as e: flash(e.message, "error") return redirect(url_for(endpoint_namespace % "account_settings")) return {}
def profile_edit(): form = UserEditForm() if form.validate_on_submit(): current_user.update( contact_name=form.contact_name.data, contact_email=form.contact_email.data, ) flash.success("Profile updated.") return redirect(url_for('.profile')) else: form.contact_name.data = current_user.contact_name form.contact_email.data = current_user.contact_email return render_template('users/profile-edit.html', form=form)
def edit(): form = ProfileEditForm() if form.validate_on_submit(): current_user.update(display_name=form.display_name.data, email=form.email.data, show_gravatar=form.show_gravatar.data) flash(gettext("Profile updated."), 'success') return redirect(url_for('user.reviews', user_id=current_user.id)) else: form.display_name.data = current_user.display_name form.email.data = current_user.email form.show_gravatar.data = current_user.show_gravatar return render_template('profile/edit.html', form=form)
def profile_update(): form = ProfileForm() if form.validate_on_submit(): current_user.real_name = form.name.data current_user.email = form.email.data current_user.settings['show_email'] = form.show_email.data current_user.settings['newsletter'] = form.newsletter.data g.cursor.execute('BEGIN') try: current_user.update() current_user.update_settings() g.cursor.execute('COMMIT') flash(_('info update'), 'info') except Exception as e: # pragma: no cover g.cursor.execute('ROLLBACK') logger.log('error', 'database', 'transaction failed', e) flash(_('error transaction'), 'error') return redirect(url_for('profile_index')) form.name.data = current_user.real_name form.email.data = current_user.email form.show_email.data = current_user.settings['show_email'] form.newsletter.data = current_user.settings['newsletter'] return render_template('profile/update.html', form=form)
def questions(): try: form = QuestionsForm(request.form) # allows us to render the form if request.method == "POST" and form.validate(): # if user hit submit button and form is complete restrictions = form.restrictions.data allergies = form.allergies.data zipcode = form.zipcode.data time = form.time.data meal = form.meal.data try: current_user.update({"restrictions": restrictions, "allergies": allergies, "zipcode": zipcode, "time": time, "meal": meal}) flash("Thank you!") return redirect(url_for('search')) # if registration was successful, except Exception as e: return(str(e)) return render_template('questions.html', form=form) except Exception as e: return(str(e))