예제 #1
0
    def setUp(self):
        app = Flask(__name__)
        app.config['SECRET_KEY'] = 'my secret'

        basic_auth = HTTPBasicAuth()
        token_auth = HTTPTokenAuth('MyToken')
        multi_auth = MultiAuth(basic_auth, token_auth)

        @basic_auth.verify_password
        def verify_password(username, password):
            return username == 'john' and password == 'hello'

        @token_auth.verify_token
        def verify_token(token):
            return token == 'this-is-the-token!'

        @token_auth.error_handler
        def error_handler():
            return 'error', 401, {'WWW-Authenticate': 'MyToken realm="Foo"'}

        @app.route('/')
        def index():
            return 'index'

        @app.route('/protected')
        @multi_auth.login_required
        def auth_route():
            return 'access granted'

        self.app = app
        self.client = app.test_client()
예제 #2
0
    def setUp(self):
        app = Flask(__name__)
        app.config['SECRET_KEY'] = 'my secret'

        basic_auth = HTTPBasicAuth()
        token_auth = HTTPTokenAuth('MyToken')
        custom_token_auth = HTTPTokenAuth(header='X-Token')
        multi_auth = MultiAuth(basic_auth, token_auth, custom_token_auth)

        @basic_auth.verify_password
        def verify_password(username, password):
            if username == 'john' and password == 'hello':
                return 'john'

        @basic_auth.get_user_roles
        def get_basic_role(username):
            if username == 'john':
                return ['foo', 'bar']

        @token_auth.verify_token
        def verify_token(token):
            return token == 'this-is-the-token!'

        @token_auth.get_user_roles
        def get_token_role(auth):
            if auth['token'] == 'this-is-the-token!':
                return 'foo'
            return

        @token_auth.error_handler
        def error_handler():
            return 'error', 401, {'WWW-Authenticate': 'MyToken realm="Foo"'}

        @custom_token_auth.verify_token
        def verify_custom_token(token):
            return token == 'this-is-the-custom-token!'

        @custom_token_auth.get_user_roles
        def get_custom_token_role(auth):
            if auth['token'] == 'this-is-the-custom-token!':
                return 'foo'
            return

        @app.route('/')
        def index():
            return 'index'

        @app.route('/protected')
        @multi_auth.login_required
        def auth_route():
            return 'access granted:' + str(multi_auth.current_user())

        @app.route('/protected-with-role')
        @multi_auth.login_required(role='foo')
        def auth_role_route():
            return 'role access granted'

        self.app = app
        self.client = app.test_client()
예제 #3
0
class Auth:
    def __init__(self):
        """Creates access control class for authentication and authorization."""
        self._basic_auth = HTTPBasicAuth()
        self._token_auth = HTTPTokenAuth()
        self._auth = MultiAuth(self._basic_auth, self._token_auth)
        self._resources = {}

    def error_handler(self, f: typing.Callable) -> typing.NoReturn:
        """Set error handler for Authentication Errors.

        :param f: error handler.
        :return: NoReturn
        """
        self._token_auth.error_handler(f)
        self._basic_auth.error_handler(f)

    def verify_password(self, f: typing.Callable) -> typing.Any:
        """ Verifies basic password.

        :param f: function defining verification process.
        :return: Any
        """
        return self._basic_auth.verify_password(f)

    def verify_token(self, f: typing.Callable) -> typing.Any:
        """ Verifies token.

        :param f: function defining verification process.
        :return: Any
        """
        return self._token_auth.verify_token(f)

    def login_required(self,
                       f: typing.Callable = None,
                       role: typing.Text = None) -> typing.Any:
        """ Identifies as login required for provided function {f}.

        :param f: input function.
        :param role: user role
        :return: func
        """
        return self._auth.login_required(f, role)
예제 #4
0
 def __init__(self):
     """Creates access control class for authentication and authorization."""
     self._basic_auth = HTTPBasicAuth()
     self._token_auth = HTTPTokenAuth()
     self._auth = MultiAuth(self._basic_auth, self._token_auth)
     self._resources = {}
예제 #5
0
from flask import g
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
import models

# itsdangerous handles all of the token work i.e json web tokens
# httpbasicauth makes it that you do not need javascript for any of this
basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Token')
auth = MultiAuth(token_auth, basic_auth) # looks at the first thing first

