Exemplo n.º 1
0
 def index(self):
     adata = app_data.get(APP_DATA_KEY)
     page_attr("Contact Us Settings")
     return {
         "recipients": adata.get("recipients"),
         "success_message": adata.get("success_message"),
     }
Exemplo n.º 2
0
Arquivo: auth.py Projeto: mardix/Mocha
    def index(self):

        page_attr("All Users")

        include_deleted = True if request.args.get("include-deleted") == "y" else False
        username = request.args.get("username")
        name = request.args.get("name")
        email = request.args.get("email")
        role = request.args.get("role")
        sorting = request.args.get("sorting", "first_name__asc")
        users = models.AuthUser.query(include_deleted=include_deleted)
        users = users.join(models.AuthUserRole).filter(models.AuthUserRole.level <= current_user.role.level)

        if username:
            users = users.filter(models.AuthUser.username.contains(username))
        if email:
            users = users.filter(models.AuthUser.email.contains(email))
        if name:
            users = models.AuthUser.search_by_name(users, name)
        if role:
            users = users.filter(models.AuthUser.role_id == int(role))
        if sorting and "__" in sorting:
            col, dir = sorting.split("__", 2)
            if dir == "asc":
                users = users.order_by(getattr(models.AuthUser, col).asc())
            else:
                users = users.order_by(getattr(models.AuthUser, col).desc())

        users = paginate(users)

        sorting = [("username__asc", "Username ASC"),
                   ("username__desc", "Username DESC"),
                   ("email__asc", "Email ASC"),
                   ("email__desc", "Email DESC"),
                   ("first_name__asc", "First Name ASC"),
                   ("first_name__desc", "First Name DESC"),
                   ("last_name__asc", "Last Name ASC"),
                   ("last_name__desc", "Last Name DESC"),
                   ("created_at__asc", "Signup ASC"),
                   ("created_at__desc", "Signup DESC"),
                   ("last_login__asc", "Login ASC"),
                   ("last_login__desc", "Login DESC")
                   ]

        return dict(user_roles_options=self._user_roles_options(),
                    sorting_options=sorting,
                    users=users,
                    search_query={
                        "include-deleted": request.args.get("include-deleted", "n"),
                        "role": int(request.args.get("role")) if request.args.get("role") else "",
                        "status": request.args.get("status"),
                        "name": request.args.get("name", ""),
                        "username": request.args.get("username", ""),
                        "email": request.args.get("email", ""),
                        "sorting": request.args.get("sorting")
                        }
                    )
Exemplo n.º 3
0
Arquivo: auth.py Projeto: mardix/Mocha
    def info(self, id):
        page_attr("User Info")
        user = models.AuthUser.get(id, include_deleted=True)
        if not user:
            abort(404, "User doesn't exist")

        if current_user.role.level < user.role.level:
            abort(403, "Not enough rights to access this user info")

        return {
            "user": user,
            "user_roles_options": self._user_roles_options()
        }
