def login(): if g.user is not None and g.user.is_authenticated(): return redirect(url_for('index')) form = LoginForm(csrf_enabled=False) if form.validate_on_submit(): session['remember_me'] = form.remember_me.data # Login from user database user = User.query.filter_by(email=form.email.data, password=hash_password( form.password.data)).first() # print "found ", user # print "email ", form.email.data # print "pwhash ", hash_password(form.password.data) if user: setup_user_session(user, form.remember_me.data) return redirect(request.args.get('next') or url_for('game_list')) else: session['user_id'] = None flash('User not found with that id/password.') # If there were validation errors, flash them to the view flash_errors(form) return render_template("/login.html", title="Login", form=form)
def employees(department_id, vacancy_id): vacancy = Vacancy.query.filter_by(id=vacancy_id).first() if not vacancy: abort(404) form = EmployeeForm(obj=request.form) if form.validate_on_submit(): employee = Employee( name=form.name.data, surname=form.surname.data, position_id=form.position_id.data, email=form.email.data, phone_number=form.phone_number.data, birth_date=form.birth_date.data, department_id=form.department_id.data, vacancy=vacancy ) if form.director.data: update_director(department_id, employee, True) db.session.add(employee) vacancy.is_open = False vacancy.employee = employee vacancy.closing_date = form.start_date.data db.session.commit() update_position(employee, form.position_id.data, form.department_id.data, form.start_date.data) db.session.commit() flash_errors(form) return redirect(url_for('department', department_id=department_id))
def project(): # this function will require testing and implementation fixes form = ProjectForm() if request.method == 'GET': group = load_group(current_user, request.args.get('group')) try: project = group.get_project(request.args.get('project')) except ValueError as e: flash(e) if request.args.get('sub'): sub = project.subs.get(id=request.args.get('sub')) return render_template('project.html', project=project, sub=sub, form=form, processLive=group.process_live()) elif request.method == 'POST': group = load_group(current_user, request.form.get('group')) if request.form.get('action') == 'delete': if request.form.get('sub'): group.delete_project(request.form.get('project'), request.form.get('sub')) else: group.delete_project(request.form.get('project')) return redirect(url_for('account')) if form.validate_on_submit(): if urlparse(form.url.data).path: if request.form.get('sub'): group.update_project(request.form.get('project'), form, request.form.get('sub')) else: group.update_project(request.form.get('project'), form) else: flash('URL is not valid.') else: flash_errors(form) query = {'group': request.form.get('group'), 'project': request.form.get('project')} if request.form.get('sub'): query['sub'] = request.form.get('sub') return redirect('/project' + urlencode(query))
def employee(department_id, employee_id): employee = Employee.query.filter_by(id=employee_id, department_id=department_id).first() if not employee: abort(404) employee_form = EmployeeForm(obj=employee, start_date=employee.vacancy.closing_date) if employee_form.validate_on_submit(): if employee.position_id != employee_form.position_id.data or employee.department_id != employee_form.department_id.data: update_position( employee, employee_form.position_id.data, employee_form.department_id.data, employee_form.start_date.data ) if employee.is_director != employee_form.director.data: update_director(department_id, employee, employee_form.director.data) employee_form.populate_obj(employee) db.session.commit() return redirect(url_for('employee', department_id=employee.department_id, employee_id=employee.id)) flash_errors(employee_form) return render_template('employee.html', employee=employee, employee_form=employee_form)
def register(): """Handle registration request. After successful registration, take user to dashboard immediately. Also start free point credit service immediately by adding entry in `FPCredit""" form = RegisterForm(request.form) if request.method == "POST" and form.validate(): password = generate_password_hash(form.password.data, method="sha256") try: user = User.objects.create(first_name=form.first_name.data, last_name=form.last_name.data, username=form.username.data, password=password) except NotUniqueError as e: key = str(e).split("index: ")[-1].split("_")[0] flash("%s already exists" % key.title()) return render_template("register.html", form=form) # take user in login_user(user) # start free-points credit service if current_user.free_points < int( app.config["FP_CREDIT_MAX_POINTS"]) and FPCredit.objects( user=current_user._get_current_object()).first() is None: fp_credit = FPCredit(user=current_user._get_current_object(), timestamp=datetime.datetime.now()) fp_credit.save() return redirect(url_for("inventory.dashboard")) else: flash_errors(form) return render_template("register.html", form=form)
def add(): if request.method == 'POST': group = load_group(current_user, request.form.get('group')) if request.form.get('parent'): form = SubForm() if form.validate_on_submit(): try: group.add_project(form, parent=request.form.get('parent')) except ValueError as e: flash(e) else: flash_errors(form) else: form = ProjectForm() if form.validate_on_submit(): try: group.add_project(form) except ValueError as e: flash(e) else: flash_errors(form) return redirect(url_for('add')) elif request.method == 'GET': group = load_group(current_user, request.args.get('group')) if request.args.get('parent'): parent = group.projects.get(id=request.args.get('parent')) form = SubForm() return render_template('new_project.html', form=form, group=group, parent=parent) else: form = ProjectForm() return render_template('new_project.html', form=form, group=group)
def profile(): # need to add aws reconfiguration somehow and allow for individual field updates form = RegisterForm() user = {'username': current_user['username'], 'email': current_user['email']} groups = current_user.get_groups(admin=True) if request.method == 'POST': if form.validate_on_submit(): current_user.update_user(request.form) return redirect(url_for('profile')) else: flash_errors(form) return render_template('profile.html', rForm = form, user=user, groups=groups)
def positions(): positions = Position.query.all() form = PositionForm() if form.validate_on_submit(): position = Position(name=form.name.data, description=form.description.data) db.session.add(position) db.session.commit() return redirect(url_for('positions')) flash_errors(form) return render_template('positions.html', form=form, positions=positions)
def register(): form = RegisterForm() if not User.objects(username=form.username.data): if form.validate_on_submit(): user = register_user(form, request) login_user(user) return redirect(url_for('account')) else: flash_errors(form) else: flash('user already exists.') return redirect(url_for('login'))
def departments(): departments = Department.query.all() form = DepartmentForm() if form.validate_on_submit(): department = Department(name=form.name.data, description=form.description.data) db.session.add(department) db.session.commit() return redirect(url_for('departments')) flash_errors(form) return render_template('departments.html', departments=departments, form=form)
def position(position_id): position = Position.query.filter_by(id=position_id).first() if not position: abort(404) form = PositionForm(obj=position) if form.validate_on_submit(): form.populate_obj(position) db.session.commit() return redirect(url_for('position', position_id=position.id)) flash_errors(form) return render_template('position.html', position=position, form=form)
def add_cast(self): # Call our add cast form and flash any errors form = AddCastForm(request.form) # Check if form is submitted and valid if request.method == 'POST' and form.validate(): # Check if a cast with the number specified exists if Bongcasts.query.filter_by(bongcast_number=form.bongcast_number.data).first(): g.error = not None flash('0Bongcast number already exists! Drats...') # If host field is empty, use the logged-in user as host if not len(form.host.data): host = g.user # Else, fetch the specified host else: host = User.query.filter(User.username.like( form.host.data)).first() # Check if host exists with given username if host is None: g.error = not None flash( '0That user doesn\'t exist! Can\'t host if they doesn\'t exist now can they?') # Add the cast, and redirect to it's page if g.error is None: new_cast = Bongcasts( bongcast_number=form.bongcast_number.data, host=host, date=form.date.data, time=form.time.data, desc=form.desc.data, picture_url=form.picture_url.data) try: db.session.add(new_cast) db.session.commit() flash('1Bongcast created! Get to pickin\'!') except Exception: flash('0Something went horribly wrong.') return redirect(url_for('CastView:view_cast', id=new_cast.bongcast_number)) helpers.flash_errors(form) # Render default add cast page return render_template('add_cast.html', title='::Add Cast', form=form)
def login(self): # Redirect to index if user is already logged in. if g.user is not None: return redirect(url_for('GenericView:index')) # Call our login form form = LoginForm(request.form) # Check if form is submitted and valid if request.method == 'POST' and form.validate(): # Fetch user with username provided user = User.query.filter(User.username.like( form.username.data)).first() # Check if username exists if user is None: g.error = not None flash('0No user ' + form.username.data + ' exists') # Check if passwords match elif user.check_password(form.password.data) is False: g.error = not None flash('0Password was incorrect.') # Check for errors if g.error is None: # Store the user's id in the session for look-up in # before_request(), make the user active, and redirect. session['user_id'] = user.id user.active = True try: db.session.commit() except Exception: flash('0Trouble making you act') if request.args.get('next') is None: return redirect(request.referrer) return redirect(request.args.get('next')) helpers.flash_errors(form) # Render default login page return render_template('login.html', title='::Login', form=form)
def vacancies(department_id): department = Department.query.filter_by(id=department_id).first() if not department: abort(404) form = VacancyForm(obj=request.form) if form.validate_on_submit(): vacancy = Vacancy( position_id=form.position_id.data, department_id=department_id, publishment_date=form.publishment_date.data ) db.session.add(vacancy) db.session.commit() flash_errors(form) return redirect(url_for('department', department_id=department_id))
def login(): """Handle login requests""" if current_user.is_authenticated: return redirect(url_for("inventory.dashboard")) form = LoginForm(request.form) if request.method == "POST" and form.validate(): user = User.objects(username=form.username.data).first() if user is None: flash("Invalid username/password") return render_template('login.html', form=form) if check_password_hash(user.password, form.password.data): login_user(user) return redirect(url_for("inventory.dashboard")) return render_template('login.html', form=form) else: flash_errors(form) return render_template('login.html', form=form)
def forgot_password(): forgot_password_form = ForgotPasswordForm() if request.method == 'GET': return render_template('forgot_password.html', forgot_password_form=forgot_password_form) else: if forgot_password_form.validate_on_submit(): user = User.query.filter_by(email=request.form['email']).first() new_password_request = ChangePasswordRequest() user.change_password_request = new_password_request new_password_request.user_id = user.id db.session.add(new_password_request) db.session.commit() flash('Steps to recover your password have been sent to your email', 'success') sendPasswordResetEmail(user.email, user.username, new_password_request.code) return redirect('/login') else: flash_errors(forgot_password_form) return render_template('forgot_password.html', forgot_password_form=forgot_password_form)
def reset_password(code): reset_password_form = ResetPasswordForm() change_password_request = ChangePasswordRequest.query.filter_by(code=code).first() if change_password_request is not None: if request.method == 'GET': return render_template('reset_password.html', reset_password_form=reset_password_form, code=code) else: if reset_password_form.validate_on_submit(): user = User.query.filter_by(id=change_password_request.user_id).first() user.password = str(bcrypt.generate_password_hash(request.form['password'])) db.session.delete(change_password_request) db.session.commit() flash('Password has been reset', 'success') return redirect('/login') else: flash_errors(reset_password_form) return render_template('reset_password.html', reset_password_form=reset_password_form, code=code) else: render_template('404.html')
def login(): login_form = LoginForm() if request.method == 'GET': return render_template('login.html', login_form=login_form) else: if login_form.validate_on_submit(): user = User.query.filter_by(username=request.form['username']).first() if bcrypt.check_password_hash(user.password, request.form['password']): if user.emailverification.verified == True: session['username'] = request.form['username'] return redirect('/') else: flash('Please confirm your email address and try again.', 'error') return render_template('login.html', login_form=login_form) else: flash('The username and password you entered did not match our records. Please double-check and try again.', 'error') return render_template('login.html', login_form=login_form) else: flash_errors(login_form) return render_template('login.html', login_form=login_form)
def vacancy(department_id, vacancy_id): vacancy = Vacancy.query.filter_by(id=vacancy_id, department_id=department_id).first() if not vacancy: abort(404) vacancy_form = VacancyForm(obj=vacancy) employee_form = EmployeeForm(department_id=department_id, position_id=vacancy.position_id) if vacancy_form.validate_on_submit(): vacancy_form.populate_obj(vacancy) db.session.commit() return redirect(url_for('vacancy', department_id=department_id, vacancy_id=vacancy_id)) flash_errors(vacancy_form) return render_template( 'vacancy.html', vacancy=vacancy, vacancy_form=vacancy_form, employee_form=employee_form )
def purchase_points(): """Purchase points. This is stub controller for testing only""" form = PurchasePointsForm() if request.method == "POST" and form.validate(): points = int(form.points.data) current_user.purchased_points += points try: current_user.save() flash("Richie !!! Let's spend some money") trans_pp = Transaction(user=current_user._get_current_object(), trans_type="PP", trans_id=generate_transaction_id(), points=points, description="Purchased %s points" % points, timestamp=datetime.datetime.now()) trans_pp.save() except Exception as e: flash("Please try again after sometime") else: flash_errors(form) return render_template("points.html", user=current_user, form=form)
def add_inventory(): """Add items to purchase. Only admin can update them.""" form = AddInventoryForm() if not current_user.admin: flash("Only admin can update inventory.") return render_template("inventory.html", inventory=Inventory.objects.all(), form=form) if request.method == "POST" and form.validate(): name = form.name.data points = int(form.points.data) if name is not None and points is not None: Inventory.objects(name=name).modify(upsert=True, new=True, set__points=points) else: flash_errors(form) return render_template("inventory.html", inventory=Inventory.objects.all(), form=form)
def register_user(self): # Redirect if already logged in if g.user is not None: return redirect(url_for('GenericView:index')) # Call our register form form = RegistrationForm(request.form) # Check if form is submitted and valid if request.method == 'POST' and form.validate(): # Check to see if username already exists if User.query.filter(User.username.like(form.username.data)).first(): g.error = not None flash('0Username taken, try another!') # Add the new user if there are no errors if g.error is None: new_user = User( username=form.username.data, password=form.password.data) try: db.session.add(new_user) db.session.commit() session['user_id'] = new_user.id flash('1You\'ve been logged in and returned to the index.') return redirect(url_for('GenericView:index')) except Exception: flash('0Couldn\'t create user,') return redirect(url_for('UserView:register')) return redirect(url_for('GenericView:index')) helpers.flash_errors(form) # Render default register page return render_template('register.html', title='::Register', form=form)
def register(): registration_form = RegistrationForm() if request.method == 'GET': return render_template('register.html', registration_form=registration_form) else: if registration_form.validate_on_submit(): new_user = User(request.form['username'], request.form['email'], request.form['password']) new_email_verification = EmailVerification() new_email_verification.user_id = new_user.id new_user.emailverification = new_email_verification db.session.add(new_user) db.session.add(new_email_verification) db.session.commit() sendRegistrationEmail(new_user.email, new_user.username, new_email_verification.code) flash('Successfully registered. Check your email to confirm your account.', 'success') return redirect('/login') else: flash_errors(registration_form) return render_template('register.html', registration_form=registration_form)
def add_pick(self, bongcast_number=None): cast = Bongcasts.query.filter_by( bongcast_number=bongcast_number).first() # Check if the cast exists if cast is None: g.error = not None flash('0That bongcast doesn\'t exist! Curious...') # Call our form, check if it's submitted and valid, and add the pick. test form = AddPickForm(request.form) if request.method == 'POST' and form.validate(): new_pick = Picks(author=g.user, bongcast=cast, artist=form.artist.data, album=form.album.data, song=form.song.data, desc=form.desc.data, waffles_link=form.waffles_link.data, what_link=form.what_link.data, other_link=form.other_link.data, picture_url=form.picture_url.data, date_added=datetime.datetime.now()) try: db.session.add(new_pick) db.session.commit() flash('1Pick Added!') except Exception: flash('0Seems something went wrong...') return redirect(url_for('CastView:view_cast', id=cast.bongcast_number)) helpers.flash_errors(form) # Render default add pick page return render_template('add_pick.html', title='::Add Pick', form=form, cast=cast)
def department(department_id): department = Department.query.filter_by(id=department_id).first() if not department: abort(404) vacancy_form = VacancyForm() department_form = DepartmentForm(obj=department) if department_form.validate_on_submit(): department_form.populate_obj(department) db.session.commit() return redirect(url_for('department', department_id=department.id)) vacancies = Vacancy.query.filter_by(department_id=department_id, is_open=True).all() employees = Employee.query.filter_by(department_id=department_id, is_fired=False).all() flash_errors(department_form) return render_template( 'department.html', department=Department.query.filter_by(id=department_id).first(), vacancy_form=vacancy_form, department_form=department_form, vacancies=vacancies, employees=employees )
def settings(self): user = User.query.get(g.user.id) form = ChangePasswordForm(request.form) if request.method == 'POST' and form.validate(): try: user.set_password(form.password.data) user.active = False db.session.commit() except Exception: flash('0Error setting password') return redirect(url_for('UserView:settings')) flash( '1Password set successfully! Please login with the new password.') session.pop('user_id') return redirect(url_for('UserView:login', next=url_for('UserView:settings'))) helpers.flash_errors(form) return render_template('edit_user.html', title='::Settings', user=user, form=form, )
def purchase_item(): """Purchase items from inventory. Use can buy same item multiple time""" form = PurchaseItemForm() if request.method == "POST" and form.validate(): name = form.name.data inventory = Inventory.objects(name=name).first() if inventory is None: flash("Sorry !!! Item is not available anymore.") return render_template("items.html", inventory=Inventory.objects.all(), form=form) price = inventory.points # discard if not enough balance if price > (current_user.free_points + current_user.purchased_points): flash("Not enough balance") return render_template("items.html", inventory=Inventory.objects.all(), form=form) trans_fp = None trans_pp = None timestamp = datetime.datetime.now() trans_id = generate_transaction_id() user = current_user._get_current_object() if (current_user.free_points - price) >= 0: # use fp current_user.free_points = current_user.free_points - price trans_fp = Transaction(user=user, trans_type="FP", trans_id=trans_id, points=-price, description="Purchased %s" % name, timestamp=timestamp) elif current_user.free_points == 0: # use pp current_user.purchased_points = current_user.purchased_points - price trans_pp = Transaction(user=user, trans_type="PP", trans_id=trans_id, points=-price, description="Purchased %s" % name, timestamp=timestamp) else: # use fp and pp required_pp = current_user.free_points - price current_user.purchased_points = current_user.purchased_points + required_pp trans_fp = Transaction(user=user, trans_type="FP", trans_id=trans_id, points=-current_user.free_points, description="Purchased %s" % name, timestamp=timestamp) current_user.free_points = 0 trans_pp = Transaction(user=user, trans_type="PP", trans_id=trans_id, points=required_pp, description="Purchased %s" % name, timestamp=timestamp) current_user.inventory_list.append(inventory) try: current_user.save() if trans_fp: trans_fp.save() if trans_pp: trans_pp.save() if current_user.free_points < int( app.config["FP_CREDIT_MAX_POINTS"]): if FPCredit.objects(user=user).first() is None: fp_credit = FPCredit(user=user, timestamp=timestamp) fp_credit.save() flash("Congrats !!! You just bought %s !!!" % name) except Exception as e: print(e) flash("Sorry !!! Please try after sometime !!!") return render_template("items.html", inventory=Inventory.objects.all(), form=form) else: flash_errors(form) return render_template("items.html", inventory=Inventory.objects.all(), form=form)