@basic_auth.verify_password
def verify_password(email_or_username, password):
    try:
        user = models.User.get(
            (models.User.email==email_or_username) |
            (models.User.username**email_or_username)
        )
        if not user.verify_password(password):
            return False
    except models.User.DoesNotExist:
        return False
    else:
        g.user = user
        return True

@token_auth.verify_token
def verify_token(token):
    user = models.User.verify_auth_token(token)
    if user is not None:
        g.user = user
        return True
예제 #6
0
log.logger.info('info')
log.logger.warning('警告')
log.logger.error('报错')
log.logger.critical('严重')
   

app = Flask(__name__)
api = Api(app)
#import config
#app.config.from_object(config)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Bearer')
multi_auth = MultiAuth(basic_auth, token_auth)

parser = reqparse.RequestParser()
parser.add_argument('task')
parser.add_argument('auth_key', type=str)
parser.add_argument('auth_value', type=str)

tokens = {}

def create_token(api_user):
    '''
    生成token
    :param api_user:用户id
    :return: token
    '''
    
예제 #7
0
"""

import time

import random
from flask import Flask, request
from flask_httpauth import HTTPBasicAuth, HTTPDigestAuth, MultiAuth
from gevent.pywsgi import WSGIServer

from tests.config import TEST_PORT, USER

app = Flask(__name__)
basic_auth = HTTPBasicAuth()
digest_auth = HTTPDigestAuth()

auth = MultiAuth(digest_auth, basic_auth)
app.config['SECRET_KEY'] = 'secret'


@basic_auth.get_password
def get_pw(username):
    if username in USER['user']:
        return USER['password']
    else:
        from tests import test_benchs
        test_benchs.local_server_exception.append('No auth')
        return None


@digest_auth.get_password
def get_pw(username):
예제 #8
0
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
from flask_migrate import Migrate
from flask_sqlalchemy.model import BindMetaMixin, Model
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base


class NoNameMeta(BindMetaMixin, DeclarativeMeta):
    pass


# Disable Table Name Generation
db = SQLAlchemy(model_class=declarative_base(
    cls=Model, metaclass=NoNameMeta, name='Model'))
basic_auth = HTTPBasicAuth()
auth = HTTPTokenAuth('Bearer')
multi_auth = MultiAuth(basic_auth, auth)
migrate = Migrate()
예제 #9
0
#!/usr/bin/env python3

from flask import Flask
from flask import g
from flask_httpauth import HTTPBasicAuth
from flask_httpauth import HTTPDigestAuth
from flask_httpauth import MultiAuth
from werkzeug.security import generate_password_hash, check_password_hash

APP = Flask(__name__)
APP.config['SECRET_KEY'] = 'secret'

BASIC_AUTH = HTTPBasicAuth()
DIGEST_AUTH = HTTPDigestAuth()
MULTI_AUTH = MultiAuth(DIGEST_AUTH, BASIC_AUTH)


@BASIC_AUTH.verify_password
def verify_password(username, password):
    g.user = username
    return username == 'username' and check_password_hash(
        generate_password_hash('password'), password)


@DIGEST_AUTH.get_password
def get_pw(username):
    if username == 'username':
        g.user = username
        return 'password'

    return None
예제 #10
0
import os
import random
import requests
import smtplib
import string
import sys
import timestring
import zerorpc

# custom files - rsappapi.py uses these files
import constants
import stripe_process

auth = HTTPBasicAuth()
tokenauth = HTTPTokenAuth("Bearer")
multiauth = MultiAuth(auth, tokenauth)
app = Flask(__name__)
CORS(app)
# Lines above are copied from the file (from rsappapi.py
#  for the example below) that has the function to test.

# https://docs.python.org/2/library/unittest.html - for more info
import unittest

# RSAPPAPI_IMPORTS - import function to test.
from rsappapiFunc import get_scan_alerts
# RSAPPAPI_IMPORTS

OK200 = "[200 OK]"
NF404 = "[404 Not Found]"
LK423 = "[423 Locked]"
from flask import g

from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth

import models

bask_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Token')
auth = MultiAuth(token_auth, bask_auth)


@bask_auth.verify_password
def verify_password(email_or_username, password):
    try:
        user = models.User.get((models.User.email == email_or_username)
                               | (models.User.username == email_or_username))
        if not user.verify_password(password):
            return False
    except models.User.DoesNotExist:
        return False
    else:
        g.user = user
        return True


@token_auth.verify_token
def verify_token(token):
    user = models.User.verify_auth_token(token)
    if user is not None:
        g.user = user
        return True
예제 #12
0
from .exceptions import BackendError, ProcessingError
from .version import __version__  # noqa
from .views import MEDIA_TYPE_TAXII_V20

# Console Handler for medallion messages
ch = logging.StreamHandler()
ch.setFormatter(default_request_formatter())

# Module-level logger
log = logging.getLogger(__name__)
log.addHandler(ch)

jwt_auth = HTTPTokenAuth(scheme='JWT')
basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Token')
auth = MultiAuth(None)


def set_multi_auth_config(main_auth, *additional_auth):
    type_to_app = {'jwt': jwt_auth, 'api_key': token_auth, 'basic': basic_auth}

    auth.main_auth = type_to_app[main_auth]
    additional_auth = [a for a in additional_auth if a != main_auth]
    auth.additional_auth = tuple(
        type_to_app[a] for a in tuple(OrderedDict.fromkeys(additional_auth)))


def set_auth_config(flask_application_instance, config_info):
    with flask_application_instance.app_context():
        log.debug("Registering medallion users configuration into {}".format(
            current_app))
예제 #13
0
from flask import g

from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth

import models

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Token')
auth = MultiAuth(token_auth, basic_auth)  # Tries token, then basic


@basic_auth.verify_password
def verify_password(email_or_username, password):
    try:
        user = models.User.get((models.User.email == email_or_username)
                               | (models.User.username == email_or_username))
        if not user.verify_password(password):
            return False
    except models.User.DoesNotExist:
        return False
    else:
        g.user = user
        return True


@token_auth.verify_token
def verify_token(token):
    user = models.User.verify_auth_token(token)
    if user is not None:
        g.user = user
        return True
예제 #14
0
from flask import g, jsonify
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
from ..models import User
from . import api
from .errors import unauthorized, forbidden

basicAuth = HTTPBasicAuth()
tokenAuth = HTTPTokenAuth(scheme='Bearer')
multiAuth = MultiAuth(basicAuth, tokenAuth)


@basicAuth.verify_password
def verify_password(email, pin):
    if email != '':
        user = User.query.filter_by(email=email.lower()).first()
        if not user:
            return False
        g.current_user = user
        g.token_used = False
        return user.verify_password(pin)
    if pin == '':
        return False
    for user in User.query.all():
        if user.verify_pin(pin):
            temp = user
            g.current_user = temp
            g.token_used = False
            return True
    return False

예제 #15
0
    resources={
        r"/api/*": {
            "origins": "*"
        },
    },
)

# from .model.UAC import UserMod, URoleMod, UGroupMod, roles_users, gps_users

# Flask-Security
# user_datastore = SQLAlchemyUserDatastore(db, UserMod, URoleMod)
# security = Security().init_app(app, user_datastore, register_blueprint=False)

baseauth = HTTPBasicAuth()
tokenauth = HTTPTokenAuth(scheme='Bearer')
auth = MultiAuth(baseauth, tokenauth)


@app.route('/')
def index():
    return render_template('index.html')


d = rt_conf.copy()
if d['APIService'] is not None:
    if d['APIService']['SQL']:
        del d['APIService']['SQL']

    if str(d['APIService']['ServerConfig']['host']) == '0.0.0.0' or \
      str(d['APIService']['ServerConfig']['host']) == '127.0.0.1' or\
      str(d['APIService']['ServerConfig']['host']) == 'host':
예제 #16
0
Authentication functions for the iffSamples RESTful API.
"""

