def register_extensions(app):
  from flask_webpack import Webpack
  webpack = Webpack()
  webpack.init_app(app)

  from security import authenticate, identity, jwt_error_handler, jwt_payload_callback
  from flask_jwt import JWT
  jwt = JWT(app, authentication_handler=authenticate, identity_handler=identity)
  jwt.jwt_error_callback = jwt_error_handler
  jwt.jwt_payload_callback = jwt_payload_callback

  from models import db
  db.init_app(app)

  print "app.debug %s" % app.debug
  print "app.config['SECRET_KEY'] %s" % app.config['SECRET_KEY']
Exemplo n.º 2
0
    def init_app(self, app):
        app.config['SECRET_KEY'] = 'super-secret'
        app.config['JWT_AUTH_URL_RULE'] = '/login'
        app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=30)

        # Register callbacks
        self.jwt = JWT(app, self.authenticate, self.identity)
        if not hasattr(app, 'extensions'):  # pragma: no cover
            app.extensions = {}

        app.extensions['auth'] = self
        global auth
        with app.app_context():
            app.register_blueprint(auth)
Exemplo n.º 3
0
def create_app(package_name, settings_override=None):
    app = Flask(package_name)
    app_root = os.path.dirname(os.path.abspath(__file__))
    app.config.from_pyfile(os.path.join(app_root, 'application.cfg'))
    if settings_override is not None:
        app.config.update(settings_override)

    db.init_app(app)
    bcrypt.init_app(app)
    jwt = JWT(app, authenticate, identity)
    jwt.auth_response_callback = auth_response_handler
    api = Api(app, catch_all_404s=True)

    # /auth endpoint is reserved by flask_jwt automatically
    api.add_resource(auth.Register, '/register')
    api.add_resource(auth.Logout, '/logout')
    api.add_resource(todo.TodoList, '/todos')
    api.add_resource(todo.Todo, '/todos/<int:todo_id>')

    if app.config.get('SWAGGER'):
        app = build_spec(app)

    return app
Exemplo n.º 4
0
        user_id=new_user.user_id, location_string="Timbuktu", active=True, date_time=datetime.datetime.now()
    )
    models.db.session.add(new_location)
    new_location2 = models.Location(
        user_id=new_user.user_id,
        location_string="Stanford",
        active=True,
        date_time=datetime.datetime.now() - datetime.timedelta(500),
    )
    models.db.session.add(new_location2)
    new_location3 = models.Location(
        user_id=new_user.user_id,
        location_string="Secret Location",
        active=False,
        date_time=datetime.datetime.now() - datetime.timedelta(50),
    )
    models.db.session.add(new_location3)
    models.db.session.commit()
    print(new_user.user_id)


models.db.create_all()

jwt = JWT(app=None, authentication_handler=authenticate, identity_handler=identity)
jwt.app = app
jwt.auth_request_callback = jwt_handlers.auth_request_handler
jwt.jwt_encode_callback = jwt_handlers.encode_handler
jwt.jwt_payload_callback = jwt_handlers.payload_handler
jwt.auth_response_callback = jwt_handlers.auth_response_handler
jwt.init_app(jwt.app)
Exemplo n.º 5
0
    CORS(app)
    app.config.from_object(config)
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    db.init_app(app)
    with app.app_context():
        db.create_all()
    app.app_context().push()
    return app


app = create_json_app(config.Config)
# Set up security -------------------------------
security = Security(app, user_datastore)

jwt = JWT(app, authenticate, jwt_identity)
jwt.jwt_payload_handler(jwt_payload_handler)

# Endpoints -------------------------------------
@app.route("/")
@jwt_required()
def index():
    return "Hello World!"


@app.route("/signup", methods=["POST"])
def signup():
    # input validation here
    signup_request = request.get_json()
    # print "Signup info is: %s" % signup_request
    if validate_signup(signup_request):
Exemplo n.º 6
0
      tok = sts.get_session_token(DurationSeconds=app.config.get('AWS_STS_EXPIRE_DELTA_SECONDS') or 900)

      return { 
         'credentials': {
            'aws_access_key_id': tok['Credentials']['AccessKeyId'], 
            'aws_secret_access_key': tok['Credentials']['SecretAccessKey'],
            'aws_session_token': tok['Credentials']['SessionToken']
         },
         'expiration': str(tok['Credentials']['Expiration'])
      }

@api.route('/apps')
class Applications(Resource):
   @jwt_required()
   def get(self):
      """Handles a GET request for the applications resource"""

      # apps at this point are in the current_identity object. technically a user
      # could unwrap it themselves but we prefer they don't depend on the jwt payload to get
      # this information just in case the implementation changes
      return current_identity.apps

jwt = JWT(app, jwt_authenticate, jwt_identity)
jwt.jwt_payload_callback = jwt_payload

if __name__ == '__main__':
   app.run()

def start():
   app.run()
Exemplo n.º 7
0
def init_auth(app):
    app.config['JWT_AUTH_URL_RULE'] = None
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7)
    app.config['JWT_AUTH_HEADER_PREFIX'] = 'JWT'
    jwt = JWT(app, None, identify)
    jwt.jwt_payload_handler(payload_handler)
Exemplo n.º 8
0
    verify_claims = app.config['JWT_VERIFY_CLAIMS']
    required_claims = app.config['JWT_REQUIRED_CLAIMS']

    options = {
        'verify_' + claim: True
        for claim in verify_claims
    }

    options.update({
        'require_' + claim: True
        for claim in required_claims
    })

    return jwt.decode(token, secret, options=options, algorithms=[algorithm], leeway=leeway , audience =  app.config['RESOURCE_ID'] )

_jwt = JWT(app , authenticate , identity )
_jwt.jwt_decode_callback = _jwt_decode_callback


def has_client_authoritie(authority):
    """View decorator that requires a valid JWT token to be present in the request

    :param realm: an optional realm
    """
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            authorities = current_identity['user_client_authorities']
            print( authority )
            if authority in authorities:
              print( authorities )
Exemplo n.º 9
0
class Auth(object):

    def __init__(self, app=None):
        self.app = app
        if app:
            self.init_app(app)

    def init_app(self, app):
        app.config['SECRET_KEY'] = 'super-secret'
        app.config['JWT_AUTH_URL_RULE'] = '/login'
        app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=30)

        # Register callbacks
        self.jwt = JWT(app, self.authenticate, self.identity)
        if not hasattr(app, 'extensions'):  # pragma: no cover
            app.extensions = {}

        app.extensions['auth'] = self
        global auth
        with app.app_context():
            app.register_blueprint(auth)

    def create_user(self, username, password):
        # Hash password
        conn = rethink_conn.conn()
        hashed_pass =  bcrypt.hashpw(password, bcrypt.gensalt(8))

        user = {}
        user['email'] = username
        user['password'] = hashed_pass

        created = r.table("users").insert(user).run(conn)

        assert created['inserted'] == 1
        # Generate token
        user_id = created['generated_keys'][0]
        user = User(user_id, username, hashed_pass)
        return self.jwt.jwt_encode_callback(user)

    def login(self, username, password):
        user = self.authenticate(username, password)
        return self.jwt.jwt_encode_callback(user)

    def authenticate(self, username, password):
        conn = rethink_conn.conn()
        username, password = username.encode('utf-8'), password.encode('utf-8')
        cursor = r.table("users").filter(r.row["email"] == username).run(conn)
        try:
            user = cursor.next()
            if not user:
                return None
            email = user['email']
            hashed_pass = user['password']

            if username == email and hashed_pass == bcrypt.hashpw(password.encode('utf-8'), hashed_pass.encode('utf-8')):
                # return User(id=user['id'], username=email)
                return User(user['id'], email, hashed_pass)
        except r.ReqlCursorEmpty:
            return None

    def identity(self, payload):
        conn = rethink_conn.conn()
        print payload
        cursor = r.table("users").filter(r.row["id"] == payload['identity']).run(conn)
        try:
            user = cursor.next()
            # return User(id=user['id'], username=user['email'])
            print user
            return User(user['id'], user['email'], user["password"])
        except r.ReqlCursorEmpty:
            return None