Esempio n. 1
0
def addMedicalHistory(current_user):
    if current_user.rol != 3:
        return  make_response('Forbidden: Access is denied', 403)

    doctor = Doctor.query\
        .filter_by(id_user = current_user.id)\
        .first()

    if not doctor:
        return jsonify({"message" : "Forbidde: Access denid, sign up incomplete"})

    if doctor.password_changed == 0:
        return  make_response('Forbidden: Change your password for get access', 403)

    data = request.json
    id_patient = data['id_patient']
    id_doctor = doctor.id
    id_patientstatus = data['id_patientstatus']
    id_medicalspecialty = doctor.id_medicalspecialty
    observation = data['observation']

    if not data or not id_patientstatus or not observation:
        return make_response('Medical History information incomplete', 422)

    new_medicalhistory = MedicalHistory(id_patient, id_doctor, id_patientstatus, id_medicalspecialty, observation)
    db.session.add(new_medicalhistory)
    db.session.commit()

    return jsonify({"message" : "Medical History registered succesfully"}), 201
Esempio n. 2
0
def signUpDoctor(current_user):
    if current_user.account_verified == 0:
        return make_response('Forbidden: First confirm your account', 403)

    if current_user.rol != 2:
        return make_response('Forbidden: Access is denied', 403)

    hospital = Hospital.query\
                    .filter_by(id_user = current_user.id)\
                    .first()

    data = request.json
    #USER TABLE INFORMATION TO INSERT
    num_doc = data['num_doc']
    email = data['email']
    password = data['password']
    telphone = data['telphone']
    uuidunique = uuid.uuid4()
    account_verified = 1
    rol = 3

    new_user = User(
        num_doc,
        email,
        telphone,
        generate_password_hash(password, method='sha256'),
        uuidunique, account_verified,
        rol)
    # GO INSERT USER
    db.session.add(new_user)
    db.session.commit()

    hospital = Hospital.query\
                .filter_by(id_user = current_user.id)\
                .first()
    print(hospital)
    #FIND NEW USER
    user = User.query\
                .filter_by(num_doc = num_doc)\
                .first()

    #DOCTOR TABLE INFORMATION TO INSERT
    name = data['name']
    address = data['address']
    password_changed = 0
    id_medicalspecialty = data['id_medicalspecialty']
    birthdate = datetime.strptime(data['birthdate'], '%d/%m/%y')
    id_user = user.id
    id_hospital = hospital.id

    if not data or not name or not address or not id_medicalspecialty or not birthdate:
        return make_response('Doctor information incomplete', 422)


    new_doctor = Doctor(name, address, birthdate, password_changed, id_medicalspecialty, id_user, id_hospital)
    db.session.add(new_doctor)
    db.session.commit()
    return jsonify({'message' : 'Doctor registered and verified successfully'}), 201
Esempio n. 3
0
def getMedicalHistoriesByDoctorID(current_user, id_doctor):
    if current_user.account_verified == 0:
        return make_response('Forbidden: First confirm your account', 403)

    if current_user.rol != 2:
        return  make_response('Forbidden: Access is denied', 403)

    result = medical_histories.dump(MedicalHistory.query\
                                        .filter_by(id_doctor = id_doctor)
                                        .all())
    if result:
        return jsonify({"All medical histories" : result })
    else:
        return jsonify({"message" : "Not medical histories found"})
Esempio n. 4
0
def completeSignUp(current_user):
    if current_user.account_verified == 0:
        return make_response('Forbidden: First confirm your account', 403)

    auth = request.json


    patient = Patient.query\
                    .filter_by(id_user = current_user.id)\
                    .first()

    hospital = Hospital.query\
                    .filter_by(id_user = current_user.id)\
                    .first()

    if patient or hospital or current_user.rol == 3:
        return jsonify({"message" : "Sign up have been completed yet"}), 409
    #PATIENT
    if current_user.rol == 1:
        name = auth['name']
        address = auth['address']
        birthdate = datetime.strptime(auth['birthdate'], '%d/%m/%y')
        id_user = current_user.id

        complete_signup = Patient(name, address, birthdate, id_user)

        if not name or not address or not birthdate:
            return make_response('Patient information incomplete', 422)
        else:
            db.session.add(complete_signup)
            db.session.commit()
            return jsonify({'message' : 'Sign Up Completed Successfully'}), 200


    #HOSPITAL
    if current_user.rol == 2:
        name = auth['name']
        address = auth['address']
        id_medicalservice = auth['id_medicalservice']
        id_user = current_user.id

        complete_signup = Hospital(name, address, id_medicalservice, id_user)


        if not name or not address or not id_medicalservice:
            return make_response('Hospital information incomplete', 422)
        else:
            db.session.add(complete_signup)
            db.session.commit()
            return jsonify({'message' : 'Sign Up Completed Successfully'}), 200
Esempio n. 5
0
def access(token):
    if not token:
        return make_response(jsonify({'operation': 'failed'}), 401)

    try:
        token = token['data']
        user_t = jwt.decode(token, config.get('JWT_KEY'))
    except:
        return make_response(jsonify({'operation': 'failed'}), 401)

    join_room('notification-{}'.format(user_t['id']))
    user = UserModel.query.filter_by(id=user_t['id']).first()
    user.status = 'Online'
    user.status_color = '#00c413'
    db.session.commit()
Esempio n. 6
0
def validateReg():
    if request.method == "POST":
        try:
            uniqueTag = request.form["tag"]
            uname = request.form["uname"]
            pwd = request.form["pwd"]
            READY = False
            if int(uniqueTag) < 10_000 or int(uniqueTag) > 100_000:
                READY = False
            elif len(uname) < 5:
                READY = False
            elif len(pwd) < 6:
                READY = False
            else:
                READY = True

            if READY:
                encodePwd = hashlib.md5(pwd.encode("utf-8"))
                token = hashlib.md5((pwd + uname).encode("utf-8"))
                con = sqlite3.connect("app/db/users.db")
                curs = con.cursor()
                SQL = "INSERT INTO users ('tag', 'uname', 'pwd', 'token') VALUES (?, ? , ? , ?)"
                curs.execute(SQL, (uniqueTag, uname, encodePwd.hexdigest(),
                                   token.hexdigest()))
                con.commit()
                con.close()
                resp = make_response(redirect("/"))
                resp.set_cookie("token", token.hexdigest())
                # resp.set_cookie("user", uniqueTag)
                return resp, 200
            else:
                return "failed", 400
def charge_merchant():
    merchant_code = request.args.get('merchant_code')
    amount = float(request.args.get('amount'))
    merchant = Merchant.query.filter_by(code=merchant_code).first()

    if merchant:
        float_balance = FloatBalance.query.filter_by(
            merchant_id=merchant.id).first()
        if float_balance.amount > 0:
            if float_balance.amount >= amount:

                balance = float_balance.amount - amount
                float_balance.amount = balance

                # update the locked balance
                # code missing....

                resp = make_response(
                    jsonify(
                        message="Float available.",
                        status=True,
                    ), 200)
                return resp
            else:
                topup = amount - float_balance.amount
                resp = make_response(
                    jsonify(
                        message="Float not sufficient. Top up Ksh " +
                        str(topup) + " or more.",
                        status=False,
                    ), 400)
                return resp
        else:
            topup = float_balance.amount - amount
            resp = make_response(
                jsonify(
                    message="Float not sufficient. Top up Ksh " + str(topup) +
                    " or more.",
                    status=False,
                ), 400)
            return resp
    else:
        resp = make_response(
            jsonify(message="Unauthorized merchant.", error=True), 401)
        return resp
Esempio n. 8
0
def login():
    # creates dictionary of form data
    auth = request.json

    if not auth or not auth['email'] or not auth['password']:
        # returns 401 if any email or / and password is missing
        return make_response(
            'Could not verify',
            401,
            {'WWW-Authenticate' : 'Basic realm ="Login required"'}
        )

    user = User.query\
        .filter_by(email = auth['email'])\
        .first()

    #CODE FOR CONFIRM USER VERIFIED
    #if user.account_verified == 0:
        #return jsonify({"message":"You have to confirm your account"})

    if not user:
        # returns 401 if user does not exist
        return make_response(
            'Could not verify',
            401,
            {'WWW-Authenticate' : 'Basic realm ="User does not exist"'},
        )

    if check_password_hash(user.password, auth['password']):
        # generates the JWT Token
        token = jwt.encode({
            'public_id': user.uuid,
            'exp' : datetime.utcnow() + timedelta(minutes = 120)
        }, app.config['SECRET_KEY'])
        return make_response(jsonify({'token' : token}), 200)

    # returns 403 if password is wrong
    return make_response(
        'Could not verify',
        403,
        {'WWW-Authenticate' : 'Basic realm ="Wrong Password !!"'}
    )
Esempio n. 9
0
def getMedicalHistories(current_user):
    if current_user.rol != 3:
        return  make_response('Forbidden: Access is denied', 403)

    doctor = Doctor.query\
                .filter_by(id_user = current_user.id)\
                .first()

    if not doctor:
        return jsonify({"message" : "Forbidde: Access denid, sign up incomplete"})

    if doctor.password_changed == 0:
        return  make_response('Forbidden: Change your password for get access', 403)

    result = medical_histories.dump(MedicalHistory.query\
                                        .filter_by(id_doctor = doctor.id)
                                        .all())
    if result:
        return jsonify({"All medical histories" : result })
    else:
        return jsonify({"message" : "Not medical histories found"})
Esempio n. 10
0
def validateLogin():
    if request.method == "POST":
        try:
            uname = request.form["uname"]
            pwd = request.form["pwd"]    
            token = hashlib.md5((pwd+uname).encode("utf-8"))
            con = sqlite3.connect("app/db/users.db")
            curs = con.cursor()
            curs.execute(f"SELECT * FROM users WHERE token = '{token.hexdigest()}'")
            row = curs.fetchall()
            con.close()
            if len(row) == 1:
                resp = make_response(redirect("/"))
                resp.set_cookie("token", token.hexdigest())
                
                return resp , 200
            else:
                return make_response(redirect("/login?err=true")), 400
            # return str(row)
         
        except Exception as e:
            return str(e), 400
Esempio n. 11
0
def getMedicalHistory(current_user):
    if current_user.account_verified == 0:
        return make_response('Forbidden: First confirm your account', 403)

    if current_user.rol != 1:
        return  make_response('Forbidden: Access is denied', 403)


    patient = Patient.query\
                    .filter_by(id_user = current_user.id)\
                    .first()

    if not patient:
        return jsonify({"message" : "Forbidden: Access is denied, Sign up incomplete"})
    result = medical_histories.dump(MedicalHistory.query\
                                        .filter_by(id_patient = patient.id)\
                                        .all())

    if result:
        return jsonify({"All medical histories" : result })
    else:
        return jsonify({"message" : "Not medical histories found"})
Esempio n. 12
0
def f_login():
    if request.method == "GET":
        return render_template("login.html")
    elif request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        user = users.User()
        status = user.login(username, password)
        if status == 0:
            session["logged_in"] = True
            response = make_response(redirect('/panel'))
            response.set_cookie('username', username)
            return response
        else:
            print("Status:", status)
            message = "Check Username and Password."
            return render_template("login.html", login_status=message)
    else:
        abort(405)
Esempio n. 13
0
def signup():

    auth = request.json
    num_doc = auth['num_doc']
    email = auth['email']
    password = auth['password']
    telphone = auth['telphone']
    uuidunique = uuid.uuid4()
    account_verified = 0
    rol = auth['rol']


    if not num_doc or not email or not password or not telphone or not rol:
        return jsonify({"message" : "User information incomplete"}), 422

    if rol > 2 or rol <= 0:
        return jsonify({"message" : "Just 2 types of users allowed by this sign up",
                        "types" : "USER, 1 for PATIENT, 2 for HOSPITAL"}), 422

    #CHECKING FOR EXISTING USER
    user =  user = User.query\
            .filter_by(num_doc = auth['num_doc'])\
            .first()

    if not user:
        new_user = User(
            num_doc,
            email,
            telphone,
            generate_password_hash(password, method='sha256'),
            uuidunique, account_verified,
            rol)
        # GO INSERT USER
        db.session.add(new_user)
        db.session.commit()

        confirmation_code_msg = Message('Codigo de confirmación [SISGESMEDHIS]', sender = '*****@*****.**', recipients = [email])
        confirmation_code_msg.body = "Codigo de confirmación de tu cuenta : " + str(uuidunique)
        mail.send(confirmation_code_msg)
        return jsonify({'message' : 'Successfully registered',
                        'important' : 'Confirmation code was sent to your email'}), 201
    else:
        return make_response('User already exists. Please Log in.', 409)
Esempio n. 14
0
def validateReg():
    if request.method == "POST":
        try:
            fname = request.form["fname"]
            uname = request.form["uname"]
            pwd = request.form["pwd"]
            email = request.form["email"]
            credentials = {
                "fname": fname,
                "uname": uname,
                "pwd": pwd,
                "email": email,
            }
            userToken = hashlib.md5((uname+pwd).encode())
            resp = make_response(addUser(credentials))
            
            resp.set_cookie("user-token", userToken.hexdigest())
        
            return resp, 200
        except:
            return "Bad Request as well", 400
Esempio n. 15
0
def validateLogin():
    if request.method == "POST":
        try:
            uname = request.form["uname"]
            pwd = request.form["pwd"]
            userToken = hashlib.md5((uname + pwd).encode())
            credentials = {
                "uname": uname,
                "pwd": pwd,
            }

            isValidLogin = isLoginValid(credentials)
            if isValidLogin:
                resp = make_response("success")
                resp.set_cookie("user-token", userToken.hexdigest())
                return resp, 200
            else:
                return "wrongcrd", 400

        except Exception as e:
            return str(e), 500
def make_login():
    username = request.form['username']
    password = request.form['password']

    if not username or not password:
        return redirect('/auth/login')

    user = PortalUser.query.filter_by(username=username).first()
    print user.password
    if user:
        password_isvalid = bcrypt.checkpw(password.encode('utf8'),
                                          user.password.encode('utf8'))
        print password_isvalid
        if password_isvalid:

            resp = make_response(redirect('/'))
            resp.set_cookie('user', user.username)
            return resp
        else:
            return redirect('/auth/login')
    else:
        return redirect('/auth/login')
def config_():
    res = make_response(json.dumps(config.get()))
    res.mimetype = 'application/json'
    return res
Esempio n. 18
0
def api_error(message, status_code=400):
    return app.make_response(json.dumps(message), status_code)
Esempio n. 19
0
def not_found(error):
    return make_response(jsonify({'error': 'Bad request'}), 400)
Esempio n. 20
0
def not_found(error):
	return make_response(jsonify({'error': 'Not found'}), 404)