Esempio n. 1
0
    def post(self):
        # register user endpoint
        data = validate_user(request.get_json())
        if data['ok']:
            data = data['data']

            # check if user exists
            user = User.query.filter_by(email=data['email']).first()
            if user:
                return { "message" : "Email has already been taken"}, 400

            # get password
            data['password'] = flask_bcrypt.generate_password_hash(data['password'])

            # find the role of the user
            role = Role.query.filter_by(name=data['role']).first()
            del data['role']
            
            # Add a new patient to db
            user_schema = UserSchema()
            new_user = user_schema.load(data, session=db.session)

            role.users.append(new_user) # add new user to their role

            db.session.add(role) # add user and role
            db.session.commit()

            return {}, 200
        else:
            return {'message': 'Please check the fields'}, 400
Esempio n. 2
0
    def post(self):
        data = self.parser.parse_args()

        # check if password given is suitable
        if not isGoodPassword(data["new_password"]):
            return {
                "message": "The new password must be at least 8 characters long"
            }, 400

        identity = get_jwt_identity()

        # Get all information about the user who is using this endpoint
        user = User.query.filter_by(id=identity["userId"]).first()

        # If old password and password we have on file match
        if user and flask_bcrypt.check_password_hash(
            user.password, data["old_password"]
        ):
            # Create new dictionary with just keys we want to replace
            updated_payload = {
                "password": flask_bcrypt.generate_password_hash(data["new_password"])
            }

            # Perform update
            update_response = userManager.update(
                "id", identity["userId"], updated_payload
            )

            update_response.pop("password")

            return update_response, 200
        else:
            return {"error": "old_password incorrect"}, 400
Esempio n. 3
0
    def put(self, reset_token):
        logging.debug('Receive Request: PUT /reset/<reset_token>')
        url = request.host_url
        try:
            user_email = serializer.loads(reset_token, max_age=60)
            if user_email is None:
                abort(400, message="reset_token not valid")

            body = _get_request_body()
            curr_user = userManager.read('email', user_email)
            if curr_user is None:
                abort(400, message='there is no user with that email')

            body['password'] = flask_bcrypt.generate_password_hash(
                body['password']).decode("utf-8")
            update_res = userManager.update("email", user_email, body)
            if not update_res:
                abort(400, message=f'"{user_email}" does not exist')

            # respond with password change success
            header = 'To:' + user_email + '\n' + 'From: ' + SENDER_EMAIL_ADDRESS + '\n' + 'Subject: Password Change \n'
            content = f'Dear User,\n\nYour password have been succsesfully changed.\n\n\nCradle Support'
            msg = header + content
            send_email(user_email, msg)
            return f'password changed for user with email address: {user_email}', 200

        except (DecodeError, InvalidTokenError):
            raise BadTokenError
        except Exception as e:
            raise InternalServerError
Esempio n. 4
0
def create_user(email, name, password, hf_name, role):
    """
    Creates a user in the database.
    """
    user = {
        "email": email,
        "firstName": name,
        "password": flask_bcrypt.generate_password_hash(password),
        "healthFacilityName": hf_name,
    }
    user_schema = UserSchema()
    user_role = Role.query.filter_by(name=role).first()
    user_role.users.append(user_schema.load(user, session=db.session))
    db.session.add(user_role)
    db.session.commit()
Esempio n. 5
0
    def _do_create(self, **kwargs) -> Any:
        import data
        from config import flask_bcrypt
        from models import User, Role

        d = dict(**kwargs)
        role_name = d["role"]
        del d["role"]  # not an actual user field so delete if from the args

        # Hash the user's password so that they can login
        d["password"] = flask_bcrypt.generate_password_hash(d["password"])

        user = marshal.unmarshal(User, d)
        crud.create(user)
        role = crud.read(Role, name=role_name)
        user.roleIds = [role]
        data.db_session.commit()
        return user
Esempio n. 6
0
def register():
    
    registerForm = forms.SignupForm(request.form)
    current_app.logger.info(request.form)

    if request.method == 'POST' and registerForm.validate() == False:
        current_app.logger.info(registerForm.errors)
        return "uhoh registration error"

    elif request.method == 'POST' and registerForm.validate():
        email = request.form['email']
        
        # generate password hash
        password_hash = flask_bcrypt.generate_password_hash(request.form['password'])

        # prepare User
        user = User(email,password_hash)
        print user

        try:
            user.save()
            if login_user(user, remember="no"):
                flash("Logged in!")
                return redirect('/sportnews')
            else:
                flash("unable to log you in")

        except:
            flash("unable to register with that email address")
            current_app.logger.error("Error on registration - possible duplicate emails")

    # prepare registration form         
    # registerForm = RegisterForm(csrf_enabled=True)
    templateData = {

        'form' : registerForm
    }

    return render_template("register.html", **templateData)
Esempio n. 7
0
    def post(self):

        data = self.parser.parse_args()

        # check if user exists
        user = User.query.filter_by(id=data["id"]).first()
        if user is None:
            return {"message": "There is no user with this id"}, 400

        # check if password given is suitable
        if not isGoodPassword(data["password"]):
            return {
                "message": "The new password must be at least 8 characters long"
            }, 400

        data["password"] = flask_bcrypt.generate_password_hash(data["password"])

        # Update password
        update_res = userManager.update("id", data["id"], data)
        update_res.pop("password")

        return update_res, 200
