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']
Ejemplo 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)
Ejemplo 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
Ejemplo n.º 4
0
import os

from flask import Flask
from flask_restful import Api
from flask_jwt import JWT
from db import db

from security import authentication, identity
from resources.user import UserRegister
from resources.item import Item, Items
from resources.store import Store, StoreList

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL',
                                                       'sqlite:///data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'richard'
api = Api(app)

jwt = JWT(app, authentication, identity)

api.add_resource(Items, '/items')
api.add_resource(Item, '/item/<string:name>')
api.add_resource(UserRegister, '/register')
api.add_resource(StoreList, '/stores')
api.add_resource(Store, '/store/<string:name>')

if __name__ == '__main__':
    db.init_app(app)
    app.run(debug=True)
Ejemplo n.º 5
0
from flask_jwt import JWT
from flask_restful import Api

from security import authenticate, identification
from Resources.user import UserRegister
from Resources.item import ItemList, Item

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = "Madiov"
api = Api(app)


@app.before_first_request
def create_table():
    db.create_all()


jwt = JWT(app, authenticate, identification)  # /auth

api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')

if __name__ == "__main__":
    from db import db

    db.init_app(app)
    app.run()
Ejemplo n.º 6
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
Ejemplo n.º 7
0
from flask import Flask

from flask_restful import Api
from auth import authenticate, identity
from client import ModifyClient, GetClient, ClientList
from flask_jwt import JWT

restApp = Flask(__name__)
restApp.secret_key = "flaskRest"
api = Api(restApp)

jwt = JWT(restApp, authenticate, identity)  # /auth

# adding the resources to the api
api.add_resource(ModifyClient, '/client')
api.add_resource(GetClient, '/client/<int:id>')
api.add_resource(ClientList, '/clients')

if __name__ == '__main__':
    restApp.run(debug=True)
Ejemplo n.º 8
0
from flask import Flask
from flask_jwt import JWT
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

from .config import Config
from .mixins.database import IdModel

db = SQLAlchemy(model_class=IdModel)
migrate = Migrate(directory=Config.MIGRATIONS_DIR)
jwt = JWT()

from .models import *  # isort:skip
from .jwt_handlers import *  # isort:skip


def create_app() -> Flask:
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)

    return app
Ejemplo n.º 9
0
    def __str__(self):
        return "User(id='%s')" % self.id


def verify(username, password):
    if not (username and password):
        return False
    if USER_DATA.get(username) == password:
        return User(id=123)


def identity(payload):
    user_id = payload["identity"]
    return {"user_id": user_id}


jwt = JWT(app, verify, identity)


class PrivateResource(Resource):
    @jwt_required()
    def get(self):
        return {"meaning_of_life": 42}


api.add_resource(PrivateResource, "/private")

if __name__ == "__main__":
    app.run(debug=True)
Ejemplo n.º 10
0
        try:
            flask.abort(code)
        except HTTPException as e:
            # JSON API specs
            kwargs['errors'] = []
            kwargs['errors'].append({})
            kwargs['errors'][0]['detail'] = message
            kwargs['errors'][0]['status'] = str(code)
            kwargs['errors'][0]['title'] = str(e).split(':')[1].lstrip(' ')
            e.data = kwargs
            raise


cors = CORS(app, resources={r'/*': {'origins': app.config['ALLOW_ORIGIN']}})
db = SQLAlchemy(app,
                session_options={
                    'autoflush': False,
                    'autocommit': False,
                    "expire_on_commit": False
                })
api = ExceptionAwareApi(app,
                        doc='/doc/',
                        title='LXC Web Panel API documentation',
                        description='https://github.com/lxc-webpanel/lxc-rest')
nslxc = api.namespace('api/v1/lxc/', description='Operations related to LXC')
nslwp = api.namespace('api/v1/lwp/',
                      description='Operations related to LXC Web Panel')
jwt = JWT(app, authenticate)

from app import handlers, models, views, routes
Ejemplo n.º 11
0
Archivo: app.py Proyecto: gushiyu01/NLP
# 获取认证的回调函数,从 request 中得到登录凭证,返回凭证所代表的 用户实体
def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'),
                             password.encode('utf-8')):
        return user