import flask

from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth

from sampledb.logic.authentication import login, login_via_api_token
from sampledb.logic.object_permissions import Permissions
from sampledb.utils import object_permissions_required as object_permissions_required_generic

__author__ = 'Florian Rhiem <*****@*****.**>'

http_basic_auth = HTTPBasicAuth()
http_token_auth = HTTPTokenAuth(scheme='Bearer')
multi_auth = MultiAuth(http_basic_auth, http_token_auth)


@http_token_auth.verify_token
def verify_token(api_token):
    if not api_token:
        return None
    flask.g.user = login_via_api_token(api_token)
    return flask.g.user


@http_basic_auth.verify_password
def verify_password(username, password):
    if not username:
        return None
    flask.g.user = login(username, password)
예제 #17
0
class Auth():
    """
    Authorization via basic auth or bearer token. Call methods as decorators.

    :var     basic_auth: Authorization via basic auth
    :vartype basic_auth: flask_httpauth.HTTPBasicAuth
    :var     token_auth: Authorization via bearer token
    :vartype token_auth: flask_httpauth.HTTPTokenAuth
    :var     multi_auth: Authorization via basic auth or bearer token
    :vartype multi_auth: flask_httpauth.MultiAuth
    """
    basic_auth = HTTPBasicAuth()
    token_auth = HTTPTokenAuth('Bearer')
    multi_auth = MultiAuth(basic_auth, token_auth)

    @staticmethod
    @basic_auth.verify_password
    def verify_password(username, password):
        """
        Verify user password in basic auth. Called this method in use of
        @basic_auth.login_required or @multi_auth.login_required decorators

        :param username: User login
        :type  username: str
        :param password: User password
        :type  password: str
        :return: True if the password matched, False otherwise
        :rtype:  bool
        """
        user = User.query.filter_by(username=username).first()
        if not user or not user.verify_password(password):
            return False
        # Insert authorized user in Flask g object
        g.user = user
        return True

    @staticmethod
    @token_auth.verify_token
    def verify_token(token):
        """
        Verify user password in bearer token auth. Called this method in use of
        @token_auth.login_required or @multi_auth.login_required decorators

        :param token: Bearer token
        :type  token: str
        :return: True if the token matched, False otherwise
        :rtype:  bool
        """
        user = User.verify_auth_token(token)
        if not user:
            return False
        # Insert authorized user in Flask g object
        g.user = user
        return True

    @staticmethod
    @token_auth.error_handler
    @basic_auth.error_handler
    def unauthorized():
        """
        Return error JSON in 401 response if authorization is failed
        """
        abort(401, message="Unauthorized access")
