Ejemplo n.º 1
0
def index():
    time = None
    medication = None
    quantity = None
    errors = {}

    if request.method == 'POST':
        delete = request.form.get('delete')

        if delete:
            reminder = Reminder.query.get(delete)
            db.session.delete(reminder)
            db.session.commit()

            return redirect(url_for('.index'))
        else:
            time = request.form.get('time')
            medication = request.form.get('medication')
            quantity = request.form.get('quantity')

            if not time:
                errors['time'] = 'Time is required.'
            else:
                time = datetime.strptime(time, '%H:%M').time().isoformat()

            if not medication:
                errors['medication'] = 'Medication is required.'

            if not quantity:
                errors['quantity'] = 'Quantity is required.'

            if not errors:
                reminder = Reminder(user_id=g.user['id'],
                                    time=datetime.strptime(time,
                                                           '%H:%M:%S').time(),
                                    medication=medication,
                                    quantity=quantity)
                db.session.add(reminder)
                db.session.commit()

                return redirect(url_for('.index'))

    reminders = Reminder.query.filter_by(user_id=g.user['id']).all()

    return render_template('reminder/index.html',
                           title='Medication Reminder',
                           time=time,
                           medication=medication,
                           quantity=quantity,
                           errors=errors,
                           reminders=reminders)
Ejemplo n.º 2
0
def login():
    email = None
    errors = {}

    if request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('password')

        if not email:
            errors['email'] = 'Email is required'
        else:
            user = User.query.filter_by(email=email.lower()).first()

            if user is None:
                errors['email'] = email + ' does not exist'
            elif not check_password_hash(user.password, password):
                errors['password'] = '******'

        if not errors:
            session.clear()
            session['user_id'] = user.id

            return redirect(url_for('general.index'))

    return render_template('auth/login.html',
                           title='Login',
                           email=email,
                           errors=errors)
Ejemplo n.º 3
0
def resend_forgot(user_id):
    link = None

    user = User.query.filter_by(id=user_id).first()

    if user is None:
        return redirect(url_for('auth.forgot'))
    else:
        fcode = ''.join(random.SystemRandom().choice(string.ascii_lowercase +
                                                     string.digits)
                        for _ in range(8))

        user.fcode = fcode
        db.session.commit()

        # Determines if ngrok is up.
        try:
            if requests.get(ngrok_url, timeout=1).status_code == 200:
                print('ngrok is up, using %s URL instead...' % ngrok_url)

                link = ngrok_url + str(user.id) + '/' + fcode
        except requests.exceptions.ConnectionError:
            print('ngrok is not up, using localhost URL instead...')

            if link is None:
                link = request.url_root + 'change/' + str(
                    user.id) + '/' + fcode
        except requests.exceptions.RequestException as e:
            print(e)

        Mail().send_mail(user.email, '[Heartphoria] Forgot Password',
                         render_template('email/forgot.html', link=link))

    return render_template('auth/forgot_success.html')
Ejemplo n.º 4
0
def signup():
    name = None
    email = None
    errors = {}

    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        password = request.form.get('password')
        confirm = request.form.get('confirm')

        if not name:
            errors['name'] = 'Name is required.'
        elif not re.match(r'[a-zA-Z]+(?:\s[a-zA-Z]+)*$', name):
            errors['name'] = 'Name is invalid'

        if not email:
            errors['email'] = 'Email is required.'
        elif not re.match(
                r"[a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$",
                email):
            errors['email'] = 'Email is invalid.'
        elif User.query.filter_by(email=email.lower()).first() is not None:
            errors['email'] = email + ' already exists'

        if not password:
            errors['password'] = '******'
        elif not re.match(r'(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}$',
                          password):
            errors['password'] = '******'
        elif not confirm:
            errors['confirm'] = 'Please re-enter password for confirmation'
        elif not password == confirm:
            errors['confirm'] = 'Passwords do not match'

        if not errors:
            user = User(email=email.lower(),
                        password=generate_password_hash(password),
                        name=name,
                        role='user')
            db.session.add(user)
            db.session.commit()

            Mail().send_mail(
                email, '[Heartphoria] Sign Up Successful',
                render_template('email/signup.html',
                                name=name,
                                email=email.lower(),
                                password=password))

            return redirect(url_for('.login'))

    return render_template('auth/signup.html',
                           title='Sign up',
                           name=name,
                           email=email,
                           errors=errors)
Ejemplo n.º 5
0
def index(user_id):
    image = None

    if g.user['id'] != user_id and g.user['role'] != 'admin':
        return redirect(url_for('general.index'))

    try:
        # Check if users profile picture exists when hosted with ngrok and on local.
        if requests.get(ngrok_url + '/static/images/dp/%s.png' % g.user['id'], timeout=1).status_code == 200 or \
                requests.get(request.url_root + 'static/images/dp/%s.png' % g.user['id'], timeout=1).status_code == 200:
            image = url_for('static',
                            filename='images/dp/%s.png' %
                            g.user['id']) + '?v=%s' % datetime.now().time()
    except requests.exceptions.ConnectionError:
        print('User has not uploaded any profile picture...')
    except requests.exceptions.RequestException as e:
        print(e)

    bmi = {
        'index':
        None if g.user['weight'] == 0 or g.user['height'] == 0 else
        round(g.user['weight'] /
              (g.user['height'] / 100 * g.user['height'] / 100))
    }

    if bmi['index']:
        if bmi['index'] >= 27.5:
            bmi['text'] = 'HIGH RISK'
        elif bmi['index'] >= 23:
            bmi['text'] = 'MODERATE RISK'
        elif bmi['index'] >= 18.5:
            bmi['text'] = 'LOW RISK'
        else:
            bmi['text'] = 'Risk Of Nutritional Deficiency'

    reminders = Reminder.query.filter_by(user_id=user_id).order_by(
        Reminder.time).limit(10).all()
    appointments = Appointment.query.filter_by(user_id=user_id).order_by(
        Appointment.date_time.desc()).limit(10).all()
    histories = History.query.filter_by(user_id=user_id).order_by(
        History.date.desc()).limit(10).all()

    return render_template('user/index.html',
                           title=g.user['name'],
                           reminders=reminders,
                           appointments=appointments,
                           histories=histories,
                           bmi=bmi,
                           image=image)
Ejemplo n.º 6
0
def edit():
    image = None
    name = None
    gender = None
    dob = None
    height = None
    weight = None
    email = None
    errors = {}

    try:
        # Check if users profile picture exists when hosted with ngrok and on local.
        if requests.get(ngrok_url + '/static/images/dp/%s.png' % g.user['id'], timeout=1).status_code == 200 or \
                requests.get(request.url_root + 'static/images/dp/%s.png' % g.user['id'], timeout=1).status_code == 200:
            image = url_for('static',
                            filename='images/dp/%s.png' %
                            g.user['id']) + '?v=%s' % datetime.now().time()
    except requests.exceptions.ConnectionError:
        print('User has not uploaded any profile picture...')
    except requests.exceptions.RequestException as e:
        print(e)

    if request.method == 'POST':
        if 'file' in request.files:
            file = request.files['file']

            if '.' in file.filename and file.filename.rsplit(
                    '.', 1)[1].lower() in ['png', 'jpg', 'jpeg']:
                file.save(
                    os.path.join(app.config['UPLOAD_FOLDER'] +
                                 str(g.user['id']) + '.png'))

            return redirect(url_for('.edit'))
        elif request.form.get('remove'):
            os.remove(
                os.path.join(app.config['UPLOAD_FOLDER'] + str(g.user['id']) +
                             '.png'))

            return redirect(url_for('.index', user_id=g.user['id']))
        else:
            name = request.form.get('name')
            gender = request.form.get('gender')
            dob = request.form.get('dob')
            height = request.form.get('height')
            weight = request.form.get('weight')
            email = request.form.get('email')
            password = request.form.get('password')
            confirm = request.form.get('confirm')
            data = {}

            if name:
                if not re.match(r'[a-zA-Z]+(?:\s[a-zA-Z]+)*$', name):
                    errors['name'] = 'Name is invalid'
                else:
                    data['name'] = name

            if gender:
                data['gender'] = gender
            else:
                errors['gender'] = 'Gender is required'

            if dob:
                try:
                    data['dob'] = datetime.strptime(dob, '%Y-%m-%d').date()
                except ValueError:
                    errors['dob'] = 'Invalid date format'

            if height:
                data['height'] = height

            if weight:
                data['weight'] = weight

            if email:
                if not re.match(
                        r"[a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$",
                        email):
                    errors['email'] = 'Email address is invalid.'
                elif g.user['email'] != email and not User.query.filter_by(
                        email=email).first() is not None:
                    errors['email'] = email + ' already exists'
                else:
                    data['email'] = email.lower()

            if password:
                if not re.match(r'(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}$',
                                password):
                    errors['password'] = '******'
                elif not confirm:
                    errors[
                        'confirm'] = 'Please re-enter password for confirmation'
                elif not password == confirm:
                    errors['confirm'] = 'Passwords do not match'
                else:
                    data['password'] = generate_password_hash(password)

            if not errors:
                if (not name or name == g.user['name']) and \
                        (not gender or gender == g.user['gender']) and \
                        (not dob or dob == str(g.user['dob'])) and \
                        (not height or height == str(g.user['height'])) and \
                        (not weight or weight == str(g.user['weight'])) and \
                        (email == g.user['email']):
                    errors['all'] = 'Nothing to update'
                else:
                    if User.query.filter_by(
                            id=g.user['id']).first() is not None:
                        User.query.filter_by(id=g.user['id']).update(data)
                        db.session.commit()

                    Mail().send_mail(
                        [g.user['email'], email] if email else g.user['email'],
                        '[Heartphoria] Account Details Changed',
                        render_template('email/edit.html',
                                        name=name,
                                        gender=gender,
                                        dob=dob,
                                        height=height,
                                        weight=weight,
                                        email=email,
                                        password=password))

                    user = User.query.filter_by(id=g.user['id']).first()

                    if user:
                        user = user.__dict__

                        if '_sa_instance_state' in user:
                            del user['_sa_instance_state']

                        g.user = user

                    return redirect(url_for('.index', user_id=g.user['id']))

    return render_template('user/edit.html',
                           title='Edit Profile',
                           name=name,
                           gender=gender,
                           dob=dob,
                           height=height,
                           weight=weight,
                           email=email,
                           errors=errors,
                           image=image)
Ejemplo n.º 7
0
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))

        return view(**kwargs)
Ejemplo n.º 8
0
def logout():
    session.clear()

    return redirect(url_for('general.index'))