def change_password(self): """ Changes the password .. tip:: On changing the password, the user is logged out and the login page is thrown at the user """ form = ChangePasswordForm(request.form) if request.method == "POST" and form.validate(): user = request.nereid_user # Confirm the current password password = form.old_password.data password += user.salt or "" if isinstance(password, unicode): password = password.encode("utf-8") password_sha = hashlib.sha1(password).hexdigest() if password_sha == user.password: self.write(request.nereid_user.id, {"password": form.password.data}) flash(_("Your password has been successfully changed! " "Please login again")) session.pop("user") return redirect(url_for("nereid.website.login")) else: flash(_("The current password you entered is invalid")) return render_template("change-password.jinja", change_password_form=form)
def github_authorized_login(cls): """ Authorized handler to which github will redirect the user to after the login attempt is made. """ github = request.nereid_website.get_github_oauth_client() if github is None: return redirect(request.referrer or url_for('nereid.website.login')) try: # The response is an oauth2 response with code. But Github API # requires the if 'oauth_verifier' in request.args: data = github.handle_oauth1_response() elif 'code' in request.args: data = github.handle_oauth2_response() else: data = github.handle_unknown_response() github.free_request_token() except Exception, exc: current_app.logger.error("Github login failed %s" % exc) flash(_("We cannot talk to github at this time. Please try again")) return redirect(request.referrer or url_for('nereid.website.login'))
def edit_post(self): """ Edit an existing post """ if self.nereid_user != request.nereid_user: abort(404) # Search for a post with same uri post_form = BlogPostForm(request.form, obj=self) with Transaction().set_context(blog_id=self.id): if request.method == 'POST' and post_form.validate(): self.title = post_form.title.data self.content = post_form.content.data self.allow_guest_comments = post_form.allow_guest_comments.data self.save() flash('Your post has been updated.') if request.is_xhr: return jsonify(success=True, item=self.serialize()) return redirect( url_for('blog.post.render', user_id=self.nereid_user.id, uri=self.uri)) if request.is_xhr: return jsonify( success=request.method != 'POST', # False for POST, else True errors=post_form.errors or None, ) return render_template('blog_post_edit.jinja', form=post_form, post=self)
def create_task(self, project_id): """Create a new task for the specified project POST will create a new task """ project = self.get_project(project_id) # Check if user is among the participants self.can_write(project, request.nereid_user) if request.method == 'POST': task_id = self.create({ 'parent': project_id, 'name': request.form['name'], 'type': 'task', 'comment': request.form.get('description', False), }) flash("Task successfully added to project %s" % project.name) return redirect( url_for('project.work.render_task', project_id=project_id, task_id=task_id ) ) flash("Could not create task. Try again.") return redirect(request.referrer)
def assign_task(self, task_id): """Assign task to a user :param task_id: Id of Task """ nereid_user_obj = Pool().get('nereid.user') task = self.get_task(task_id) new_assignee = nereid_user_obj.browse(int(request.form['user'])) if self.can_write(task.parent, new_assignee): self.write(task.id, { 'assigned_to': new_assignee.id }) if request.is_xhr: return jsonify({ 'success': True, }) flash("Task assigned to %s" % new_assignee.name) return redirect(request.referrer) flash("Only employees can be assigned to tasks.") return redirect(request.referrer)
def remove_tag(cls, task_id, tag_id): """ Assigns the provided to this task :param task_id: ID of task :param tag_id: ID of tag """ Activity = Pool().get('nereid.activity') task = cls.get_task(task_id) cls.write( [task], {'tags': [('remove', [tag_id])]} ) Activity.create([{ 'actor': request.nereid_user.id, 'object_': 'project.work, %d' % task.id, 'verb': 'removed_tag_from_task', 'target': 'project.work, %d' % task.parent.id, 'project': task.parent.id, }]) if request.method == 'POST': flash('Tag removed from task %s' % task.rec_name) return redirect(request.referrer) flash("Tag cannot be removed") return redirect(request.referrer)
def add(cls): """ Adds a contact mechanism to the party's contact mechanisms """ form = cls.get_form() if form.validate_on_submit(): cls.create( [ { "party": request.nereid_user.party.id, "type": form.type.data, "value": form.value.data, "comment": form.comment.data, } ] ) if request.is_xhr: return jsonify({"success": True}) return redirect(request.referrer) if request.is_xhr: return jsonify({"success": False}) else: for field, messages in form.errors: flash("<br>".join(messages), "Field %s" % field) return redirect(request.referrer)
def get_linkedin_oauth_client(self, scope='r_basicprofile,r_emailaddress', token='linkedin_oauth_token'): """Returns a instance of WebCollect :param scope: Scope of information to be fetched from linkedin :param token: Token for authentication """ if not all([self.linkedin_api_key, self.linkedin_api_secret]): current_app.logger.error("LinkedIn api settings are missing") flash(_("LinkedIn login is not available at the moment")) return None oauth = OAuth() linkedin = oauth.remote_app( 'linkedin', base_url='https://api.linkedin.com', request_token_url='/uas/oauth/requestToken', access_token_url='/uas/oauth/accessToken', authorize_url='/uas/oauth/authenticate', consumer_key=self.linkedin_api_key, consumer_secret=self.linkedin_api_secret, request_token_params={'scope': scope}) linkedin.tokengetter_func = lambda *a: session.get(token) return linkedin
def linkedin_authorized_login(cls): """Authorized handler to which linkedin will redirect the user to after the login attempt is made. """ Party = Pool().get('party.party') linkedin = request.nereid_website.get_linkedin_oauth_client() if linkedin is None: return redirect(request.referrer or url_for('nereid.website.login')) try: if 'oauth_verifier' in request.args: data = linkedin.handle_oauth1_response() elif 'code' in request.args: data = linkedin.handle_oauth2_response() else: data = linkedin.handle_unknown_response() linkedin.free_request_token() except Exception, exc: current_app.logger.error("LinkedIn login failed %s" % exc) flash( _("We cannot talk to linkedin at this time. Please try again")) return redirect(request.referrer or url_for('nereid.website.login'))
def get_github_oauth_client(self, site=None, scope='', token='github_oauth_token'): """Returns a instance of LinkedIn OAuth :param site: Browserecord of the website, If not specified, it will be guessed from the request context """ if site is None: site = request.nereid_website if not all([site.github_id, site.github_secret]): current_app.logger.error("Github api settings are missing") flash(_("Github login is not available at the moment")) return None oauth = OAuth() github = oauth.remote_app( 'github', base_url='https://github.com', request_token_url=None, access_token_url='/login/oauth/access_token', authorize_url='/login/oauth/authorize', consumer_key=site.github_id, consumer_secret=site.github_secret, request_token_params={'scope': scope}, access_token_method="POST", ) github.tokengetter_func = lambda *a: session.get(token) return github
def get_linkedin_oauth_client(self, site=None, scope='r_basicprofile,r_emailaddress', token='linkedin_oauth_token'): """Returns a instance of WebCollect :param site: Browserecord of the website, If not specified, it will be guessed from the request context """ if site is None: site = request.nereid_website if not all([site.linkedin_api_key, site.linkedin_api_secret]): current_app.logger.error("LinkedIn api settings are missing") flash(_("LinkedIn login is not available at the moment")) return None oauth = OAuth() linkedin = oauth.remote_app('linkedin', base_url='https://api.linkedin.com', request_token_url='/uas/oauth/requestToken', access_token_url='/uas/oauth/accessToken', authorize_url='/uas/oauth/authenticate', consumer_key=site.linkedin_api_key, consumer_secret=site.linkedin_api_secret, request_token_params={'scope': scope} ) linkedin.tokengetter_func = lambda *a: session.get(token) return linkedin
def revenue_opportunity(self): """ Set the Conversion Probability and estimated revenue amount """ NereidUser = Pool().get('nereid.user') nereid_user = NereidUser.search( [('employee', '=', self.employee.id)], limit=1 ) if nereid_user: employee = nereid_user[0] else: employee = None if request.method == 'POST': self.write([self], { 'probability': request.form['probability'], 'amount': Decimal(request.form.get('amount')) }) flash('Lead has been updated.') return redirect( url_for('sale.opportunity.admin_lead', active_id=self.id) + "#tab-revenue" ) return render_template( 'crm/admin-lead.jinja', lead=self, employee=employee, )
def reset_account(cls): """ Reset the password for the user. .. tip:: This does NOT reset the password, but just creates an activation code and sends the link to the email of the user. If the user uses the link, he can change his password. """ if request.method == 'POST': user_ids = cls.search([ ('email', '=', request.form['email']), ('company', '=', request.nereid_website.company.id), ]) if not user_ids: flash(_('Invalid email address')) return render_template('reset-password.jinja') nereid_user, = user_ids nereid_user.create_act_code("reset") nereid_user.send_reset_email() flash( _('An email has been sent to your account for resetting' ' your credentials')) return redirect(url_for('nereid.website.login')) return render_template('reset-password.jinja')
def new_password(cls): """Create a new password .. tip:: Unlike change password this does not demand the old password. And hence this method will check in the session for a parameter called allow_new_password which has to be True. This acts as a security against attempts to POST to this method and changing password. The allow_new_password flag is popped on successful saving This is intended to be used when a user requests for a password reset. """ form = NewPasswordForm(request.form) if request.method == 'POST' and form.validate(): if not session.get('allow_new_password', False): current_app.logger.debug('New password not allowed in session') abort(403) cls.write([request.nereid_user], {'password': form.password.data}) session.pop('allow_new_password') flash( _('Your password has been successfully changed! ' 'Please login again')) session.pop('user') return redirect(url_for('nereid.website.login')) return render_template('new-password.jinja', password_form=form)
def github_authorized_login(cls): """ Authorized handler to which github will redirect the user to after the login attempt is made. """ github = request.nereid_website.get_github_oauth_client() if github is None: return redirect( request.referrer or url_for('nereid.website.login') ) try: # The response is an oauth2 response with code. But Github API # requires the if 'oauth_verifier' in request.args: data = github.handle_oauth1_response() elif 'code' in request.args: data = github.handle_oauth2_response() else: data = github.handle_unknown_response() github.free_request_token() except Exception, exc: current_app.logger.error("Github login failed %s" % exc) flash(_("We cannot talk to github at this time. Please try again")) return redirect( request.referrer or url_for('nereid.website.login') )
def new_password(self): """Create a new password .. tip:: Unlike change password this does not demand the old password. And hence this method will check in the session for a parameter called allow_new_password which has to be True. This acts as a security against attempts to POST to this method and changing password. The allow_new_password flag is popped on successful saving This is intended to be used when a user requests for a password reset. """ form = NewPasswordForm(request.form) if request.method == "POST" and form.validate(): if not session.get("allow_new_password", False): current_app.logger.debug("New password not allowed in session") abort(403) self.write(request.nereid_user.id, {"password": form.password.data}) session.pop("allow_new_password") flash(_("Your password has been successfully changed! " "Please login again")) session.pop("user") return redirect(url_for("nereid.website.login")) return render_template("new-password.jinja", password_form=form)
def get_linkedin_oauth_client(self, site=None, scope='r_basicprofile,r_emailaddress', token='linkedin_oauth_token'): """Returns a instance of WebCollect :param site: Browserecord of the website, If not specified, it will be guessed from the request context """ if site is None: site = request.nereid_website if not all([site.linkedin_api_key, site.linkedin_api_secret]): current_app.logger.error("LinkedIn api settings are missing") flash(_("LinkedIn login is not available at the moment")) return None oauth = OAuth() linkedin = oauth.remote_app( 'linkedin', base_url='https://api.linkedin.com', request_token_url='/uas/oauth/requestToken', access_token_url='/uas/oauth/accessToken', authorize_url='/uas/oauth/authenticate', consumer_key=site.linkedin_api_key, consumer_secret=site.linkedin_api_secret, request_token_params={'scope': scope}) linkedin.tokengetter_func = lambda *a: session.get(token) return linkedin
def checkout(self): '''Submit of default checkout A GET to the method will result in passing of control to begin as that is basically the entry point to the checkout A POST to the method will result in the confirmation of the order and subsequent handling of data. ''' cart_obj = Pool().get('nereid.cart') sale_obj = Pool().get('sale.sale') cart = cart_obj.open_cart() if not cart.sale: # This case is possible if the user changes his currency at # the point of checkout and the cart gets cleared. return redirect(url_for('nereid.cart.view_cart')) sale = cart.sale if not sale.lines: flash(_("Add some items to your cart before you checkout!")) return redirect(url_for('nereid.website.home')) if request.method == 'GET': return (self._begin_guest() if request.is_guest_user \ else self._begin_registered()) elif request.method == 'POST': form, do_process = self._submit_guest() if request.is_guest_user \ else self._submit_registered() if do_process: # Process Shipping self._process_shipment(sale, form) # Process Payment, if the returned value from the payment # is a response object (isinstance) then return that instead # of the success page. This will allow reidrects to a third # party gateway or service to collect payment. response = self._process_payment(sale, form) if isinstance(response, BaseResponse): return response if sale.state == 'draft': # Ensure that the order date is that of today cart_obj.check_update_date(cart) # Confirm the order sale_obj.quote([sale.id]) sale_obj.confirm([sale.id]) flash(_("Your order #%(sale)s has been processed", sale=sale.reference)) if request.is_guest_user: return redirect(url_for('nereid.website.home')) else: return redirect( url_for( 'sale.sale.render', sale=sale.id, confirmation=True ) ) return render_template('checkout.jinja', form=form, cart=cart)
def reset_account(cls): """ Reset the password for the user. .. tip:: This does NOT reset the password, but just creates an activation code and sends the link to the email of the user. If the user uses the link, he can change his password. """ form = ResetAccountForm() if form.validate_on_submit(): try: nereid_user, = cls.search([ ('email', '=', form.email.data), ('company', '=', request.nereid_website.company.id), ]) except ValueError: return cls.build_response( 'Invalid email address', render_template('reset-password.jinja'), 400 ) nereid_user.send_reset_email() return cls.build_response( 'An email has been sent to your account for resetting' ' your credentials', redirect(url_for('nereid.website.login')), 200 ) elif form.errors: if request.is_xhr or request.is_json: return jsonify(error=form.errors), 400 flash(_('Invalid email address.')) return render_template('reset-password.jinja')
def revenue_opportunity(self): """ Set the Conversion Probability and estimated revenue amount """ NereidUser = Pool().get('nereid.user') nereid_user = NereidUser.search([('employee', '=', self.employee.id)], limit=1) if nereid_user: employee = nereid_user[0] else: employee = None if request.method == 'POST': self.write( [self], { 'probability': request.form['probability'], 'amount': Decimal(request.form.get('amount')) }) flash('Lead has been updated.') return redirect( url_for('sale.opportunity.admin_lead', active_id=self.id) + "#tab-revenue") return render_template( 'crm/admin-lead.jinja', lead=self, employee=employee, )
def registration(self): """ Invokes registration of an user """ registration_form = self.get_registration_form() if request.method == "POST" and registration_form.validate(): existing = self.search( [("email", "=", request.form["email"]), ("company", "=", request.nereid_website.company.id)] ) if existing: flash(_("A registration already exists with this email. " "Please contact customer care")) else: user_id = self.create( { "name": registration_form.name.data, "display_name": registration_form.name.data, "email": registration_form.email.data, "password": registration_form.password.data, "company": request.nereid_website.company.id, } ) self.create_act_code(user_id) registration.send(user_id) user = self.browse(user_id) self.send_activation_email(user) flash(_("Registration Complete. Check your email for activation")) return redirect(request.args.get("next", url_for("nereid.website.home"))) return render_template("registration.jinja", form=registration_form)
def facebook_authorized_login(self): """Authorized handler to which facebook will redirect the user to after the login attempt is made. """ website_obj = Pool().get('nereid.website') facebook = website_obj.get_facebook_oauth_client() if facebook is None: return redirect( request.referrer or url_for('nereid.website.login') ) try: if 'oauth_verifier' in request.args: data = facebook.handle_oauth1_response() elif 'code' in request.args: data = facebook.handle_oauth2_response() else: data = facebook.handle_unknown_response() facebook.free_request_token() except Exception, exc: current_app.logger.error("Facebook login failed", exc) flash(_("We cannot talk to facebook at this time. Please try again")) return redirect( request.referrer or url_for('nereid.website.login') )
def delete_task(cls, task_id): """ Delete the task from project Tasks can be deleted only if 1. The user is project admin 2. The user is an admin member in the project :param task_id: Id of the task to be deleted """ task = cls.get_task(task_id) # Check if user is among the project admins if not request.nereid_user.is_admin_of_project(task.parent): flash("Sorry! You are not allowed to delete tasks. \ Contact your project admin for the same.") return redirect(request.referrer) cls.write([task], {'active': False}) if request.is_xhr: return jsonify({ 'success': True, }) flash("The task has been deleted") return redirect( url_for('project.work.render_project', project_id=task.parent.id))
def new_password(cls): """Create a new password .. tip:: Unlike change password this does not demand the old password. And hence this method will check in the session for a parameter called allow_new_password which has to be True. This acts as a security against attempts to POST to this method and changing password. The allow_new_password flag is popped on successful saving This is intended to be used when a user requests for a password reset. """ form = NewPasswordForm(request.form) if request.method == 'POST' and form.validate(): if not session.get('allow_new_password', False): current_app.logger.debug('New password not allowed in session') abort(403) cls.write( [request.nereid_user], {'password': form.password.data} ) session.pop('allow_new_password') flash(_( 'Your password has been successfully changed! ' 'Please login again')) session.pop('user') return redirect(url_for('nereid.website.login')) return render_template('new-password.jinja', password_form=form)
def set_language(self): """Sets the language in the session of the user. Also try to guess the currency of the user, if not use the default currency of the website Accepted Methods: GET, POST Accepts XHR: Yes The language has to be provided in the GET arguments of POST form. It is more convenient to pass the language code than the id of the language because it makes it more readable in URLs """ raise DeprecationWarning("Set language is deprecated") lang_obj = Pool().get('ir.lang') language = request.values.get('language') exists = lang_obj.search([('code', '=', language)], limit=1) if exists: flash(_('Your language preference have been saved.')) else: flash(_('Sorry! we do not speak your language yet!')) # redirect to the next url if given else take to home page redirect_to = request.values.get('next') if redirect_to: redirect_to.replace(session['language'], language) return redirect( request.values.get('next', url_for('nereid.website.home')) )
def nereid_add_payment_profile(cls): """ Add card to user profile. """ AddPaymentProfileWizard = Pool().get( 'party.party.payment_profile.add', type='wizard' ) Address = Pool().get('party.address') gateway = request.nereid_website.credit_card_gateway form = PaymentProfileForm() if form.validate_on_submit(): profile_wiz = AddPaymentProfileWizard( AddPaymentProfileWizard.create()[0] ) profile_wiz.card_info.party = current_user.party profile_wiz.card_info.address = Address(form.address.data) profile_wiz.card_info.provider = gateway.provider profile_wiz.card_info.gateway = gateway profile_wiz.card_info.owner = form.owner.data profile_wiz.card_info.number = form.number.data profile_wiz.card_info.expiry_month = form.expiry_month.data profile_wiz.card_info.expiry_year = \ unicode(form.expiry_year.data) profile_wiz.card_info.csc = form.cvv.data try: profile_wiz.transition_add() flash(_('Credit Card added successfully!')) except UserError, e: # pragma: no cover flash(_(e.message)) finally:
def reset_account(cls): """ Reset the password for the user. .. tip:: This does NOT reset the password, but just creates an activation code and sends the link to the email of the user. If the user uses the link, he can change his password. """ form = ResetAccountForm() if form.validate_on_submit(): try: nereid_user, = cls.search([ ('email', '=', form.email.data), ('company', '=', current_website.company.id), ]) except ValueError: return cls.build_response( 'Invalid email address', render_template('reset-password.jinja'), 400 ) nereid_user.send_reset_email() return cls.build_response( 'An email has been sent to your account for resetting' ' your credentials', redirect(url_for('nereid.website.login')), 200 ) elif form.errors: if request.is_xhr or request.is_json: return jsonify(error=form.errors), 400 flash(_('Invalid email address.')) return render_template('reset-password.jinja')
def delete_task(cls, task_id): """ Delete the task from project Tasks can be deleted only if 1. The user is project admin 2. The user is an admin member in the project :param task_id: Id of the task to be deleted """ task = cls.get_task(task_id) # Check if user is among the project admins if not request.nereid_user.is_admin_of_project(task.parent): flash( "Sorry! You are not allowed to delete tasks. \ Contact your project admin for the same." ) return redirect(request.referrer) cls.write([task], {"active": False}) if request.is_xhr: return jsonify({"success": True}) flash("The task has been deleted") return redirect(url_for("project.work.render_project", project_id=task.parent.id))
def change_constraint_dates(cls, task_id): """ Change the constraint dates """ Activity = Pool().get("nereid.activity") task = cls.get_task(task_id) data = {"constraint_start_time": False, "constraint_finish_time": False} constraint_start = request.form.get("constraint_start_time", None) constraint_finish = request.form.get("constraint_finish_time", None) if constraint_start: data["constraint_start_time"] = datetime.strptime(constraint_start, "%m/%d/%Y") if constraint_finish: data["constraint_finish_time"] = datetime.strptime(constraint_finish, "%m/%d/%Y") cls.write([task], data) Activity.create( [ { "actor": request.nereid_user.id, "object_": "project.work, %d" % task.id, "verb": "changed_date", "project": task.parent.id, } ] ) if request.is_xhr: return jsonify({"success": True}) flash("The constraint dates have been changed for this task.") return redirect(request.referrer)
def remove_tag(cls, task_id, tag_id): """ Assigns the provided to this task :param task_id: ID of task :param tag_id: ID of tag """ Activity = Pool().get("nereid.activity") task = cls.get_task(task_id) cls.write([task], {"tags": [("unlink", [tag_id])]}) Activity.create( [ { "actor": request.nereid_user.id, "object_": "project.work, %d" % task.id, "verb": "removed_tag_from_task", "target": "project.work, %d" % task.parent.id, "project": task.parent.id, } ] ) if request.method == "POST": flash("Tag removed from task %s" % task.rec_name) return redirect(request.referrer) flash("Tag cannot be removed") return redirect(request.referrer)
def reset_account(self): """ Reset the password for the user. .. tip:: This does NOT reset the password, but just creates an activation code and sends the link to the email of the user. If the user uses the link, he can change his password. """ if request.method == "POST": user_ids = self.search( [("email", "=", request.form["email"]), ("company", "=", request.nereid_website.company.id)] ) if not user_ids: flash(_("Invalid email address")) return render_template("reset-password.jinja") self.create_act_code(user_ids[0], "reset") user = self.browse(user_ids[0]) self.send_reset_email(user) flash(_("An email has been sent to your account for resetting" " your credentials")) return redirect(url_for("nereid.website.login")) return render_template("reset-password.jinja")
def registration(self): """ Invokes registration of an user """ registration_form = self.get_registration_form() if request.method == 'POST' and registration_form.validate(): existing = self.search([ ('email', '=', request.form['email']), ('company', '=', request.nereid_website.company.id), ]) if existing: flash(_('A registration already exists with this email. ' 'Please contact customer care') ) else: user_id = self.create({ 'name': registration_form.name.data, 'display_name': registration_form.name.data, 'email': registration_form.email.data, 'password': registration_form.password.data, 'company': request.nereid_website.company.id, }) self.create_act_code(user_id) registration.send(user_id) user = self.browse(user_id) self.send_activation_email(user) flash( _('Registration Complete. Check your email for activation') ) return redirect( request.args.get('next', url_for('nereid.website.home')) ) return render_template('registration.jinja', form=registration_form)
def get_linkedin_oauth_client( self, scope='r_basicprofile,r_emailaddress', token='linkedin_oauth_token' ): """Returns a instance of WebCollect :param scope: Scope of information to be fetched from linkedin :param token: Token for authentication """ if not all([self.linkedin_api_key, self.linkedin_api_secret]): current_app.logger.error("LinkedIn api settings are missing") flash(_("LinkedIn login is not available at the moment")) return None oauth = OAuth() linkedin = oauth.remote_app( 'linkedin', base_url='https://api.linkedin.com', request_token_url='/uas/oauth/requestToken', access_token_url='/uas/oauth/accessToken', authorize_url='/uas/oauth/authenticate', consumer_key=self.linkedin_api_key, consumer_secret=self.linkedin_api_secret, request_token_params={'scope': scope} ) linkedin.tokengetter_func = lambda *a: session.get(token) return linkedin
def remove_tag(cls, task_id, tag_id): """ Assigns the provided to this task :param task_id: ID of task :param tag_id: ID of tag """ Activity = Pool().get('nereid.activity') task = cls.get_task(task_id) cls.write([task], {'tags': [('remove', [tag_id])]}) Activity.create([{ 'actor': request.nereid_user.id, 'object_': 'project.work, %d' % task.id, 'verb': 'removed_tag_from_task', 'target': 'project.work, %d' % task.parent.id, 'project': task.parent.id, }]) if request.method == 'POST': flash('Tag removed from task %s' % task.rec_name) return redirect(request.referrer) flash("Tag cannot be removed") return redirect(request.referrer)
def get_facebook_oauth_client(self, site=None): """Returns a instance of WebCollect :param site: Browserecord of the website, If not specified, it will be guessed from the request context """ if site is None: site = request.nereid_website if not all([site.facebook_app_id, site.facebook_app_secret]): current_app.logger.error("Facebook api settings are missing") flash(_("Facebook login is not available at the moment")) return None oauth = OAuth() facebook = oauth.remote_app('facebook', base_url='https://graph.facebook.com/', request_token_url=None, access_token_url='/oauth/access_token', authorize_url='https://www.facebook.com/dialog/oauth', consumer_key=site.facebook_app_id, consumer_secret=site.facebook_app_secret, request_token_params={'scope': 'email'} ) facebook.tokengetter_func = lambda *a: session.get( 'facebook_oauth_token' ) return facebook
def change_password(cls): """ Changes the password .. tip:: On changing the password, the user is logged out and the login page is thrown at the user """ form = ChangePasswordForm(request.form) if request.method == 'POST' and form.validate(): if request.nereid_user.match_password(form.old_password.data): cls.write( [request.nereid_user], {'password': form.password.data} ) flash( _('Your password has been successfully changed! ' 'Please login again') ) logout_user() return redirect(url_for('nereid.website.login')) else: flash(_("The current password you entered is invalid")) return render_template( 'change-password.jinja', change_password_form=form )
def render_comments(self): """ Render comments GET: Return json of all the comments of this post. POST: Create new comment for this post. """ if self.state != 'Published': abort(404) # Add re_captcha if the configuration has such an option and user # is guest if 're_captcha_public' in CONFIG.options and request.is_guest_user: comment_form = GuestCommentForm( request.form, captcha={'ip_address': request.remote_addr} ) else: comment_form = PostCommentForm(request.form) if request.method == 'GET': if self.nereid_user == request.nereid_user: return jsonify(comments=[ comment.serialize() for comment in self.comments ]) return jsonify(comments=[ comment.serialize() for comment in self.comments if not comment.is_spam ]) # If post does not allow guest comments, # then dont allow guest user to comment if not self.allow_guest_comments and request.is_guest_user: flash('Guests are not allowed to write comments') if request.is_xhr: return jsonify( success=False, errors=['Guests are not allowed to write comments'] ) return redirect(url_for( 'blog.post.render', user_id=self.nereid_user.id, uri=self.uri )) if request.method == 'POST' and comment_form.validate(): self.write([self], { 'comments': [('create', [{ 'nereid_user': current_user.id if not current_user.is_anonymous() else None, 'name': current_user.display_name if not current_user.is_anonymous() else comment_form.name.data, 'content': comment_form.content.data, }])] }) if request.is_xhr: return jsonify(success=True) if comment_form.validate() \ else jsonify(success=False, errors=comment_form.errors) return redirect(url_for( 'blog.post.render', user_id=self.nereid_user.id, uri=self.uri ))
def delete_from_cart(cls, line): """ Delete a line from the cart. The required argument in POST is: line_id : ID of the line Response: 'OK' if X-HTTPRequest else redirect to shopping cart """ SaleLine = Pool().get('sale.line') cart = cls.open_cart() if not cart.sale: abort(404) try: sale_line, = SaleLine.search([ ('id', '=', line), ('sale', '=', cart.sale.id), ]) except ValueError: message = 'Looks like the item is already deleted.' else: SaleLine.delete([sale_line]) message = 'The order item has been successfully removed.' cart_updated.send(cart) flash(_(message)) if request.is_xhr: return jsonify(message=message) return redirect(url_for('nereid.cart.view_cart'))
def new_post(cls): """Create a new post """ post_form = BlogPostForm(request.form) if request.method == 'POST' and post_form.validate(): post, = cls.create([{ 'title': post_form.title.data, 'uri': post_form.uri.data, 'content': post_form.content.data, 'nereid_user': request.nereid_user.id, 'allow_guest_comments': post_form.allow_guest_comments.data, }]) if post_form.publish.data: cls.publish([post]) flash('Your post has been published.') else: flash('Your post has been saved.') if request.is_xhr: return jsonify(success=True, item=post.serialize()) return redirect(url_for( 'blog.post.render', user_id=post.nereid_user.id, uri=post.uri )) if request.is_xhr: return jsonify( success=request.method != 'POST', # False for POST, else True errors=post_form.errors or None, ) return render_template('blog_post_form.jinja', form=post_form)
def edit_post(self): """ Edit an existing post """ if self.nereid_user != request.nereid_user: abort(404) # Search for a post with same uri post_form = BlogPostForm(request.form, obj=self) with Transaction().set_context(blog_id=self.id): if request.method == 'POST' and post_form.validate(): self.title = post_form.title.data self.content = post_form.content.data self.allow_guest_comments = post_form.allow_guest_comments.data self.save() flash('Your post has been updated.') if request.is_xhr: return jsonify(success=True, item=self.serialize()) return redirect(url_for( 'blog.post.render', user_id=self.nereid_user.id, uri=self.uri )) if request.is_xhr: return jsonify( success=request.method != 'POST', # False for POST, else True errors=post_form.errors or None, ) return render_template( 'blog_post_edit.jinja', form=post_form, post=self )
def get_facebook_oauth_client(self, site=None): """Returns a instance of WebCollect :param site: Browserecord of the website, If not specified, it will be guessed from the request context """ if site is None: site = request.nereid_website if not all([site.facebook_app_id, site.facebook_app_secret]): current_app.logger.error("Facebook api settings are missing") flash(_("Facebook login is not available at the moment")) return None oauth = OAuth() facebook = oauth.remote_app( 'facebook', base_url='https://graph.facebook.com/', request_token_url=None, access_token_url='/oauth/access_token', authorize_url='https://www.facebook.com/dialog/oauth', consumer_key=site.facebook_app_id, consumer_secret=site.facebook_app_secret, request_token_params={'scope': 'email'}) facebook.tokengetter_func = lambda *a: session.get( 'facebook_oauth_token') return facebook
def facebook_authorized_login(self): """Authorized handler to which facebook will redirect the user to after the login attempt is made. """ website_obj = Pool().get('nereid.website') facebook = website_obj.get_facebook_oauth_client() if facebook is None: return redirect(request.referrer or url_for('nereid.website.login')) try: if 'oauth_verifier' in request.args: data = facebook.handle_oauth1_response() elif 'code' in request.args: data = facebook.handle_oauth2_response() else: data = facebook.handle_unknown_response() facebook.free_request_token() except Exception, exc: current_app.logger.error("Facebook login failed", exc) flash( _("We cannot talk to facebook at this time. Please try again")) return redirect(request.referrer or url_for('nereid.website.login'))
def reset_account(cls): """ Reset the password for the user. .. tip:: This does NOT reset the password, but just creates an activation code and sends the link to the email of the user. If the user uses the link, he can change his password. """ if request.method == 'POST': user_ids = cls.search( [ ('email', '=', request.form['email']), ('company', '=', request.nereid_website.company.id), ] ) if not user_ids or not request.form['email']: flash(_('Invalid email address')) return render_template('reset-password.jinja') nereid_user, = user_ids nereid_user.send_reset_email() flash(_('An email has been sent to your account for resetting' ' your credentials')) return redirect(url_for('nereid.website.login')) return render_template('reset-password.jinja')
def delete_from_cart(cls, line): """ Delete a line from the cart. The required argument in POST is: line_id : ID of the line Response: 'OK' if X-HTTPRequest else redirect to shopping cart """ SaleLine = Pool().get('sale.line') cart = cls.open_cart() if not cart.sale: abort(404) try: sale_line, = SaleLine.search([ ('id', '=', line), ('sale', '=', cart.sale.id), ]) except ValueError: message = 'Looks like the item is already deleted.' else: SaleLine.delete([sale_line]) message = 'The order item has been successfully removed.' flash(_(message)) if request.is_xhr: return jsonify(message=message) return redirect(url_for('nereid.cart.view_cart'))
def linkedin_authorized_login(cls): """Authorized handler to which linkedin will redirect the user to after the login attempt is made. """ Party = Pool().get('party.party') linkedin = request.nereid_website.get_linkedin_oauth_client() if linkedin is None: return redirect( request.referrer or url_for('nereid.website.login') ) try: if 'oauth_verifier' in request.args: data = linkedin.handle_oauth1_response() elif 'code' in request.args: data = linkedin.handle_oauth2_response() else: data = linkedin.handle_unknown_response() linkedin.free_request_token() except Exception, exc: current_app.logger.error("LinkedIn login failed %s" % exc) flash(_( "We cannot talk to linkedin at this time. Please try again" )) return redirect( request.referrer or url_for('nereid.website.login') )
def logout(cls): "Log the user out" logout_user() flash( _('You have been logged out successfully. Thanks for visiting us')) return redirect( request.args.get('next', url_for('nereid.website.home')))
def cms_static_upload(cls, upload_type): """ Upload the file for cms """ StaticFile = Pool().get("nereid.static.file") file = request.files['file'] if file: static_file, = StaticFile.create([{ 'folder': current_website.cms_static_folder, 'name': '_'.join([ str(int(time.time())), secure_filename(file.filename), ]), 'type': upload_type, 'file_binary': file.read(), }]) if request.is_xhr: return jsonify(success=True, item=static_file.serialize()) flash("File uploaded") if request.is_xhr: return jsonify(success=False) return redirect(request.referrer)
def clear_cart(cls): """ Clears the current cart and redirects to shopping cart page """ cart = cls.open_cart() cart._clear_cart() flash(_('Your shopping cart has been cleared')) return redirect(url_for('nereid.cart.view_cart'))
def validate_for_product_inventory(self): """ This method validates the sale line against the product's inventory attributes. This method requires request context. """ if has_request_context() and not self.product.can_buy_from_eshop(): flash(_('This product is no longer available')) abort(redirect(request.referrer))
def registration(cls): """ Invokes registration of an user """ Party = Pool().get('party.party') ContactMechanism = Pool().get('party.contact_mechanism') registration_form = cls.get_registration_form() if registration_form.validate_on_submit(): with Transaction().set_context(active_test=False): existing = cls.search([ ('email', '=', registration_form.email.data.lower()), ('company', '=', current_website.company.id), ]) if existing: message = _('A registration already exists with this email. ' 'Please contact customer care') if request.is_xhr or request.is_json: return jsonify(message=unicode(message)), 400 else: flash(message) else: party = Party(name=registration_form.name.data) party.addresses = [] party.contact_mechanisms = [ ContactMechanism(type="email", value=registration_form.email.data) ] party.save() nereid_user = cls( **{ 'party': party.id, 'display_name': registration_form.name.data, 'email': registration_form.email.data, 'password': registration_form.password.data, 'company': current_website.company.id, }) nereid_user.save() registration.send(nereid_user) nereid_user.send_activation_email() message = _( 'Registration Complete. Check your email for activation') if request.is_xhr or request.is_json: return jsonify(message=unicode(message)), 201 else: flash(message) return redirect( request.args.get('next', url_for('nereid.website.home'))) if registration_form.errors and (request.is_xhr or request.is_json): return jsonify({ 'message': unicode(_('Form has errors')), 'errors': registration_form.errors, }), 400 return render_template('registration.jinja', form=registration_form)
def validate_payment_profile(self, payment_profile): """ Checks if payment profile belongs to right party """ if not current_user.is_anonymous and \ payment_profile.party != current_user.party: # verify that the payment profile belongs to the registered # user. flash(_('The payment profile chosen is invalid')) return redirect(url_for('nereid.checkout.payment_method'))
def build_response(cls, message, response, xhr_status_code): """ Method to handle response for jinja and XHR requests. message: Message to show as flash and send as json response. response: redirect or render_template method. xhr_status_code: Status code to be sent with json response. """ if request.is_xhr or request.is_json: return jsonify(message=message), xhr_status_code flash(_(message)) return response
def assign_lead(self): "Change the employee on lead" NereidUser = Pool().get('nereid.user') new_assignee = NereidUser(int(request.form['user'])) if self.employee.id == new_assignee.employee.id: flash("Lead already assigned to %s" % new_assignee.party.name) return redirect(request.referrer) self.write([self], {'employee': new_assignee.employee.id}) flash("Lead assigned to %s" % new_assignee.party.name) return redirect(request.referrer)
def remove_address(self): """ Make address inactive if user removes the address from address book. """ if self.party == current_user.party: self.active = False self.save() flash(_('Address has been deleted successfully!')) if request.is_xhr: return jsonify(success=True) return redirect(request.referrer) abort(403)
def _add_or_update(self, product_id, quantity, action='set'): '''Add item as a line or if a line with item exists update it for the quantity :param product: ID of the product :param quantity: Quantity :param action: set - set the quantity to the given quantity add - add quantity to existing quantity ''' SaleLine = Pool().get('sale.line') Product = Pool().get('product.product') order_line = self.find_existing_line(product_id) product = Product(product_id) old_price = Decimal('0.0') if order_line: old_price = order_line.unit_price order_line.unit = order_line.unit.id order_line.quantity = \ quantity if action == 'set' else quantity + order_line.quantity else: order_line = SaleLine( **{ 'product': product_id, 'sale': self, 'type': 'line', 'sale': self.id, 'sequence': 10, 'quantity': quantity, 'unit': None, 'description': None, 'warehouse': self.warehouse }) order_line.on_change_product() order_line.on_change_quantity() if old_price and old_price != order_line.unit_price: vals = (product.name, self.currency.symbol, old_price, self.currency.symbol, order_line.unit_price) if old_price < order_line.unit_price: message = _( "The unit price of product %s increased from %s%d to " "%s%d." % vals) else: message = _("The unit price of product %s dropped from %s%d " "to %s%d." % vals) flash(message) return order_line
def activate(self, sign, max_age=24 * 60 * 60): """A web request handler for activation of the user account. This method verifies the email and if it succeeds, activates the account. If your workflow requires a manual approval of every account, override this to not activate an account, or make a no op out of this method. If all what you require is verification of email, `verify_email` method could be used. """ try: unsigned = self._serializer.loads( self._signer.unsign(sign, max_age=max_age), salt='activation' ) except SignatureExpired: flash(_("The activation link has expired")) except BadSignature: flash(_("The activation token is invalid!")) else: if self.id == unsigned: self.active = True self.email_verified = True self.save() flash(_('Your account has been activated. Please login now.')) else: flash(_('Invalid Activation Code')) return redirect(url_for('nereid.website.login'))
def change_party(cls, party_id): """ Updates the current party of the nereid_user to the new party_id if it is one of the parties in the list of parties of the user :param party_id: ID of the party """ for party in request.nereid_user.parties: if party.id == party_id: cls.write([request.nereid_user], {'party': party.id}) break else: flash("The party is not valid") return redirect( request.args.get('next', url_for('nereid.website.home')))
def change_estimated_hours(self): """Change estimated hours. :param task_id: ID of the task. """ if not request.nereid_user.employee: flash("Sorry! You are not allowed to change estimate hours.") return redirect(request.referrer) estimated_hours = request.form.get('new_estimated_hours', None, type=float) if estimated_hours: self.write([self], {'effort': estimated_hours}) flash("The estimated hours have been changed for this task.") return redirect(request.referrer)
def nereid_pay_using_profile(self, payment_profile_id, amount): """ Pay the amount using the given profile. Ensures that the profile belongs to the current user. """ PaymentProfile = Pool().get('party.payment_profile') payment_profile = PaymentProfile(payment_profile_id) if payment_profile.party != current_user.party: # verify that the payment profile belongs to the registered # user. flash(_('The payment profile chosen is invalid')) return redirect( url_for('nereid.checkout.payment_method') ) return self._pay_using_profile(payment_profile, amount)