Example #1
0
def check_auth(request):
    # return '0'
    access_token = request.headers.get("Authorization", "")[len("Bearer ") :]
    if not db.token(access=access_token) or db.token(access=access_token)[0]["expire_time"] < datetime.now():
        return None

    return db.token(access=access_token)[0]["user_id"]
Example #2
0
def put_bid_item(id):
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 401

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        id = int(id)
        if id not in db.bid or db.bid[id]['user_id'] != user_id:
            raise Exception()
    except:
        return '', 404

    try:
        bid = request.get_json(force=True)
        #for event in bid['event']:
        #    if event['id'] not in db.event or 'amount' not in event:
        #        raise Exception()
        if bid['event']['id'] not in db.event:
            raise Exception()
        if 'number_tickets' not in bid:
            raise Exception()
    except:
        return '', 400

    db.bid.update(db.bid[id], event=bid['event'],
                                  number_tickets=bid['number_tickets'])

    db.bid.commit()

    return '', 200
Example #3
0
def post_bids():
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 401

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        bid = request.get_json(force=True)
        #print bid['event']
        #for event in bid['event']:
            #print bid['event']['id']
        #if event['id'] not in db.event:
        if bid['event']['id'] not in db.event:
            raise Exception()
        if 'number_tickets' not in bid:
            raise Exception()
    except:
        return '', 400

    id = db.bid.insert(user_id=user_id,
                        event=bid['event'],
                        number_tickets=bid['number_tickets'])

    db.bid.commit()

    return '', 201, {
        'Location': '/bids/{}'.format(id)
    }
Example #4
0
def put_order_item(id):
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 403

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        id = int(id)
        if id not in db.order or db.order[id]['user_id'] != user_id:
            raise Exception()
    except:
        return '', 404

    try:
        order = request.json
        for food in order['food']:
            if food['id'] not in db.food or 'amount' not in food:
                raise Exception()
        if 'delivery_location' not in order:
            raise Exception()
    except:
        return '', 400

    db.order.update(db.order[id], food=order['food'],
                                  delivery_location=order['delivery_location'],
                                  time_placed=datetime.now())
    db.order.commit()

    return '', 200
Example #5
0
def post_orders():
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 403

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        order = request.json
        for food in order['food']:
            if food['id'] not in db.food or 'amount' not in food:
                raise Exception()
        if 'delivery_location' not in order:
            raise Exception()
    except:
        return '', 400

    id = db.order.insert(user_id=user_id,
                         food=order['food'],
                         delivery_location=order['delivery_location'],
                         time_placed=datetime.now())
    db.order.commit()

    return '', 201, {
        'Location': '/orders/{}'.format(id)
    }
Example #6
0
def token():
    try:
        grant_type = request.form.get("grant_type")
        client_id = request.form.get("client_id")
        client_secret = request.form.get("client_secret")
    except KeyError:
        return json.dumps({"error": "invalid_request"}), 400, {"Content-Type": "application/json;charset=UTF-8"}

    try:
        client_id = int(client_id)
    except:
        client_id = None
    if client_id not in db.client or db.client[client_id]["secret"] != client_secret:
        print(client_id)
        print(client_secret)
        return json.dumps({"error": "invalid_client"}), 400, {"Content-Type": "application/json;charset=UTF-8"}

    if grant_type == "authorization_code":
        try:
            code = request.form.get("code")
        except KeyError:
            return json.dumps({"error": "invalid_request"}), 400, {"Content-Type": "application/json;charset=UTF-8"}

        if not db.authorization_code(code=code) or db.authorization_code(code=code)[0]["expire_time"] < datetime.now():
            return json.dumps({"error": "invalid_grant"}), 400, {"Content-Type": "application/json;charset=UTF-8"}

        user_id = db.authorization_code(code=code)[0]["user_id"]

        db.authorization_code.delete(db.authorization_code(code=code))
        db.authorization_code.commit()
    elif grant_type == "refresh_token":
        try:
            refresh_token = request.form.get("refresh_token")
        except KeyError:
            return json.dumps({"error": "invalid_request"}), 400, {"Content-Type": "application/json;charset=UTF-8"}

        if not db.token(refresh=refresh_token):
            return json.dumps({"error": "invalid_grant"}), 400, {"Content-Type": "application/json;charset=UTF-8"}

        user_id = db.token(refresh=refresh_token)[0]["user_id"]

        db.token.delete(db.token(refresh=refresh_token))
        db.token.commit()
    else:
        return json.dumps({"error": "unsupported_grant_type"}), 400, {"Content-Type": "application/json;charset=UTF-8"}

    access_token = sha256(str(uuid4()).encode("UTF-8")).hexdigest()
    expire_time = datetime.now() + timedelta(hours=1)
    refresh_token = sha256(str(uuid4()).encode("UTF-8")).hexdigest()
    db.token.insert(user_id=user_id, access=access_token, expire_time=expire_time, refresh=refresh_token)
    db.token.commit()

    return (
        json.dumps(
            {"access_token": access_token, "token_type": "bearer", "expires_in": 3600, "refresh_token": refresh_token}
        ),
        200,
        {"Content-Type": "application/json;charset=UTF-8", "Cache-Control": "no-store", "Pragma": "no-cache"},
    )