# 通过 token 获得认证主体的回调函数
def identity(payload):
    user_id = payload['identity']
    return userid_table.get(user_id, None)


app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)  # 用 JWT 初始化应用


@app.route('/protected', methods=["GET", "POST"])  # 定义一个 endpoint
@jwt_required()  # 声明需要 token 才能访问
def protected():
    return '%s' % current_identity  # 验证通过返回 认证主体


if __name__ == '__main__':
    app.run()
Ejemplo n.º 12
0
def config_jwt(app):
    app.config['SECRET_KEY'] = 'super-secret'
    # global jwt?
    jwt = JWT(app, verify, identity)
Ejemplo n.º 13
0
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT

from items import Item, ItemList
from security import authenticate, identity
from user import UserRegister, Users

app = Flask(__name__)
app.secret_key = 'MarkoGeslo'
api = Api(app)

jwt = JWT(app, authenticate, identity)  # s tem dobimo nov endpoint /auth

api.add_resource(Item,
                 '/item/<string:name>')  # http://127.0.0.1:5000/item/omara
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')
api.add_resource(Users, '/users')

if __name__ == '__main__':  # ce smo v glavnem modulu, pozeni, sicer pa ne, ker smo v import knjiznici
    # python modulu, ki ga pozenemo, doloci flag __main__
    app.run(debug=True)  # p5000 je sicer default, lahko ni izpustili
Ejemplo n.º 14
0
from flask import Flask
from flask_jwt import JWT
from flask_restful import Api
from security import authenticate, identify

from user import UserRegister

# import item and itemList form item
from item import Item, ItemList

app = Flask(__name__)
# assihng app  to the api
api = Api(app)

app.secret_key = '54321'

# list that will hold the dictinaries

jwt = JWT(app, authenticate, identify)  # creates a new endpoint know us /auth
items = []

# http://127.0.0.1:5000/student/ian
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    app.run(port=5000, debug=True)
Ejemplo n.º 15
0
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT

from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from db import db

app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'Bapat'
api = Api(app)

jwt = JWT(app, authenticate, identity)  # for authentication of user

api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    db.init_app(app)
    app.run(port=5000, debug=True)
Ejemplo n.º 16
0
from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.store import Store, StoreList  # need for creating tables using db.create_all()

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = '#Flask$RESTful*'
api = Api(app)


@app.before_first_request
def create_tables():
    db.create_all()


jwt = JWT(app, authenticate, identity)  # localhost:5000/auth

api.add_resource(Item, '/item/<string:item_name>')
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')

api.add_resource(Store, '/store/<string:store_name>')
api.add_resource(StoreList, '/stores')

if __name__ == '__main__':
    from db import db  # avoid circular import. that's why importing here
    db.init_app(app)
    app.run(port=5000, debug=True)
Ejemplo n.º 17
0
from flask_jwt import JWT
from security import authenticate, idendity
from resources.user import UserRegister
from resources.playbook import Playbook, PlaybookList
from resources.adhoc_cmd import AdhocCmd
from db import db
# from item import Item, ItemList

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URL'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'dipesh'
api = Api(app)


@app.before_first_request
def create_table():
    db.create_all()


jwt = JWT(app, authenticate, idendity)  #auth

api.add_resource(Playbook, '/playbook/<string:name>')
api.add_resource(PlaybookList, '/playbooks')
api.add_resource(AdhocCmd, '/adhoc')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    db.init_app(app)
    app.run(port=5000, debug=True)
Ejemplo n.º 18
0
from db import db
from flask_cors import CORS

from resources import Predict

from security import authenticate, identity

app = Flask(__name__)

app.secret_key = "to the milky way"
app.config[
    'PROPAGATE_EXCEPTIONS'] = True  # To allow flask propagating exception even if debug is set to false on app
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
api = Api(app)
JWT(app, authenticate, identity)
cors = CORS(app, resources={r"/*": {"origins": "*"}})


@app.before_first_request
def create_tables():
    db.create_all()


