예제 #1
0
def register():
    """ Registration process that creates a user
    """
    try:
        req_json = request.get_json()
        # validate registration record
        if not validate_registration_record(
                registration_code=req_json['registrationCode'],
                email=req_json['email']):
            msg = "Registration code and email do not align"
            raise InvalidUsage(msg)
        # validate fields
        validate_user_create_fields(req_json)
        # create user
        create_user(req_json)
        session.commit()
    except InvalidUsage as iux:
        session.rollback()
        raise iux
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        session.rollback()
        raise InvalidUsage(str(exc), status_code=400)
    finally:
        session.close()
    json_dict = {"success": True}
    return jsonify(json_dict)
예제 #2
0
def registration_request():
    """ First step in registration is requesting a registration key be
    emailed to a user, this verifies the email doesn't have an outstanding
    reg key and sends it back to the front end
    """
    try:
        request_json = request.get_json()
        email = request_json['email']
        if not validate_email(email):
            msg = "invalid email"
            raise InvalidUsage(msg, status_code=400)
        registration_code = create_registration_record(email)
        session.commit()
    except InvalidUsage as iux:
        session.rollback()
        raise iux
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        session.rollback()
        raise InvalidUsage(str(exc), status_code=400)
    finally:
        session.close()

    if FLASK_ENV in ("development", "testing"):
        json_dict = {"success": True, "registration_code": registration_code}
    else:
        json_dict = {"success": True}
        send_email(registration_code=registration_code, email=email)
    return jsonify(json_dict)
예제 #3
0
def get_user_details(user_id):
    """
    simple endpoint to return a json object
    with user basics
    """
    logging.info("user_id")
    logging.info(user_id)
    json_dict = {}
    try:
        user = session.query(User).get(user_id)
        if user is None:
            # we should never get here because of the authorize decorator
            msg = "user not found"
            raise InvalidUsage(msg, status_code=404)
        json_dict = object_as_dict(user)
        json_dict.pop('admin')
        json_dict.pop('password')
        json_dict.pop('registered_on')
        json_dict.pop('registration_request_id')
    except InvalidUsage as iux:
        raise iux
    except Exception as exc:
        msg = str(exc)
        raise InvalidUsage(msg, status_code=400)
    return jsonify(json_dict)
예제 #4
0
def registration_request():
    """ First step in registration is requesting a registration key be
    emailed to a user, this verifies the email doesn't have an outstanding
    reg key and sends it back to the front end
    """
    json_dict = {}
    try:
        request_json = request.get_json()
        logging.info(request_json)
        email = request_json['email']
        optin = request_json['optin']
        if not validate_email(email.lower()):
            msg = "invalid email"
            raise InvalidUsage(msg, status_code=400)
        json_dict['registration_code'] = uuid.uuid4().hex
        if FLASK_ENV not in ("development"):  #pylint: disable=superfluous-parens
            send_reg_code_email(
                registration_code=json_dict['registration_code'],
                email=email.lower())
        create_registration_record(email.lower(), optin,
                                   json_dict['registration_code'])
        session.commit()
    except InvalidUsage as iux:
        session.rollback()
        raise iux
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        session.rollback()
        raise InvalidUsage(str(exc), status_code=400)
    finally:
        session.close()

    return jsonify(json_dict)
예제 #5
0
def login():
    """ Basic login, sets session for now, will change to JWT later
    """
    try:
        req_json = request.get_json()
        email = req_json['email'].lower()
        user = session.query(User).filter(
            func.lower(User.email) == email).first()
        if not user.is_authenticated(req_json['password']):
            msg = "Invalid password"
            raise InvalidUsage(msg, status_code=401)
        jwt = encode_auth_token(user.id)
    except InvalidUsage as iux:
        raise iux
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        raise InvalidUsage(str(exc), status_code=400)
    #logging.info(str(jwt))
    # This looks like noise, but otherwise we get the b'' wrappers
    # around our jwt
    tmp = base64.urlsafe_b64encode(jwt)
    jtw = tmp.decode('utf-8')
    json_dict = {"success": True, "jwt": jtw}
    return jsonify(json_dict)
예제 #6
0
def register():
    """ Registration process that creates a user
    """
    try:
        req_json = request.get_json()
        email = req_json['email'].lower()
        # validate registration record
        if not validate_registration_record(
                registration_code=req_json['registrationCode'], email=email):
            msg = "Registration code and email do not align"
            raise InvalidUsage(msg)
        # validate fields
        validate_user_create_fields(req_json)
        # create user
        user = create_user(req_json)
        session.commit()
        jtw = encode_auth_token(user.id)
        tmp = base64.urlsafe_b64encode(jtw)
        jwt = tmp.decode('utf-8')

        if FLASK_ENV not in ("development"):  #pylint: disable=superfluous-parens
            send_join_successful_email(email)
    except InvalidUsage as iux:
        session.rollback()
        raise iux
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        session.rollback()
        raise InvalidUsage(str(exc), status_code=400)
    finally:
        session.close()
    json_dict = {"success": True, 'jwt': jwt}
    return jsonify(json_dict)
예제 #7
0
def token_verification(token):
    """ Endpoint for the Front end to verify a token a client is holding is
    still valid
    """
    try:
        decode_auth_token(token)
    except ExpiredSignatureError:
        msg = "expired token"
        raise InvalidUsage(msg, status_code=401)
    except InvalidTokenError:
        msg = "invalid token"
        raise InvalidUsage(msg, status_code=403)
    json_dict = {"tokenValid": True}
    return jsonify(json_dict)