Example #7
0
def check_auth(request):
    # return '0'
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(
            access=access_token)[0]['expire_time'] < datetime.now():
        return None

    return db.token(access=access_token)[0]['user_id']
Example #8
0
def check_auth(request):
   # return '0'
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return None


    return db.token(access=access_token)[0]['user_id']
Example #9
0
def get_me():
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 403 

    user_id = db.token(access=access_token)[0]['user_id']

    return json.dumps({
        'login': db.user[user_id]['login'],
        'name': db.user[user_id]['name'],
        'email': db.user[user_id]['email'],
        'phone': db.user[user_id]['phone'],
    }, indent=4), 200, {
        'Content-Type': 'application/json;charset=UTF-8',        
    }
Example #10
0
def delete_bid_item(id):
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 401

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        id = int(id)
        if id not in db.bid or db.bid[id]['user_id'] != user_id:
            raise Exception()
    except:
        return '', 404

    db.bid.delete(db.bid[id])
    db.bid.commit()

    return '', 200
Example #11
0
def get_bid_item(id):
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 401

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        id = int(id)
        if id not in db.bid or db.bid[id]['user_id'] != user_id:
            raise Exception()
    except:
        return '', 404

    bid = db.bid[id]
    return json.dumps({
        'id': bid['__id__'],
        'event': bid['event'],
        'number_tickets': bid['number_tickets'],
    }, indent=4), 200, {
        'Content-Type': 'application/json;charset=UTF-8',        
    }
Example #12
0
def get_orders():
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 403 

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        per_page = int(request.args.get('per_page', 20))
        if per_page < 20 or per_page > 100:
            raise Exception()
        page = int(request.args.get('page', 0))
        if page < 0 or page > len(db.order(user_id=user_id)) // per_page:
            raise Exception()
    except:
        return '', 400

    items = []
    for i, order in enumerate(db.order(user_id=user_id)):
        if i < page * per_page:
            continue
        if i >= (page + 1) * per_page:
            break
        items.append({
            'id': order['__id__'],
            'food': order['food'],
            'delivery_location': order['delivery_location'],
            'time_placed': order['time_placed'].isoformat(),
            'time_delivered': None if order['time_delivered'] is None else order['time_delivered'].isoformat(),
        })

    return json.dumps({
        'items': items,
        'per_page': per_page,
        'page': page,
        'page_count': math.ceil(len(db.order) / per_page)
    }, indent=4), 200, {
        'Content-Type': 'application/json;charset=UTF-8',        
    }
Example #13
0
def get_bids():
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 401 

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        per_page = int(request.args.get('per_page', 20))
        if per_page < 2 or per_page > 100:
            raise Exception()
        page = int(request.args.get('page', 0))
        if page < 0 or page > len(db.bid(user_id=user_id)) // per_page:
            raise Exception()
    except:
        return '', 400

    items = []
    for i, bid in enumerate(db.bid(user_id=user_id)):
        if i < page * per_page:
            continue
        if i >= (page + 1) * per_page:
            break
        items.append({
            'id': bid['__id__'],
            'event': bid['event'],
            'number_tickets': bid['number_tickets'],
        })

    return json.dumps({
        'items': items,
        'per_page': per_page,
        'page': page,
        'page_count': math.ceil(len(db.bid) / per_page)
    }, indent=4), 200, {
        'Content-Type': 'application/json;charset=UTF-8',        
    }
Example #14
0
def get_orders_item(id):
    access_token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not db.token(access=access_token) or db.token(access=access_token)[0]['expire_time'] < datetime.now():
        return '', 403

    user_id = db.token(access=access_token)[0]['user_id']

    try:
        id = int(id)
        if id not in db.order or db.order[id]['user_id'] != user_id:
            raise Exception()
    except:
        return '', 404

    order = db.order[id]
    return json.dumps({
        'id': order['__id__'],
        'food': order['food'],
        'delivery_location': order['delivery_location'],
        'time_placed': order['time_placed'].isoformat(),
        'time_delivered': None if order['time_delivered'] is None else order['time_delivered'].isoformat(),
    }, indent=4), 200, {
        'Content-Type': 'application/json;charset=UTF-8',        
    }
Example #15
0
def token():
    try:
        grant_type = request.form.get('grant_type')
        client_id = request.form.get('client_id')
        client_secret = request.form.get('client_secret')
    except KeyError:
        return json.dumps({'error': 'invalid_request'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8',        
        }

    try:
        client_id = int(client_id)
    except:
        client_id = None
    if client_id not in db.client or db.client[client_id]['secret'] != client_secret:
        return json.dumps({'error': 'invalid_client'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8',        
        }

    if grant_type == 'authorization_code':
        try:
            code = request.form.get('code')
        except KeyError:
            return json.dumps({'error': 'invalid_request'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',        
            }

        if not db.authorization_code(code=code) or db.authorization_code(code=code)[0]['expire_time'] < datetime.now():
            return json.dumps({'error': 'invalid_grant'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',        
            }

        user_id = db.authorization_code(code=code)[0]['user_id']

        db.authorization_code.delete(db.authorization_code(code=code))
        db.authorization_code.commit()
    elif grant_type == 'refresh_token':
        try:
            refresh_token = request.form.get('refresh_token')
        except KeyError:
            return json.dumps({'error': 'invalid_request'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',        
            }

        if not db.token(refresh=refresh_token):
            return json.dumps({'error': 'invalid_grant'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',        
            }

        user_id = db.token(refresh=refresh_token)[0]['user_id']

        db.token.delete(db.token(refresh=refresh_token))
        db.token.commit()
    else:
        return json.dumps({'error': 'unsupported_grant_type'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8',        
        }

    access_token = sha256(str(uuid4()).encode('UTF-8')).hexdigest()
    expire_time = datetime.now() + timedelta(hours=1)
    refresh_token = sha256(str(uuid4()).encode('UTF-8')).hexdigest()
    db.token.insert(user_id=user_id,
                    access=access_token,
                    expire_time=expire_time,
                    refresh=refresh_token)
    db.token.commit()

    return json.dumps({
        'access_token': access_token,
        'token_type': 'bearer',
        'expires_in': 3600,
        'refresh_token': refresh_token,
    }), 200, {
        'Content-Type': 'application/json;charset=UTF-8',        
        'Cache-Control': 'no-store',
        'Pragma': 'no-cache',
    }
Example #16
0
def token():
    try:
        grant_type = request.form.get('grant_type')
        client_id = request.form.get('client_id')
        client_secret = request.form.get('client_secret')
    except KeyError:
        return json.dumps({'error': 'invalid_request'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8',
        }

    try:
        client_id = int(client_id)
    except:
        client_id = None
    if client_id not in db.client or db.client[client_id][
            'secret'] != client_secret:
        print(client_id)
        print(client_secret)
        return json.dumps({'error': 'invalid_client'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8',
        }

    if grant_type == 'authorization_code':
        try:
            code = request.form.get('code')
        except KeyError:
            return json.dumps({'error': 'invalid_request'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',
            }

        if not db.authorization_code(code=code) or db.authorization_code(
                code=code)[0]['expire_time'] < datetime.now():
            return json.dumps({'error': 'invalid_grant'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',
            }

        user_id = db.authorization_code(code=code)[0]['user_id']

        db.authorization_code.delete(db.authorization_code(code=code))
        db.authorization_code.commit()
    elif grant_type == 'refresh_token':
        try:
            refresh_token = request.form.get('refresh_token')
        except KeyError:
            return json.dumps({'error': 'invalid_request'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',
            }

        if not db.token(refresh=refresh_token):
            return json.dumps({'error': 'invalid_grant'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8',
            }

        user_id = db.token(refresh=refresh_token)[0]['user_id']

        db.token.delete(db.token(refresh=refresh_token))
        db.token.commit()
    else:
        return json.dumps({'error': 'unsupported_grant_type'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8',
        }

    access_token = sha256(str(uuid4()).encode('UTF-8')).hexdigest()
    expire_time = datetime.now() + timedelta(hours=1)
    refresh_token = sha256(str(uuid4()).encode('UTF-8')).hexdigest()
    db.token.insert(user_id=user_id,
                    access=access_token,
                    expire_time=expire_time,
                    refresh=refresh_token)
    db.token.commit()

    return json.dumps({
        'access_token': access_token,
        'token_type': 'bearer',
        'expires_in': 3600,
        'refresh_token': refresh_token,
    }), 200, {
        'Content-Type': 'application/json;charset=UTF-8',
        'Cache-Control': 'no-store',
        'Pragma': 'no-cache',
    }