def reg(self): title = 'Registration' usertypes = userTypes() states = get_states() msg = '' form = Form(self.request, schema=Registration) if 'form_submitted' in self.request.POST and form.validate(): try: resp = self.request.POST['g-recaptcha-response'] except: self.request.session.flash( 'danger; Failed captcha due to slow network') return HTTPFound(location=self.request.route_url('reg')) recaptcha_r = requests.post( recaptcha_endpoint, dict(secret=buddy_settings('recaptcha_secret'), response=resp)) rdata = recaptcha_r.json() if rdata: if not rdata['success']: msg = 'Failed recaptcha, please solve again' return dict(form=FormRenderer(form), msg=msg, title=title, usertypes=usertypes, states=states) user = form.bind(Users()) if 'ref_email' in self.request.session: referrer = Users.get_by_email( self.request.session['ref_email']) if referrer: user.parent_id = referrer.id with transaction.manager: DBSession.add(user) user.prefix = create_path(user.user_fullname, is_unique) DBSession.flush() timestamp = time.time() + 3600 hmac_key = hmac.new( '%s:%s:%d' % (str(user.id), 'r5$55g35%4#$:l3#24&', timestamp), user.email).hexdigest()[0:10] time_key = base64.urlsafe_b64encode('%d' % timestamp) email_hash = '%s%s' % (hmac_key, time_key) user_regmail(self.request, user.id, user.email, email_hash) headers = buddy_remember(self.request, user, event='R') self.session.flash( "success;You should be receiving an email with a link to activate your " "account within 10 minutes. Doing so will let you post properties/blog on this website." ) return HTTPFound(location=self.request.route_url('account'), headers=headers) return dict(form=FormRenderer(form), title=title, usertypes=usertypes, msg=msg, states=states)
def login(self): title = "Login" login_url = self.request.route_url('login') referrer = self.request.url if referrer == login_url: referrer = '/myaccount' # never use the login form itself as came_from came_from = self.request.params.get('came_from', referrer) message = '' error_cls = '' form = Form(self.request, schema=LoginForm) if 'form_submitted' in self.request.POST and form.validate(): ''' try: resp = self.request.POST['g-recaptcha-response'] except: message="Slow network, please solve the challenge" return dict(title=title, message = message, form =FormRenderer(form), error_cls = error_cls, url = self.request.application_url + '/login', came_from = came_from) recaptcha_r = requests.post(recaptcha_endpoint, dict(secret=buddy_settings('recaptcha_secret'), response=resp)) rdata = recaptcha_r.json() if rdata: if not rdata['success']: message="Failed recaptcha, please solve the challenge" error_cls = 'has-error' return dict(title=title, message = message, form =FormRenderer(form), error_cls = error_cls, url = self.request.application_url + '/login', came_from = came_from) ''' email = form.data['email'] password = form.data['password'] user = Users.get_by_email(email) if Users.check_password(email, password): headers = buddy_remember(self.request, user) return HTTPFound(location=came_from, headers=headers) message = 'Failed login, incorrect email or password, Please try again' error_cls = 'has-error' return dict(title=title, message=message, form=FormRenderer(form), error_cls=error_cls, url=self.request.application_url + '/login', came_from=came_from)
def restpass(request): title = "Reset password" submitted_hmac = request.matchdict.get('hmac') user_id = request.matchdict.get('user_id') form = Form(request, schema=ResetPasswordForm) if 'form_submitted' in request.POST and form.validate(): user = Users.get_by_id(user_id) current_time = time.time() time_key = int(base64.b64decode(submitted_hmac[10:])) if current_time < time_key: hmac_key = hmac.new( '%s:%s:%d' % (str(user.id), 'r5$55g35%4#$:l3#24&', time_key), user.email).hexdigest()[0:10] if hmac_key == submitted_hmac[0:10]: #Fix me reset email, no such attribute email user.password = form.data['password'] DBSession.merge(user) DBSession.flush() request.session.flash( 'success; Password Changed. Please log in') return HTTPFound(location=request.route_url('login')) else: request.session.flash( 'warning; Invalid request, please try again') return HTTPFound(location=request.route_url('forgot_password')) action_url = request.route_url("reset_password", user_id=user_id, hmac=submitted_hmac) return { 'title': title, 'form': FormRenderer(form), 'action_url': action_url }
def user_listing(self): form = Form(self.request) path = self.request.matchdict['prefix'] user = Users.get_by_path(path) page = int(self.request.params.get("page", 1)) page_url = PageURL_WebOb(self.request) active_listings = DBSession.query(Listings).filter(Listings.user == user).filter(Listings.approved==True).\ filter(Listings.declined==False).filter(Listings.status==True).all() past_sales = DBSession.query(Listings).filter( Listings.user == user).filter(Listings.status == False).all() active_paginator = Page(active_listings, page=int(self.request.params.get("page", 1)), items_per_page=10, url=page_url) pastsales_paginator = Page(past_sales, page=int(self.request.params.get("page", 1)), items_per_page=10, url=page_url) title = user.fullname + "'s Listings" return dict(user=user, pastsales_paginator=pastsales_paginator, lis="d", form=FormRenderer(form), active_paginator=active_paginator, title=title)
def ratings(self): form = Form(self.request, schema=UserRatingSchema) prefix = self.request.matchdict['prefix'] user = Users.get_by_path(prefix) title = 'Rate ' + user.fullname if 'form_submitted' in self.request.POST and form.validate(): if user.id == self.request.user.id: self.request.session.flash("danger; You can't rate yourself") return HTTPFound( location=self.request.route_url('profile', prefix=prefix)) if user.rating: for rating in user.rating: if rating.rater_id == self.request.user.id: self.request.session.flash( "warning; You have rated %s before" % user.fullname) return HTTPFound(location=self.request.route_url( 'profile', prefix=prefix)) rating = UserRating(rater_id=self.request.user.id, rated_id=user.id, rating=form.data['rating'], review=form.data['review']) DBSession.add(rating) DBSession.flush() self.request.session.flash("success; Success") return HTTPFound( location=self.request.route_url('profile', prefix=prefix)) self.request.session.flash("danger; An Error occured") return HTTPFound( location=self.request.route_url('profile', prefix=prefix))
def userblogfilter(self): path = self.request.matchdict['prefix'] form = Form(self.request) #id = self.request.matchdict['id'] category = self.request.matchdict['category'] user = Users.get_by_path(path) blogs = user.content.filter(Content.type == 'blog').filter( Blogs.categories.any(name=category)).all() bcategor = user.content.filter(Content.type == 'blog').filter( Blogs.user_id == user.id).all() bc = [s.categories for s in bcategor] bc = histogram(bc) title = user.fullname + "'s Blogs on " + category page_url = PageURL_WebOb(self.request) page = int(self.request.params.get('page', 1)) paginator = Page(blogs, page=page, url=page_url) if page > 1: title = title + ' page ' + str(page) return dict(user=user, paginator=paginator, blog_nav_cat=get_navcategories(), form=FormRenderer(form), bl='bl', category=category, title=title, bcategories=bc)
def denyverify(request): prefix = request.matchdict['prefix'] user = Users.get_by_path(prefix) if not user: request.session.flash('danger; user not found') user.is_verified = False request.session.flash('success; user verification denied') return HTTPFound(location=request.route_url('user_list'))
def _to_python(self, value, user): 'Check whether the value is unique' if not Users.check_password( email=get_current_request().authenticated_userid, password=value): raise Invalid('Your old password doesn\'t match', value, user) # Return return value
def delete(self): prefix = self.request.matchdict['prefix'] user = Users.get_by_path(prefix) if user: DBSession.delete(user) DBSession.flush() return HTTPFound(location=self.request.route_url('home')) else: self.request.session.flash("warning; User not found") return HTTPFound(location='/')
def verify(request): prefix = request.matchdict['prefix'] user = Users.get_by_path(prefix) if not user: request.session.flash('danger; user not found') user.is_verified = True user_parent = user.parent silver_plan = DBSession.query(Plans).filter(Plans.name == 'Silver').first() if user_parent: if not user_parent.earned_benefit: if user.active_subscription: active_sub = user.active_subscription[0] subscription = Subscription(user=user, plan=silver_plan, amount=0, no_of_months=1, discount=u"100%", status=u"Active") subscription.start_date = active_sub.end_date subscription.end_date = active_sub.end_date + timedelta( days=30) else: subscription = Subscription(user=request.user, plan=silver_plan, amount=0, no_of_months=1, discount=u"100%", start_date=datetime.today(), end_date=datetime.today() + timedelta(days=30), status=u"Active") DBSession.add(subscription) DBSession.flush() body = """<html><head><title>Verified on nairabricks.com</title></head><body> <p>Dear %s,<p><br> <p>You are now verified as a professional in Nairabricks</p> <p>However, please note that we still have the right to decline your listings if they violate our property listing policy</p> <p>Moreso, ensure that your listings are not duplicated. Instead of having duplicate listings, update your listing frequently to keep it at the top</p> <p>Yours sincerely,</p> <p>The Happy Nairabricks Info Robot</p> </body> </html> """ % user.fullname html_email_sender(request, subject="Congratulations", recipients=user.email, body=body) request.session.flash('success; user verified') return HTTPFound(location=request.route_url('user_list'))
def promo_sub(request): id = request.matchdict['id'] user = Users.get_by_id(id) if not user: return HTTPNotFound() form = Form(request, schema=PromoSubSchema) if 'submit' in request.POST and form.validate(): plan_id = form.data['plan'] plan = DBSession.query(Plans).get(plan_id) if plan: subscription = Subscription(user=user, plan=plan, amount=0, no_of_months=1, discount="100%", status="Active", start_date=datetime.today(), end_date=datetime.today() + timedelta(days=30)) DBSession.add(subscription) DBSession.flush() if request.is_xhr: html = """<div class="alert alert-success alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> User subscription </div>""" return Response(html) request.session.flash('success; User subscribed') return HTTPFound( location=request.route_url('profile', prefix=user.prefix)) if request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> An error occured, user Not subscribed </div>""" return Response(html) request.session.flash('danger; An error occured, user subscribed %s' % form.all_errors()) return HTTPFound( location=request.route_url('profile', prefix=user.prefix)) if request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> An error occured, user Not subscribed </div>""" return Response(html) request.session.flash('danger; An error occured, user subscribed %s' % form.all_errors()) return HTTPFound(location=request.route_url('profile', prefix=user.prefix))
def profile(self): form = Form(self.request) prefix = self.request.matchdict['prefix'] user = Users.get_by_path(prefix) if not user: self.session.flash('warning; No user with the given profile') return HTTPFound(location='/') total_sales = DBSession.query(Listings).filter_by(user=user).filter( Listings.status == False).count() title = user.fullname + "'s" + " profile" return dict(user=user, form=FormRenderer(form), title=title, total_sales=total_sales, profile_page="profile_page")
def userblog(self): path = self.request.matchdict['prefix'] user = Users.get_by_path(path) blogs = DBSession.query(Blogs).filter(Blogs.user == user).filter( Blogs.status == True).all() form = Form(self.request) title = user.fullname + "'s Blogs" page_url = PageURL_WebOb(self.request) page = int(self.request.params.get('page', 1)) paginator = Page(blogs, page=page, url=page_url) return dict(user=user, paginator=paginator, form=FormRenderer(form), bl='bl', title=title)
def user_favourites(self): path = self.request.matchdict['prefix'] user = Users.get_by_path(path) form = Form(self.request) listings = user.favourites title = "%s Saved Properties" % user.fullname page_url = PageURL_WebOb(self.request) page = int(self.request.params.get("page", 1)) paginator = Page(listings, page=page, items_per_page=10, url=page_url) return dict(user=user, paginator=paginator, form=FormRenderer(form), saved='saved', title=title)
def make_admin(request): id = request.matchdict['id'] user = Users.get_by_id(id) pos = request.matchdict['pos'] group = DBSession.query(Groups).filter(Groups.name == pos).first() if user and group: try: user.mygroups.append(group) request.session.flash('success; %s added to group %s' % (user.fullname, group.name)) except: request.session.flash('danger; request not completed') return HTTPFound(location=request.route_url('search_user_list')) request.session.flash('danger; Not successfull') return HTTPFound(location=request.route_url('user_list'))
def make_premium(self): for r in self.request.params: opts = r params = json.loads(opts) id = params['id'] user_id = params['user_id'] user = Users.get_by_id(user_id) positive = params['positive'] listing = Listings.get_by_id(id) if listing: if int(positive) == 1: #we already have it as premium, remove premium = DBSession.query(Featured_Content).filter( Featured_Content.name == 'Premium').first() premium.featured_properties.remove(listing) DBSession.flush() return dict(isOk=1, message="listing removed from premium") else: active_sub = user.active_subscription if not active_sub: return dict( isOk=0, message="Upgrade your account to feature this listing") premium = DBSession.query(Featured_Content).filter( Featured_Content.name == 'Premium').first() if premium.featured_properties: user_total_premium = 0 for item in premium.featured_properties: if item.user == user: user_total_premium += 1 if user_total_premium < active_sub[ 0].plan.max_premium_listings: premium.featured_properties.append(listing) DBSession.flush() return dict(isOk=1, message="listing given a premium identity") return dict( isOk=0, message= "You have exceeded your allocation. Upgrade for more") premium.featured_properties.append(listing) DBSession.flush() return dict(isOk=1, message="listing given a premium identity") return dict(isOk=0, message="No such listing")
def ratingsandreview(self): prefix = self.request.matchdict['prefix'] form = Form(self.request) user = Users.get_by_path(prefix) title = user.fullname + "'s" + " Ratings and Reviews" ratings = user.rating page_url = PageURL_WebOb(self.request) paginator = Page(ratings, page=int(self.request.params.get("page", 1)), items_per_page=5, url=page_url) return dict(paginator=paginator, user=user, rv='rv', title=title, form=FormRenderer(form), rating_page="rating_page")
def populate_superuser(): admin = Users( firstname = u"Ephraim", surname = u"Anierobi", password = u"mypassword", email = u"*****@*****.**", company_name=u"Zebraware Group Ltd", prefix = u"Zebraware", email_verified = True ) group1 = Groups(name=u"superadmin", description=u"Last Admin") group2 = Groups(name=u"admin", description=u"Admin") group3 = Groups(name=u"supermod",description=u"Super moderator") group4 = Groups(name=u"mod", description=u"Moderator") with transaction.manager: DBSession.add_all([group1,group2,group3,group4]) admin.mygroups.append(group1)
def inbox(self): id = self.request.matchdict['id'] user = Users.get_by_id(id) if not user: self.session.flash('info; No such user') return HTTPFound(location=self.request.route_url('home')) messages = DBSession.query(Messages).filter( Messages.user_id == user.id).order_by( Messages.created.desc()).all() page_url = PageURL_WebOb(self.request) paginator = Page(messages, page=int(self.request.params.get("page", 1)), url=page_url) for message in messages: message.is_seen = True DBSession.flush() return dict(user=user, paginator=paginator, mess='mess')
def passforgot(request): form = Form(request, schema=ForgotPasswordForm) if 'form_submitted' in request.POST and form.validate(): user = Users.get_by_email(form.data['email']) if user: timestamp = time.time() + 3600 hmac_key = hmac.new( '%s:%s:%d' % (str(user.id), 'r5$55g35%4#$:l3#24&', timestamp), user.email).hexdigest()[0:10] time_key = base64.urlsafe_b64encode('%d' % timestamp) email_hash = '%s%s' % (hmac_key, time_key) email_forgot(request, user.id, user.email, email_hash) request.session.flash('success; Password reset email sent') return HTTPFound(location=request.route_url('login')) request.session.flash('danger; No user with the given email address') return HTTPFound(location=request.route_url('login')) request.session.flash('danger; No such user') return HTTPFound(location=request.route_url('login'))
def deny_admin(request): id = request.matchdict['id'] user = Users.get_by_id(id) pos = request.matchdict['pos'] group = DBSession.query(Groups).filter(Groups.name == pos).first() if user and group: try: user.mygroups.remove(group) request.session.flash('success; %s removed from group %s' % (user.fullname, group.name)) except: request.session.flash( 'danger; Action cannot be performed because %s is not in the group %s' % (user.fullname, group.name)) return HTTPFound(location=request.route_url('search_user_list')) request.session.flash('danger; Not successfull') return HTTPFound(location=request.route_url('user_list'))
def userdraft(self): path = self.request.matchdict['prefix'] user = Users.get_by_path(path) blogs = DBSession.query(Blogs).filter(Blogs.user == user).filter( Blogs.status == False).all() bc = [s.categories for s in blogs if s.status == 0] bc = histogram(bc) form = Form(self.request) title = 'Drafts' page_url = PageURL_WebOb(self.request) page = int(self.request.params.get('page', 1)) paginator = Page(blogs, page=page, url=page_url) if page > 1: title = title + ' page ' + str(page) return dict(user=user, paginator=paginator, bl='bl', form=FormRenderer(form), title=title, bcategories=bc)
def contactAgent(self): form = Form(self.request, schema=ContactSchema) prefix = self.request.matchdict['prefix'] user = Users.get_by_path(prefix) if not user: self.session.flash('warning; No such user') return HTTPFound(location='/') if 'form_submitted' in self.request.POST and form.validate(): receiver = user.email fullname = form.data['fullname'] phone = form.data['mobile'] email = form.data['email'] body = form.data['body'] footer = "Reply this email to contact the sender" msg_body = "%s is requesting to contact you through nairabricks.com\r\n"%fullname +\ "Name: %s \n"%fullname+\ "Phone: %s\n"%phone+\ "Message: %s\n"%body+\ "%s"%footer sender = "%s via nairabricks.com <*****@*****.**>" % fullname extra_headers = { 'Reply-To': '{name} <{sender}>'.format(**{ 'name': fullname, 'sender': email }), } subject = "Contact request from %s via nairabricks.com" % fullname non_html_email_sender(self.request, recipients=receiver, subject=subject, body=msg_body, sender=sender, extra_headers=extra_headers) self.request.session.flash("success; Email sent") return HTTPFound( location=self.request.route_url('profile', prefix=prefix)) self.request.session.flash("success; Email not sent") return HTTPFound( location=self.request.route_url('profile', prefix=prefix))
def verify_email(request): title = "Email Confirmation" submitted_hmac = request.matchdict.get('hmac') user_id = request.matchdict.get('user_id') user = Users.get_by_id(user_id) current_time = time.time() time_key = int(base64.b64decode(submitted_hmac[10:])) if current_time < time_key: hmac_key = hmac.new( '%s:%s:%d' % (str(user.id), 'r5$55g35%4#$:l3#24&', time_key), user.email).hexdigest()[0:10] if hmac_key == submitted_hmac[0:10]: #Fix me reset email, no such attribute email user.email_verified = True DBSession.merge(user) DBSession.flush() if user.email_verified: message = 'Your email is now confirmed. Thank you for joining us' request.session.flash('success;%s' % message) return HTTPFound(location='/') else: message = 'Error verifying message' request.session.flash('success;%s' % message) return HTTPFound(location='/')
def check_email(request): email = request.params.get('email') if Users.get_by_email(email): return "The email you entered is already in use" return "true"
def _to_python(self, value, user): 'Check whether the value is unique' if Users.get_by_email(value) is None: raise Invalid('Sorry that email doesn\'t exist.', value, user) # Return return value
def is_unique(path): url = Users.get_by_path(path) if url: return False return True