예제 #1
0
    def wrapper_function(*args, **kwargs):

        if 'session_key' in args[0].session:
            session_key = args[0].session['session_key']
            table = Table("SessionStore")
            response = table.scan(FilterExpression={
                'session_key': session_key,
            }, ).values()

            if response['Count'] == 0:
                return function(*args, **kwargs)

            isDoctor0 = response['Items'][0]['isDoctor']
            isVerified = response['Items'][0]['isVerified']
            timestamp = response['Items'][0]['timestamp']
            email = response['Items'][0]['email']

            if (isVerified == 0):
                return HttpResponseRedirect('/accounts/verifyotp/')

            if (datetime.strptime(timestamp, "%Y%m%d%H%M%S") +
                    timedelta(days=7) < datetime.now()):
                return function(*args, **kwargs)

            if (isDoctor0 == 0):
                return HttpResponse("<H1> Patient HomePage </H1>")
            return HttpResponse("<H1> Doctor HomePage </H1>")

        return function(*args, **kwargs)
예제 #2
0
def index(request):
    appointment_id = print(request.GET.get('app_id'))
    if request.method == "POST":
        table = Table('pres_table')
        notes = request.POST['dis_notes']
        symptoms = request.POST['pres_symp']
        medicine = request.POST['pres_med']
        name = request.POST['name']
        age = request.POST['age']
        sex = request.POST['sex']
        print(name,age,sex)
        symptoms = listToString(symptoms)
        table.insertValues(values=[
            {
                'name' : name,
                'age' : age,
                'sex':sex,
                'app_id' : appoint_id,
                'symptoms' : symptoms,
                'notes' : notes,
                'tabs' : medicine,
            }]
        )
        print('put done')
        return render(request,'appointments/dashboard.html')
    return render(request,'prescription/mainpage.html')
예제 #3
0
def sendOtp(to, val1):
    otp_gen = random.randint(100000, 999999)
    otp = hashlib.sha256((str(otp_gen) + SECRET_KEY).encode()).hexdigest()
    subject = 'Your otp for DOCA registration  is ' + str(otp_gen)
    message = ' it  means a world to us thanks for choosing us \n your otp is : ' + str(
        otp_gen)
    email_from = settings.EMAIL_HOST_USER
    recipient_list = [
        to,
    ]
    message = EmailMultiAlternatives(subject=subject,
                                     body=message,
                                     from_email=email_from,
                                     to=recipient_list)
    htmlTemplate = render_to_string('accounts/email_template/sign_up.html',
                                    {'otp': otp_gen})
    message.attach_alternative(htmlTemplate, 'text/html')
    response = message.send()
    if response == 1:
        table = Table('otp')
        table.insertValues(
            values=[{
                'otp': otp,
                'email': to,
                'isRegister': val1,
                'timestamp': str(datetime.now().strftime("%Y%m%d%H%M%S"))
            }])
    return response
예제 #4
0
def logoutD(request):
    if 'session_key' in request.session:
        table = Table('SessionStore')
        table.delete(
            FilterExpression={'session_key': request.session['session_key']})
        del request.session['session_key']
    return HttpResponse("LOGED OUT")
예제 #5
0
    def wrapper_function(*args, **kwargs):
        print(args)
        if 'session_key' in args[0].session:

            session_key = args[0].session['session_key']
            table = Table("SessionStore")
            response = table.scan(FilterExpression={
                'session_key': session_key,
            }, ).values()

            if response['Count'] == 0:
                print(session_key)
                return HttpResponseRedirect("/accounts/login/")

            isVerified = response['Items'][0]['isVerified']
            timestamp = response['Items'][0]['timestamp']
            email = response['Items'][0]['email']

            if (datetime.strptime(timestamp, "%Y%m%d%H%M%S") +
                    timedelta(days=7) < datetime.now()):
                table.delete(FilterExpression={
                    'session_key': args[0].session['session_key']
                })
                del args[0].session['session_key']
                return HttpResponseRedirect("/accounts/login/")

            if isVerified == 0:

                print("isVerfied")
                return function(*args, **kwargs)

        print("not Found")
        return HttpResponseRedirect("/accounts/login/")
