Exemplo n.º 1
0
    def send(self, request: Request, session: Session, mail: Mail,
             validate: Validator):
        errors = request.validate(validate.required('email'),
                                  validate.email('email'))

        if errors:
            return request.back().with_errors(errors)

        email = request.input('email')
        user = AUTH['guards']['web']['model'].where('email', email).first()

        if user:
            if not user.remember_token:
                user.remember_token = str(uuid.uuid4())
                user.save()
            message = 'Please visit {}/password/{}/reset to reset your password'.format(
                env('SITE', 'http://localhost:8000'), user.remember_token)
            mail.subject('Reset Password Instructions').to(
                user.email).send(message)

        session.flash(
            'success',
            'If we found that email in our system then the email has been sent. Please follow the instructions in the email to reset your password.'
        )
        return request.redirect('/password')
Exemplo n.º 2
0
    def send(self, request: Request, session: Session, mail: Mail,
             validate: Validator):
        errors = request.validate(validate.required("email"),
                                  validate.email("email"))

        if errors:
            return request.back().with_errors(errors)

        email = request.input("email")
        user = AUTH["guards"]["web"]["model"].where("email", email).first()

        if user:
            if not user.remember_token:
                user.remember_token = str(uuid.uuid4())
                user.save()
            message = "Please visit {}/password/{}/reset to reset your password".format(
                env("SITE", "http://localhost:8000"), user.remember_token)
            mail.subject("Reset Password Instructions").to(
                user.email).send(message)

        session.flash(
            "success",
            "If we found that email in our system then the email has been sent. Please follow the instructions in the email to reset your password.",
        )
        return request.redirect("/password")
Exemplo n.º 3
0
    def send(self, request: Request, session: Session, mail: Mail,
             validate: Validator):

        errors = request.validate(validate.required("email"),
                                  validate.email("email"))

        if errors:
            request.session.flash("error", errors)
            return request.back()

        email = request.input("email")
        user = AUTH["model"].where("email", email).first()

        if user:
            if not user.remember_token:
                user.remember_token = str(uuid.uuid4())
                user.save()

            link = "{}/users/reset-password/{}".format(
                request.environ["HTTP_HOST"], user.remember_token)

            mail.subject("{}: Reset Your Password".format(
                config("application.name"))).template(
                    "users/password-reset-email", {
                        "name": user.name,
                        "link": link
                    }).to(user.email).send()

        session.flash("success", self.reset_message)

        return request.redirect("/")
Exemplo n.º 4
0
    def store(self, request: Request, auth: Auth, validate: Validator,
              view: View):
        user = User.all()

        email = User.lists('email')
        pw = User.lists('password')

        errors = request.validate(validate.required(['email', 'password']),
                                  validate.email('email'))

        #checks for errors in login inputs and redirects user back to login page.
        if errors:
            return request.back().with_errors(errors).with_input()

        elif request.input('email') not in email and request.input(
                'password') not in pw:
            return request.back().with_errors(
                {'email': ["Email and password not found. Please register."]})

        #check to see if user already had an account which they may have closed/cancelled and need to register for a new account or reactivate account.
        if user.where('email',
                      request.input('email')).where('cancelled', 'Yes'):
            # cancelled = True
            user_id = User.where('email',
                                 request.input('email')).get().pluck('id')
            return request.redirect('/reregister/' + str(user_id[0]))

        #logins user if no errors and account has not been closed/cancelled before
        if auth.login(request.input('email'), request.input('password')):
            return request.redirect('/')

        # returns back to login page if email or password are incorrect
        return request.back().with_errors(
            {'email': ["Email or password is incorrect"]})
    def send(self, view: View, request: Request, auth: Auth,
             validate: Validator, mail: Mail):
        email_list = User.lists('email')
        email = request.input('email')
        encoded_jwt = jwt.encode(
            {
                'email': email,
                'httpMethod': 'GET'
            },
            'secret',
            algorithm='HS256',
        ).decode('utf-8')

        errors = request.validate(validate.required('email'),
                                  validate.email('email'))

        if errors:
            return request.back().with_errors(errors)

        if email not in email_list:
            return request.back().with_errors({
                'error':
                ['We can not find your email.  Please enter correct email']
            })

        else:
            message = 'Please visit {}/password/reset/get/{} to reset your password'.format(
                env('APP_URL', 'http://localhost:8000'), encoded_jwt)
            mail.subject('Reset Password Instructions').to(email).send(message)
            request.session.flash(
                'success',
                'An email has been sent. Please follow the instructions in the email to reset your password.'
            )
            return request.redirect('login'), email
