def search_product(term): '''Case-insensitive search for term in field product.name.''' lower_term = term.lower() found = (models.Product.select().where( (fn.Lower(models.Product.name).contains(lower_term)) | (fn.Lower(models.Product.description).contains(lower_term)))) return found
def exists(email, member_id=None): if member_id: return Entity.select().where((fn.Lower(Entity.email) == email.lower()) & Entity.is_member, (Entity.id != member_id)).count() == 1 else: return Entity.select().where((fn.Lower(Entity.email) == email.lower()) & Entity.is_member).count() == 1
def _get_port_name_FK(self, port_name): """ Lookup up contacts FK by port_name """ try: return Ports.get(fn.Lower(Ports.port_name) % fn.Lower(port_name)) except Ports.DoesNotExist as e: self._logger.error(str(e)) return None
def search_topic_nodes(kinds=None, query=None, page=1, items_per_page=10, exact=True, **kwargs): """ Search all nodes and return limited fields. :param kinds: A list of content kinds. :param query: Text string to search for in titles or extra fields. :param page: Which page of the paginated search to return. :param items_per_page: How many items on each page of the paginated search. :param exact: Flag to allow for an exact match, if false, always return more than one item. :return: A list of dictionaries containing content metadata. """ if query: if not kinds: kinds = ["Video", "Audio", "Exercise", "Document", "Topic"] try: topic_node = Item.select( Item.title, Item.description, Item.available, Item.kind, Item.id, Item.path, Item.slug, ).where((fn.Lower(Item.title) == query) & (Item.kind.in_(kinds))).get() if exact: # If allowing an exact match, just return that one match and we're done! return [model_to_dict(topic_node)], True, None except DoesNotExist: topic_node = {} pass # For efficiency, don't do substring matches when we've got lots of results topic_nodes = Item.select( Item.title, Item.description, Item.available, Item.kind, Item.id, Item.path, Item.slug, ).where((Item.kind.in_(kinds)) & ((fn.Lower(Item.title).contains(query)) | (fn.Lower(Item.extra_fields).contains(query)))) pages = topic_nodes.count() / items_per_page topic_nodes = [ item for item in topic_nodes.paginate(page, items_per_page).dicts() ] if topic_node: # If we got an exact match, show it first. topic_nodes.insert(0, model_to_dict(topic_node)) return topic_nodes, False, pages
def _get_vessel_FK(self, vessel_name, registration_code): """ Lookup up vessel FK by vessel_name and registration_code """ try: return Vessels.get((fn.Lower(Vessels.vessel_name) % fn.Lower(vessel_name)) & ((Vessels.state_reg_number == registration_code) | (Vessels.coast_guard_number == registration_code))) except Vessels.DoesNotExist as e: self._logger.error(str(e)) return None
def get_user(self, identifier): from peewee import fn as peeweeFn try: return self.user_model.get(self.user_model.id == identifier) except ValueError: pass for attr in get_identity_attributes(): column = getattr(self.user_model, attr) try: return self.user_model.get( peeweeFn.Lower(column) == peeweeFn.Lower(identifier)) except self.user_model.DoesNotExist: pass
def get_user(self, identifier): if isinstance(identifier, int): try: return self.user_model.get( self.user_model.id == identifier) except self.user_model.DoesNotExist: pass for attr in get_identity_attributes(): column = getattr(self.user_model, attr) try: return self.user_model.get( fn.Lower(column) == fn.Lower(identifier)) except self.user_model.DoesNotExist: pass
def submit(ptype, sub): if ptype not in ['link', 'text', 'poll', 'upload']: abort(404) captcha = None if misc.get_user_level(current_user.uid)[0] <= 4: captcha = misc.create_captcha() form = CreateSubPostForm() if current_user.canupload: form.ptype.choices.append(('upload', _l('Upload file'))) form.ptype.data = ptype if sub != '': form.sub.data = sub try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) subdata = misc.getSubData(sub.sid) if subdata.get('allow_polls', False): form.ptype.choices.append(('poll', _l('Poll'))) except Sub.DoesNotExist: abort(404) if request.args.get('title'): form.title.data = request.args.get('title') if request.args.get('url'): form.link.data = request.args.get('url') return engine.get_template('sub/createpost.html').render( {'error': misc.get_errors(form, True), 'form': form, 'sub': sub, 'captcha': captcha})
def insert_media(): data = webapp_news_main\ .select(webapp_news_main.source,\ webapp_keyword.keyword,\ fn.count(1),\ fn.sum(webapp_news_main.share_count).alias('share_count'),\ fn.sum(webapp_news_main.view_count).alias('view_count'),\ fn.sum(webapp_news_main.positive).alias('positive'),\ fn.sum(webapp_news_main.negative).alias('negative'),\ fn.Lower('itri').alias('username')\ )\ .join(webapp_keyword_match,\ on=(webapp_news_main.url == webapp_keyword_match.guid))\ .join(webapp_keyword,\ on=(webapp_keyword_match.kwgrp == webapp_keyword.kwgrp))\ .where(webapp_keyword_match.kwgrp << (34,3,4,5,6,42,2,8,18,19,20,9),\ ~(webapp_news_main.source % 'Match%'))\ .group_by(webapp_news_main.source, webapp_keyword.keyword)\ .order_by(webapp_news_main.source, webapp_keyword.keyword) print data query = (media_keyword_group\ .insert_from(\ fields=[media_keyword_group.source,\ media_keyword_group.keyword,\ media_keyword_group.count,\ media_keyword_group.share_count,\ media_keyword_group.view_count,\ media_keyword_group.positive,\ media_keyword_group.negative,\ media_keyword_group.username,\ ],\ query=data)\ .execute()) print query
def edit_sub_css(sub): """ Here we can edit sub info and settings """ try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) if not current_user.is_mod(sub.sid, 1) and not current_user.is_admin(): abort(403) c = SubStylesheet.get(SubStylesheet.sid == sub.sid) form = EditSubCSSForm(css=c.source) stor = 0 ufiles = SubUploads.select().where(SubUploads.sid == sub.sid) for uf in ufiles: stor += uf.size / 1024 return engine.get_template('sub/css.html').render({ 'sub': sub, 'form': form, 'error': False, 'storage': int(stor), 'files': ufiles })
def get_current_user(request: Request) -> UserSchema: jwt_token = request.cookies.get('Authorization') # Apparently the testclient's cookies aren't detected, although they're in the header. # We just try to get them manually here if that's the case if not jwt_token: try: cookie_str = request.headers.get('cookie', '') jwt_token = next( re.finditer('Authorization=(Bearer .*?)(?:[; ]|$)', cookie_str)).group(1) except (StopIteration, AttributeError): pass if jwt_token is None: raise HTTPException(401, 'authentication required') jwt_token = jwt_token.split(' ')[-1] try: decoded = jwt.decode(jwt_token, key=JWT_SECRET, algorithms=['HS256']) email = decoded.get('email') except jwt.exceptions.DecodeError: raise HTTPException(401, 'invalid jwt token') user_orm = User.select().where(fn.Lower(User.email) == email).first() user = UserSchema.from_orm(user_orm) return user
def edit_sub_user_flairs(sub): """Here we manage user flairs""" try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) if not current_user.is_mod(sub.sid, 1) and not current_user.is_admin(): abort(403) flairs = SubUserFlairChoice.select().where(SubUserFlairChoice.sub == sub.sid) # assigned_flairs = SubUserFlair.select(SubUserFlair.flair_choice, SubUserFlair.flair, User.name)\ # .join(User).where(SubUserFlair.sub == sub.sid).dicts() assignflair = AssignSubUserFlair() formflairs = [] for flair in flairs: formflairs.append(EditSubFlair(flair=flair.id, text=flair.flair)) assignflair.flair_id.choices.append((flair.id, flair.flair)) # formuserflairs = [] # for flair in assigned_flairs: # formuserflairs.append(EditSubUserFlair(flair=flair['flair_choice'], text=flair['flair'], user=flair['name'])) return engine.get_template("sub/user_flairs.html").render( { "sub": sub, "flairs": formflairs, "createflair": CreateSubFlair(), # 'assigned_flairs': formuserflairs, "assignflair": assignflair, } )
def view_user_posts(user, page): """ WIP: View user's recent posts """ try: user = User.get(fn.Lower(User.name) == user.lower()) except User.DoesNotExist: abort(404) if user.status == 10 and not current_user.is_admin(): return view_deleted_user(user) include_deleted_posts = user.uid == current_user.uid or current_user.is_admin( ) if not include_deleted_posts and current_user.is_a_mod: modded_subs = [s.sid for s in misc.getModSubs(current_user.uid, 2)] if modded_subs: include_deleted_posts = modded_subs posts = misc.getPostList( misc.postListQueryBase( include_deleted_posts=include_deleted_posts, noAllFilter=not current_user.is_admin(), noUserFilter=True, ).where(User.uid == user.uid), "new", page, ) return render_template( "userposts.html", page=page, sort_type="user.view_user_posts", posts=posts, user=user, )
def comment_voting(page, term): """ WIP: View comment voting habits """ if current_user.is_admin(): try: user = User.get(fn.Lower(User.name) == term.lower()) msg = [] votes = SubPostCommentVote.select(SubPostCommentVote.positive, SubPostCommentVote.cid, SubPostComment.uid, User.name, SubPostCommentVote.datetime, SubPost.pid, Sub.name.alias('sub')) votes = votes.join(SubPostComment, JOIN.LEFT_OUTER, on=SubPostComment.cid == SubPostCommentVote.cid).join(SubPost).join(Sub) votes = votes.switch(SubPostComment).join( User, JOIN.LEFT_OUTER, on=SubPostComment.uid == User.uid) votes = votes.where(SubPostCommentVote.uid == user.uid).dicts() except User.DoesNotExist: votes = [] msg = 'user not found' return render_template('admin/commentvoting.html', page=page, msg=msg, admin_route='admin.comment_voting', votes=votes, term=term) else: abort(404)
def reports_sub(sub, page): """ WIP: Sub Report Queue """ try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) subInfo = misc.getSubData(sub.sid) subMods = misc.getSubMods(sub.sid) if not (current_user.is_mod(sub.sid, 1) or current_user.is_admin()): abort(404) reports = getReports("mod", "open", page, sid=sub.sid) return engine.get_template("mod/sub_reports.html").render({ "sub": sub, "reports": reports, "page": page, "subInfo": subInfo, "subMods": subMods, })
def view_sub_hot(sub, page): """ The index page, /hot sorting """ if sub.lower() == "all": return redirect(url_for("home.all_hot", page=1)) try: sub = Sub.select().where( fn.Lower(Sub.name) == sub.lower()).dicts().get() except Sub.DoesNotExist: abort(404) isSubMod = current_user.is_mod(sub["sid"], 1) or current_user.is_admin() posts = misc.getPostList( misc.postListQueryBase(noAllFilter=True, isSubMod=isSubMod).where(Sub.sid == sub["sid"]), "hot", page, ).dicts() return engine.get_template("sub.html").render({ "sub": sub, "subInfo": misc.getSubData(sub["sid"]), "posts": posts, "page": page, "sort_type": "sub.view_sub_hot", "subMods": misc.getSubMods(sub["sid"]), })
def view_user_posts(user, page): """ WIP: View user's recent posts """ try: user = User.get(fn.Lower(User.name) == user.lower()) except User.DoesNotExist: abort(404) if user.status == 10: abort(404) if current_user.is_admin(): posts = misc.getPostList( misc.postListQueryBase(include_deleted_posts=True).where( User.uid == user.uid), "new", page, ).dicts() else: posts = misc.getPostList( misc.postListQueryBase( include_deleted_posts=(user.uid == current_user.uid), noAllFilter=True).where(User.uid == user.uid), "new", page, ).dicts() return render_template( "userposts.html", page=page, sort_type="user.view_user_posts", posts=posts, user=user, )
def edit_sub_mods(sub): """ Here we can edit moderators for a sub """ try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) if (current_user.is_mod(sub.sid, 2) or current_user.is_modinv(sub.sid) or current_user.is_admin()): subdata = misc.getSubData(sub.sid, extra=True) subMods = misc.getSubMods(sub.sid) modInvites = (SubMod.select( User.name, SubMod.power_level).join(User).where((SubMod.sid == sub.sid) & SubMod.invite)) return engine.get_template("sub/mods.html").render({ "sub": sub, "subdata": subdata, "editmod2form": EditMod2Form(), "subMods": subMods, "subModInvites": modInvites, }) else: abort(403)
def edit_sub(sub): """ Here we can edit sub info and settings """ try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) if current_user.is_mod(sub.sid, 1) or current_user.is_admin(): submeta = misc.metadata_to_dict( SubMetadata.select().where(SubMetadata.sid == sub.sid)) form = EditSubForm() # pre-populate the form. form.subsort.data = submeta.get("sort") form.sidebar.data = sub.sidebar form.title.data = sub.title return engine.get_template("sub/settings.html").render({ "sub": sub, "editsubform": form, "metadata": submeta }) else: abort(403)
def edit_sub_css(sub): """Here we can edit sub info and settings""" try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) if not current_user.is_mod(sub.sid, 1) and not current_user.is_admin(): abort(403) subInfo = misc.getSubData(sub.sid) subMods = misc.getSubMods(sub.sid) c = SubStylesheet.get(SubStylesheet.sid == sub.sid) form = EditSubCSSForm(css=c.source) stor = 0 ufiles = SubUploads.select().where(SubUploads.sid == sub.sid) for uf in ufiles: stor += uf.size / 1024 return engine.get_template("sub/css.html").render( { "sub": sub, "form": form, "error": False, "storage": int(stor), "max_storage": config.storage.sub_css_max_file_size, "files": ufiles, "subInfo": subInfo, "subMods": subMods, } )
def view_sub_new(sub, page): """The index page, all posts sorted as most recent posted first""" if sub.lower() == "all": return redirect(url_for("home.all_new", page=1)) flair = request.args.get("flair") try: sub = Sub.select().where(fn.Lower(Sub.name) == sub.lower()).dicts().get() except Sub.DoesNotExist: abort(404) isSubMod = current_user.is_mod(sub["sid"], 1) or current_user.is_admin() posts = misc.getPostList( misc.postListQueryBase(noAllFilter=True, isSubMod=isSubMod, flair=flair).where( Sub.sid == sub["sid"] ), "new", page, ) return engine.get_template("sub.html").render( { "sub": sub, "subInfo": misc.getSubData(sub["sid"]), "posts": posts, "page": page, "sort_type": "sub.view_sub_new", "subMods": misc.getSubMods(sub["sid"]), "flair": flair, } )
def view_sublog(sub, page): """Here we can see a log of mod/admin activity in the sub""" try: sub = Sub.select().where(fn.Lower(Sub.name) == sub.lower()).dicts().get() except Sub.DoesNotExist: abort(404) subInfo = misc.getSubData(sub["sid"]) if not config.site.force_sublog_public: log_is_private = subInfo.get("sublog_private", 0) == "1" if log_is_private and not ( current_user.is_mod(sub["sid"], 1) or current_user.is_admin() ): abort(404) subMods = misc.getSubMods(sub["sid"]) logs = ( SubLog.select() .where(SubLog.sid == sub["sid"]) .order_by(SubLog.lid.desc()) .paginate(page, 50) ) return engine.get_template("sub/log.html").render( {"sub": sub, "logs": logs, "page": page, "subInfo": subInfo, "subMods": subMods} )
def password_recovery(): """ Endpoint for the password recovery form """ if current_user.is_authenticated: return redirect(url_for("home.index")) form = PasswordRecoveryForm() captcha = misc.create_captcha() if not form.validate(): return engine.get_template("user/password_recovery.html").render({ "lpform": form, "error": misc.get_errors(form, True), "captcha": captcha }) if not misc.validate_captcha(form.ctok.data, form.captcha.data): return engine.get_template("user/password_recovery.html").render({ "lpform": form, "error": _("Invalid captcha."), "captcha": captcha }) try: email = normalize_email(form.email.data) user = User.get(fn.Lower(User.email) == email.lower()) if user.status == UserStatus.OK: send_password_recovery_email(user) except User.DoesNotExist: # Yield no information. pass return redirect(url_for("user.recovery_email_sent"))
def extendQueryWithFilter(columnNameToEntityMap, filterModel, query): if len(filterModel.keys()) > 0: for column, filter in filterModel.iteritems(): if filter["filtertype"] == "freetext": query = query.where( fn.Lower(columnNameToEntityMap[column]).contains( filter["filter"])) elif filter["filtertype"] == "checkboxes": if "isBoolean" in filter.keys() and filter["isBoolean"]: where = columnNameToEntityMap[column].in_( [x for x in filter["filter"] if x is not None]) if None in filter["filter"]: where = (where | columnNameToEntityMap[column].is_null()) query = query.where(where) else: query = query.where(columnNameToEntityMap[column].in_( filter["filter"])) elif filter[ "filtertype"] == "boolean" and filter["filter"] != "all": if not filter["filter"] or filter["filter"] == "false": query = query.where(~columnNameToEntityMap[column]) else: query = query.where(columnNameToEntityMap[column]) elif filter["filtertype"] == "time": if filter["filter"]["before"]: query = query.where(columnNameToEntityMap[column] < filter["filter"]["before"]) if filter["filter"]["after"]: query = query.where(columnNameToEntityMap[column] > filter["filter"]["after"]) return query
def view_sub_bans(sub): """ See banned users for the sub """ try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) subInfo = misc.getSubData(sub.sid) if not config.site.force_sublog_public: banned_users_is_private = subInfo.get('sub_banned_users_private', 0) == '1' if banned_users_is_private and not (current_user.is_mod(sub.sid, 1) or current_user.is_admin()): abort(404) user = User.alias() created_by = User.alias() banned = SubBan.select(user, created_by, SubBan.created, SubBan.reason, SubBan.expires) banned = banned.join(user, on=SubBan.uid).switch(SubBan).join(created_by, JOIN.LEFT_OUTER, on=SubBan.created_by_id) banned = banned.where((SubBan.sid == sub.sid) & ((SubBan.effective == True) & ((SubBan.expires.is_null(True)) | (SubBan.expires > datetime.datetime.utcnow())))) banned = banned.order_by(SubBan.created.is_null(True), SubBan.created.desc()) xbans = SubBan.select(user, created_by, SubBan.created, SubBan.reason, SubBan.expires) xbans = xbans.join(user, on=SubBan.uid).switch(SubBan).join(created_by, JOIN.LEFT_OUTER, on=SubBan.created_by_id) xbans = xbans.where(SubBan.sid == sub.sid) xbans = xbans.where((SubBan.effective == False) | ((SubBan.expires.is_null(False)) & (SubBan.expires < datetime.datetime.utcnow()))) xbans = xbans.order_by(SubBan.created.is_null(True), SubBan.created.desc(), SubBan.expires.asc()) return engine.get_template('sub/bans.html').render({'sub': sub, 'banned': banned, 'xbans': xbans, 'banuserform': BanUserSubForm(), 'submods': misc.getSubMods(sub.sid)})
def login(): """ Logs the user in. Parameters (json): username and password Returns: access token and refresh token """ if not request.is_json: return jsonify(msg="Missing JSON in request"), 400 username = request.json.get('username', None) password = request.json.get('password', None) if not username: return jsonify(msg="Missing username parameter"), 400 if not password: return jsonify(msg="Missing password parameter"), 400 try: user = User.get(fn.Lower(User.name) == username.lower()) except User.DoesNotExist: return jsonify(msg="Bad username or password"), 401 if user.status != 0: return jsonify(msg="Forbidden"), 403 if not auth_provider.validate_password(user, password): return jsonify(msg="Bad username or password"), 401 # Identity can be any data that is json serializable access_token = create_access_token(identity=user.uid, fresh=True) refresh_token = create_refresh_token(identity=user.uid) return jsonify(access_token=access_token, refresh_token=refresh_token, username=user.name), 200
def resend_confirmation_email(): if current_user.is_authenticated: return redirect(url_for("home.index")) form = ResendConfirmationForm() if not form.validate(): return engine.get_template("user/resend_confirmation.html").render({ "form": form, "error": misc.get_errors(form, True) }) try: email = normalize_email(form.email.data) user = User.get(fn.Lower(User.email) == email.lower()) except User.DoesNotExist: return redirect(url_for("user.recovery_email_sent")) if user.status == UserStatus.PROBATION: send_login_link_email(user) session.pop("reg", None) return redirect(url_for("auth.confirm_registration")) elif user.status == UserStatus.OK: flash(_("Your email is already confirmed.")) return redirect(url_for("auth.login")) return engine.get_template("user/check-your-email.html").render({ "reason": "registration", "email": "", "show_resend_link": False })
def get_user(username): """ Returns user profile data """ try: user = User.select().where((User.status == 0) & ( fn.Lower(User.name) == username.lower())).get() except User.DoesNotExist: return jsonify(msg="User does not exist"), 404 level = misc.get_user_level(user.uid, user.score) pcount = SubPost.select().where(SubPost.uid == user.uid).count() ccount = SubPostComment.select().where( SubPostComment.uid == user.uid).count() modsquery = SubMod.select( Sub.name, SubMod.power_level).join(Sub).where((SubMod.uid == user.uid) & (SubMod.invite == False)) owns = [x.sub.name for x in modsquery if x.power_level == 0] mods = [x.sub.name for x in modsquery if 1 <= x.power_level <= 2] return jsonify( user={ 'name': user.name, 'score': user.score, 'given': user.given, 'joindate': user.joindate, 'level': level[0], 'xp': level[1], 'badges': misc.getUserBadges(user.uid), 'posts': pcount, 'comments': ccount, 'subs': { 'owns': owns, 'mods': mods } })
def post_voting(page, term): """ WIP: View post voting habits """ if not current_user.is_admin(): abort(404) try: user = User.get(fn.Lower(User.name) == term.lower()) msg = [] votes = SubPostVote.select( SubPostVote.positive, SubPostVote.pid, User.name, SubPostVote.datetime, SubPostVote.pid, ) votes = votes.join(SubPost, JOIN.LEFT_OUTER, on=SubPost.pid == SubPostVote.pid) votes = votes.switch(SubPost).join( User, JOIN.LEFT_OUTER, on=SubPost.uid == User.uid ) votes = votes.where(SubPostVote.uid == user.uid).dicts() except User.DoesNotExist: votes = [] msg = "user not found" return render_template( "admin/postvoting.html", page=page, msg=msg, admin_route="admin.post_voting", votes=votes, term=term, )
def reports_sub(sub, page): """ WIP: Sub Report Queue """ try: sub = Sub.get(fn.Lower(Sub.name) == sub.lower()) except Sub.DoesNotExist: abort(404) subInfo = misc.getSubData(sub.sid) subMods = misc.getSubMods(sub.sid) if not (current_user.is_mod(sub.sid, 1) or current_user.is_admin()): abort(404) reports = getReports('mod', 'open', page, sid=sub.sid) return engine.get_template('mod/sub_reports.html').render({ 'sub': sub, 'reports': reports, 'page': page, 'subInfo': subInfo, 'subMods': subMods })