"""
api.add_resource(StockData, "/stockData/<string:name>")
api.add_resource(UserRegister, "/userregister" )
"""
# prediction models
# date details should be in header
api.add_resource(Predict, "/predict")
Ejemplo n.º 19
0
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required
from security import authenticate, identity
import io
from PIL import Image
from datetime import datetime
import datetime
import time
from datetime import date

import matplotlib.pyplot as plt

app = Flask(__name__)
api = Api(app)
app.config['SECRET_KEY'] = 'somerandomstring'
jwt = JWT(app, authenticate,
          identity)  #jwt creates a new endpoint which is /auth


class AI(Resource):
    @jwt_required()
    def post(self):
        token = request.form.get('token')
        frm_id = request.form.get("frm_id")
        img = request.files.get('img')
        img = Image.open(img)
        open_cv_image = np.array(img)
        img = open_cv_image[:, :, ::-1].copy()
        today = date.today()
        filename = str(today.year) + str(today.month) + str(today.day) + str(
            time.time()) + '.png'
        cv2.imwrite("/ImageData/" + filename, img)
Ejemplo n.º 20
0
import os
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT

from security import auth, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.store import Store, StoreList

app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'jose'
api = Api(app)

jwt = JWT(app, auth, identity)

api.add_resource(Store, '/store/<string:name>')
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')
api.add_resource(StoreList, '/stores')

if __name__ == '__main__':
    db.init_app(app)
    app.run(debug=True)  # important to mention debug=True
Ejemplo n.º 21
0

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Headers',
                         'Content-Type, Authorization')
    return response


app.config.from_object(app_config[config_name])

from utils.security_user import SecurityUser

JWT.JWT_EXPIRATION_DELTA = datetime.timedelta(seconds=99999999)
app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(seconds=9999999)
jwt = JWT(app, SecurityUser.authenticate, SecurityUser.identity)

api.add_resource(SecurityUser, '/auth')

from resources.vendor_resource import VendorResource

api.add_resource(VendorResource, '/vendor')

from resources.branch_resource import BranchResource

api.add_resource(BranchResource, '/branch')

from resources.consumer_resource import ConsumerResource

api.add_resource(ConsumerResource, '/consumer')
Ejemplo n.º 22
0
## Reference Code - https://github.com/tecladocode/rest-api-sections/tree/master/section4
## Import Libraries
from flask import Flask
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required
from Proper_REST_API.security import authenticate, identity

## Create the flask application
app = Flask(__name__)  # '__main__'
app.secret_key = 'lala' ## If prod API, this would need to be a real key
api = Api(app)  ## Allow for easy resource addition with GET, POST, DELETE, etc.

## Return JWT token for auth later on
jwt = JWT(app, authentication_handler=authenticate, identity_handler=identity) #/auth

## Dummy list of dicts for items - Will setup a DB in a later project
items = []

## All resources must be classes and inherit from Resource class
##################### Example #####################
## Student Class / Resource
# class Student(Resource):
#     ## Resource that can only be access with a GET method
#     def get(self, name):
#         return {'student': name}

## Add student resource
# api.add_resource(Student, '/student/<string:name>') ## http://127.0.0.1:5000/student/JC
###################################################

## Item Class
Ejemplo n.º 23
0
import os
import re
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT
from security import authentication, identify
from resourses.User import UserRegister
from resourses.items import Item, ItemList
from resourses.stores import Stores, StoreList

app = Flask(__name__)
uri = os.getenv("DATABASE_URL")  # or other relevant config var
if uri.startswith("postgres://"):
    uri = uri.replace("postgres://", "postgresql://", 1)
app.config['SQLALCHEMY_DATABASE_URI'] = uri
# 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = "sadeghi"
jwt = JWT(app, authentication, identify)  # /auth
api = Api(app)

api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(Stores, '/store/<string:name>')
api.add_resource(StoreList, '/stores')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    app.run(port=5000, debug=True)
Ejemplo n.º 24
0
from flask_jwt import JWT
from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.store import Store, StoresList

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
    'DATABASE_URL', 'sqlite:///data.db'
)  #to mention data.db file to SQL alchemy, DATABASE_URL is gv value in hroku for postgress db and for same purpose we use import os
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'jose'
api = Api(app)