Exemplo n.º 6
0
    def reregister(self, request: Request, validate: Validator, auth: Auth):
        today_date = date.today()

        errors = request.validate(
            validate.required([
                'firstname', 'lastname', 'address', 'email', 'username',
                'password', 'cell_phone'
            ]),
            validate.email('email'),
            validate.strong(
                'password',
                length=8,
                special=1,
                uppercase=1,
                # breach=True checks if the password has been breached before.
                # Requires 'pip install pwnedapi'
                breach=False))
        if errors:
            return request.back().with_errors(errors).with_input()

        if request.input('password') != request.input('password_confirm'):
            return request.back().with_errors({
                'error':
                ['Passwords do not match.  Please make sure passwords match']
            })

        User.where(
            'id',
            request.param('id')).update(firstname=request.input('firstname'))
        User.where(
            'id',
            request.param('id')).update(lastname=request.input('lastname'))
        User.where(
            'id', request.param('id')).update(address=request.input('address'))
        User.where(
            'id',
            request.param('id')).update(cell_phone=request.input('cell_phone'))
        User.where('id',
                   request.param('id')).update(email=request.input('email'))
        User.where(
            'id',
            request.param('id')).update(username=request.input('username'))
        User.where('id', request.param('id')).update(
            password=password(request.input('password')))
        User.where('id', request.param('id')).update(cancelled='No')
        User.where('id', request.param('id')).update(re_activated='Yes')
        User.where('id', request.param('id')).update(reactivated_on=today_date)

        auth.login(request.input('email'), request.input('password'))

        request.session.flash(
            'success',
            'Your account has been reactivated.  Thank you for trusing us again.'
        )

        return request.redirect('/')
Exemplo n.º 7
0
    def store(
        self,
        request: Request,
        mail_manager: MailManager,
        auth: Auth,
        validate: Validator,
    ):
        """Register the user with the database.

        Arguments:
            request {masonite.request.Request} -- The Masonite request class.

        Returns:
            masonite.request.Request -- The Masonite request class.
        """
        errors = request.validate(
            validate.required(["name", "email", "password"]),
            validate.email("email"),
            validate.strong(
                "password",
                length=8,
                special=1,
                uppercase=1,
                # breach=True checks if the password has been breached before.
                # Requires 'pip install pwnedapi'
                breach=False,
            ),
        )
        if User.where('email', request.input("email")).limit(1).first():
            print('error', errors)
            errors.merge({'email': ["Email was used by someone else"]})
            print('error', errors)
            # return request.back().with_errors(errors).with_input()

        if errors:
            return request.back().with_errors(errors).with_input()

        user = auth.register({
            "name": request.input("name"),
            "password": request.input("password"),
            "email": request.input("email"),
        })

        if isinstance(user, MustVerifyEmail):
            user.verify_email(mail_manager, request)

        # Login the user
        if auth.login(request.input("email"), request.input("password")):
            # Redirect to the homepage
            return request.redirect("/home")

        # Login failed. Redirect to the register page.
        return request.back().with_input()
    def update(self, request: Request, validate: Validator, auth: Auth,
               view: View):
        user = User.all()
        customer = request.user()

        email = User.lists('email')
        user_name = User.lists('username')

        #Checks to see if updated email or username already exists
        if request.input('email') != customer.email:
            if request.input('email') in email:
                return request.back().with_errors({
                    'error':
                    ['{} already exists'.format(request.input('email'))]
                })
        elif request.input('username') != customer.username:
            if request.input('username') in user_name:
                return request.back().with_errors({
                    'error':
                    ['{} already exists'.format(request.input('username'))]
                })

        #Inputs to update customer information
        user.where(
            'id',
            customer.id).first().update(firstname=request.input('firstname'))
        user.where(
            'id',
            customer.id).first().update(lastname=request.input('lastname'))
        user.where(
            'id', customer.id).first().update(address=request.input('address'))
        user.where(
            'id',
            customer.id).first().update(cell_phone=request.input('cell_phone'))
        user.where('id',
                   customer.id).first().update(email=request.input('email'))
        user.where(
            'id',
            customer.id).first().update(username=request.input('username'))

        #Checks that all information is filled out properly
        errors = request.validate(
            validate.required(
                ['firstname', 'lastname', 'address', 'email', 'username']),
            validate.email('email'))

        if errors:
            return request.back().with_errors(errors).with_input()
        else:
            request.session.flash(
                'success', 'Your account has been successfully updated.')
            return request.redirect('account')
