Ejemplo n.º 1
0
def deleteTask():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json':
        abort(400)

    task_id = request.json.get('task_id')

    try:
        # r.table('UsersInfo').get(mobileNo).update({"smscode": SMScode}).run(g.rdb_conn)
        r.table('Tasks').get(task_id).delete().run(g.rdb_conn)
    except RqlError:
        logging.warning('DB code verify failed on /api/deleteTask/')

        payload = "LOG_INFO=" + simplejson.dumps({ '/editTask/<username>/<task_id>/':'DB operation failed on /editTask/<task_id>/' })
        requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload)
        
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    resp = make_response(jsonify({"OK": "Task Deleted"}), 200)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 2
0
def confirmUser(smscode):
    # make request to get one task
    if 'username' not in request.cookies:
        return redirect('/')

    username = request.cookies.get('username')

    try:
        user = r.table(
            'UsersInfo').get(username).pluck('smscode').run(g.rdb_conn)
        r.table('UsersInfo').get(username).update({"userVerified": "yes"})

    except RqlError:
        logging.warning('DB op failed on /confirmUser/')

        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    if str(user) is not str(smscode):
        return
        """
        EMAIL VERFICATION FAILED
        """

    return redirect("/task/createTask/", code=302)
Ejemplo n.º 3
0
def addNewsLetter():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json':
        abort(400)

    email = request.json.get('email')
    # mobile no is the id - primary key

    try:
        r.table('newsLetter').insert({
            'email': email,
        }).run(g.rdb_conn)
    except RqlError:
        logging.warning('DB could not write on /api/newsLetter/')
        resp = make_response(jsonify({'Error': 'Save Failed'}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    resp = make_response(jsonify({'OK': 'Content Saved'}), 202)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 4
0
def getRandID():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json':
        abort(400)

    # use the mobile number as the id number its a unique entity
    username = request.json.get('username')
    email = request.json.get('email')
    password = request.json.get('password')
    email = str(email)
    username = str(username)

    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)
        if user is not None:
            resp = make_response(jsonify({"Error": "User Exists"}), 400)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        user = r.table('UsersInfo').filter({"email": email}).limit(1).run(g.rdb_conn)
        if user is not None:
            resp = make_response(jsonify({"Error": "User Exists"}), 400)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp


    except RqlError:
        logging.warning('DB code verify failed on /api/signUp/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    SMScode = randint(10000, 99999)
    # sendMail.sendMail(email, SMScode, username)

    hashed_password = hashlib.sha512(password + salt).hexdigest()

    try:
        r.table(
            'UsersInfo').insert({"state": "", "username": username, "dob": "", "email": email, "password": hashed_password,
                                 "smscode": SMScode, "mobileNo": ""}).run(g.rdb_conn)
    except RqlError:
        logging.warning('DB code verify failed on /api/signUp/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp


    resp = make_response(jsonify({"OK": "Signed Up"}), 202)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 5
0
def editTask(task_id):
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json; charset=UTF-8':
        abort(400)

    username = request.json.get('username')

    if username not in session:
        return redirect('/')

    task_urgency = request.json.get('task_urgency')
    task_title = request.json.get('title')
    task_desc = request.json.get('description')
    # task_category = request.json.get('category')
    due_date = request.json.get('due_date')
    task_id = request.json.get('task_id')
    locationData = request.json.get('locationData')
    contactPersons = request.json.get('contactPersons')

    # make request to get one task
    if request.method == 'GET':
        try:
            user_task = r.table('Tasks').get(task_id).run(g.rdb_conn)

        except RqlError:
            logging.warning('DB op failed on /api/editTask/')
            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        resp = make_response(jsonify({"Task fetched": user_task}), 202)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    try:
        r.table(
            'Tasks').get(task_id).update({'task_desc': task_desc, 'task_title': task_title,
                                          'task_urgency': task_urgency,
                                          'due_date': due_date, "locationData": locationData, 
                                          'contactPersons': contactPersons }).run(g.rdb_conn)

    except RqlError:
        logging.warning('DB code verify failed on /api/editTask/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    resp = make_response(jsonify({"OK": "Task Updated"}), 202)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 6
0
def credit(username):
    if username not in session:
        return redirect("/")

    if request.method == "GET":

        if not request.json:
            abort(400)

        if request.headers["Content-Type"] != "application/json; charset=UTF-8":
            abort(400)

        password = request.json.get("password")
        username = request.json.get("username")

        try:
            user = r.table("Payments").get(str(username)).pluck("credit_available").run(g.rdb_conn)

            credit = json.dumps(user)
            resp = make_response(jsonify(credit), 202)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        except RqlError:
            logging.warning("DB code verify failed on /api/credit" + username)
            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

    if request.method == "POST":

        if not request.json:
            abort(400)

        if request.headers["Content-Type"] != "application/json; charset=UTF-8":
            abort(400)

        password = request.json.get("password")
        username = request.json.get("username")

        try:
            user = r.table("Payments").get(str(username)).pluck("credit_available").run(g.rdb_conn)

            resp = make_response(jsonify({"OK": "User Updated"}), 202)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        except RqlError:
            logging.warning("DB code verify failed on /api/credit" + username)
            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp
Ejemplo n.º 7
0
def getAdminTasks():
    if request.method == 'POST':

        if not request.json:
            abort(400)

        if request.headers['Content-Type'] != 'application/json; charset=UTF-8':
            abort(400)

        
        # add to sessions then login
        if 'username' not in request.cookies:
            return redirect('/')

        username = request.cookies.get('username')
        if request.cookies.get('username') == '' or request.cookies.get('username') is None:
            return redirect('/')


        taskData = []
        try:
            tasks = r.table('Tasks').filter(
                {'task_urgency': 'started'}).limit(50).run(g.rdb_conn)
            for data in tasks:
                taskData.append(data)

        except RqlError:
            logging.warning('DB code verify failed on /api/adminTasks/')
            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        taskData = dumps(taskData)

        resp = make_response(taskData, 200)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    try:
        task_size = r.table('Tasks').count().run(g.rdb_conn)

    except RqlError:
        logging.warning('DB code verify failed on /api/adminTasks/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    return render_template('adminViewTasks.html', task_size=task_size)
Ejemplo n.º 8
0
def taskInfo(task_id):
    if 'username' not in request.cookies:
        return redirect('/')

    if request.cookies.get('username') == '' or request.cookies.get('username') is None:
        return redirect('/')

    username = request.cookies.get('username')

    try:
        user = r.table('Tasks').get(task_id).run(g.rdb_conn)

        task_title = str(user['task_title'])
        task_desc = str(user['task_desc'])
        task_urgency = str(user['task_urgency'])
        task_category = str(user['task_category'])
        due_date = str(user['due_date'])
        contactPersons = str(user['contactPersons'])
        location = str(user['locationData'])


    except RqlError:
        logging.warning('DB operation failed on /editTask/<task_id>/')

        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    return render_template(
        'EditTask.html', task_category=task_category, task_urgency=task_urgency, locationData=location, contactPersons=contactPersons,
        task_desc=task_desc, task_title=task_title, due_date=due_date, username=username, task_id=task_id)
Ejemplo n.º 9
0
def adminSign():
    if request.method == 'POST':

        if not request.json:
            abort(400)

        if request.headers['Content-Type'] != 'application/json':
            abort(400)

        username = request.json.get('username')
        password = request.json.get('password')

        try:
            user = r.table('Admin').get(username).run(g.rdb_conn)
        except Exception, e:
            logging.warning('DB failed on /admin/ -> user not found')
            raise e

        if user is None:
            resp = make_response(jsonify({"Not Found": "User Not Found"}), 404)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        resp = make_response(jsonify({"OK": "Signed In"}), 200)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp
Ejemplo n.º 10
0
def getTasks():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json; charset=UTF-8':
        abort(400)

    username = request.json.get('username')

    if username not in session:
        return redirect('/')

    taskData = []
    try:
        tasks = r.table('Tasks').filter({"username": username}).run(g.rdb_conn)
        for data in tasks:
            taskData.append(data)

    except RqlError:
        logging.warning('DB code verify failed on /api/getTasks/')
        
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    taskData = dumps(taskData)

    resp = make_response(taskData, 200)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 11
0
def getTasks():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json':
        abort(400)

    username = request.json.get('username')

    taskData = []
    try:
        tasks = r.table('Tasks').filter({"username": username}).run(g.rdb_conn)
        for data in tasks:
            taskData.append(data)

    except RqlError:
        payload = "LOG_INFO=" + simplejson.dumps({ 'Request':'app.before' })
        requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload)

        logging.warning('DB code verify failed on /api/getTasks/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    taskData = dumps(taskData)

    resp = make_response(taskData, 200)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 12
0
def addUser():
    if not request.json:
        abort(400)

    if request.headers["Content-Type"] != "application/json; charset=UTF-8":
        abort(400)

    username = request.json.get("username")

    if username not in session:
        return redirect("/")

    # get JSON params
    fname = request.json.get("fname")
    lname = request.json.get("lname")
    mobileNo = request.json.get("mobileNo")
    state = request.json.get("state")
    location = request.json.get("location")
    email = request.json.get("email")

    if mobileNo.startswith("0"):
        mobileNo = mobileNo[1:]

    if mobileNo.startswith("+254"):
        mobileNo = mobileNo[4:]

    try:
        r.table("UsersInfo").insert(
            {
                "fname": fname,
                "lname": lname,
                "mobileNo": mobileNo,
                "email": email,
                "state": state,
                "userVerified": "False",
                "location": location,
            }
        ).run(g.rdb_conn)
    except RqlError:
        logging.warning("DB could not write on /api/adduser")

    resp = make_response(jsonify({"OK": "Content Saved"}), 202)
    resp.headers["Content-Type"] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 13
0
def forgotPassword():
    if request.method == "POST":

        if not request.json:
            abort(400)

        if request.headers["Content-Type"] != "application/json; charset=UTF-8":
            abort(400)

        email = request.json.get("email")

        # check password match

        try:
            user = r.table("UsersInfo").filter({"email": email}).limit(1).pluck("username").run(g.rdb_conn)
            if user is None:
                resp = make_response(jsonify({"Missing": "Not Found"}), 400)
                resp.headers["Content-Type"] = "application/json"
                resp.cache_control.no_cache = True
                return resp

            new_password = randint(10000, 99999)
            new_password = str(new_password)
            hashed_password = hashlib.sha512(new_password + salt).hexdigest()
            data = []

            for el in user:
                data.append(el)

            username = data[0]["username"]

            r.table("UsersInfo").get(username).update({"password": hashed_password}).run(g.rdb_conn)

            passwordReset(email, new_password)

        except RqlError:
            logging.warning("DB pass reset failed on /reset/")

        resp = make_response(jsonify({"OK": "Email Sent"}), 200)
        resp.headers["Content-Type"] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    return render_template("forgot-pass.html")
Ejemplo n.º 14
0
def getRandID():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json; charset=UTF-8':
        abort(400)

    # use the mobile number as the id number its a unique entity
    username = request.json.get('username')
    email = request.json.get('email')
    # then update userInfo
    password = request.json.get('password')
    email = str(email)
    username = str(username)

    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)
        if user is not None:
            resp = make_response(jsonify({"Error": "User Exists"}), 400)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        """
        user = r.table('UsersInfo').filter({"email": email}).limit(1).run(g.rdb_conn)
        userData =[]

        for data in user:
            userData.append(data)

        if userData != []:
            resp = make_response(jsonify({"Error": "User Email Exists"}), 400)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp
        """

    except RqlError:
        logging.warning('DB code verify failed on /api/signUp/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    SMScode = randint(10000, 99999)

    # verify user send email with code
    # sendText(mobileNo, SMScode)
    # @task sendMail
    try:
        sendMail(email, SMScode, username)
    except urllib2.URLError:
        logging.warning('sendMail verify failed on /api/signUp/')
        abort(500)
    except Exception, e:
        logging.warning('SendMail error on /api/signUp/ %s' %(e) )
Ejemplo n.º 15
0
def post_payment_pesapal():
    if 'username' not in request.cookies:
        return redirect('/')

    username = request.cookies.get('username')
    # with ref set in rand generator
    pesapal_merchant_ref = request.args.get('pesapal_merchant_reference')
    pesapal_merchant_id  = request.args.get('pesapal_transaction_tracking_id')
    
    print(pesapal_merchant_id)
    print(pesapal_merchant_ref)

    # store merchant info in db
    # basic post_payment page TO LOAD
    pesapal_data = { "pesapal_transaction_tracking_id": pesapal_merchant_id,
        "pesapal_merchant_reference": pesapal_merchant_ref, "username": username }

    try:
        r.table('Payments').insert(pesapal_data).run(g.rdb_conn)
    except Exception:
        logging.warning('DB code verify failed on /post_payment/')

        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    # optional get payment status - info sent to pesapla ipn notification
    # per user info - render post payment page - by merchant ref
    """
    post_params = {
      'pesapal_merchant_reference': '000',
      'pesapal_transaction_tracking_id': '000'
    }
    """

    status = process_payments.queryPaymentByRef(pesapal_data)
    return render_template('PostPayment.html', status=status, username=username)
Ejemplo n.º 16
0
def addTask():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json':
        abort(400)

    username = request.json.get('username')
    task_desc = request.json.get('description')
    task_title = request.json.get('title')
    # then update userInfo
    task_category = request.json.get('category')
    task_urgency = request.json.get('urgency')
    due_date = request.json.get('due_date')

    taskData = {"username": username, "task_title": task_title, "task_desc": task_desc,
                "task_category": task_category, "task_urgency": "started", "due_date": due_date}

    text_all = "LinkUs new task -> " + task_title + task_desc

    try:
        r.table('Tasks').insert(taskData).run(g.rdb_conn)
    except RqlError:
        logging.warning('DB code verify failed on /api/addTask/')

        payload = "LOG_INFO=" + simplejson.dumps({ '/api/addTask/':'DB operation failed on /addTask/' })
        requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload)

        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    resp = make_response(jsonify({"OK": "Task Created"}), 200)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 17
0
def signIn():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json':
        abort(400)

    password = request.json.get('password')
    username = request.json.get('username')
    email = request.json.get('email')

    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning('DB signIn failed on /api/signIn/ - user Not Found')
        raise e
Ejemplo n.º 18
0
def removeUser():
    if not request.json:
        abort(400)

    if request.headers["Content-Type"] != "application/json; charset=UTF-8":
        abort(400)

    password = request.json.get("password")
    username = request.json.get("username")

    if username not in session:
        return redirect("/")

    try:
        user = r.table("UsersInfo").get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning("DB signIn failed on /api/signIn/ -> user not found")
        raise e
Ejemplo n.º 19
0
def signIn():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json; charset=UTF-8':
        abort(400)

    session.permanent = True

    password = request.json.get('password')
    username = request.json.get('username')

    # join to another table
    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning('DB signIn failed on /api/signIn/ -> user not found')
        raise e
Ejemplo n.º 20
0
def confirmUser(username, smscode):
    # make request to get one task
    try:
        user = r.table(
            'UsersInfo').get(username).pluck('smscode').run(g.rdb_conn)
    except RqlError:
        logging.warning('DB op failed on /confirmUser/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    if str(user) is not str(smscode):
        return
        """
        EMAIL VERFICATION FAILED
        """

    url = "/tasks/" + username + "/"

    return redirect(url, code=302)
Ejemplo n.º 21
0
def getTasks():
    if request.method is 'POST':
        if request.headers['Content-Type'] != 'text/plain':
            abort(400)

        text = request.data
        sender = request.args.get('from')

        try:
            tasks = r.table('Client').get(sender).update(text).run(g.rdb_conn)
        except RqlError:
            logging.warning('DB code verify failed on /api/getTasks/')

            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        resp = make_response(tasks, 200)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp
Ejemplo n.º 22
0
def getTasks():
    if request.method is "POST":
        if request.headers["Content-Type"] != "text/plain":
            abort(400)

        text = request.data
        sender = request.args.get("from")

        try:
            tasks = r.table("Client").get(sender).update(text).run(g.rdb_conn)
        except RqlError:
            logging.warning("DB code verify failed on /api/getTasks/")

            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        resp = make_response(tasks, 200)
        resp.headers["Content-Type"] = "application/json"
        resp.cache_control.no_cache = True
        return resp
Ejemplo n.º 23
0
def taskInfo(username, calendar_id):
    try:
        user = r.table('Tasks').get(task_id).run(g.rdb_conn)

        task_title = str(user['task_title'])
        task_desc = str(user['task_desc'])
        task_urgency = str(user['task_urgency'])
        task_category = str(user['task_category'])
        due_date = str(user['due_date'])

    except RqlError:
        payload = "LOG_INFO=" + simplejson.dumps({ '/editTask/<username>/<task_id>/':'DB operation failed on /editTask/<task_id>/' })
        requests.post("https://logs-01.loggly.com/inputs/e15fde1a-fd3e-4076-a3cf-68bd9c30baf3/tag/python/", payload)

        logging.warning('DB operation failed on /editTask/<task_id>/')
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    return render_template(
        'editCalendar.html', task_category=task_category, task_urgency=task_urgency, locationData= "Nairobi", contactPersons="James",
        task_desc=task_desc, task_title=task_title, due_date=due_date, username=username, task_id=task_id)
Ejemplo n.º 24
0
    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning('DB signIn failed on /api/signIn/ -> user not found')
        raise e

    if user is None:
        resp = make_response(jsonify({"Not Found": "User Not Found"}), 404)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    hashed_password = hashlib.sha512(str(password) + salt).hexdigest()

    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)

        if str(user['password']) != str(hashed_password):
            # add user to session then log in
            resp = make_response(
                jsonify({"Password": "******"}), 404)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp
    except RqlError:
        logging.warning('raise RqlError DB signIn failed on /api/signIn/')

    # manage sessions - add user to session
    # redis sessions -> flask
    # redis k/v store | dict
    session[username] = username
Ejemplo n.º 25
0
def payments():
    if "username" not in request.cookies:
        return redirect("/")

    if request.cookies.get("username") == "" or request.cookies.get("username") is None:
        return redirect("/")

    username = request.cookies.get("username")

    if request.method == "POST":

        if not request.json:
            abort(400)

        if request.headers["Content-Type"] != "application/json; charset=UTF-8":
            abort(400)

        email = request.json.get("email")
        dob = request.json.get("dob")
        state = request.json.get("state")
        mobileNo = request.json.get("mobileNo")

        if mobileNo.startswith("0"):
            mobileNo = mobileNo[1:]

        if mobileNo.startswith("+254"):
            mobileNo = mobileNo[4:]

        try:
            user = (
                r.table("UsersInfo")
                .get(str(username))
                .update({"email": email, "state": state, "dob": dob, "mobileNo": mobileNo})
                .run(g.rdb_conn)
            )

            resp = make_response(jsonify({"OK": "User Updated"}), 202)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        except RqlError:
            logging.warning("DB code verify failed on /profile/api/" + username)
            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

    """
    try:
        user = r.table('Payments').get(str(username)).run(g.rdb_conn)
        username = str(user['username'])
        credit = str(user['credit_available'])

    except RqlError:
        logging.warning('DB code verify failed on /payments/' + mobileNo)
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp
    """

    return render_template("payments.html", username=username)
Ejemplo n.º 26
0
    try:
        user = r.table("UsersInfo").get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning("DB signIn failed on /api/signIn/ -> user not found")
        raise e

    if user is None:
        resp = make_response(jsonify({"Not Found": "User Not Found"}), 404)
        resp.headers["Content-Type"] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    hashed_password = hashlib.sha512(str(password) + salt).hexdigest()

    try:
        user = r.table("UsersInfo").get(username).run(g.rdb_conn)

        if str(user["password"]) != str(hashed_password):
            # add user to session then log in
            resp = make_response(jsonify({"Password": "******"}), 404)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp
    except RqlError:
        logging.warning("Wrong password user failed on /api/signIn/")

    session.pop(username, None)

    try:
        r.table("UsersInfo").get(username).delete().run(g.rdb_conn)
    except RqlError:
Ejemplo n.º 27
0
def ussdCallBack():
    if request.method is "POST":
        if request.headers["Content-Type"] != "text/plain":
            abort(400)

        text = request.data

        # Reads the variables sent via POST from our gateway
        sessionId = request.args.get("sessionId")
        serviceCode = request.args.get("serviceCode")
        phoneNumber = request.args.get("phoneNumber")
        text = request.args.get("text")

        if request.args.get("text") is "":
            # load menu
            menu_text = """CON What would you like to do? \n
            1. To pay a distributor \n
            2. To check balance \n
            3. To make a credit request \n
            4. Check my transaction history \n
            """

            resp = make_response(menu_text, 200)
            resp.headers["Content-Type"] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        elif request.args.get("text") is "1":
            # pay a distributor
            balance = "END your balance is 2000 Kshs"

            resp = make_response(balance, 200)
            resp.headers["Content-Type"] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        elif request.args.get("text") is "2":
            balance = "END your balance is 2000 Kshs"
            resp = make_response(balance, 200)

            resp.headers["Content-Type"] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        elif request.args.get("text") is "2":
            balance = "END your balance is 2000 Kshs"
            resp = make_response(balance, 200)

            resp.headers["Content-Type"] = "text/plain"
            resp.cache_control.no_cache = True
            return resp
        else:
            balance = "END your balance is 2000 Kshs"
            resp = make_response(balance, 200)
            resp.headers["Content-Type"] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        try:
            tasks = r.table("Client").get(sender).update(text).run(g.rdb_conn)
        except RqlError:
            logging.warning("DB code verify failed on /api/getTasks/")

            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        resp = make_response(tasks, 200)
        resp.headers["Content-Type"] = "application/json"
        resp.cache_control.no_cache = True
        return resp
Ejemplo n.º 28
0
def profile():
    if "username" not in request.cookies:
        return redirect("/")

    if request.cookies.get("username") == "" or request.cookies.get("username") is None:
        return redirect("/")

    username = request.cookies.get("username")

    if request.method == "POST":

        if not request.json:
            abort(400)

        if request.headers["Content-Type"] != "application/json; charset=UTF-8":
            abort(400)

        password = request.json.get("password")
        email = request.json.get("email")
        dob = request.json.get("dob")
        username = request.json.get("username")
        firstname = request.json.get("firstname")
        lastname = request.json.get("lastname")
        state = request.json.get("state")
        mobileNo = request.json.get("mobileNo")

        if mobileNo.startswith("0"):
            mobileNo = mobileNo[1:]

        if mobileNo.startswith("+254"):
            mobileNo = mobileNo[4:]

        try:
            user = (
                r.table("UsersInfo")
                .get(str(username))
                .update(
                    {
                        "email": email,
                        "lname": lastname,
                        "fname": firstname,
                        "state": state,
                        "dob": dob,
                        "mobileNo": mobileNo,
                    }
                )
                .run(g.rdb_conn)
            )

            resp = make_response(jsonify({"OK": "User Updated"}), 202)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        except RqlError:
            logging.warning("DB code verify failed on /profile/api/" + username)
            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers["Content-Type"] = "application/json"
            resp.cache_control.no_cache = True
            return resp

    try:
        user = r.table("UsersInfo").get(str(username)).run(g.rdb_conn)

        name = str(user["username"])
        state = str(user["state"])
        smscode = str(user["smscode"])
        # password = str(user['password'])
        email = str(user["email"])
        mobileNo = str(user["mobileNo"])
        firstname = str(user["fname"])
        lastname = str(user["lname"])

    except RqlError:
        logging.warning("DB code verify failed on /profile/" + mobileNo)
        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers["Content-Type"] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    # profile url fix - only on signUp
    default_url = "https://www.gravatar.com/avatar"
    size = 80
    profile_url = "https://www.gravatar.com/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"
    profile_url += urllib.urlencode({"d": default_url, "s": str(size)})

    return render_template(
        "Profile.html",
        name=name,
        lastname=lastname,
        firstname=firstname,
        email=email,
        smscode=smscode,
        state=state,
        username=username,
        mobileNo=mobileNo,
        profile_image=profile_url,
    )
Ejemplo n.º 29
0
def withdraw(username):
    try:
        user = r.table("Admin").get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning("DB failed on /admin/ -> user not found")
        raise e
Ejemplo n.º 30
0
def ussdCallBack():
    if request.method is 'POST':
        if request.headers['Content-Type'] != 'text/plain':
            abort(400)

        text = request.data

        # Reads the variables sent via POST from our gateway
        sessionId = request.args.get("sessionId")
        serviceCode = request.args.get("serviceCode")
        phoneNumber = request.args.get("phoneNumber")
        text = request.args.get("text")

        if request.args.get('text') is '':
            # load menu
            menu_text = """CON What would you like to do? \n
            1. To pay a distributor \n
            2. To check balance \n
            3. To make a credit request \n
            4. Check my transaction history \n
            """

            resp = make_response(menu_text, 200)
            resp.headers['Content-Type'] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        elif request.args.get('text') is '1':
            # pay a distributor
            balance = "END your balance is 2000 Kshs"

            resp = make_response(balance, 200)
            resp.headers['Content-Type'] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        elif request.args.get('text') is '2':
            balance = "END your balance is 2000 Kshs"
            resp = make_response(balance, 200)

            resp.headers['Content-Type'] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        elif request.args.get('text') is '2':
            balance = "END your balance is 2000 Kshs"
            resp = make_response(balance, 200)

            resp.headers['Content-Type'] = "text/plain"
            resp.cache_control.no_cache = True
            return resp
        else:
            balance = "END your balance is 2000 Kshs"
            resp = make_response(balance, 200)
            resp.headers['Content-Type'] = "text/plain"
            resp.cache_control.no_cache = True
            return resp

        try:
            tasks = r.table('Client').get(sender).update(text).run(g.rdb_conn)
        except RqlError:
            logging.warning('DB code verify failed on /api/getTasks/')

            resp = make_response(jsonify({"Error": "503 DB error"}), 503)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp

        resp = make_response(tasks, 200)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp
Ejemplo n.º 31
0
def withdraw(username):
    try:
        user = r.table('Admin').get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning('DB failed on /admin/ -> user not found')
        raise e
Ejemplo n.º 32
0
def addTask():
    if not request.json:
        abort(400)

    if request.headers['Content-Type'] != 'application/json; charset=UTF-8':
        abort(400)

    username = request.json.get('username')

    if username not in session:
        return redirect('/')

    task_desc = request.json.get('description')
    task_title = request.json.get('title')
    # then update userInfo
    task_category = request.json.get('category')
    task_urgency = request.json.get('urgency') # checkbox
    due_date = request.json.get('due_date')
    locationData = request.json.get('locationData')
    contactPersons = request.json.get('contactPersons')
    task_price = request.json.get('taskPrice')
    task_creation_date = str(datetime.now())

    # unpaid status - pending - started - finished
    taskData = { "username": username, "task_title": task_title, 
    "task_desc": task_desc, "locationData": locationData, "task_category": task_category, 
    "task_urgency": "UNPAID", "due_date": due_date, "contactPersons": contactPersons, 'task_creation_date': task_creation_date }

    text_all = "taskwetu new task %s " %(task_title)

    try:
        r.table('Tasks').insert(taskData).run(g.rdb_conn)
    except RqlError:
        logging.warning('DB code verify failed on /api/addTask/')

        resp = make_response(jsonify({"Error": "503 DB error"}), 503)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    # send email and SMS notification
    # rabbitMQ tasks
    try:
        send_notification_task("+254710650613", str(text_all))
        new_task_message("*****@*****.**", str(taskData), username)
        new_task_message("*****@*****.**", str(taskData), username)
    except Exception:
        logging.warning('Send SMS failed on /api/addTask/ notification failed')

    try:
        user_info = r.table('UsersInfo').get(username).pluck('email').run(g.rdb_conn)
        usermobileNo = r.table('UsersInfo').get(username).pluck('mobileNo').run(g.rdb_conn)
        email = user_info['email']
        mobileNo = ""
        if usermobileNo is not None:
            mobileNo = usermobileNo['mobileNo']

    except Exception:
        logging.warning('Fetch of userInfo failed on /api/addTask/')

    # setup URL to payments - user specific data
    merchant_ref = "Ta" + str(randint(10000, 99999)) + "W"
    #merchant_ref = '12erwe'
    # amount ?
    task_price = 500
    request_data = {
        'Amount': str(task_price),
        'Description': str(task_title),
        'Type': 'MERCHANT',
        'Reference': str(merchant_ref),
        'PhoneNumber': str(mobileNo),
        'Email': str(email)
    }

    url = process_payments.postOrder(request_data)

    # store URL in redis under username
    # set with expire
    red.hset(username, 'url', url)
    red.expire(username, 300)

    # resp = make_response(redirect(pay_url, code=302))

    resp = make_response(jsonify({"OK": "Task Created"}), 200)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp
Ejemplo n.º 33
0
    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)
    except Exception, e:
        logging.warning('DB signIn failed on /api/signIn/ - user Not Found')
        raise e

    if user is None:
        resp = make_response(jsonify({"Not Found": "User Not Found"}), 404)
        resp.headers['Content-Type'] = "application/json"
        resp.cache_control.no_cache = True
        return resp

    hashed_password = hashlib.sha512(str(password) + salt).hexdigest()

    try:
        user = r.table('UsersInfo').get(username).run(g.rdb_conn)

        if str(user['password']) != str(hashed_password):
            resp = make_response(
                jsonify({"Password": "******"}), 404)
            resp.headers['Content-Type'] = "application/json"
            resp.cache_control.no_cache = True
            return resp
    except RqlError:
        logging.warning('raise RqlError DB signIn failed on /api/signIn/')


    resp = make_response(jsonify({"OK": "Signed In"}), 200)
    resp.headers['Content-Type'] = "application/json"
    resp.cache_control.no_cache = True
    return resp