Example #1
0
def _get_flask_app(roles=False, **kwargs):
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(
        SECRET_KEY, db=db, roles=roles, password_minlen=3, **kwargs)
    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.add(user)

    user2 = User(login=u'foo', password='******')
    db.add(user2)
    db.commit()

    app = Flask('test')
    app.secret_key = os.urandom(32)
    app.testing = True

    @app.route('/protected/')
    @auth.protected()
    def protected():
        return u'Welcome'

    authcode.setup_for_flask(auth, app)
    auth.session = {}
    return auth, app, user
def test_setup_flask_no_views():
    app = Flask(__name__)
    db = SQLAlchemy('sqlite:///', app)
    auth = authcode.Auth(SECRET_KEY, db=db, views=[])

    authcode.setup_for_flask(auth, app)
    assert len(app.url_map._rules) == 1
def test_flask_sqlalchemy():
    from flask.ext.sqlalchemy import SQLAlchemy as FlaskSQLAlchemy

    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
    db = FlaskSQLAlchemy(app)

    class UserMixin(object):
        email = db.Column(db.Unicode(300))

        def __init__(self, login, email):
            self.login = login
            self.email = email
            self.password = '******'

    class RoleMixin(object):
        description = db.Column(db.UnicodeText)

    auth = authcode.Auth(SECRET_KEY, db=db, UserMixin=UserMixin, RoleMixin=RoleMixin)
    authcode.setup_for_flask(auth, app)
    User = auth.User

    db.create_all()
    user = User(u'meh', u'*****@*****.**')
    db.session.add(user)
    db.session.commit()

    assert user.login == u'meh'
    assert user.email == u'*****@*****.**'
    assert hasattr(user, 'password')
    assert hasattr(user, 'last_sign_in')
    assert repr(user) == '<User meh>'
def test_setup_for_flask():
    app = Flask(__name__)
    db = SQLAlchemy('sqlite:///', app)
    auth = authcode.Auth(SECRET_KEY, db=db)
    authcode.setup_for_flask(auth, app)

    assert auth.render == flask.render_template
    assert auth.request.__name__ == flask.request.__name__
    assert auth.session.__name__ == flask.session.__name__
    assert app.jinja_env.globals['csrf_token']
    assert app.jinja_env.globals['auth']
def test_setup_flask_partial_views_1():
    app = Flask(__name__)
    db = SQLAlchemy('sqlite:///', app)
    auth = authcode.Auth(SECRET_KEY, db=db, views='sign_in sign_out'.split())

    authcode.setup_for_flask(auth, app)
    rules = app.url_map._rules
    names = [ru.endpoint for ru in rules]

    assert 'auth_sign_in' in names
    assert 'auth_sign_out' in names
    assert 'auth_reset_password' not in names
    assert 'auth_change_password' not in names
Example #6
0
def test_custom_templates():
    db = SQLAlchemy('sqlite:///:memory:')
    options = {
        'template_sign_in': 'sign-in.html',
        'template_sign_out': 'sign-out.html',
        'template_reset': 'reset-password.html',
        'template_reset_email': 'reset-password-email.html',
        'template_change_password': '******',
    }
    inbox = []

    def send_email(user, subject, msg):
        inbox.append(msg)

    auth = authcode.Auth(SECRET_KEY, db=db, **options)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.add(user)
    db.commit()

    custom_templates = os.path.join(
        os.path.dirname(__file__),
        'custom_templates'
    )
    app = Flask('test', template_folder=custom_templates)
    app.secret_key = os.urandom(32)
    app.testing = True
    authcode.setup_for_flask(auth, app, send_email=send_email)
    auth.session = {}
    client = app.test_client()

    resp = client.get(auth.url_sign_in)
    assert resp.data == b'OK SIGN IN'

    resp = client.get(auth.url_reset_password)
    assert resp.data == b'OK RESET PASSWORD'

    data = dict(login=user.login, _csrf_token=auth.get_csrf_token())
    resp = client.post(auth.url_reset_password, data=data)
    assert inbox[0] == 'OK RESET PASSWORD EMAIL'

    auth.login(user)

    resp = client.get(auth.url_change_password)
    assert resp.data == b'OK CHANGE PASSWORD'

    url = '{0}?_csrf_token={1}'.format(auth.url_sign_out, auth.get_csrf_token())
    resp = client.get(url)
    assert resp.data == b'OK SIGN OUT'