Exemplo n.º 9
0
    def register(self, request: Request, auth: Auth, validate: Validator):

        """ register a new administrator and also checks that form is filled out properly without errors and checks to see if email, passwords, and
        usernames alread exits"""

        email = Administrator.lists('admin_email')
        user_name = Administrator.lists('admin_username')
        pw = Administrator.lists('password')

        #check to see if emails or usernames already exist
        accounts = [email, user_name]
        inputs = [request.input('admin_email'), request.input('admin_username')]

        for input in inputs:
            for account in accounts:
                if inputs[0] in accounts[0] and inputs[1] in accounts[1]:
                    return request.back().with_errors({'error': ['{} and {} already exists'.format(inputs[0], inputs[1])]})
                elif input in account:
                    return request.back().with_errors({'error': ['{} already exists'.format(input)]})

        #checking to see if password already exists

        for pw in pw:
            if bcrypt.checkpw(bytes(request.input('admin_password'), 'utf-8'), bytes(pw, 'utf-8')):
                return request.back().with_errors({'error': ['Password already exists.  Please create a new password.']})

        #checking for user entry errors when registering as an Administrator
        errors = request.validate(
            validate.required(['admin_name', 'admin_cell_phone', 'admin_address', 'admin_email', 'admin_username', 'admin_password']),
            validate.email('admin_email'),
            validate.strong('admin_password', length=8, special=1, uppercase=1)
            )

        if errors:
            return request.back().with_errors(errors).with_input()
        #when everything above checks out ok, then go ahead and insert data in Administrator table
        else:
            encoded_jwt = jwt.encode({'email': request.input('admin_email')},os.getenv('KEY') ,algorithm='HS256')
            encrypted_password = password(request.input('admin_password'))
            Administrator.insert(admin_name=request.input('admin_name'),
                                    admin_cell_phone=request.input('admin_cell_phone'),
                                    admin_address=request.input('admin_address'),
                                    admin_email=request.input('admin_email'),
                                    admin_username=request.input('admin_username'),
                                    password=encrypted_password,
                                    remember_token=encoded_jwt)

        return request.redirect('/admin')
Exemplo n.º 10
0
    def store(
        self,
        request: Request,
        mail_manager: MailManager,
        auth: Auth,
        validate: Validator,
    ):

        errors = request.validate(
            validate.required(["name", "email", "password"]),
            validate.email("email"),
            validate.not_in_database(
                "email",
                table="users",
                column="email",
                messages={"email": "This email address is already registered"},
            ),
            validate.confirmed("password"),
            validate.length(
                "password",
                min=config("auth.password_min_length"),
                max=config("auth.password_max_length"),
            ),
        )

        if errors:
            return return_with_errors(errors)

        auth.register({
            "name": request.input("name"),
            "password": request.input("password"),
            "email": request.input("email"),
        })

        user = User.where("email", request.input("email")).first()

        if isinstance(user, MustVerifyEmail):
            user.verify_email(mail_manager, request)

        # Login the user
        if auth.login(user.email, request.input("password")):
            request.session.flash(
                "success",
                "Your account has been successfully created. Check your email to verify your email address.",
            )
            return request.redirect("/")
Exemplo n.º 11
0
    def store(self, request: Request, mail_manager: MailManager, auth: Auth,
              validate: Validator, event: Event):
        """Register the user with the database.

        Arguments:
            request {masonite.request.Request} -- The Masonite request class.

        Returns:
            masonite.request.Request -- The Masonite request class.
        """
        errors = request.validate(
            validate.required(["name", "email", "password"]),
            validate.email("email"),
            validate.strong(
                "password",
                length=8,
                special=1,
                uppercase=1,
                # breach=True checks if the password has been breached before.
                # Requires 'pip install pwnedapi'
                breach=False,
            ),
        )

        if errors:
            return request.back().with_errors(errors).with_input()

        user = auth.register({
            "name": request.input("name"),
            "password": request.input("password"),
            "email": request.input("email"),
        })

        # fire signup event to set is_admin column
        event.fire('user.signedup', user=user, isAdmin=False)

        if isinstance(user, MustVerifyEmail):
            user.verify_email(mail_manager, request)

        # Login the user
        if auth.login(user.email, request.input("password")):
            # Redirect to the homepage
            return request.redirect("/home")

        # Login failed. Redirect to the register page.
        return request.back().with_input()
Exemplo n.º 12
0
    def sign_in(self, request: Request, auth: Auth, validate: Validator):
        errors = request.validate(
            validate.required(["email", "password"]),
            validate.email("email"),
        )

        if errors:
            return return_with_errors(errors)

        user = auth.login(request.input("email"), request.input("password"))

        if not user:
            return return_with_errors(
                {"password": "******"})

        request.session.flash("success", "You have been logged in.")
        return request.redirect("/")
Exemplo n.º 13
0
    def login(self, request: Request, session: SessionManager,
              validate: Validator):

        tech = Technician.all()
        tech_emails = Technician.lists('pool_tech_email')

        pool_tech_user = tech.where('pool_tech_email',
                                    request.input('email')).first()
        pw = tech.where('password', request.input('password')).first()

        errors = request.validate(
            validate.required(['email', 'password']), validate.email('email'),
            validate.strong('password', length=8, special=1, uppercase=1))

        #checks for errors in login inputs and redirects user back to login page.
        if errors:
            return request.back().with_errors(errors).with_input()

        #checks to see if admin enters correct email/password credentials and if no admin account exits and needs to register for one.

        if request.input('email') not in tech_emails:
            if not any(
                    bcrypt.checkpw(bytes(request.input('password'), 'utf-8'),
                                   bytes(pw, 'utf-8'))
                    for pw in Technician.lists('password')):
                return request.back().with_errors({
                    'email': [
                        'Credentials not found. Please register as a new pool technician.'
                    ]
                })
            else:
                return request.back().with_errors(
                    {'email': ['Email is incorrect!']})

        elif pool_tech_user and not bcrypt.checkpw(
                bytes(request.input('password'), 'utf-8'),
                bytes(pool_tech_user.password, 'utf-8')):
            return request.back().with_errors(
                {'email': ['Password is incorrect!']})

        else:
            session.driver('cookie').set('key', 'value')
            return request.redirect('/tech/dashboard/')
Exemplo n.º 14
0
    def update(self, view: InertiaResponse, validate: Validator,
               upload: Upload):
        user = User.find(self.request.param("user"))
        if user.is_demo_user:
            self.request.session.flash(
                'error', 'Updating the demo user is not allowed.')
            return self.request.redirect(
                f"/users/{user.id}/edit"
            )  #.with_errors("Updating the demo user is not allowed.")

        errors = self.request.validate(
            validate.required(['first_name', 'last_name', 'email', 'owner']),
            validate.length(['first_name', 'last_name', 'email'], max=50),
            validate.email('email'),
            validate.when(validate.exists('password')).then(
                validate.strong('password', length=8, special=1))
            # TODO: add unique
        )

        if errors:
            return self.request.redirect(f"users/{user.id}").with_errors(
                errors).with_input()

        # update user
        user.first_name = self.request.input('first_name')
        user.last_name = self.request.input('last_name')
        user.email = self.request.input('email')
        user.owner = self.request.input('owner')

        if self.request.input('password'):
            pass

        photo_path = None
        if self.request.input('photo'):
            photo_path = upload.driver('disk').store(
                self.request.input('file_upload'), location='disk.profiles')
            user.photo_path = photo_path

        user.save()

        self.request.session.flash('success', 'User updated.')
        return self.request.back()
Exemplo n.º 15
0
    def store(self, request: Request, mail_manager: MailManager, auth: Auth,
              validate: Validator):
        """Register the user with the database.

        Arguments:
            request {masonite.request.Request} -- The Masonite request class.

        Returns:
            masonite.request.Request -- The Masonite request class.
        """
        errors = request.validate(
            validate.required(['name', 'email', 'password']),
            validate.email('email'),
            validate.strong(
                'password',
                length=8,
                special=1,
                uppercase=1,
                # breach=True checks if the password has been breached before.
                # Requires 'pip install pwnedapi'
                breach=False))

        if errors:
            return request.back().with_errors(errors).with_input()

        user = auth.register({
            'name': request.input('name'),
            'password': request.input('password'),
            'email': request.input('email'),
        })

        if isinstance(user, MustVerifyEmail):
            user.verify_email(mail_manager, request)

        # Login the user
        if auth.login(request.input('email'), request.input('password')):
            # Redirect to the homepage
            return request.redirect('/home')

        # Login failed. Redirect to the register page.
        return request.back().with_input()