예제 #18
0
            insert('loginhistory', {
                'username': username,
                'createdate': createdate
            })

            return True
        except Exception as e:
            return str(e)
    except Exception as e:
        return str(e)


# 基本认证
auth = HTTPBasicAuth()
authtoken = HTTPTokenAuth()
authmulti = MultiAuth(auth, authtoken)


@auth.verify_password
def verify_pw(username, pwd):
    haveauser = findeuser("users", {'username': username}, 'username', 'pwd')
    if haveauser[-1]['len'] != 0:
        if verify_password(pwd, haveauser[0]['pwd']):
            return True
    return None


@authtoken.verify_token
def verify_token(token):
    if userverify_token(token):
        logined = findeuser('loginedtoken', {'token': token}, 'username')
예제 #19
0
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
from flask_restful import Resource, Api
from flask_cors import CORS
import sqlalchemy
from itsdangerous import TimedJSONWebSignatureSerializer as JSONSigSerializer
from werkzeug.security import generate_password_hash, check_password_hash

db = None  # call initialize() to fill these up
serializer = None  # this one is used for the token auth


# Set up the authentication (see https://flask-httpauth.readthedocs.io/).

auth_basic = HTTPBasicAuth()
auth_token = HTTPTokenAuth('Bearer')
auth = MultiAuth(auth_basic, auth_token)

@auth_basic.verify_password
def verify_password(usernameOrEmail, password):
    res = dbget('id,password', 'users where username=? or email=?',
        (usernameOrEmail, usernameOrEmail))
    if len(res) == 1:
        g.user_id = res[0]['id']
        return check_password_hash(res[0]['password'], password)
    else:
        return False

@auth_token.verify_token
def verify_token(token):
    try:
        g.user_id = serializer.loads(token)
from flask import g
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth

import models

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Token')
auth = MultiAuth(token_auth,
                 basic_auth)  # try token_auth first, and then try basic_auth


@basic_auth.verify_password
def verify_password(email_or_username, password):
    try:
        user = models.User.get((models.User.email == email_or_username)
                               | (models.User.username == email_or_username))
        if not user.verify_password(password):
            return False
    except models.User.DoesNotExist:
        return False
    else:
        g.user = user
        return True


@token_auth.verify_token
def verify_token(token):
    user = models.User.verify_auth_token(token)
    if user is not None:
        g.user = user
        return True
예제 #21
0
from flask import g

from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth

import models

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Token')
auth = MultiAuth(token_auth, basic_auth)


@basic_auth.verify_password
def verify_password(username_or_token, password):
    user = models.User.verify_auth_token(username_or_token)
    if not user:
        user = models.User.get((models.User.email == username_or_token)
                               | (models.User.username == username_or_token))
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True