Esempio n. 8
0
    def post(self):
        # register user endpoint
        data = validate_user(request.get_json())
        if data["ok"]:
            data = data["data"]

            # check if user exists
            user = User.query.filter_by(email=data["email"]).first()
            if user:
                return {"message": "Email has already been taken"}, 400

            # get password
            data["password"] = flask_bcrypt.generate_password_hash(data["password"])

            # find the role of the user
            role = Role.query.filter_by(name=data["role"]).first()
            if (
                role
                and data["role"] == "ADMIN"
                and data["healthFacilityName"] == "Null"
            ):
                data["healthFacilityName"] = None
            del data["role"]

            # Add a new user to db
            user_schema = UserSchema()
            new_user = user_schema.load(data, session=db.session)

            role.users.append(new_user)  # add new user to their role

            db.session.add(role)  # add user and role
            db.session.commit()

            return new_user.id, 201
        else:
            return {"message": "Please check the fields"}, 400
Esempio n. 9
0
def seed():
    # SEED health facilities
    print('Seeding health facilities...')

    healthfacility_schema = HealthFacilitySchema()
    counter = 0
    for hf in healthFacilityList:
        hf_schema = {
            "healthFacilityName": hf,
            "healthFacilityPhoneNumber": facilityPhoneNumbers[counter],
            "facilityType": facilityType[counter],
            "about": facilityAbout[counter],
            "location": facilityLocation[counter]
        }
        counter += 1
        db.session.add(healthfacility_schema.load(hf_schema))
    db.session.commit()

    # SEED roles
    role1 = Role(name='VHT')
    role2 = Role(name='HCW')
    role3 = Role(name='ADMIN')
    role4 = Role(name='CHO')

    print('Seeding roles...')
    db.session.add_all([role1, role2, role3, role4])
    db.session.commit()

    role_admin = Role.query.filter_by(name='ADMIN').first()
    role_hcw = Role.query.filter_by(name='HCW').first()
    role_vht = Role.query.filter_by(name='VHT').first()
    role_cho = Role.query.filter_by(name='CHO').first()

    user_schema = UserSchema()
    u0 = {
        'email': '*****@*****.**',
        'firstName': 'Admin',
        'password': flask_bcrypt.generate_password_hash('admin123'),
        "healthFacilityName": getRandomHealthFacilityName()
    }
    u1 = {
        'email': '*****@*****.**',
        'firstName': 'Brian',
        'password': flask_bcrypt.generate_password_hash('hcw123'),
        "healthFacilityName": getRandomHealthFacilityName()
    }
    u2 = {
        'email': '*****@*****.**',
        'firstName': 'TestVHT',
        'password': flask_bcrypt.generate_password_hash('vht123'),
        "healthFacilityName": getRandomHealthFacilityName()
    }
    u3 = {
        'email': '*****@*****.**',
        'firstName': 'TestCHO',
        'password': flask_bcrypt.generate_password_hash('cho123'),
        "healthFacilityName": getRandomHealthFacilityName()
    }
    role_admin.users.append(user_schema.load(u0, session=db.session))
    role_hcw.users.append(user_schema.load(u1, session=db.session))
    role_vht.users.append(user_schema.load(u2, session=db.session))
    role_cho.users.append(user_schema.load(u3, session=db.session))

    print('Seeding users...')
    db.session.add(role_admin)
    db.session.add(role_hcw)
    db.session.add(role_vht)
    db.session.add(role_cho)
    db.session.commit()

    print('Seeding Patients with readings and referrals...')
    # seed patients with readings and referrals
    patient_schema = PatientSchema()
    reading_schema = ReadingSchema()
    referral_schema = ReferralSchema()
    for patientId in patientList:

        # get random patient
        p1 = {
            "patientId": patientId,
            "patientName": getRandomInitials(),
            "patientAge": getRandomAge(),
            "gestationalAgeUnit": "GESTATIONAL_AGE_UNITS_WEEKS",
            "gestationalAgeValue": "51",
            "villageNumber": getRandomVillage(),
            "patientSex": "FEMALE",
            "isPregnant": "true"
        }
        db.session.add(patient_schema.load(p1))
        db.session.commit()

        numOfReadings = random.randint(1, 5)
        dateList = [getRandomDate() for i in range(numOfReadings)]
        dateList.sort()

        userId = getRandomUser()
        for i in range(numOfReadings):
            readingId = str(uuid.uuid4())
            healthFacilityName = getRandomHealthFacilityName()

            # get random reading(s) for patient
            r1 = {
                "userId": userId,
                "patientId": patientId,
                "dateTimeTaken": dateList[i],
                "readingId": readingId,
                "bpSystolic": getRandomBpSystolic(),
                "bpDiastolic": getRandomBpDiastolic(),
                "heartRateBPM": getRandomHeartRateBPM(),
                "symptoms": getRandomSymptoms(),
            }
            db.session.add(reading_schema.load(r1))
            db.session.commit()

            if i == numOfReadings - 1 and random.choice([True, False]):
                referral1 = {
                    "patientId":
                    patientId,
                    "readingId":
                    readingId,
                    "dateReferred":
                    r1['dateTimeTaken'] +
                    int(timedelta(days=10).total_seconds()),
                    "referralHealthFacilityName":
                    healthFacilityName,
                    "comment":
                    "She needs help!"
                }
                db.session.add(referral_schema.load(referral1))
                db.session.commit()

    print('Complete!')