예제 #6
0
def getEmail(session_key):
    table = Table("SessionStore")
    response = table.scan(FilterExpression={
        'session_key': session_key,
    },
                          Projection=['email']).values()

    return response['Items'][0]['email']
예제 #7
0
def Appointemets(request):
    uid=getEmail(request.session['session_key'])
    table = Table('appointments')
    appointments = table.scan(FilterExpression={'user_id':uid}).values()
    rdict={}
    if appointments['Count']!=0:
        rdict={'appointements':appointments['Items']}
    return render(request,'book_appointement/pat_Appointement.html',rdict)
예제 #8
0
def dropdown_med(request):
    if request.method == "POST":
        send_list = []
        word = request.POST['word']
        table = Table('med')
        res = table.scan({})
        for dude in res.values()['Items']:
            if word in dude['med']:
                send_list.append(dude['med'])
        return render(None,'prescription/dropdown_med.html',{'items' : send_list})
예제 #9
0
def dashboard(request):
    email = getEmail(request.session['session_key'])
    Date = str(date.today())
    today = Date[8:10] + Date[5:7] + Date[0:4]
    table = Table('appointments')
    result = table.scan(FilterExpression={
        'date': today,
        'doc_id': email
    }).values()
    return render(request, 'appointments/dashboard.html',
                  {'app': result['Items']})
예제 #10
0
def getSpecialization(request):
    if 'spec' in request.GET:
        table = Table('Specilizations')
        spec0 = request.GET['spec']
        specs = table.scan().values()['Items']
        res = []
        for spec1 in specs:
            if spec0.lower() in spec1['spec'].lower():
                res.append(spec1['spec'], )
        return Response({
            "code": 0,
            "results": res,
        })
    return Response({"code": "404", "message": "invalid request"})
예제 #11
0
def getCities(request):
    if 'city' in request.GET:
        table = Table('Cities')
        spec0 = request.GET['city']
        specs = table.scan().sort("city_id")['Items']
        res = []
        for spec1 in specs:
            if spec0.lower() in spec1['city'].lower():
                res.append({"city": spec1['city'], "state": spec1['state']})
        return Response({
            "code": 0,
            "results": res,
        })
    return Response({"code": "404", "message": "invalid request"})
예제 #12
0
def check_avail(request):
    if request.method == "POST":
        table = Table('slots')
        city = request.POST['city_name']
        locality = request.POST['locality']
        spec = request.POST['spec']
        date = request.POST['date_app']
        info = table.scan(FilterExpression={'spec': spec}).sort("start_time")
        doc_info = info['Items']
        print(info)
        return render(request, "appointments/pat_book.html",
                      {'doc_info': doc_info})
    else:
        return render(request, "appointments/pat_slots.html")
예제 #13
0
def med_list(request):
    if is_authenticated != 0:
        table = Table('med')
        res = table.scan(FilterExpression={}).values()
        if request.method == "GET":
            for i in res['Items']:
                i['_id'] = str(i['_id'])
            return Response(res)

        elif request.method == 'POST':
            med_data = request.data
            if med_data['method'] == 'get_medications':
                res = table.scan(FilterExpression={
                    'med_id': med_data['med_id']
                }).values()
                for i in res['Items']:
                    i['_id'] = str(i['_id'])
                return Response(res)
            elif med_data['method'] == 'add_medications':
                for id in res['Items']:
                    # print(id, type(id))
                    mid = id['med_id']
                mid = int(mid) + 1
                table.insertValues(values=[{
                    'med_id': str(mid),
                    'med': med_data['med']
                }])
                return HttpResponse("Added Medicines")
            elif med_data['method'] == 'delete_medcations':
                table.delete(FilterExpression={'med_id': med_data['med_id']})
                return HttpResponse("Deleted that slot id")