@token_auth.verify_token
def verify_token(token):
    user = models.User.verify_auth_token(token)
    if user is not None:
        g.user = user
        return True
    return False
예제 #22
0
# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

# app.config['LDAP_HOST'] = 'ldap.example.com'
# app.config['LDAP_DOMAIN'] = 'example.com'
# app.config['LDAP_AUTH_TEMPLATE'] = 'login.html'
# app.config['LDAP_PROFILE_KEY'] = 'employeeID'

# extensions
db = SQLAlchemy(app)
auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Bearer')
multi_auth = MultiAuth(auth, token_auth)
# ldap = LDAP(app)


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), index=True)
    password_hash = db.Column(db.String(64))

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)
예제 #23
0
from flask import Flask, abort, request, jsonify, g, url_for
from .user_model import db, User
from . import user_controller 
from . import rule_controller
from . import engine_controller
from time import gmtime, strftime
import datetime
from flask_httpauth import HTTPTokenAuth,HTTPBasicAuth,MultiAuth

@app.route('/health')
def health():
        return user_controller.get_health()

auth = HTTPBasicAuth()
auth_token = HTTPTokenAuth('Bearer')
multi_auth = MultiAuth(auth, auth_token) 

@auth.verify_password
def verify_password(username_or_token, password):
    return user_controller.test_password(username_or_token, password)

@auth_token.verify_token
def verify_token(username_or_token):
    return user_controller.test_token(username_or_token)

@app.route('/api/users', methods=['POST'])
def add_new_user():
    return user_controller.new_user()

@app.route('/api/token')
@multi_auth.login_required
예제 #24
0
from util.user import basic_login, get_user_token, is_valid_token, create_token

app = Flask(__name__)
# configure socket to the application
socketio = SocketIO(app)
# Set CORS options on app configuration
app.config['CORS_HEADERS'] = "Content-Type"
app.config['CORS_RESOURCES'] = {r"/*": {"origins": "*"}}
sentry = None
if os.environ.get('SENTRY_DSN'):
    sentry = Sentry(app, dsn=os.environ.get('SENTRY_DSN'))
else:
    app.debug = True
token_auth = HTTPTokenAuth(scheme='Token')
basic_auth = HTTPBasicAuth()
multi_auth = MultiAuth(HTTPBasicAuth, HTTPTokenAuth)


def get_app():
    return app


@token_auth.verify_token
def verify_token(token):
    g.user_id = None
    try:
        is_valid = is_valid_token(token)

        return is_valid
    except:
        return False
예제 #25
0
		return False
	try:
		verifed_payload = jwt.decode(access_token, JWT_SALT, True, verify_exp=False)
	except exceptions.ExpiredSignatureError as e:#exp超时就停止验证
		tokenauth.error_handler(return_error('SIGN_ERROR', e).__repr__)	
		return False
	except jwt.DecodeError as e:#header,payload(base64双数据字符),crypto格式不对
		tokenauth.error_handler(return_error('SIGN_ERROR', e).__repr__)	
		return False
	except jwt.InvalidTokenError as e:#格式是对的,header,payload,crypto对不上
		tokenauth.error_handler(return_error('SIGN_ERROR', e).__repr__)	
		return False
	return True

# multiauth = MultiAuth(baseauth,tokenauth)
multiauth = MultiAuth(tokenauth, baseauth)

#生成jwt
def create_token(user, expires=300):
	#构造header
	headers = {
	'tye':'jwt',
	'alg':'HS256'
	}
	#构造payload
	payload = {
	'user_id':user.id,
	'username':user.username,
	'iat': datetime.datetime.now(),
	'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=expires)#jwt解码时datetime.utcnow()
	}		
예제 #26
0
from flask import Flask, logging, jsonify, request, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, HTTPDigestAuth, MultiAuth

from config import config

db = SQLAlchemy()
token_auth = HTTPTokenAuth()
multi_auth = MultiAuth(token_auth)


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config.get(config_name) or config['default'])

    db.init_app(app)

    from app.main import main_bp
    from app.auth import auth_bp
    from app.user import user_bp
    from app.redis_db import redis_db_bp
    from app.redis_server import redis_server_bp

    app.register_blueprint(main_bp, url_prefix='/')
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(user_bp, url_prefix='/user')
    app.register_blueprint(
        redis_db_bp,
        url_prefix='/redis_db/<int:redis_server_id>/<int:redis_db_num>')
    app.register_blueprint(redis_server_bp, url_prefix='/redis_server')