Exemplo n.º 4
0
        def index(error):

            page_attr("Error %s" % error.code)

            # if isinstance(error, SQLAlchemyError):
            #     error = SQLAlchemyHTTPException(error)
            # we'll log non 4** errors
            if int(error.code // 100) != 4:
                _error = str(error)
                _error += " - HTTException Code: %s" % error.code
                _error += " - HTTException Description: %s" % error.description
                logging.error(_error)

            if renderer:
                return renderer(error)
            else:
                return cls.render({"error": error}, _template=template_page)
Exemplo n.º 5
0
Arquivo: auth.py Projeto: mardix/Mocha
    def lost_password(self):

        if not __options__.get("allow_login"):
            abort(403, "Login is not allowed. Contact admin if it's a mistake")

        page_attr("Lost Password")

        if request.method == "POST":
            username = request.form.get("username")
            user = models.AuthUser.get_by_username(username)
            if user:
                user = UserModel(user)
                user.send_password_reset(view_class=self)
                flash_success("A new password has been sent to '%s'" % user.email)
                return redirect(self.login)
            else:
                flash_error("Invalid login")
                return redirect(self.lost_password)
Exemplo n.º 6
0
Arquivo: auth.py Projeto: mardix/Mocha
    def login(self):
        if not __options__.get("allow_login"):
            abort(403, "Login is not allowed. Contact admin if it's a mistake")

        if request.method == "POST":
            username = request.form.get("username", "").strip()
            password = request.form.get("password", "").strip()
            try:
                if not username or not password:
                    raise mocha_exc.AppError("Email/Username or Password is empty")

                user = authenticate(username=username, password=password)
                if not user:
                    raise mocha_exc.AppError("Email or Password is invalid")

                create_session(user)

                # if user.require_password_change is True:
                #     flash_info("Password change is required")
                #     session_set_require_password_change(True)
                # return redirect(views.auth.Account.account_settings, edit_password=1)

                return redirect(request.form.get("next") or __options__.get("login_view"))

            except exceptions.VerifyEmailError as ve:
                return redirect(self.login, username=username, v="1")
            except (mocha_exc.AppError, exceptions.AuthError) as ae:
                flash_error(str(ae))
            except Exception as e:
                logging.exception(e)
                flash_error("Unable to login")

            return redirect(self.login, next=request.form.get("next"))

        page_attr("Login")
        return {
            "username": request.args.get("username"),
            "login_url_next": request.args.get("next", ""),
            "allow_registration": __options__.get("allow_registration"),
            "show_verification_message": True if request.args.get("v") == "1" else False
        }
Exemplo n.º 7
0
Arquivo: auth.py Projeto: mardix/Mocha
    def request_email_verification(self):
        """"""
        if not __options__.get("verify_email"):
            return redirect(self.login)

        if request.method == "POST":
            email = request.form.get("email")
            if email and utils.is_email_valid(email):
                user = models.AuthUser.get_by_email(email)
                if user:
                    if not user.email_verified:
                        send_email_verification_email(user, view_class=self)
                        flash_success(
                            "A verification email has been sent to %s" % email)
                    else:
                        flash_success("Your account is already verified")
                    return redirect(self.login, email=email)
            flash_error("Invalid account")
            return redirect(self.request_email_verification, email=email)

        page_attr("Request Email Verification")
        return {
            "email": request.args.get("email"),
        }
Exemplo n.º 8
0
    def page(self):

        recipients = app_data.get(APP_DATA_KEY, "recipients") \
                     or __options__.get("recipients") \
                     or config("CONTACT_EMAIL")

        if not recipients:
            abort(500, "ContactPage missing email recipient")

        success_message = app_data.get(APP_DATA_KEY,
                                       "success_message",
                                       __options__.get("success_message"))

        return_to = __options__.get("return_to", None)
        if return_to:
            if "/" not in return_to:
                return_to = url_for(return_to)
        else:
            return_to = url_for(self)

        if request.method == "POST":
            email = request.form.get("email")
            subject = request.form.get("subject")
            message = request.form.get("message")
            name = request.form.get("name")

            try:
                if recaptcha.verify():
                    if not email or not subject or not message:
                        raise exceptions.AppError("All fields are required")
                    elif not utils.is_email_valid(email):
                        raise exceptions.AppError("Invalid email address")
                    else:
                        try:
                            send_mail(to=recipients,
                                      reply_to=email,
                                      mail_from=email,
                                      mail_subject=subject,
                                      mail_message=message,
                                      mail_name=name,
                                      template=__options__.get("template",
                                                               "contact-us.txt")
                                      )
                            flash_data("ContactPage:EmailSent")
                        except Exception as ex:
                            logging.exception(ex)
                            raise exceptions.AppError("Unable to send email")
                else:
                    raise exceptions.AppError("Security code is invalid")
            except exceptions.AppError as e:
                flash_error(e.message)
            return redirect(self)

        title = __options__.get("title", _("Contact Us"))
        page_attr(title)

        fd = get_flash_data()
        return {
            "title": title,
            "email_sent": True if fd and "ContactPage:EmailSent" in fd else False,
            "success_message": success_message,
            "return_to": return_to
        }
Exemplo n.º 9
0
Arquivo: main.py Projeto: mardix/Mocha
 def index(self):
     page_attr(title="Hello View!")
     return
Exemplo n.º 10
0
Arquivo: auth.py Projeto: mardix/Mocha
    def roles(self):
        """
        Only admin and super admin can add/remove roles
        RESTRICTED ROLES CAN'T BE CHANGED
        """
        roles_max_range = 11
        if request.IS_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 models.AuthUserRole.ROLES]
                    _names = [r[1] for r in models.AuthUserRole.ROLES]
                    if level in _levels or name in _names:
                        raise exceptions.AuthError(
                            "Can't modify PRIMARY Roles - name: %s, level: %s " % (
                                name, level))
                    else:
                        if id:
                            role = models.AuthUserRole.get(id)
                            if role:
                                if action == "delete":
                                    role.update(level=0)  # Free the role
                                    role.delete()
                                    flash_success(
                                        "Role '%s' deleted successfully!" % role.name)
                                elif action == "update":
                                    if role.level != level and models.AuthUserRole.get_by_level(
                                            level):
                                        raise exceptions.AuthError(
                                            "Role Level '%s' exists already" % level)
                                    elif role.name != models.AuthUserRole.slug_name(
                                            name) and models.AuthUserRole.get_by_name(
                                        name):
                                        raise exceptions.AuthError(
                                            "Role Name '%s'  exists already" % name)
                                    else:
                                        role.update(name=name, level=level)
                                        flash_success(
                                            "Role '%s (%s)' updated successfully" % (
                                                name, level))
                            else:
                                raise exceptions.AuthError("Role doesn't exist")
                        else:
                            if models.AuthUserRole.get_by_level(level):
                                raise exceptions.AuthError(
                                    "New Role Level '%s' exists already" % level)
                            elif models.AuthUserRole.get_by_name(name):
                                raise exceptions.AuthError(
                                    "New Role Name '%s'  exists already" % name)
                            else:
                                models.AuthUserRole.new(name=name, level=level)
                                flash_success(
                                    "New Role '%s (%s)' addedd successfully" % (
                                        name, level))
            except exceptions.AuthError as ex:
                flash_error("%s" % ex.message)
            return redirect(self.roles)

        page_attr("User Roles")
        roles = models.AuthUserRole.query().order_by(
            models.AuthUserRole.level.desc())

        allocated_levels = [r.level for r in roles]
        # levels_options = [(l, l) for l in range(1, roles_max_range) if l not in allocated_levels]
        levels_options = [(l, l) for l in range(1, roles_max_range)]

        return {
            "roles": roles,
            "levels_options": levels_options
        }
