def login(self): """ Login page """ self._login_enabled() logout_user() self.tmp_data = None self.meta_(title="Login") if request.method == "POST": email = request.form.get("email").strip() password = request.form.get("password").strip() if not email or not password: flash_error("Email or Password is empty") return redirect(url_for(login_view, next=request.form.get("next"))) user = User.get_by_email(email) if user and user.password_hash and user.password_matched(password): self.login_user(user) return redirect(request.form.get("next") or url_for(on_signin_view)) else: flash_error("Email or Password is invalid") return redirect(url_for(login_view, next=request.form.get("next"))) return self.render_( login_url_next=request.args.get("next", ""), login_url_default=url_for(on_signin_view), signup_enabled=self.config_("MODULE_USER_ACCOUNT_ENABLE_SIGNUP"), oauth_enabled=self.config_("MODULE_USER_ACCOUNT_ENABLE_OAUTH_LOGIN"), view_template_=template_page % "login", )
def cms_admin_types(self): self.meta_(title="Post Types") if request.method == "POST": try: id = request.form.get("id", None) action = request.form.get("action") name = request.form.get("name") slug = request.form.get("slug", None) if not id: PostModel.Type.new(name=name, slug=slug) flash_success("New type '%s' added" % name) else: post_type = PostModel.Type.get(id) if post_type: if action == "delete": post_type.delete() flash_success("Type '%s' deleted successfully!" % post_type.name) else: post_type.update(name=name, slug=slug) flash_success("Type '%s' updated successfully!" % post_type.name) except Exception as ex: flash_error("Error: %s" % ex.message) return redirect(url_for("CmsAdmin:types")) else: types = PostModel.Type.all().order_by(PostModel.Type.name.asc()) return self.render_(types=types, view_template_=template_page % "types")
def lost_password(self): self._login_enabled() logout_user() self.meta_(title="Lost Password") if request.method == "POST": email = request.form.get("email") user = User.get_by_email(email) if user: delivery = self.config_("MODULE_USER_ACCOUNT_RESET_PASSWORD_METHOD") new_password = None if delivery.upper() == "TOKEN": token = user.set_temp_login() url = url_for("UserAccount:reset_password", token=token, _external=True) else: new_password = user.set_password(password=None, random=True) url = url_for("UserAccount:login", _external=True) mailer.send_template( "reset-password.txt", method_=delivery, to=user.email, name=user.email, url=url, new_password=new_password, ) flash_success("A new password has been sent to '%s'" % email) else: flash_error("Invalid email address") return redirect(url_for(login_view)) else: return self.render_(view_template_=template_page % "lost_password")
def user_admin_reset_password(self): """ Reset the password :returns string: The new password string """ try: id = request.form.get("id") user = User.get(id) if not user: raise ViewError("Invalid User") method_ = self.config_("LOGIN_RESET_PASSWORD_METHOD", "").upper() new_password = None if method_ == "TOKEN": token = user.set_temp_login() url = url_for("UserAccount:temp_login_token", token=token, _external=True) else: new_password = user.set_password(password=None, random=True) url = url_for("UserAccount:login", _external=True) mailer.send_template( "reset-password.txt", method_=method_, to=user.email, name=user.email, url=url, new_password=new_password, ) flash_success("Password Reset instruction is sent to email") except Exception as ex: flash_error("Error: %s " % ex.message) return redirect(url_for("UserAdmin:get", id=id))
def user_admin_roles(self): """ Only admin and super admin can add/remove roles RESTRICTED ROLES CAN'T BE CHANGED """ roles_rage_max = 11 if request.method == "POST": try: id = request.form.get("id") name = request.form.get("name") level = request.form.get("level") action = request.form.get("action") if name and level: level = int(level) name = name.upper() _levels = [r[0] for r in Role.PRIMARY] _names = [r[1] for r in Role.PRIMARY] if level in _levels or name in _names: raise ViewError("Can't modify PRIMARY Roles - name: %s, level: %s " % (name, level)) else: if id: role = Role.get(id) if role: if action == "delete": role.delete() flash_success("Role '%s' deleted successfully!" % role.name) elif action == "update": if role.level != level and Role.get_by_level(level): raise ViewError("Role Level '%s' exists already" % level) elif role.name != name and Role.get_by_name(name): raise ViewError("Role Name '%s' exists already" % name) else: role.update(name=name, level=level) flash_success("Role '%s (%s)' updated successfully" % (name, level)) else: raise ViewError("Role doesn't exist") else: if Role.get_by_level(level): raise ViewError("Role Level '%s' exists already" % level) elif Role.get_by_name(name): raise ViewError("Role Name '%s' exists already" % name) else: Role.new(name=name, level=level) flash_success("New Role '%s (%s)' addedd successfully" % (name, level)) except Exception as ex: flash_error("Error: %s" % ex.message) return redirect(url_for("UserAdmin:roles")) else: self.meta_(title="User Roles - Users Admin") roles = Role.all().order_by(Role.level.desc()) allocated_levels = [r.level for r in roles] levels_options = [(l, l) for l in range(1, roles_rage_max) if l not in allocated_levels] return self.render_(roles=roles, levels_options=levels_options, view_template_=template_page % "roles")
def oauth_connect(self): """ To login via social """ email = request.form.get("email").strip() name = request.form.get("name").strip() provider = request.form.get("provider").strip() provider_user_id = request.form.get("provider_user_id").strip() image_url = request.form.get("image_url").strip() next = request.form.get("next", "") try: current_user.oauth_connect( provider=provider, provider_user_id=provider_user_id, email=email, name=name, image_url=image_url ) except Exception as ex: flash_error("Unable to link your account") return redirect(url_for("%s:account_settings" % view_name))
def signup(self): """ For Email Signup :return: """ self._login_enabled() self._signup_enabled() self.meta_(title="Signup") if request.method == "POST": # reCaptcha if not recaptcha.verify(): flash_error("Invalid Security code") return redirect(url_for("UserAccount:signup", next=request.form.get("next"))) try: name = request.form.get("name") email = request.form.get("email") password = request.form.get("password") password2 = request.form.get("password2") profile_image_url = request.form.get("profile_image_url", None) if not name: raise ViewError("Name is required") elif not utils.is_valid_email(email): raise ViewError("Invalid email address '%s'" % email) elif not password.strip() or password.strip() != password2.strip(): raise ViewError("Passwords don't match") elif not utils.is_valid_password(password): raise ViewError("Invalid password") else: new_account = User.new( email=email, password=password.strip(), first_name=name, profile_image_url=profile_image_url, signup_method="email", ) self.login_user(new_account) return redirect(request.form.get("next") or url_for(on_signin_view)) except Exception as ex: flash_error(ex.message) return redirect(url_for("UserAccount:signup", next=request.form.get("next"))) logout_user() return self.render_(login_url_next=request.args.get("next", ""), view_template_=template_page % "signup")
def cms_admin_tags(self): self.meta_(title="Post Tags") if request.method == "POST": id = request.form.get("id", None) action = request.form.get("action") name = request.form.get("name") slug = request.form.get("slug", None) ajax = request.form.get("ajax", False) try: if not id: tag = PostModel.Tag.new(name=name, slug=slug) if ajax: return jsonify({ "id": tag.id, "name": tag.name, "slug": tag.slug, "status": "OK" }) flash_success("New Tag '%s' added" % name) else: post_tag = PostModel.Tag.get(id) if post_tag: if action == "delete": post_tag.delete() flash_success("Tag '%s' deleted successfully!" % post_tag.name) else: post_tag.update(name=name, slug=slug) flash_success("Tag '%s' updated successfully!" % post_tag.name) except Exception as ex: if ajax: return jsonify({ "error": True, "error_message": ex.message }) flash_error("Error: %s" % ex.message) return redirect(url_for("CmsAdmin:tags")) else: tags = PostModel.Tag.all().order_by(PostModel.Tag.name.asc()) return self.render_(tags=tags, view_template_=template_page % "tags")
def cms_admin_upload_image(self): """ Placeholder for markdown """ try: ajax = request.form.get("ajax", False) allowed_extensions = ["gif", "png", "jpg", "jpeg"] if request.files.get("file"): _file = request.files.get('file') obj = storage.upload(_file, prefix="cms-uploads/", allowed_extensions=allowed_extensions, public=True) if obj: description = os.path.basename(obj.name) description = description.replace(".%s" % obj.extension, "") description = description.split("__")[0] upload_object = PostModel.UploadObject.create(name=obj.name, provider=obj.provider_name, container=obj.container.name, extension=obj.extension, type=obj.type, object_path=obj.path, object_url=obj.url, size=obj.size, description=description) if ajax: return jsonify({ "id": upload_object.id, "url": upload_object.object_url }) else: flash_success("Image '%s' uploaded successfully!" % upload_object.name) else: flash_error("Error: Upload object file is invalid or doesn't exist") except Exception as e: flash_error("Error: %s" % e.message) return redirect(url_for("CmsAdmin:images"))
def reset_password(self, token): self._login_enabled() logout_user() self.meta_(title="Reset Password") user = User.get_by_temp_login(token) if user: if not user.has_temp_login: return redirect(url_for(on_signin_view)) if request.method == "POST": try: self.change_password_handler(user_context=user) user.clear_temp_login() flash_success("Password updated successfully!") return redirect(url_for(on_signin_view)) except Exception as ex: flash_error("Error: %s" % ex.message) return redirect(url_for("UserAccount:reset_password", token=token)) else: return self.render_(token=token, view_template_=template_page % "reset_password") else: abort(404, "Invalid token")
def user_admin_create(self): try: email = request.form.get("email") first_name = request.form.get("first_name") last_name = request.form.get("last_name") user_role = request.form.get("user_role") _role = Role.get(user_role) if not _role: raise ViewError("Invalid role") if current_user.role.level < _role.level: raise ViewError("Can't be assigned a greater user role") if not first_name: raise ViewError("First Name is required") elif not email: raise ViewError("Email is required") elif not utils.is_valid_email(email): raise ViewError("Invalid email address") if User.get_by_email(email): raise ViewError("Email '%s' exists already" % email) else: user = User.new( email=email, first_name=first_name, last_name=last_name, signup_method="email-from-admin", role_id=_role.id, ) if user: flash_success("User created successfully!") return redirect(url_for("UserAdmin:get", id=user.id)) else: raise ViewError("Couldn't create new user") except Exception as ex: flash_error("Error: %s" % ex.message) return redirect(url_for("UserAdmin:index"))
def contact_page(self): if not self.config_("MAILER_URI") \ or not self.config_("MODULE_CONTACT_PAGE_EMAIL"): abort(500, "Mailer Error. Invalid [ MAILER_URI ] " "or [ MODULE_CONTACT_PAGE_EMAIL ] is missing or empty") contact_email = self.config_("MODULE_CONTACT_PAGE_EMAIL") if request.method == "POST": error_message = None email = request.form.get("email") subject = request.form.get("subject") message = request.form.get("message") name = request.form.get("name") if recaptcha.verify(): if not email or not subject or not message: error_message = "All fields are required" elif not utils.is_valid_email(email): error_message = "Invalid email address" if error_message: flash_error(error_message) else: mailer.send_template("contact-us.txt", to=contact_email, reply_to=email, mail_from=email, mail_subject=subject, mail_message=message, mail_name=name) flash_success("Message sent. Thank you!") else: flash_error("Security code is invalid") return redirect(url_for("ContactPage")) else: self.meta_(title="Contact Us") return dict(view_template_=template_page % "contact_page")
def upload(self): self.meta_(title="Upload Demo") if request.method == "POST": try: _file = request.files.get('file') if _file: my_object = storage.upload(_file, prefix="demo/", public=True, allowed_extensions=["gif", "jpg", "jpeg", "png"]) if my_object: return redirect(url_for("Account:upload", object_name=my_object.name)) except Exception as e: flash_error(e.message) return redirect(url_for("Account:upload")) my_object = None object_name = request.args.get("object_name") if object_name: my_object = storage.get(object_name=object_name) return dict(my_object=my_object)
def account_settings(self): self.meta_(title="Account Settings") if request.method == "POST": action = request.form.get("action") try: action = action.lower() # if action == "info": first_name = request.form.get("first_name").strip() last_name = request.form.get("last_name", "").strip() data = {"first_name": first_name, "last_name": last_name} current_user.update(**data) flash_success("Account info updated successfully!") # elif action == "login": confirm_password = request.form.get("confirm-password").strip() if current_user.password_matched(confirm_password): self.change_login_handler() flash_success("Login Info updated successfully!") else: flash_error("Invalid password") # elif action == "password": confirm_password = request.form.get("confirm-password").strip() if current_user.password_matched(confirm_password): self.change_password_handler() flash_success("Password updated successfully!") else: flash_error("Invalid password") elif action == "profile-photo": file = request.files.get("file") if file: prefix = "profile-photos/%s/" % current_user.id extensions = ["jpg", "jpeg", "png", "gif"] my_photo = storage.upload(file, prefix=prefix, allowed_extensions=extensions) if my_photo: url = my_photo.url current_user.update(profile_image_url=url) flash_success("Profile Image updated successfully!") else: raise ViewError("Invalid action") except Exception as e: flash_error(e.message) return redirect(url_for("UserAccount:account_settings")) return self.render_(view_template_=template_page % "account_settings")
def cms_admin_post(self): id = request.form.get("id") title = request.form.get("title") slug = request.form.get("slug") content = request.form.get("content") description = request.form.get("description") type_id = request.form.get("type_id") post_categories = request.form.getlist("post_categories") published_date = request.form.get("published_date") status = request.form.get("status", "draft") is_published = True if status == "publish" else False is_draft = True if status == "draft" else False is_public = True if request.form.get("is_public") == "y" else False is_sticky = True if request.form.get("is_sticky") == "y" else False is_featured = True if request.form.get("is_featured") == "y" else False featured_image = request.form.get("featured_image") featured_embed = request.form.get("featured_embed") featured_media_top = request.form.get("featured_media_top", "") social_options = request.form.getlist("social_options") tags = list(set(request.form.get("tags", "").split(","))) now_dt = datetime.datetime.now() data = { "title": title, "content": content, "description": description, "featured_image": featured_image, "featured_embed": featured_embed, "featured_media_top": featured_media_top, "type_id": type_id, "is_sticky": is_sticky, "is_featured": is_featured, "is_public": is_public } if status in ["draft", "publish"] and (not title or not type_id): if not title: flash_error("Post Title is missing ") if not type_id: flash_error("Post type is missing") data.update({ "published_date": published_date, "post_categories": post_categories, "options": {"social_options": social_options}, }) flash_data(data) if id: url = url_for("CmsAdmin:edit", id=id, error=1) else: url = url_for("CmsAdmin:new", error=1) return redirect(url) published_date = datetime.datetime.strptime(published_date, "%Y-%m-%d %H:%M:%S") \ if published_date else now_dt if id and status in ["delete", "revision"]: post = PostModel.Post.get(id) if not post: abort(404, "Post '%s' doesn't exist" % id) if status == "delete": post.delete() flash_success("Post deleted successfully!") return redirect(url_for("CmsAdmin:index")) elif status == "revision": data.update({ "user_id": current_user.id, "parent_id": id, "is_revision": True, "is_draft": False, "is_published": False, "is_public": False }) post = PostModel.Post.create(**data) return jsonify({"revision_id": post.id}) elif status in ["draft", "publish"]: data.update({ "is_published": is_published, "is_draft": is_draft, "is_revision": False, "is_public": is_public }) if id: post = PostModel.Post.get(id) if not post: abort(404, "Post '%s' doesn't exist" % id) elif post.is_revision: abort(403, "Can't access this post") else: if is_sticky and not post.is_sticky: data["sticky_at"] = now_dt if is_featured and not post.is_featured: data["featured_at"] = now_dt post.update(**data) else: data["user_id"] = current_user.id if is_published: data["published_at"] = published_date if is_sticky: data["sticky_at"] = now_dt if is_featured: data["featured_at"] = now_dt post = PostModel.Post.create(**data) # prepare tags _tags = [] for tag in tags: tag = tag.strip().lower() _tag = PostModel.Tag.get_by_slug(name=tag) if tag and not _tag: _tag = PostModel.Tag.new(name=tag) if _tag: _tags.append(_tag.id) post.update_tags(_tags) post.set_slug(slug or title) post.update_categories(map(int, post_categories)) post.set_options("social", social_options) if post.is_published and not post.published_at: post.update(published_at=published_date) flash_success("Post saved successfully!") return redirect(url_for("CmsAdmin:edit", id=post.id)) else: abort(400, "Invalid post status")
def oauth_login(self, provider): """ Login via oauth providers """ self._login_enabled() self._oauth_enabled() provider = provider.lower() result = oauth.login(provider) response = oauth.response popup_js_custom = {"action": "", "url": ""} if result: if result.error: pass elif result.user: result.user.update() oauth_user = result.user user = User.get_by_oauth(provider=provider, provider_user_id=oauth_user.id) if not user: if oauth_user.email and User.get_by_email(oauth_user.email): flash_error( "Account already exists with this email '%s'. " "Try to login or retrieve your password " % oauth_user.email ) popup_js_custom.update( {"action": "redirect", "url": url_for(login_view, next=request.form.get("next"))} ) else: tmp_data = { "is_oauth": True, "provider": provider, "id": oauth_user.id, "name": oauth_user.name, "picture": oauth_user.picture, "first_name": oauth_user.first_name, "last_name": oauth_user.last_name, "email": oauth_user.email, "link": oauth_user.link, } if not oauth_user.email: self.tmp_data = tmp_data popup_js_custom.update( {"action": "redirect", "url": url_for("UserAccount:setup_login")} ) else: try: picture = oauth_user.picture user = User.new( email=oauth_user.email, name=oauth_user.name, signup_method=provider, profile_image_url=picture, ) user.add_oauth( provider, oauth_user.provider_id, name=oauth_user.name, email=oauth_user.email, profile_image_url=oauth_user.picture, link=oauth_user.link, ) except ModelError as e: flash_error(e.message) popup_js_custom.update({"action": "redirect", "url": url_for("UserAccount:login")}) if user: self.login_user(user) return self.render_( popup_js=result.popup_js(custom=popup_js_custom), view_template_=template_page % "oauth_login" ) return response
def setup_login(self): """ Allows to setup a email password if it's not provided specially coming from oauth-login :return: """ self._login_enabled() self.meta_(title="Setup Login") # Only user without email can set email if current_user.is_authenticated() and current_user.email: return redirect(url_for("%s:account_settings" % view_name)) if self.tmp_data: if request.method == "POST": if not self.tmp_data["is_oauth"]: return redirect("UserAccount:login") try: email = request.form.get("email") password = request.form.get("password") password2 = request.form.get("password2") if not utils.is_valid_email(email): raise ViewError("Invalid email address '%s'" % email) elif User.get_by_email(email): raise ViewError("An account exists already with this email address '%s' " % email) elif not password.strip() or password.strip() != password2.strip(): raise ViewError("Passwords don't match") elif not utils.is_valid_password(password): raise ViewError("Invalid password") else: user = User.new( email=email, password=password.strip(), name=self.tmp_data["name"], profile_image_url=self.tmp_data["picture"], signup_method=self.tmp_data["provider"], ) user.add_oauth( self.tmp_data["provider"], self.tmp_data["id"], name=self.tmp_data["name"], email=email, profile_image_url=self.tmp_data["picture"], link=self.tmp_data["link"], ) self.login_user(user) self.tmp_data = None return redirect(request.form.get("next") or url_for(on_signin_view)) except Exception as ex: flash_error(ex.message) return redirect(url_for("UserAccount:setup_login")) return self.render_(provider=self.tmp_data, view_template_=template_page % "setup_login") else: return redirect(url_for("UserAccount:login"))
def user_admin_post(self): try: id = request.form.get("id") user = User.get(id, include_deleted=True) if not user: flash_error("Can't change user info. Invalid user") return redirect(url_for("UserAdmin:index")) if current_user.role.level < user.role.level: abort(403, "Not enough rights to update this user info") email = request.form.get("email", "").strip() first_name = request.form.get("first_name") last_name = request.form.get("last_name") user_role = request.form.get("user_role") action = request.form.get("action") if user.id != current_user.id: _role = Role.get(user_role) if not _role: raise ViewError("Invalid role") if current_user.role.name.lower() not in PRIVILEDGED_ROLES: raise ViewError("Not Enough right to change user's info") if action == "activate": user.update(active=True) flash_success("User has been ACTIVATED") elif action == "deactivate": user.update(active=False) flash_success("User is now DEACTIVATED") elif action == "delete": user.delete() flash_success("User has been deleted") elif action == "undelete": user.delete(False) flash_success("User is now active") else: if email and email != user.email: if not utils.is_valid_email(email): raise ViewError("Invalid email address '%s'" % email) else: if User.get_by_email(email): raise ViewError("Email exists already '%s'" % email) user.update(email=email) user.update(first_name=first_name, last_name=last_name, role_id=_role.id) else: if email and email != user.email: if not utils.is_valid_email(email): raise ViewError("Invalid email address '%s'" % email) else: if User.get_by_email(email): raise ViewError("Email exists already '%s'" % email) user.update(email=email) user.update(first_name=first_name, last_name=last_name) flash_success("User's Info updated successfully!") except Exception as ex: flash_error("Error: %s " % ex.message) return redirect(url_for("UserAdmin:get", id=id))