예제 #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')
예제 #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")
    def once(self, request: Request, validate: Validator, mail: Mail):
        email = request.input('email')
        encoded_jwt = jwt.encode({'email': email, 'httpMethod': 'GET'}, 'secret', algorithm='HS256', ).decode('utf-8')

        errors = request.validate(
            validate.required(['service_type', 'name', 'address', 'email', 'cell_phone']))
            
        if errors:
            return request.back().with_errors(errors)

        OneTimeService.insert({
            'service': request.input('service_type'),
            'customer_name': request.input('name'),
            'address': request.input('address'),
            'service_date': request.input('date')[0],
            'service_time': request.input('date')[1],
            "email": request.input('email'),
            'cell_phone': request.input('cell_phone'),
            'remember_token': encoded_jwt
        })

        email = request.input('email')
        encoded_jwt = jwt.encode({'email': email, 'httpMethod': 'GET'}, 'secret', algorithm='HS256', ).decode('utf-8')

        mail.subject('Pool Appointment Confirmation').to(request.input('email')).template('mail/appt_confirm_guest', {'service': request.input('service_type'),
            'service_date': request.input('date')[0], 'service_time': request.input('date')[1], 'token': encoded_jwt }).send()
       
        request.session.flash('success', 'Your appointment has been successfully scheduled!  A confirmation email has been sent.')

        return request.redirect('/') 
    def update(self, view: View, request: Request, validate: Validator, mail: Mail):
        schedule_date_info =  request.input('date')
        customer = request.user()

        #checking that all required fields are entered and no errors are found.
        errors = request.validate(
            validate.required(['service_type', 'name', 'address']))
            
        if errors:
            return request.back().with_errors(errors)

        if not schedule_date_info[0] or not schedule_date_info[1]:
            request.session.flash('success', "The service date and service time is required.")
            return request.back()

        update_schedule = Schedule.where('id', '=', request.param('slug')).update(service=request.input('service_type'), 
            service_date=schedule_date_info[0], service_time=schedule_date_info[1])

        #need to changed this variable to current new updated info to send in email confirmation.
        customer_schedule = Schedule.get().last()

        #sends email with pool appointment schedule details
        mail.subject('Pool Appointment Update Confirmation').to(customer.email).template('mail/appt_confirm', {'service_id': request.param('slug'), 'service': customer_schedule.service, 
                                'service_date':customer_schedule.service_date, 'service_time':customer_schedule.service_time}).send()
        request.session.flash('success', 'Your appointment has been updated!  A confirmation email has been sent.')

        return request.redirect('/')
예제 #5
0
    def sign_in(self, request: Request, response: Response, auth: Auth,
                validate: Validator):

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

        if errors:
            return errors

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

        if user_auth_res is False:
            return response.json({"error": "Check your credentials"})

        msg = {
            "id": user_auth_res.id,
            "email": user_auth_res.email,
            "name": user_auth_res.name,
            "govId": user_auth_res.gov_id,
            "type": user_auth_res.type,
        }

        enc = utils.encode_message(msg)
        if enc != False:
            return response.json({"access_token": enc.decode("utf-8")})

        return response.json(
            {"error": "You cannot access this system at the time"})
예제 #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('/')
    def store(self, request: Request, validator: Validator):
        errors = request.validate(validator.required(['name', 'description']))

        if errors:
            return {'errors': errors}

        Competition.create(name=request.input('name'),
                           description=request.input('description'))

        return {'status': 'success'}
예제 #8
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')
예제 #10
0
    def update(self, view: View, request: Request, auth: Auth,
               validate: Validator):
        user = User.all()
        pws = User.lists('password')

        customer = request.user()
        pw = customer.password

        if bcrypt.checkpw(bytes(request.input('password'), 'utf-8'),
                          bytes(pw, 'utf-8')) == False:
            return request.back().with_errors(
                {'error': ['Please enter correct old password']})

        new_password = request.input('new_password')
        confirm_password = request.input('confirm_password')

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

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

        if errors:
            return request.back().with_errors(errors).with_input()
        elif new_password != confirm_password:
            return request.back().with_errors({
                'error':
                ['New password and confirm new password do not match!']
            })
        else:
            user.where(
                'id',
                customer.id).first().update(password=password(new_password))
            request.session.flash(
                'success', 'Your password has been successfully updated.')
            return request.redirect('account')
예제 #11
0
    def contact(self, request: Request, auth: Auth, validate: Validator, mail: Mail):
        user_email = request.user().email
        message = request.input('contact')
        message_subject = request.input('subject')

        errors = request.validate(
            validate.required(['subject', 'contact']),
        )
        if errors:
            return request.back().with_errors(errors)
        else:
            mail.send_from(user_email).subject(message_subject).to('*****@*****.**').send(message)
            request.session.flash('success', 'Your message has been successfully sent!')

        return request.redirect('/')
    def store(self, request: Request, response: Response, validate: Validator):
        errors = request.validate(
            validate.required("symptoms"),
            validate.required("diagnosis"),
            validate.required("treatment_plan"),
            validate.required("seen_by"),
        )

        if errors:
            return errors

        patient_id = request.param("patient_id")
        patient_record = {
            "author": f"{self.user.gov_id}@afyamkononi",
            "timestamp": calendar.timegm(time.gmtime()),
            "symptoms": request.input("symptoms"),
            "diagnosis": request.input("diagnosis"),
            "treatment_plan": request.input("treatment_plan"),
            "seen_by": request.input("seen_by"),
        }

        patient_account = self.ibc.get_account_details(
            request.param("patient_id"))

        if patient_account.detail == "":
            return response.json({"error": "No such account"})

        unpacked_data = json.loads(patient_account.detail)
        patient_history = utils.filter_medical_data(unpacked_data)

        history_update = []
        if patient_history == []:
            history_update.append(patient_record)
        else:
            history_update += patient_history
            history_update.append(patient_record)

        history_update = utils.remove_duplicates(history_update)

        blockchain_status = self.ibc.set_patient_record(
            User.where("gov_id", patient_id).first(), history_update)
        print(blockchain_status)
        iroha_message = iroha_messages.update_medical_history_failed(
            blockchain_status)
        if iroha_message is not None:
            return response.json(iroha_message)

        return response.json({"success": "Medical data added successfully"})
예제 #13
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')
예제 #14
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()
예제 #15
0
    def store(self, auth: Auth, request: Request,
              response: Response):  # store register user
        errors = request.validate({
            "email": "required",
            "name": "required",
            "password": "******",
        })

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

        user = auth.register(request.only("name", "email", "password"))

        if not user:
            return response.redirect("/register")

        return response.redirect("/home")
예제 #16
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("/")
    def cancel(sef, request: Request, auth: Auth, validate: Validator,
               mail: Mail):
        user = User.all()
        customer = request.user()

        pw = customer.password

        reason = request.input('radio')
        confirm_password = request.input('password')

        #checking that all required fields are entered and no errors are found.
        errors = request.validate(
            validate.required(
                ['radio', 'password'],
                messages={'radio': "Please choose a reason for cancelling."}))

        if errors:
            return request.back().with_errors(errors)
        elif not bcrypt.checkpw(bytes(confirm_password, 'utf-8'),
                                bytes(pw, 'utf-8')):
            return request.back().with_errors(
                {'error': ["Are you sure that's the right password?"]})

        user_id = user.where('id', customer.id).first()
        # User.where('id', customer.id).where_null('cancelled').update(cancelled='Yes')
        User.where('id', customer.id).update(cancelled="Yes")

        CancelledAccount.insert({
            'user_id': user_id.id,
            'cancel_reason': request.input('radio'),
            'suggestions': request.input('suggestion')
        })

        request.session.flash(
            'success',
            'Your account has been successfully cancelled. Thank you for your business.'
        )
        mail.send_from('*****@*****.**').subject(
            'Cancellation Confirmation').to(customer.email).template(
                'mail/cancel_member', {
                    'title': 'Kennedy Pools & Supplies'
                }).send()
        auth.logout()
        return request.redirect('/')
예제 #18
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/')
예제 #19
0
    def schedule(self, view: View, request: Request, validate: Validator, mail: Mail):
        user = User.all()
        customer = request.user()
        
        name = request.input('name')
        address = request.input('address')
        
        schedule_date_info =  request.input('date')
        path = request.path
    
         #checking that all required fields are entered and no errors are found.
        errors = request.validate(
            validate.required(['service_type', 'name', 'address']))
            
        if errors:
            return request.back().with_errors(errors)

        if not schedule_date_info[0] or not schedule_date_info[1]:
            request.session.flash('success', "The service date and service time is required.")
            return request.back()

        schedule_id = user.where('id', customer.id).first()
        
        Schedule.insert({
            'schedule_id': schedule_id.id,
            'service': request.input('service_type'),
            'service_date': schedule_date_info[0],
            'service_time': schedule_date_info[1], 
            'customer_name': request.input('name')
        })

        #getting the schedules table data
        customer_schedule = Schedule.get().last()
        
         #sends email with pool appointment schedule details
        mail.subject('Pool Appointment Confirmation').to(customer.email).template('mail/appt_confirm', {'service_id': customer_schedule.id, 'service': customer_schedule.service, 
                                'service_date':customer_schedule.service_date, 'service_time':customer_schedule.service_time}).send()
        
        request.session.flash('success', 'Your appointment has been successfully scheduled!  A confirmation email has been sent.')
        
        return request.redirect('/') 
예제 #20
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()
예제 #21
0
    def reset(
        self,
        view: View,
        request: Request,
        validate: Validator,
    ):
        new_password = request.input('new_password')
        pws = User.lists('password')
        decoded_token = jwt.decode(request.param('id'),
                                   'secret',
                                   algorithm='HS256')
        user_email = decoded_token['email']

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

        errors = request.validate(
            validate.required('new_password'),
            validate.strong('new_password',
                            length=8,
                            special=1,
                            uppercase=1,
                            breach=False)
        )  # breach=True checks if the password has been breached before.
        # Requires 'pip install pwnedapi'
        if errors:
            return request.back().with_errors(errors).with_input()
        else:
            AUTH['guards']['web']['model'].where(
                'email',
                user_email).first().update(password=password(new_password))
            request.session.flash(
                'success', 'Your password has been successfully updated.')
            return request.redirect('login')
예제 #22
0
    def update(self, request: Request, validate: Validator):
        errors = request.validate(
            validate.required('password'),
            # TODO: only available in masonite latest versions (which are not compatible with Masonite 2.2)
            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)

        user = AUTH['guards']['web']['model'].where(
            'remember_token', request.param('token')).first()
        if user:
            user.password = bcrypt_password(request.input('password'))
            user.save()
            return request.redirect('/login')
예제 #23
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"]})
예제 #24
0
    def update(self, request: Request, validate: Validator):
        errors = request.validate(
            validate.required("password"),
            # TODO: only available in masonite latest versions (which are not compatible with Masonite 2.2)
            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)

        user = (AUTH["guards"]["web"]["model"].where(
            "remember_token", request.param("token")).first())
        if user:
            user.password = bcrypt_password(request.input("password"))
            user.save()
            return request.redirect("/login")
예제 #25
0
    def register(self, request: Request, response: Response, auth: Auth,
                 validate: Validator):

        errors = request.validate(
            validate.required("name"),
            validate.required("email"),
            validate.required("type"),
            validate.required("gov_id"),
            validate.required("phone_number"),
        )

        if errors:
            return errors

        priv_key = IrohaCrypto.private_key()
        pub_key = IrohaCrypto.derive_public_key(priv_key)

        user = User()
        user.name = request.input("name")
        user.email = request.input("email")
        user.type = request.input("type")
        user.gov_id = request.input("gov_id")
        user.phone_number = request.input("phone_number")
        user.private_key = priv_key.decode("utf-8")
        user.public_key = pub_key.decode("utf-8")
        if user.type == "user":
            user.password = str(random.randrange(1000, 9999))
        else:
            user.password = request.input("password")

        blockchain_status = self.ibc.create_account(user)
        iroha_message = iroha_messages.create_account_failed(blockchain_status)
        if iroha_message != None:
            return response.json(iroha_message)

        blockchain_status = self.ibc.grant_set_account_detail_perms(user)
        iroha_message = iroha_messages.grant_set_account_detail_perms_failed(
            blockchain_status)
        if iroha_message != None:
            return response.json(iroha_message)

        blockchain_status = self.ibc.set_account_details(user)
        iroha_message = iroha_messages.set_account_details_failed(
            blockchain_status)
        if iroha_message != None:
            return response.json(iroha_message)

        if user.type != "user":
            blockchain_status = self.ibc.append_role(user)
            iroha_message = iroha_messages.append_role_failed(
                blockchain_status)
            if iroha_message != None:
                return response.json(iroha_message)

        if user.type == "user":
            blockchain_status = self.ibc.revoke_set_account_detail_perms(user)
            iroha_message = iroha_messages.revoke_set_account_detail_perms_failed(
                blockchain_status)
            if iroha_message != None:
                return response.json(iroha_message)

        res = auth.register({
            "name": user.name,
            "email": user.email,
            "password": user.password,
            "type": user.type,
            "private_key": user.private_key,
            "public_key": user.public_key,
            "gov_id": user.gov_id,
            "phone_number": user.phone_number,
        })

        if res is None and user.type == "user":
            message = Mail(
                from_email=env("MAIL_FROM_ADDRESS"),
                to_emails=user.email,
                subject="Afya Mkononi Auth Details",
                html_content=
                f"<div> <p>Welcome to this cool health service</p> <p>Your email: { user.email }</p> <p>Your Password: { user.password }</p>",
            )

            sg = SendGridAPIClient(env("SENDGRID_KEY"))
            sg.send(message)
            return response.json(
                {"success": "Check your email for your credentials"})

        elif res is None:
            return response.json({"success": "Account has been added"})

        return response.json({"error": "Failed to add account"})
예제 #26
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()