jwt = JWT(
    app, authenticate, identity
)  # JWT cretes new endpoint /auth(we sent username and password) these were sent to authenticate method by JWT

api.add_resource(Store,
                 '/store/<string:name>')  #http://127.0.0.1:5000/student/parag
api.add_resource(StoresList, '/stores')
api.add_resource(Item,
                 '/item/<string:name>')  #http://127.0.0.1:5000/student/parag
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)
Ejemplo n.º 25
0
"""Create and configure the app."""
from flask import Flask
from flask_jwt import JWT
from flask_migrate import Migrate
from flask_restful import Api

from .common.connection import db
from .config import app_config
from .model.user import User as UserModel
from .resource.hello import Helloworld
from .resource.tweet import Tweet
from .resource.user import User, UserList

migrate = Migrate()
jwt = JWT(None, UserModel.authenticate, UserModel.identity)


def create_app(config_name='development'):

    app = Flask(__name__)
    api = Api(app)
    app.config.from_object(app_config[config_name])
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)

    api.add_resource(Helloworld, '/')
    api.add_resource(User, '/user/<string:username>')
    api.add_resource(UserList, '/users')
    api.add_resource(Tweet, '/tweet/<string:username>')
    return app
Ejemplo n.º 26
0
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required
from security import authenticate, identity

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
app.debug = True
api = Api(app)

jwt = JWT(app, authenticate, identity)  # new endpoint: '/auth'

items = []


class Item(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('price',
                        type=float,
                        required=True,
                        help="This field cannot be left blank!")

    @jwt_required()
    def get(self, name):
        item = next(
            filter(lambda x: x['name'] == name, items), None
        )  # list(): need to use to cast the filter return, next(): gives the first item return by the filter
        return {'item': item}, 200 if item else 404  #HTTP error not found

    def post(self, name):
        if next(filter(lambda x: x['name'] == name, items), None):
Ejemplo n.º 27
0
import datetime

from security import authenticate, identity
from resources.user import UserRegister # work on importing the user UserRegister from user.py first 
from resources.item import Item, ItemList
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' # we can specify the type of database from sqlite to postgres and it should work out of the box
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # disable SQLALCHEMy sessions to make code run faster we use Flask SQL ALCHEMY tracker
app.secret_key = 'thereisawoman'
api = Api(app)

@app.before_first_request
def create_tables():
    db.create_all()
    
jwt = JWT(app, authenticate, identity) # JWT creates a new end point, that is /auth
# config JWT to expire within half an hour
app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(days=365) 


#items = []





api.add_resource(Item, '/item/<string:name>') # http://127.0.0.1:5000/birds/weidevogels
api.add_resource(ItemList, '/items') # http://127.0.0.1:5000/birds/
api.add_resource(UserRegister, '/register') # http://127.0.0.1:5000/register/

if __name__=='__main__':
Ejemplo n.º 28
0
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.store import Store, StoreList
from db import db

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'didier'
api = Api(app)


# create database
@app.before_first_request
def create_tables():
    db.create_all()


jwt = JWT(app, authenticate, identify)  # create endpoint: /auth

# im this section we conect APIs to a database.
api.add_resource(Store, '/store/<string:name>')
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(StoreList, '/stores')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    db.init_app(app)
    app.run(port=5000, debug=True)
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.store import Store, StoreList

app = Flask(__name__)

#app.config['DEBUG'] = True

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL',
                                                       'sqlite:///data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'loic'
api = Api(app)

jwt = JWT(app, authenticate, identity)  # /auth

api.add_resource(Store, '/store/<string:name>')
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(StoreList, '/stores')

api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)

    # if app.config['DEBUG']:
    #     @app.before_first_request