예제 #8
0
    def decorated_function(*args, **kws):
        if not 'Authorization' in request.headers:
            msg = 'no token'
            raise InvalidUsage(msg, status_code=401)
        user = None
        token = request.headers['Authorization'][7:]
        token = base64.urlsafe_b64decode(token)

        try:
            user = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])['sub']
        except Exception as exc:
            logging.info("token exception %s", str(exc))
            msg = 'invalid token'
            raise InvalidUsage(msg, status_code=401)

        return fff(user, *args, **kws)
예제 #9
0
def registration_removal(registration_id):
    """ Invalidate a registration key
    """
    try:
        if invalidate_registration_record_by_code(registration_id):
            json_dict = {"burned": True}
        else:
            msg = "record not found"
            raise InvalidUsage(msg, status_code=404)
        session.commit()
    except InvalidUsage as iux:
        raise iux
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        raise InvalidUsage(str(exc), status_code=400)
    return jsonify(json_dict)
예제 #10
0
def validate_user_create_fields(params):
    """ Method to check for appropriate fields being present
    """
    registration_args = ['email', 'fullName', 'password', 'location']
    for key in registration_args:
        if key not in params.keys():
            details = "we don't have %s key" % key
            logging.info(details)
            raise InvalidUsage(details)
예제 #11
0
def lookup_by_account_name(account_name):
    """ Do the actual lookup, return the snapshot
    """
    try:
        account = session.query(SnapshotBalance).filter(
            func.lower(SnapshotBalance.account_name) ==
            account_name.lower()).first()
    except IntegrityError as pie:
        msg = str(pie)
        raise InvalidUsage(msg, status_code=400)
    return account
예제 #12
0
def registration_validation(registration_id):
    """ Validate we have a legit registration key
    """
    json_dict = {"recordValid": False}
    try:
        json_dict['recordValid'] = is_valid_registration_record(
            registration_id)
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        raise InvalidUsage(str(exc), status_code=400)
    return jsonify(json_dict)
예제 #13
0
def update_password(user_id):
    """
    Allow a user to change their password.
    """
    try:
        req_json = request.get_json()
        password = req_json["password"]
        if not bool(re.match(PASSWORD_REGEXP, password)):
            msg = 'Password does not meet the requirements.'
            raise InvalidUsage(msg, status_code=400)
        user = session.query(User).get(user_id)
        user.password = BCRYPT.generate_password_hash(password).decode('utf-8')
        session.add(user)
        session.commit()
    except InvalidUsage as iux:
        raise iux
    except Exception as exc:
        msg = str(exc)
        raise InvalidUsage(msg, status_code=400)
    json_dict = {'success': True}
    return jsonify(json_dict)
예제 #14
0
def lookup_snapshot(account_name):
    """
    this looks up agains the snap shot
    """
    balance = lookup_by_account_name(account_name)
    if balance is None:
        msg = "No account found with that name"
        raise InvalidUsage(msg, status_code=404)
    else:
        total = balance.total
    json_dict = {"total": total}

    return jsonify(json_dict)
예제 #15
0
def create_user(params):
    """ User creator from params,
        assumes valid registration code
    """
    try:
        user = User(params['email'], params['password'])
        user.location = params['location']
        registration_record = session.query(RegistrationRequest).filter_by(
            registration_code=params['registrationCode']).first()
        user.registration_request = registration_record
        user.registered_on = datetime.now()
        user.full_name = params["fullName"]
        session.add(user)
    except IntegrityError as pic:
        logging.info(pic)
        msg = "Invalid parameters"
        session.rollback()
        raise InvalidUsage(msg, status_code=400)
    except Exception as exc:
        logging.info(type(exc))
        logging.info(str(exc))
        raise InvalidUsage(str(exc), status_code=400)
    return user
예제 #16
0
def create_registration_record(email):
    """ Method to create a registration record
    """
    try:
        registration_code = uuid.uuid4().hex
        reg_req = RegistrationRequest(email=email,
                                      registration_code=registration_code,
                                      valid=True)
        session.add(reg_req)
    except IntegrityError as pic:
        logging.info(pic)
        msg = "user already has a code"
        session.rollback()
        raise InvalidUsage(msg, status_code=400)

    return registration_code
예제 #17
0
def invalidate_registration_record_by_code(registration_code,
                                           invalidation_type='voided'):
    """ Method to find and invalidate registration record
    """
    try:
        registration_record = session.query(RegistrationRequest).filter_by(
            registration_code=registration_code).first()
        if registration_record is None:
            return False
        registration_record.valid = False
        if invalidation_type == 'voided':
            registration_record.voided_on = datetime.now()
        elif invalidation_type == 'spent':
            registration_record.spent_on = datetime.now()
        else:
            raise Exception('improper invalidation')
    except IntegrityError as pic:
        logging.info(pic)
        msg = "invalid code"
        session.rollback()
        raise InvalidUsage(msg, status_code=400)
    except Exception as exc:
        raise exc
    return True
예제 #18
0
def error_please():
    """
    Prove the routes are working
    """
    msg = "record not found"
    raise InvalidUsage(msg, status_code=400)