예제 #14
0
def symp_list(request):
    if is_authenticated != 0:
        table = Table('symp')
        res = table.scan(FilterExpression={}).values()
        if request.method == "GET":
            for i in res['Items']:
                i['_id'] = str(i['_id'])
            return Response(res)

        elif request.method == 'POST':
            symp_data = request.data
            if symp_data['method'] == 'get_symptoms':
                res = table.scan(FilterExpression={
                    'symp_id': symp_data['symp_id']
                }).values()
                for i in res['Items']:
                    i['_id'] = str(i['_id'])
                return Response(res)
            elif symp_data['method'] == 'add_symptoms':
                for id in res['Items']:
                    # print(id, type(id))
                    sid = id['symp_id']
                sid = int(sid) + 1
                table.insertValues(values=[{
                    'symp_id': str(sid),
                    'symp': symp_data['symp']
                }])
                return HttpResponse("Added Symptoms")
            elif symp_data['method'] == 'delete_symptoms':
                table.delete(
                    FilterExpression={'symp_id': symp_data['symp_id']})
                return HttpResponse("Deleted that slot id")
예제 #15
0
def cancel_appointments(request):
    table = Table('appointments')

    list = []
    if request.method == 'POST':
        # print(request.POST)
        for key, val in request.POST.items():
            if val == 'on':
                list.append(key)
    print(list)
    for id in list:
        table.delete(FilterExpression={'app_id': id})
    response = redirect('/appointments/check_app/')
    return response
예제 #16
0
def del_slots(request):
    table = Table('slots')
    email = getEmail(request.session['session_key'])

    list = []
    if request.method == 'POST':
        # print(request.POST)
        for key, val in request.POST.items():
            if val == 'on':
                list.append(key)
    print(list)
    for id in list:
        table.delete(FilterExpression={'slot_id': id})
    response = redirect('/appointments/')
    return response
예제 #17
0
def doc_home(request):
    table = Table('slots')
    email = getEmail(request.session['session_key'])
    response = table.scan(FilterExpression={'doc_id': email}).values()
    items = response['Items']
    c = 1
    for item in items:
        item['num'] = c
        item['start_time'] = str(item['start_time'][0:2]) + ":" + str(
            item['start_time'][2:4])
        item['end_time'] = str(item['end_time'][0:2]) + ":" + str(
            item["end_time"][2:4])
        item['fees'] = str(item['fees'])
        c += 1
    return render(request, "appointments/doc_slots.html", {'items': items})
예제 #18
0
def initiate_payment(request):
    if request.method == "POST":
        amount = int(request.POST['amount'])
        user = request.user.username
        made_on = datetime.datetime.utcnow()
        order_id = made_on.strftime('PAY2ME%Y%m%d_%H%M%S')
        table = Table('transaction')
        table.insertValues(values=[{
            'order_id': order_id,
            'made_by' : user,
            'amount' : amount,
        }])
        # transaction = Transaction.objects.create(made_by=user, amount=amount)
        # transaction.save()
        merchant_key = settings.PAYTM_SECRET_KEY

        param_dict = (
            ('MID', settings.PAYTM_MERCHANT_ID),
            ('ORDER_ID', str(table.scan().values()['Items'][-1]['order_id'])),
            ('CUST_ID', str(table.scan().values()['Items'][-1]['made_by'])),
            ('TXN_AMOUNT', str(table.scan().values()['Items'][-1]['amount'])),
            ('CHANNEL_ID', settings.PAYTM_CHANNEL_ID),
            ('WEBSITE', settings.PAYTM_WEBSITE),
            # ('EMAIL', request.user.email),
            # ('MOBILE_N0', '9911223388'),
            ('INDUSTRY_TYPE_ID', settings.PAYTM_INDUSTRY_TYPE_ID),
            ('CALLBACK_URL', 'http://127.0.0.1:8000/payment/callback/'),
            # ('PAYMENT_MODE_ONLY', 'NO'),
        )
        param_dict = dict(param_dict)
        param_dict['CHECKSUMHASH'] = paytm.generate_checksum(param_dict, merchant_key)
        print(param_dict)
        return render(request, 'payments/redirect.html', {'param_dict': param_dict})

    return render(request, 'payments/pay.html')
예제 #19
0
def signup(request):
    if request.method == "GET":
        return render(request, 'accounts/signup.html')

    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            table = Table('users')
            if (isvalidPassword(password) and isvalidUserName(username)
                    and isValidEmail(email)):
                password = hashlib.sha256((password + SECRET_KEY).encode())
                password = password.hexdigest()

                table.insertValues(values=[{
                    'email': email,
                    'password': password,
                    'username': username,
                    'isVerified': 0,
                }])

                table = Table('SessionStore')

                tkey = email + datetime.now().strftime(
                    "%Y%m%d%H%M%S") + SECRET_KEY
                tkey = str(hashlib.sha256(tkey.encode()).hexdigest())
                table.insertValues(values=[
                    {
                        "session_key": tkey,
                        "email": email,
                        "timestamp": datetime.now().strftime("%Y%m%d%H%M%S"),
                        "isVerified": 0,
                        "isDoctor": 0,
                    }
                ])
                request.session['session_key'] = tkey

                return HttpResponseRedirect("/accounts/verifyotp/")

            emailerr = usernameerr = passworderr = ""
            if (isValidEmail(email) == False):
                emailerr = "Invalid email address"
            if (isvalidPassword(password) == False):
                passworderr = "Invalid Password"
            if (isvalidUserName(username) == False):
                usernameerr = "Invalid UserName"
            print(username + "\t" + password + "\t" + email)
        return render(
            request, 'accounts/signup.html',
            {'err': emailerr + '\t' + passworderr + '\t' + usernameerr})
예제 #20
0
def add_slots(request):
    table = Table('slots')
    email = getEmail(request.session['session_key'])
    days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']

    if request.method == 'POST':
        st_time = request.POST['st_time']
        end_time = request.POST['end_time']
        fees = request.POST['fees']
        dow = []
        for d in days:
            string = 'weekday-' + d
            if string in request.POST.keys():
                dow.append(d)
        data = table.scan(FilterExpression={}).values()
        items = data['Items']
        l = len(str(email))
        num = 0
        for it in items:
            c = int(it['slot_id'][l:])
            if (c > num):
                num = c
        num += 1
        num = email + str(num)
        table.insertValues(values=[{
            'slot_id': num,
            'doc_id': email,
            'start_time': st_time,
            'end_time': end_time,
            'fees': fees,
            'days': dow
        }])
        print(table.scan(FilterExpression={'doc_id': email}).values())
    response = redirect('/appointments/doc_slots/')
    return response
예제 #21
0
def register(request):
    print(request.POST)
    if 'username' in request.POST and 'email' in request.POST and 'password' in request.POST:
        username = request.POST['username']
        password = request.POST['password']
        email = request.POST['email']
        table = Table('users')
        if (isvalidPassword(password) and isvalidUserName(username)
                and isValidEmail(email)):
            password = hashlib.sha256((password + SECRET_KEY).encode())
            password = password.hexdigest()
            """table.put_item(Item={
                'email': email,
                'password': password,
                'username': username,
                'isVerified': 0,
            })"""

            register_token = jwt.encode(
                {
                    'email':
                    email,
                    'timestamp':
                    (datetime.now() +
                     timedelta(minutes=15)).strftime("%Y%d%M%H%M%S"),
                },
                register_secret_key,
                algorithm='HS256')

            return Response({
                "code": "0",
                "register_token": register_token,
            })

        emailerr = usernameerr = passworderr = ""
        if (isValidEmail(email) == False):
            emailerr = "Invalid email address"
        if (isvalidPassword(password) == False):
            passworderr = "Invalid Password"
        if (isvalidUserName(username) == False):
            usernameerr = "Invalid UserName"

        return Response({
            "code":
            "1",
            "err":
            emailerr + "\n" + passworderr + "\n" + usernameerr,
        })
    return Response({
        "code": "2",
        "err": "Invalid request",
    })
예제 #22
0
def appoint_list(request):
    if is_authenticated != 0:
        table = Table('appointments')
        res = table.scan(FilterExpression={}).values()
        if request.method == "GET":
            for i in res['Items']:
                i['_id'] = str(i['_id'])
            return Response(res)

        elif request.method == 'POST':
            appoint_data = request.data
            if appoint_data['method'] == 'get_appointments':
                res = table.scan(FilterExpression={
                    'doc_id': appoint_data['doc_id']
                }).values()
                for i in res['Items']:
                    i['_id'] = str(i['_id'])
                return Response(res)
            elif appoint_data['method'] == 'add_appointments':
                for id in res['Items']:
                    # print(id, type(id))
                    aid = id['app_id']
                aid = int(aid) + 1
                table.insertValues(
                    values=[{
                        'app_id': str(aid),
                        'doc_id': appoint_data['doc_id'],
                        'spec': appoint_data['spec'],
                        'pat_id': appoint_data['pat_id'],
                        'start_time': appoint_data['start_time'],
                        'end_time': appoint_data['end_time'],
                        'fees': appoint_data['fees'],
                        'date': appoint_data['date']
                    }])
                return HttpResponse("Added Appointments")
            elif appoint_data['method'] == 'delete_appointments':
                table.delete(
                    FilterExpression={'app_id': appoint_data['app_id']})
                return HttpResponse("Deleted that slot id")
예제 #23
0
def pres_table_list(request):
    if is_authenticated != 0:
        table = Table('pres_table')
        res = table.scan(FilterExpression={}).values()
        if request.method == "GET":
            for i in res['Items']:
                i['_id'] = str(i['_id'])
            return Response(res)

        elif request.method == 'POST':
            pres_table_data = request.data
            if pres_table_data['method'] == 'get_prescriptions':
                res = table.scan(FilterExpression={
                    'app_id': pres_table_data['app_id']
                }).values()
                for i in res['Items']:
                    i['_id'] = str(i['_id'])
                return Response(res)
            elif pres_table_data['method'] == 'add_prescriptions':
                for id in res['Items']:
                    # print(id, type(id))
                    pid = id['app_id']
                pid = int(pid) + 1
                table.insertValues(
                    values=[{
                        'app_id': str(pid),
                        'doc_id': pres_table_data['doc_id'],
                        'pat_id': pres_table_data['pat_id'],
                        'symptoms': pres_table_data['symptoms'],
                        'notes': pres_table_data['notes'],
                        'tabs': pres_table_data['tabs']
                    }])
                return HttpResponse("Added prescription")
            elif pres_table_data['method'] == 'delete_prescriptions':
                table.delete(
                    FilterExpression={'app_id': pres_table_data['app_id']})
                return HttpResponse("Deleted that slot id")
예제 #24
0
def create_doc(request):
    table = Table('slots')
    table.delete()
    fake = Faker()
    for i in range(1, 1001):
        doc = fake.email()
        lat = str(fake.latitude())
        lon = str(fake.longitude())
        fees = random.randint(100, 1000)
        special = [
            'Allergists', 'Anesthesiologists', 'Cardiologists',
            'Dermatologists', 'Endocrinologists', 'FamilyPhysicians',
            'Gastroenterologists', 'Hematologists',
            'InfectiousDiseaseSpecialists', 'Internists', 'MedicalGeneticists',
            'Nephrologists', 'Neurologists', 'Obstetricians', 'Gynecologists',
            'Oncologists', 'Ophthalmologists', 'Osteopaths',
            'Otolaryngologists', 'Pathologists', 'Pediatricians',
            'Physiatrists', 'PlasticSurgeons', 'Podiatrists',
            'PreventiveMedicineSpecialists', 'Psychiatrists', 'Pulmonologists',
            'Radiologists', 'Rheumatologists', 'GeneralSurgeons', 'Urologists'
        ]
        s_rand = random.randint(0, 30)
        spec = special[s_rand]
        th1 = random.randint(0, 23)
        th2 = (th1 + 2) % 24
        t1 = str(th1) + "00"
        t2 = str(th2) + "00"
        dow = ['mon', 'tue', 'wed', 'thu', 'fri']
        r = random.random()
        if r >= 0.8:
            dow.append('sat')
        if r >= 0.9:
            dow.append('sun')
        table.insertValues(values=[{
            'slot_id': str(i),
            'doc_id': doc,
            'spec': spec,
            'start_time': t1,
            'end_time': t2,
            'fees': fees,
            # 'days': dow,
            'lon': lon,
            'lat': lat
        }])
    return HttpResponse("You have generated data")
예제 #25
0
def forgot(request):
    if request.method == "GET":
        return render(request, 'accounts/forgot_password.html')
    if request.method == "POST":
        form = FindAccountForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data['user']
            table = Table('users')
            if (isValidEmail(user)):
                response = table.scan(FilterExpression={
                    'email': user
                }).values()

                if response['Count'] == 1:
                    timestamp0 = datetime.now().strftime('%Y%m%d%H%M%S')
                    signature = hashlib.sha256(
                        (user + timestamp0 + SECRET_KEY).encode()).hexdigest()
                    table = Table('forgototpsignatures')
                    table.insertValues(values=[{
                        'signature': signature,
                    }])

                    tk = jwt.encode(
                        {
                            'email': user,
                            'timestamp': timestamp0,
                            'signature': signature
                        },
                        SECRET_KEY,
                        algorithm='HS256')
                    tk = tk.decode('utf8')
                    sendLink(user, tk)
                    return HttpResponse(
                        "We have sent link to your email check it")
                return render(request, 'accounts/forgot_password.html',
                              {'err': 'Account not found'})
            return render(request, 'accounts/forgot_password.html',
                          {'err': 'Invalid Email Address'})
        return render(request, 'accounts/forgot_password.html',
                      {'err': 'Something went wrong'})
예제 #26
0
def slots_Available(request):
    if 'doc_id' in request.GET and 'date' in request.GET:
        docTable = Table('doctor')
        result = docTable.scan(FilterExpression={'doc_id':request.GET['doc_id']}).values()['Items'][0]
        
        doc = {
                'doc_id':  result['doc_id'],
                'name': "Dr."+result['first_name']+" "+result['last_name'],
                'address': result['address']+","+result['city'],
                'spec': result['spec'],
                "slotAvailabe":slots_Available,
                'experience':'9+ year Experience',
                'rating':96,
                'fee':300,         
            }
        
        appointement_helper = Table('appointement_helper')
        
        result2 = appointement_helper.scan(FilterExpression={
            'doc_id':result['doc_id'],
            'date': request.GET['date'],
        }).values()['Items'][0]['avilableSlots']
        
        return render(request,'book_appointement/select_slot.html',{'slots':result2,'doc':doc,'date':request.GET['date'],})
예제 #27
0
def SearchDoctor(request):
    
    if "spec" in request.GET and "city" in request.GET and 'date' in request.GET:
        specialization = request.GET['spec']
        city = request.GET['city']
        date0 = request.GET['date']
        
        date = datetime.strptime(date0, '%Y-%m-%d')
        
        table = Table('doctor')
        
        results = table.scan(FilterExpression={"spec":specialization,'city':city}).values()
        
        data=[]
        
        for result in results['Items']:
            weekdays = ['mon','tue','wed','thu','fri','sat','sun']
            slotTable = Table('slots')
            
            appointement_helper = Table('appointement_helper')
            slots_Available = 0
            result2 = appointement_helper.scan(FilterExpression={
                'doc_id':result['doc_id'],
                'date': date0,
            }).values()
            
            if result2['Count'] == 0:
                results0 = slotTable.scan(FilterExpression={
                    'doc_id': result['doc_id'],
                    }).values()
                scount = 0
                availableSlots=[]
                for day in results0['Items']:
                    print(weekdays[date.weekday()-1])
                    print(day)
                    if weekdays[date.weekday()] in day['days']:
                        availableSlots.append({
                            "slot_id": day['slot_id'],
                            "start_time":day['start_time'],
                            "end_time":day["end_time"],
                            "fee":day['fees']
                        })
                        scount+=1;
                slots_Available = scount
                
                appointement_helper.insertValues(values=[{
                    'id':result['doc_id']+date0,
                    'date':date0,
                    'doc_id':result['doc_id'],
                    'avilableSlots':availableSlots,
                }])
            else:
               slots_Available  = len(result2['Items'][0]['avilableSlots'])
               
               
                
                
            data.append({
                'doc_id':  result['doc_id'],
                'name': "Dr."+result['first_name']+" "+result['last_name'],
                'address': result['address']+","+result['city'],
                'spec': result['spec'],
                "slotAvailabe":slots_Available,
                'experience':'9+ year Experience',
                'rating':96,
                'fee':300,         
            })
            
        print(data)
               
        return render(request,'book_appointement/doctor_list.html',{'doctors':data,'date':date0})
    
    else:
        return render(request,'book_appointement/b_app_find.html')
예제 #28
0
def slots_list(request):
    if is_authenticated != 0:
        table = Table('slots')
        res = table.scan(FilterExpression={}).values()
        if request.method == "GET":
            for i in res['Items']:
                i['_id'] = str(i['_id'])
            return Response(res)

        elif request.method == 'POST':
            slots_data = request.data
            # print(slots_data)
            if slots_data['method'] == "get_slots":
                res = table.scan(FilterExpression={
                    'spec': slots_data['spec']
                }).values()
                for i in res['Items']:
                    i['_id'] = str(i['_id'])
                return Response(res)

            elif slots_data['method'] == "add_slots":
                d1 = table.scan(
                    FilterExpression={
                        'doc_id': slots_data['doc_id'],
                        'spec': slots_data['spec'],
                        'lon': slots_data['lon'],
                        'lat': slots_data['lat']
                    }).values()
                if d1['Count'] == 0:
                    l = slots_data['doc_id']
                    sid = 0
                    for i in res['Items']:
                        if int(i['slot_id'][l:]) > sid:
                            sid = i['slot_id'][l:]
                    sid = int(sid) + 1
                    table.insertValues(
                        values=[{
                            'slot_id': slots_data['doc_id'] + str(sid),
                            'doc_id': slots_data['doc_id'],
                            'spec': slots_data['spec'],
                            'start_time': slots_data['start_time'],
                            'end_time': slots_data['end_time'],
                            'fees': slots_data['fees'],
                            'days': slots_data['days'],
                            'lon': slots_data['lon'],
                            'lat': slots_data['lat']
                        }])
                    return HttpResponse("Added new value")
                else:
                    for item in d1['Items']:
                        sst = int(slots_data['start_time'])
                        snt = int(slots_data['end_time'])
                        ist = int(item['start_time'])
                        iet = int(item['end_time'])
                        if ist < sst < iet:
                            return HttpResponse(
                                "New slot can't be created due to clashing of slot times"
                            )
                        elif ist < snt < iet:
                            return HttpResponse(
                                "New slot can't be created due to clashing of slot times"
                            )
                        elif (sst == ist) & (snt == iet):
                            return HttpResponse(
                                "New slot can't be created due to clashing of slot times"
                            )
                        else:
                            l = slots_data['doc_id']
                            sid = 0
                            for i in res['Items']:
                                if int(i['slot_id'][l:]) > sid:
                                    sid = i['slot_id'][l:]
                            sid = int(sid) + 1
                            table.insertValues(values=[
                                {
                                    'slot_id': slots_data['doc_id'] + str(sid),
                                    'doc_id': slots_data['doc_id'],
                                    'spec': slots_data['spec'],
                                    'start_time': slots_data['start_time'],
                                    'end_time': slots_data['end_time'],
                                    'fees': slots_data['fees'],
                                    'days': slots_data['days'],
                                    'lon': slots_data['lon'],
                                    'lat': slots_data['lat']
                                }
                            ])
                            return HttpResponse("Added new value")

            elif slots_data['method'] == "delete_slots":
                table.delete(
                    FilterExpression={'slot_id': slots_data['slot_id']})
                return HttpResponse("Deleted that slot id")
예제 #29
0
def appoint(request):
    table = Table('appointments')
    table2 = Table('slots')
    data = table.scan(FilterExpression={}).values()
    email = getEmail(request.session['session_key'])
    # print(data)
    # print(request.POST['slot_id'])
    # email = "*****@*****.**"
    if request.method == "POST":
        num = 0
        items = data['Items']
        for it in items:
            c = int(it['app_id'])
            if (c > num):
                num = c
        num += 1
        # print(num)
        d = table2.scan(FilterExpression={
            'slot_id': request.POST['slot_id']
        }).values()
        for it in d['Items']:
            print(it)
            doc_id = it['doc_id']
            spec = it['spec']
            start_time = it['start_time']
            end_time = it['end_time']
            fees = it['fees']
        d1 = table.scan(
            FilterExpression={
                'doc_id': doc_id,
                'spec': spec,
                'pat_id': email,
                'start_time': start_time,
                'end_time': end_time
            }).values()
        if d1['Count'] == 0:
            table.insertValues(values=[{
                'app_id': str(num),
                'doc_id': doc_id,
                'spec': spec,
                'pat_id': email,
                'start_time': start_time,
                'end_time': end_time,
                'fees': fees,
                'date': '30072020'
            }])
            # return render(request, "p/", {'app_id':str(num)})
            return HttpResponse("Appointment Added")
        else:
            for item in d1['Items']:
                sst = int(start_time)
                snt = int(end_time)
                ist = int(item['start_time'])
                iet = int(item['end_time'])
                if ist < sst < iet:
                    return HttpResponse(
                        "New appointment can't be created due to clashing of appointment times"
                    )
                elif ist < snt < iet:
                    return HttpResponse(
                        "New appointment can't be created due to clashing of appointment times"
                    )
                elif (sst == ist) & (snt == iet):
                    return HttpResponse(
                        "New appointment can't be created due to clashing of appointment times"
                    )
                else:
                    table.insertValues(values=[{
                        'app_id': str(num),
                        'doc_id': doc_id,
                        'spec': spec,
                        'pat_id': email,
                        'start_time': start_time,
                        'end_time': end_time,
                        'fees': fees,
                        'date': '30072020'
                    }])
                    return HttpResponse("Appointment Added")
예제 #30
0
def getTokenPair(request):
    print(request.POST)
    if 'user' in request.POST and 'password' in request.POST:
        user = request.POST['user']
        password = request.POST['password']
        table = Table("users")
        if (isValidEmail(user) and isvalidPassword(password)):
            password = hashlib.sha256((password + SECRET_KEY).encode())
            password = password.hexdigest()
            response = table.scan(FilterExpression={'email': user}).values()
            if response['Count'] == 0:
                return Response({
                    "code":
                    "1",
                    "message":
                    "Incorrect Username/email address or password"
                })

            password0 = response['Items'][0]['password']
            if (password == password0):
                if response['Items'][0]['isVerified'] == 0:
                    return Response({
                        "code":
                        "2",
                        "message":
                        "please verify your email id first",
                    })
                isDoctor = 1 if 'isDoctor' in response['Items'][0] else 0
                if isDoctor == 0:
                    primary_token = jwt.encode(
                        {
                            "email":
                            user,
                            "timestamp":
                            (datetime.now() +
                             timedelta(minutes=15)).strftime("%Y%m%d%H%M%S"),
                        },
                        SECRET_KEY2,
                        algorithm="HS256")
                    refresh_token = jwt.encode(
                        {
                            "email":
                            user,
                            "timestamp":
                            (datetime.now() +
                             timedelta(days=7)).strftime("%Y%m%d%H%M%S"),
                        },
                        SECRET_KEY,
                        algorithm="HS256")

                    return Response({
                        "code": "0",
                        "refresh_token": refresh_token,
                        "primary_token": primary_token,
                    })

        elif (isvalidUserName(user) and isvalidPassword(password)):
            password = hashlib.sha256((password + SECRET_KEY).encode())
            password = password.hexdigest()
            response = table.scan(FilterExpression={'username': user}).values()
            if response['Count'] == 0:
                return Response({
                    "code":
                    "1",
                    "message":
                    "Incorrect Username/email address or password"
                })
            user = response['Items'][0]['email']
            password0 = response['Items'][0]['password']
            if (password == password0):
                if response['Items'][0]['isVerified'] == 0:
                    return Response({
                        "code":
                        "2",
                        "message":
                        "please verify your email id first",
                    })
                isDoctor = 1 if 'isDoctor' in response['Items'][0] else 0
                if isDoctor == 0:
                    primary_token = jwt.encode(
                        {
                            "email":
                            user,
                            "timestamp":
                            (datetime.now() +
                             timedelta(minutes=15)).strftime("%Y%m%d%H%M%S"),
                        },
                        SECRET_KEY2,
                        algorithm="HS256")
                    refresh_token = jwt.encode(
                        {
                            "email":
                            user,
                            "timestamp":
                            (datetime.now() +
                             timedelta(days=7)).strftime("%Y%m%d%H%M%S"),
                        },
                        SECRET_KEY,
                        algorithm="HS256")

                    return Response({
                        "code": "0",
                        "refresh_token": refresh_token,
                        "primary_token": primary_token,
                    })

    return Response({
        "code": "1",
        "message": "Incorrect Username/email address or password"
    })