def test_setup_flask_views_callable_urls():
    app = Flask(__name__)
    db = SQLAlchemy('sqlite:///', app)
    config = {
        'url_sign_in': lambda: '/my-login',
        'url_reset_password': lambda: '/reset-secret',
    }
    auth = authcode.Auth(SECRET_KEY, db=db, **config)

    authcode.setup_for_flask(auth, app)
    rules = app.url_map._rules
    endpoints = dict([(ru.endpoint, ru.rule) for ru in rules])

    assert endpoints['auth_sign_in'] == '/my-login'
    assert endpoints['auth_reset_password'] == '/reset-secret/<token>/'
def test_setup_flask_views_urls():
    app = Flask(__name__)
    db = SQLAlchemy('sqlite:///', app)
    config = {
        'url_sign_in': '/ingresar/',
        'url_sign_out': '/salir/',
        'url_reset_password': '******',
        'url_change_password': '******',
    }
    auth = authcode.Auth(SECRET_KEY, db=db, **config)

    authcode.setup_for_flask(auth, app)
    rules = app.url_map._rules
    endpoints = dict([(ru.endpoint, ru.rule) for ru in rules])

    assert endpoints['auth_sign_in'] == config['url_sign_in']
    assert endpoints['auth_sign_out'] == config['url_sign_out']
    assert endpoints['auth_change_password'] == config['url_change_password']
    assert endpoints['auth_reset_password'] == config['url_reset_password'] + '<token>/'
def test_setup_flask_custom():
    app = Flask(__name__)
    db = SQLAlchemy('sqlite:///', app)
    auth = authcode.Auth(SECRET_KEY, db=db)

    def send_email(user, subject, msg):
        pass

    def render(tmpl, **kwargs):
        pass

    class CustomSession(object):
        pass
    session = CustomSession()

    authcode.setup_for_flask(
        auth, app,
        render=render, send_email=send_email, session=session
    )
    assert auth.render == render
    assert auth.send_email == send_email
    assert auth.session == session
Example #10
0
app = Flask(__name__)

SECRET_KEY = '1234567890qwertyuiopasdfghjklzxcvbnm=+!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
app.config['SECRET_KEY'] = SECRET_KEY
db = SQLAlchemy(app)


def send_auth_email(user, subject, msg):
    print('To:', user)
    print('Subject:', subject)
    print (msg)


auth = authcode.Auth(SECRET_KEY, db=db)
authcode.setup_for_flask(auth, app, send_email=send_auth_email)
User = auth.User


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


if __name__ == '__main__':
    db.create_all()
    db.session.add(User(login=u'authcode', password=u'authcode'))
    db.session.commit()

    app.run(debug=True)
Example #11
0
from authcode import Auth, setup_for_flask

import settings
from app import app, db


class UserMixin(object):
    twitter_id = db.Column(db.String(255), nullable=True)
    twitter_username = db.Column(db.String(255), nullable=True)
    twitter_token = db.Column(db.String(255), nullable=True)
    twitter_secret = db.Column(db.String(255), nullable=True)

    facebook_id = db.Column(db.String(255), nullable=True)
    facebook_token = db.Column(db.String(255), nullable=True)


auth = Auth(settings.SECRET_KEY, db=db, UserMixin=UserMixin, roles=False,
            **settings.AUTH_SETTINGS)
setup_for_flask(auth, app)
User = auth.User


def get_unique_login(target):
    num = 1
    login = target
    while True:
        if not User.by_login(login):
            return login
        num = num + 1
        login = '******'.format(target=target, num=num)
Example #12
0
from authcode import Auth, setup_for_flask

import settings
from app import app, db, mailer


class UserMixin(object):
    email = db.Column(db.Unicode)

auth = Auth(settings.SECRET_KEY, db=db, UserMixin=UserMixin, roles=True,
            **settings.AUTH_SETTINGS)

User = auth.User


def send_email(user, subject, msg):
    if not user.email:
        return
    try:
        print(msg)
        mailer.send(
            subject, html_content=msg,
            from_email=settings.MAILER_SENDER,
            to=user.email
        )
    except:
        pass


setup_for_flask(auth, app, send_email=send_email)