Exemplo n.º 11
0
Arquivo: auth.py Projeto: mardix/Mocha
 def account_settings(self):
     page_attr("Account Info")
     return {}
Exemplo n.º 12
0
Arquivo: auth.py Projeto: mardix/Mocha
    def register(self):
        """ Registration """

        if not __options__.get("allow_registration"):
            abort(403, "Registration is not allowed. Contact admin if it's a mistake")

        page_attr("Register")

        if request.method == "POST":
            try:
                if not recaptcha.verify():
                    raise mocha_exc.AppError("Invalid Security code")

                email = request.form.get("email", "").strip()
                username = request.form.get("username", "").strip()
                password = request.form.get("password", "").strip()
                password_confirm = request.form.get("password_confirm", "").strip()
                first_name = request.form.get("first_name", "").strip()
                last_name = request.form.get("last_name", "").strip()

                with_oauth = request.form.get("with_oauth") == "1"
                oauth_provider = request.form.get("oauth_provider")
                oauth_user_id = request.form.get("oauth_user_id")

                login_method = None

                # Require username and email
                if __options__.get("registration_username"):
                    if "@" in username:
                        raise exceptions.AuthError(_("Username can't be an email"))
                    if not utils.is_email_valid(email):
                        raise exceptions.AuthError(_("Invalid email address"))
                    login_method = "username"

                # Require only email. Email will be used as username and email
                elif __options__.get("registration_email"):
                    if not utils.is_email_valid(username):
                        raise exceptions.AuthError(_("Invalid email address"))
                    email = username
                    login_method = "email"

                if not first_name:
                    raise mocha_exc.AppError(
                        _("First Name or Name is required"))
                elif not password or password != password_confirm:
                    raise mocha_exc.AppError(_("Passwords don't match"))

                if not login_method:
                    raise exceptions.AuthError(_("Registration is disabled"))

                user = create_user(username=username,
                                   password=password,
                                   email=email,
                                   first_name=first_name,
                                   last_name=last_name,
                                   login_method=login_method)

                # WITH OAUTH, we can straight up login user
                if with_oauth and oauth_provider and oauth_user_id:
                    user.add_federation(oauth_provider, oauth_user_id)
                    create_session(user)
                    return redirect(request.form.get(
                        "next") or views.auth.Account.account_settings)

                if __options__.get("require_email_verification"):
                    user.send_welcome_email(view_class=self)
                    flash_success(_("Please check your email. We've sent you a message"))

                return redirect(
                    request.form.get("next") or __options__.get("login_view"))

            except (mocha_exc.AppError, exceptions.AuthError) as ex:
                flash_error(str(ex))
            except Exception as e:
                logging.exception(e)
                flash_error("Unable to register")
            return redirect(self.register, next=request.form.get("next"))

        return {
            "reg_email": __options__.get("registration_email"),
            "reg_username": __options__.get("registration_username"),
            "reg_social": __options__.get("registration_social"),
            "reg_full_name": __options__.get("registration_full_name"),
            "login_url_next": request.args.get("next", ""),

            "with_oauth": has_oauth_request(),
            "oauth_provider": get_oauth_session().get("provider"),
            "oauth_user_id": get_oauth_session().get("user_id"),
            "email": get_oauth_session().get("email") or "",
            "name": get_oauth_session().get("name") or "",
        }