Exemplo n.º 16
0
    def store(self, request: Request, auth: Auth, validate: Validator):
        """Login the user.

        Arguments:
            request {masonite.request.Request} -- The Masonite request class.
            auth {masonite.auth.auth} -- The Masonite auth class.
            validate {masonite.validator.Validator} -- The Masonite Validator class.

        Returns:
            masonite.request.Request -- The Masonite request class.
        """
        errors = request.validate(
            validate.required(["email", "password"]),
            validate.email("email"),
        )

        if errors:
            return request.back().with_errors(errors).with_input()

        if auth.login(request.input("email"), request.input("password")):
            return request.redirect("/home")

        return request.back().with_errors({"email": ["Email or password is incorrect"]})
Exemplo n.º 17
0
    def store(self, view: InertiaResponse, validate: Validator,
              upload: Upload):
        errors = self.request.validate(
            validate.required(['email', 'first_name', 'last_name', 'owner']),
            validate.truthy('owner'),
            validate.length(['first_name', 'last_name', 'email'], max=50),
            validate.email('email'),
            # validate.when(
            #     validate.exists('photo')
            # ).then(
            #     validate.image('photo')
            # ), TODO: fix the error, file validators do not work with FieldStorage for now ...
            validate.when(validate.exists('password')).then(
                validate.strong('password', length=8, special=1)))

        if errors:
            # return self.request.back().with_errors(errors).with_input()
            # return view.render('Users/Create').with_errors(errors).with_input()
            return self.request.redirect('users/create').with_errors(
                errors).with_input()

        photo_path = None
        if self.request.input('photo'):
            # save file
            photo_path = upload.driver('disk').store(
                self.request.input('file_upload'), location='disk.profiles')

        self.request.user().account.users().create(
            first_name=self.request.input('first_name'),
            last_name=self.request.input('last_name'),
            email=self.request.input('email'),
            owner=self.request.input('owner'),
            password=self.request.input('password'),
            photo_path=photo_path)

        self.request.session.flash('success', 'User created.')
        return self.request.redirect('/users')
Exemplo n.º 18
0
    def register(self, request: Request, auth: Auth, validate: Validator,
                 mail: Mail):
        """ register a new customer and also checks that form is filled out properly without errors and checks to see if email, passwords, and
        usernames alread exits"""

        email = User.lists('email')
        user_name = User.lists('username')
        pws = User.lists('password')

        errors = request.validate(
            validate.required([
                'firstname', 'lastname', 'address', 'email', 'username',
                'password', 'cell_phone'
            ]),
            validate.email('email'),
            validate.strong(
                'password',
                length=8,
                special=1,
                uppercase=1,
                # breach=True checks if the password has been breached before.
                # Requires 'pip install pwnedapi'
                breach=False))

        #Will display what errors where committed when filling out registration form.
        if errors:
            return request.back().with_errors(errors).with_input()

        #check to see if emails or usernames already exist
        accounts = [email, user_name]
        inputs = [request.input('email'), request.input('username')]

        for input in inputs:
            for account in accounts:
                if inputs[0] in accounts[0] and inputs[1] in accounts[1]:
                    return request.back().with_errors({
                        'error': [
                            '{} and {} already exists'.format(
                                inputs[0], inputs[1])
                        ]
                    })
                elif input in account:
                    return request.back().with_errors(
                        {'error': ['{} already exists'.format(input)]})

        # checking to see if password already exists
        for pw in pws:
            if bcrypt.checkpw(bytes(request.input('password'), 'utf-8'),
                              bytes(pw, 'utf-8')):
                return request.back().with_errors({
                    'error': [
                        'Password already exists.  Please create a new password.'
                    ]
                })

        if request.input('password') != request.input('password_confirm'):
            return request.back().with_errors({
                'error':
                ['Passwords do not match.  Please make sure passwords match']
            })

        #This registers a new account
        user = auth.register({
            'firstname': request.input('firstname'),
            'lastname': request.input('lastname'),
            'address': request.input('address'),
            'cell_phone': request.input('cell_phone'),
            'email': request.input('email'),
            'username': request.input('username'),
            'password': request.input('password')
        })
        #Checking to see if all inputs on registration form are in correct format.

        #Will send an email confirming account has been created.
        mail.send_from(
            '*****@*****.**').subject('Account Confirmation').to(
                request.input('email')).template('mail/mail').send()

        # Login the user
        if auth.login(request.input('email'), request.input('password')):
            # Redirect to the homepage
            return request.redirect('/')

        return request.back().with_input()