Ejemplo n.º 31
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):
Ejemplo n.º 32
0
    if not auth_header_value:
        return

    parts = auth_header_value.split()

    if parts[0].lower() != auth_header_prefix.lower():
        raise JWTError('Invalid JWT header', 'Unsupported authorization type')
    elif len(parts) == 1:
        raise JWTError('Invalid JWT header', 'Token missing')
    elif len(parts) > 2:
        raise JWTError('Invalid JWT header', 'Token contains spaces')

    return parts[1]


jwt = JWT(app, authenticate, identity)
jwt.request_handler(jwt_request_handler)


@app.route("/login", methods=["POST"])
def login():
    """
    User authenticate method.
    ---
    description: Authenticate user with supplied credentials.
    parameters:
      - name: username
        in: formData
        type: string
        required: true
      - name: password
Ejemplo n.º 33
0
# config JWT to expire within half an hour
app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=1800)
# config JWT auth key name to be 'email' instead of default 'username'
# app.config['JWT_AUTH_USERNAME_KEY'] = "email"

# To allow flask propagating exception even if debug is set to false on app
app.config['PROPAGATE_EXCEPTIONS'] = True

# Set up flask-uploads configs
app.config['UPLOADED_MENU_DEST'] = os.path.join('static', 'images', 'menu')
patch_request_class(app, 10 * 1024 * 1024)  # restrict max upload image size to 10MB
configure_uploads(app, MENU_IMAGE_SET)

# ================================== endpoints ======================================
jwt = JWT(app, authenticate, identity)  # set up '/auth'

api.add_resource(User, '/user')
api.add_resource(UserUpdate, '/user/password')
api.add_resource(UserByID, '/user/id/<int:userID>')

api.add_resource(Restaurant, '/restaurant')
api.add_resource(RestaurantByID, '/restaurant/id/<int:id>')

api.add_resource(Menu, '/menu')
api.add_resource(MenuByID, '/menu/id/<int:id>')
api.add_resource(MenuByRestaurant, '/menu/restaurant/<int:restaurantID>')

api.add_resource(MenuImage, '/image/menu/<int:menu_id>')

api.add_resource(EphemeralKey, '/transaction/ephemeral_key')
Ejemplo n.º 34
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 )
Ejemplo n.º 35
0
from flask_jwt import JWT

jwt = JWT(authentication_handler=lambda *args, **kwargs: None,
          identity_handler=lambda payload: payload['identity'])
Ejemplo n.º 36
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()
Ejemplo n.º 37
0
@app.before_first_request
def create_table():
    db.create_all()


app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'False'

# This code changes the default jwt `/auth` endpoint to /login
app.config['JWT_AUTH_URL_RULE'] = '/login'
# This code changes the expiration time of the access_key from 5mins (default) to 30mins
app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(seconds=1800)
# # config JWT auth key name to be 'email' instead of default 'username'
# app.config['JWT_AUTH_USERNAME_KEY'] = 'email'

# this create an instance '/auth' endpoint (nb changed it above) and the username and pword passes is checked in authenticate() then calls the identity to confirm the token
jwt = JWT(app, authenticate, identity_function)


@jwt.jwt_error_handler
def customized_error_handler(error):
    return jsonify({
        'message': error.description,
        'code': error.status_code
    }), error.status_code


api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(UserRegister, '/register')
api.add_resource(Store, '/store/<string:name>')
api.add_resource(StoreList, '/stores')
Ejemplo n.º 38
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)
Ejemplo n.º 39
0
# Aim3: Improving Error correction using filter functions.
# Aim4: Apply authentication and logging with Flask JWT.
#       Adding secret key and security.py
# Aim5: Adding reqparse from flask_restful and optimising
#       final code.

from flask import Flask, request
from flask_restful import Api, Resource, reqparse
from flask_jwt import JWT, jwt_required
from security import authenticate, identity

app = Flask(__name__)
app.secret_key = "qwerty"
api = Api(app)

jwt = JWT(app, authenticate, identity)  # creates a new end point /auth

stores = []


class Store(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument("noOfBooks",
                        type=int,
                        required=True,
                        help="This field cannot be left blank!")

    @jwt_required()  # means authenticate before using this method
    def get(self, name):
        # for store in stores:
        #   if store['name'] == name: