Ejemplo n.º 1
0
def main():
    """Create a configured wsgi app"""
    settings = {}
    debug = os.environ.get('DEBUG', True)
    settings['reload_all'] = debug
    settings['debug_all'] = debug
    settings['auth.username'] = os.environ.get('AUTH_USERNAME', 'admin')
    manager = BCRYPTPasswordManager()
    settings['auth.password'] = os.environ.get(
        'AUTH_PASSWORD', manager.encode('secret'))
    if not os.environ.get('TESTING', False):
        # only bind the session if we are not testing
        engine = sa.create_engine(DATABASE_URL)
        DBSession.configure(bind=engine)
    # add a secret value for auth tkt signing
    auth_secret = os.environ.get('JOURNAL_AUTH_SECRET', 'itsaseekrit')
    # configuration setup
    config = Configurator(
        settings=settings,
        authentication_policy=AuthTktAuthenticationPolicy(
            secret=auth_secret,
            hashalg='sha512'
        ),
        authorization_policy=ACLAuthorizationPolicy(),
    )
    config.include('pyramid_tm')
    config.include('pyramid_jinja2')
    config.add_route('home', '/')
    config.add_route('add', '/add')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_static_view('static', os.path.join(HERE, 'static'))
    config.scan()
    app = config.make_wsgi_app()
    return app
Ejemplo n.º 2
0
    def test_fail_2(self):
        def return_none(*args):
            return None

        bcrypt = BCRYPTPasswordManager()
        bcrypt.crypt_rn = return_none
        bcrypt.encode("foo")
Ejemplo n.º 3
0
def main():
    """Create a configured wsgi app"""
    settings = {}
    settings['reload_all'] = os.environ.get('DEBUG', True)
    settings['debug_all'] = os.environ.get('DEBUG', True)
    settings['db'] = os.environ.get(
        'DATABASE_URL', 'dbname=learning_journal user=efrain-petercamacho')
    settings['auth.username'] = os.environ.get('AUTH_USERNAME', 'admin')
    manager = BCRYPTPasswordManager()
    settings['auth.password'] = os.environ.get('AUTH_PASSWORD',
                                               manager.encode('secret'))
    secret = os.environ.get('JOURNAL_SESSION_SECRET', 'itsaseekrit')
    session_factory = SignedCookieSessionFactory(secret)
    auth_secret = os.environ.get('JOURNAL_AUTH_SECRET', 'anotherseekrit')
    # configuration setup
    config = Configurator(
        settings=settings,
        session_factory=session_factory,
        authentication_policy=AuthTktAuthenticationPolicy(secret=auth_secret,
                                                          hashalg='sha512'),
        authorization_policy=ACLAuthorizationPolicy(),
    )
    jinja2.filters.FILTERS['markdown'] = markd
    config.include('pyramid_jinja2')
    config.add_static_view('static', os.path.join(here, 'static'))
    config.add_route('home', '/')
    config.add_route('add', '/add')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('details', '/details/{id}')
    config.add_route('editor', '/editor/{id}')
    config.add_route('delete', '/delte/{id}')
    config.scan()
    app = config.make_wsgi_app()
    return app
Ejemplo n.º 4
0
def main(argv=None):
    if len(argv) != 3:
        print "Usage: create_user.py <username> <password>"
        sys.exit(1)

    session = dbsession()
    username = argv[1]
    password = argv[2]
    manager = BCRYPTPasswordManager()
    hashed_password = manager.encode(password)

    user = User()
    user.username = username
    user.password = hashed_password
    user.active_ind = True

    try:
        session.add(user)
        session.commit()
        print "User {0} created.".format(username)
    except:
        print "Error adding user."
        session.rollback()
        session.close()
        sys.exit(1)

    session.close()
    sys.exit(0)
Ejemplo n.º 5
0
def password_check(password, stored_passw):
    """
    Returns a boolean of whether the password was correct.
    """
    from cryptacular.bcrypt import BCRYPTPasswordManager
    manager = BCRYPTPasswordManager()
    return manager.check(stored_passw, password)
Ejemplo n.º 6
0
    def test_fail_3(self):
        def return_none(*args):
            return None

        bcrypt = BCRYPTPasswordManager()
        pw = bcrypt.encode("foobar")
        bcrypt.crypt_rn = return_none
        bcrypt.check(pw, "foo")
Ejemplo n.º 7
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    @forbidden_view_config(renderer='templates/forbidden.jinja2')
    def forbidden(request):
        return {}

    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    auth_secret = os.environ.get('TASTEBUDDIES_AUTH_SECRET', 'tastynoms')

    authn_policy = AuthTktAuthenticationPolicy(
        secret=auth_secret,
        hashalg='sha512',
        callback=groupfinder,
    )

    authz_policy = ACLAuthorizationPolicy()

    settings['auth.username'] = os.environ.get('AUTH_USERNAME', 'admin')
    manager = BCRYPTPasswordManager()
    settings['auth.password'] = os.environ.get(
        'AUTH_PASSWORD', manager.encode('secret')
    )

    config = Configurator(
        settings=settings,
        authentication_policy=authn_policy,
        authorization_policy=authz_policy,
    )

    config.include('pyramid_jinja2')
    config.include('pyramid_tm')

    config.add_static_view('static', 'static', cache_max_age=3600)

    config.add_route('home', '/')
    config.add_route('user_create', '/create_user')
    config.add_route('user_login', '/login')
    config.add_route('verify', '/verify', factory=Root)
    config.add_route('send_email', '/send_email', factory=Root)
    config.add_route('logout', '/logout', factory=Root)
    config.add_route('profile_edit', '/profile/edit/{username}',
                     factory=Root)
    config.add_route('group_create', '/group/create_group',
                     factory=Root)
    config.add_route('group_edit', '/group/edit/{group_name}',
                     factory=Root)
    config.add_route('profile_detail', '/profile/{username}',
                     factory=UserFactory, traverse='/{username}')
    config.add_route('group_detail', '/group/{group_name}',
                     factory=Root)
    config.scan()

    return config.make_wsgi_app()
Ejemplo n.º 8
0
 def _makeOne(self, email, password, id=False):
     m = BPM()
     hashed = m.encode(password)
     if id:
         return self._getTargetClass()(id=id, email=email, password=hashed)
     return self._getTargetClass()(
         email=email,
         password=hashed,
     )
Ejemplo n.º 9
0
 def check_password(cls, username, password, session=None):
     if session is None:
         session = DBSession
     manager = BCRYPTPasswordManager()
     try:
         user = User.by_username(username)
     except NoResultFound:
         return False
     return manager.check(user.password, password)
Ejemplo n.º 10
0
def do_login(request):
    username = request.params.get('username', None)
    password = request.params.get('password', None)
    if not (username and password):
        raise ValueError('both username and password are required')
    settings = request.registry.settings
    manager = BCRYPTPasswordManager()
    if username == settings.get('auth.username', ''):
        hashed = settings.get('auth.password', '')
        return manager.check(hashed, password)
Ejemplo n.º 11
0
def login(request):
    username = request.params.get("username", None)
    password = request.params.get("password", None)
    if not (username and password):
        raise ValueError("Username and password are required")
    manager = BCRYPTPasswordManager()
    try:
        user = User.get_by_username(username)
    except:
        raise ValueError("User does not exist")
    return manager.check(user.password, password)
Ejemplo n.º 12
0
    def validate_user_password(cls, username, password):
        user = DBSession.query(cls).options(noload(cls.groups)).filter(cls.username == username.lower()).first()

        if user is None:
            return None

        manager = BCRYPTPasswordManager()
        if manager.check(user.credentials, password):
            return user

        return None
Ejemplo n.º 13
0
def do_login(request):
    username = request.params.get('username', None)
    password = request.params.get('password', None)
    if not (username and password):
        raise ValueError('both username and password are required')

    settings = request.registry.settings
    manager = BCRYPTPasswordManager()
    if username == settings.get('auth.username', ''):
        hashed = settings.get('auth.password', '')
        return manager.check(hashed, password)
Ejemplo n.º 14
0
    def _set_password(self, raw_password):
        """ Encrypt the password.

        Encrypt `raw_password` with bcrypt and set it as the account
        password.

        :param raw_password: the unencrypted user password
        :type username: unicode
        :return: the bcrypt encrypted password
        :rtype: unicode
        """
        bcrypt = BCRYPTPasswordManager()
        self._password = unicode(bcrypt.encode(raw_password, rounds=12))
Ejemplo n.º 15
0
def test_create_user(db_session):
    kwargs = {
        'username': "******",
        'password': "******"
    }
    kwargs['session'] = db_session
    user = app.User.new(**kwargs)
    db_session.flush()
    u = db_session.query(app.User).filter(app.User.id == user.id).one()
    assert getattr(u, 'id', '') is not None
    assert getattr(u, 'username', '') == "Test_Username"
    manager = BCRYPTPasswordManager()
    assert manager.check(getattr(user, 'password', ''), "testpassword")
Ejemplo n.º 16
0
 def new(cls, username=None, password=None, session=DBSession):
     """Stores password in database already hashed"""
     manager = BCRYPTPasswordManager()
     if not (username and password):
         raise ValueError("Username and password needed")
     hashed = unicode(manager.encode(password))
     try:
         instance = cls(username=username, password=hashed)
         session.add(instance)
         session.flush()
     except IntegrityError:
         raise ValueError("Username already in use")
     return instance
Ejemplo n.º 17
0
def _initTestingDB(makeuser=False):
    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)
    DBSession.configure(bind=engine)
    if makeuser:
        m = BPM()
        hashed = m.encode(u'1234567')
        with transaction.manager:
            user = User(email=u'*****@*****.**',
                        password=hashed,
                        )
            DBSession.add(user)
    return DBSession
Ejemplo n.º 18
0
def auth_req(request):
    manager = BCRYPTPasswordManager()
    settings = {
        'auth.username': '******',
        'auth.password': manager.encode('secret'),
    }
    testing.setUp(settings=settings)
    req = testing.DummyRequest()

    def cleanup():
        testing.tearDown()
    request.addfinalizer(cleanup)
    return req
Ejemplo n.º 19
0
def do_login(request):
    username = request.params.get('username', None)
    password = request.params.get('password', None)
    if not (username and password):
        raise ValueError('both username and password are required')

    settings = request.registry.settings
    # you can always get hold of application settings with
    # `request.registry.settings`
    manager = BCRYPTPasswordManager()
    if username == settings.get('auth.username', ''):
        hashed = settings.get('auth.password', '')
        return manager.check(hashed, password)
    return False
Ejemplo n.º 20
0
def _initTestingDB(makeuser=False):
    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)
    DBSession.configure(bind=engine)
    if makeuser:
        m = BPM()
        hashed = m.encode(u'1234567')
        with transaction.manager:
            user = User(
                email=u'*****@*****.**',
                password=hashed,
            )
            DBSession.add(user)
    return DBSession
Ejemplo n.º 21
0
def auth_req(request):
    manager = BCRYPTPasswordManager()
    settings = {
        'auth.username': '******',
        'auth.password': manager.encode('secret'),
    }
    testing.setUp(settings=settings)
    req = testing.DummyRequest()

    def cleanup():
        testing.tearDown()

    request.addfinalizer(cleanup)

    return req
Ejemplo n.º 22
0
def do_login(request):
    login_result = False
    manager = BCRYPTPasswordManager()

    entered_username = request.params.get('username', None)
    entered_password = request.params.get('password', None)

    user_obj = User.lookup_by_attribute(username=entered_username)[0]
    db_username = user_obj.username

    if entered_username == db_username:
        db_hashed = user_obj.password
        # manager.check returns BOOL
        login_result = manager.check(db_hashed, entered_password)

    return login_result
Ejemplo n.º 23
0
 def create_user(cls, username, password, first="", last="",
                 dflt_medium=1, timezone='America/Los_Angeles',
                 session=None):
     """Instantiates a new user, and writes it to the database.
     User must supply a username and password.
     """
     if session is None:
         session = DBSession
     manager = BCRYPTPasswordManager()
     hashed = manager.encode(password)
     instance = cls(first=first, last=last, username=username,
                    password=hashed, dflt_medium=dflt_medium,
                    timezone=timezone)
     session.add(instance)
     session.flush()
     return instance
Ejemplo n.º 24
0
def main():
    """Create a configured wsgi app."""
    settings = {}
    settings['reload_all'] = os.environ.get('DEBUG', True)
    settings['debug_all'] = os.environ.get('DEBUG', True)
    # settings['db'] = os.environ.get(
    #     'DATABASE_URL', 'dbname=learning-journal user=mark'
    # )
    settings['sqlalchemy.url'] = os.environ.get(
        # must be rfc1738 URL
        'DATABASE_URL', 'postgresql://mark:@localhost:5432/learning-journal'
    )
    engine = sa.engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    # Add authentication setting configuration
    settings['auth.username'] = os.environ.get('AUTH_USERNAME', 'admin')
    manager = BCRYPTPasswordManager()
    settings['auth.password'] = os.environ.get(
        'AUTH_PASSWORD', manager.encode('secret'))
    # secret value for session signing:
    secret = os.environ.get('JOURNAL_SESSION_SECRET', 'itsaseekrit')
    session_factory = SignedCookieSessionFactory(secret)
    # add a secret value for auth tkt signing
    auth_secret = os.environ.get('JOURNAL_AUTH_SECRET', 'anotherseekrit')
    # configuration setup
    config = Configurator(
        settings=settings,
        session_factory=session_factory,
        authentication_policy=AuthTktAuthenticationPolicy(
            secret=auth_secret,
            hashalg='sha512'
        ),
        authorization_policy=ACLAuthorizationPolicy(),

    )
    config.include('pyramid_jinja2')
    config.include('pyramid_tm')
    config.add_static_view('static', os.path.join(here, 'static'))
    config.add_route('home', '/')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('detail', '/detail/{id:\d+}')
    config.add_route('edit', '/edit')
    config.add_route('new', '/new')
    config.scan()
    app = config.make_wsgi_app()
    return app
Ejemplo n.º 25
0
def main(argv=sys.argv):
    manager = BCRYPTPasswordManager()
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    if 'DATABASE_URL' in os.environ:
        settings['sqlalchemy.url'] = os.environ['DATABASE_URL']
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        password = manager.encode(u'admin')
        admin = User(name=u'admin', password=password)
        DBSession.add(admin)
Ejemplo n.º 26
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    if 'DATABASE_URL' in os.environ:
        settings['sqlalchemy.url'] = os.environ['DATABASE_URL']
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        manager = Manager()
        password = manager.encode(u'admin')
        admin = User(username=u'admin', hashed_password=password)
        DBSession.add(admin)
Ejemplo n.º 27
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)

    manager = BCRYPTPasswordManager()
    pw = getpass.getpass('Admin password: '******'admin', email='*****@*****.**', password=hashed)
        DBSession.add(admin)
Ejemplo n.º 28
0
def get_hashed_password(password):
    """
    Returns hashed password

    :param password: String
    :return: String
    """
    return BCRYPTPasswordManager().encode(password)
Ejemplo n.º 29
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:

        manager = Manager()
        password = manager.encode('admin')

        DBSession.add(Entry(title=u'title', body=u'body'))
        DBSession.add(User(username=u'admin', password=password))
Ejemplo n.º 30
0
    def check_password(cls, username, password):
        """ Check the user password.

        Check if the submited password for username is the same than the
        encrypted one recorded in the database. Return None if the username
        did not exist.

        :param username: the user username
        :type username: unicode
        :param username: the submited password
        :type username: unicode
        :return: True if the password is correct. false if incorect
        :rtype: boolean
        """
        bcrypt = BCRYPTPasswordManager()
        user = cls.get_by_username(username)
        if user:
            return bcrypt.check(user.password, password)
Ejemplo n.º 31
0
 def test_shorthash(self):
     manager = BCRYPTPasswordManager()
     def match(hash):
         return True
     manager.match = match
     short_hash = manager.encode(self.snowpass)[:28]
     assert_true(manager.match(short_hash))
     manager.check(short_hash, self.snowpass)
Ejemplo n.º 32
0
 def _store_data(self, appstruct):
     password = appstruct.get('password', '')
     if not password:
         return
     manager = getattr(self.context, 'pwd_manager', None)
     if manager is None:
         manager = BCRYPTPasswordManager()
         self.context.pwd_manager = manager
     password_encoded = self.context.pwd_manager.encode(password)
     self.context.password = password_encoded
Ejemplo n.º 33
0
class User(Folder):
    """ Represents a user.  """
    tzname = 'UTC' # backwards compatibility default

    pwd_manager = BCRYPTPasswordManager()

    groupids = multireference_sourceid_property(UserToGroup)
    groups = multireference_source_property(UserToGroup)
    name = renamer()

    def __init__(self, password=None, email=None, tzname=None):
        Folder.__init__(self)
        if password is not None:
            password = self.pwd_manager.encode(password)
        self.password = password
        self.email = email
        if tzname is None:
            tzname = 'UTC'
        self.tzname = tzname

    def __dump__(self):
        return dict(password=self.password)

    @property
    def timezone(self):
        return pytz.timezone(self.tzname)

    def check_password(self, password):
        """ Checks if the plaintext password passed as ``password`` matches
        this user's stored, encrypted password.  Returns ``True`` or
        ``False``."""
        statsd_gauge('check_password', 1)
        return self.pwd_manager.check(self.password, password)

    def set_password(self, password):
        self.password = self.pwd_manager.encode(password)

    def email_password_reset(self, request):
        """ Sends a password reset email."""
        root = request.root
        sitename = getattr(root, 'title', None) or 'Substance D'
        principals = find_service(self, 'principals')
        reset = principals.add_reset(self)
        # XXX should this really point at an SDI URL?
        reseturl = request.application_url + request.sdiapi.mgmt_path(reset)
        if not self.email:
            raise ValueError('User does not possess a valid email address.')
        message = Message(
            subject = 'Account information for %s' % sitename,
            recipients = [self.email],
            body = render('templates/resetpassword_email.pt',
                          dict(reseturl=reseturl))
            )
        mailer = get_mailer(request)
        mailer.send(message)
Ejemplo n.º 34
0
def main():
    """Create a configured wsgi app"""
    settings = {}
    settings['reload_all'] = os.environ.get('DEBUG', True)
    settings['debug_all'] = os.environ.get('DEBUG', True)
    settings['sqlalchemy.url'] = os.environ.get(
        'DATABASE_URL',
        'postgresql://roberthaskell:@localhost:5432/learning_journal'  #'dbname=learning_journal user=cewing'
    )
    engine = sa.engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    settings['auth.username'] = os.environ.get('AUTH_USERNAME', 'admin')
    manager = BCRYPTPasswordManager()
    settings['auth.password'] = os.environ.get('AUTH_PASSWORD',
                                               manager.encode('secret'))
    # secret value for session signing:
    secret = os.environ.get('JOURNAL_SESSION_SECRET', 'itsaseekrit')
    session_factory = SignedCookieSessionFactory(secret)
    auth_secret = os.environ.get('JOURNAL_AUTH_SECRET', 'anotherseekrit')
    # configuration setup
    config = Configurator(
        settings=settings,
        session_factory=session_factory,
        authentication_policy=AuthTktAuthenticationPolicy(secret=auth_secret,
                                                          hashalg='sha512'),
        authorization_policy=ACLAuthorizationPolicy(),
    )
    jinja2.filters.FILTERS['markdown'] = markd
    config.include('pyramid_tm')
    config.include('pyramid_jinja2')
    config.add_static_view('static', os.path.join(here, 'static'))
    config.add_route('home', '/')
    config.add_route('add', '/add')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('details', '/details/{id}')
    config.add_route('editor', '/editor/{id}')
    config.add_route('delete', '/delete/{id}')
    config.add_route('tweet', '/tweet')
    config.scan()
    app = config.make_wsgi_app()
    return app
Ejemplo n.º 35
0
def main():
    # Create a configured wsgi app
    settings = {}
    debug = os.environ.get('DEBUG', True)
    settings['reload_all'] = debug
    settings['debug_all'] = debug
    settings['auth.username'] = os.environ.get('AUTH_USERNAME', 'admin')
    manager = BCRYPTPasswordManager()
    settings['auth.password'] = os.environ.get(
        'AUTH_PASSWORD', manager.encode('secret')
    )
    if not os.environ.get("TESTING", False):
        # only bind the session if it isn't already bound, while testing
        engine = sa.create_engine(DATABASE_URL)
        DBSession.configure(bind=engine)

    # add a secret value for auth tkt signing
    auth_secret = os.environ.get('JOURNAL_AUTH_SECRET', 'itsaseekrit')

    # and add a new value to the constructor for our Configurator:
    config = Configurator(
        settings=settings,
        authentication_policy=AuthTktAuthenticationPolicy(
            secret=auth_secret,
            hashalg='sha512',
        ),
        authorization_policy=ACLAuthorizationPolicy(),
    )

    # we want to use the transaction management provided by pyramid-tm
    config.include("pyramid_tm")
    config.include("pyramid_jinja2")
    config.add_static_view('static', os.path.join(HERE, 'static'))
    config.add_route('home', '/')
    config.add_route('detail', '/detail/{id}')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('edit', '/edit/{entry_id}')
    config.add_route('create', '/create')
    config.scan()
    app = config.make_wsgi_app()
    return app
Ejemplo n.º 36
0
def auth_req(request):
    manager = BCRYPTPasswordManager()
    settings = {
        'auth.username': '******',
        # Password encryption
        'auth.password': manager.encode('secret'),
    }
    testing.setUp(settings=settings)
    req = testing.DummyRequest()

    print
    print "check fixture:"
    print settings['auth.password']

    def cleanup():
        testing.tearDown()

    request.addfinalizer(cleanup)

    return req
Ejemplo n.º 37
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)

    m = BPM()
    a_email = raw_input('Enter email for admin account: ')
    a_pw = getpass('Enter password for admin account: ')
    a_hashed = m.encode(a_pw)

    with transaction.manager:
        admin = User(
                        email=a_email,
                        password=a_hashed,
                    )
        DBSession.add(admin)
Ejemplo n.º 38
0
    def check_password(cls, **kwargs):
        if kwargs.has_key('id'):
            user = cls.get_by_id(kwargs['id'])
        if kwargs.has_key('username'):
            user = cls.get_by_username(kwargs['username'])

        if not user:
            return False
        if BCRYPTPasswordManager().check(user.password, kwargs['password']):
            return True
        else:
            return False
Ejemplo n.º 39
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)

    m = BPM()
    a_email = raw_input('Enter email for admin account: ')
    a_pw = getpass('Enter password for admin account: ')
    a_hashed = m.encode(a_pw)

    with transaction.manager:
        admin = User(
            email=a_email,
            password=a_hashed,
        )
        DBSession.add(admin)
Ejemplo n.º 40
0
def edit_user(request):
    user = request.context
    if request.method == 'POST':
        user.username = request.authenticated_userid
        password = request.params.get('password')
        manager = BCRYPTPasswordManager()
        hashed = manager.encode(password)
        user.password = hashed
        user.first_name = request.params.get('first_name')
        user.last_name = request.params.get('last_name')
        default_medium = request.params.get('default_medium').lower()
        if default_medium == 'email':
            user.dflt_medium = 1
        if default_medium == 'text':
            user.dflt_medium = 2
        else:
            raise ValueError()
        user.timezone = request.params.get('timezone')
        return HTTPFound(request.route_url('list'))
    else:
        return {'user': user}
Ejemplo n.º 41
0
def main():
    """Create a configured wsgi app"""
    settings = {}
    settings['reload_all'] = os.environ.get('DEBUG', True)
    settings['debug_all'] = os.environ.get('DEBUG', True)
    settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL',
                                                'postgresql:///whiteknight')
    engine = sa.engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    settings['auth.username'] = os.environ.get('AUTH_USERNAME', 'admin')
    manager = BCRYPTPasswordManager()
    settings['auth.password'] = os.environ.get('AUTH_PASSWORD',
                                               manager.encode('secret'))
    secret = os.environ.get('JOURNAL_SESSION_SECRET', 'itsaseekrit')
    session_factory = SignedCookieSessionFactory(secret)
    auth_secret = os.environ.get('JOURNAL_AUTH_SECRET', 'anotherseekrit')
    config = Configurator(
        settings=settings,
        session_factory=session_factory,
        authentication_policy=AuthTktAuthenticationPolicy(secret=auth_secret,
                                                          hashalg='sha512',
                                                          debug=True),
        authorization_policy=ACLAuthorizationPolicy(),
    )
    config.add_static_view('static', os.path.join(here, 'static'))
    config.include('pyramid_jinja2')
    config.include('pyramid_tm')
    config.add_route('home', '/')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('feed', '/feed')
    config.add_route('scrape', '/scrape')
    config.add_route('scrape_twitter', '/scrape_twitter')
    config.add_route('tweet', '/tweet/{id}')
    config.add_route('edit_comment', '/edit_comment/{id}')
    config.add_route('remove_one', '/remove_one/{id}')
    config.add_route('delete_all', '/delete_all')
    config.scan()
    app = config.make_wsgi_app()
    return app
Ejemplo n.º 42
0
class User(Base):
    """
    Class constants representing database table and its columns.

    id -- integer, primary key
    email -- string, unique, max 255 characters.
    givenname -- string, max 255 characters.
    surname -- string, max 255 characters.
    password -- string, bcrypt, max 255 characters.
    archived -- boolean.
    blocked -- boolean.
    updated -- datetime.
    """
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    email = Column(String(255), unique=True, nullable=False)
    givenname = Column(String(255))
    surname = Column(String(255))
    password = Column(String(255), nullable=False)
    archived = Column(Boolean, default=False)
    blocked = Column(Boolean, default=False)
    last_logged = Column(DateTime, default=datetime.utcnow)
    created = Column(DateTime, default=datetime.utcnow)
    updated = Column(DateTime, onupdate=datetime.utcnow)
    """ Class constant used for accessing Bcrypt password manager. """
    pm = BCRYPTPasswordManager()
    """ Method for returning a user based on id.

    id -- int, user id.
    """
    @classmethod
    def by_id(cls, id):
        return DBSession.query(User).filter(User.id == id).first()

    """ Method for returning a user based on email.
    We can do this, because the email column in the database is set as unique.

    email -- string, email.
    """

    @classmethod
    def by_email(cls, email):
        return DBSession.query(User).filter(User.email == email).first()

    """ Method for checking object password against string.

    password -- string.
    """

    def verify_password(self, password):
        return self.pm.check(self.password, password)
Ejemplo n.º 43
0
class User(Base):

    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(Unicode(255), unique=True, nullable=False)
    email = Column(Unicode(255), unique=True, nullable=False)
    password = Column(Unicode(255), nullable=False)
    last_logged = Column(DateTime, default=datetime.utcnow)

    pm = BCRYPTPasswordManager()

    @classmethod
    def by_id(cls, id):
        return DBSession.query(User).filter(User.id == id).first()

    @classmethod
    def by_uname_email(cls, login):
        return DBSession.query(User).filter(or_(User.username == login,\
                                                User.email == login))\
                                    .first()

    def verify_password(self, password):
        return self.pm.check(self.password, password)

    def hash_password(self, password):
        return self.pm.encode(password)

    def my(self):
        return DBSession.query(Bookmark).filter(Bookmark.owner_id == self.id)

    def bookmarks(self, request, page=1):
        page_url = PageURL_WebOb(request)
        return Page(self.my().all(), page, url=page_url, items_per_page=12)

    def bookmark(self, id):
        return self.my().filter(Bookmark.id == id).first()

    def bookmark_tags(self, request, string='', page=1):
        page_url = PageURL_WebOb(request)
        tag = "%" + string + "%"
        bookmarks = self.my().filter(Bookmark.tags.like(tag)).all()
        return Page(bookmarks, page, url=page_url, items_per_page=12)

    def bookmark_search(self, request, string='', page=1):
        page_url = PageURL_WebOb(request)
        string = "%" + string + "%"
        bookmarks = self.my().filter(or_(Bookmark.title.like(string),\
                                         Bookmark.url.like(string))).all()
        return Page(bookmarks, page, url=page_url, items_per_page=12)
Ejemplo n.º 44
0
def user_create_view(request):

    username = request.authenticated_userid

    if request.method == 'POST':

        try:
            manager = BCRYPTPasswordManager()
            username = request.params.get('username')
            password = request.params.get('password')
            hashed = manager.encode(password)
            email = request.params.get('email')
            user = User.add(
                username=username,
                password=hashed,
                email=email,
            )
            Criteria.add(user=user)
            headers = remember(request, username)

            return HTTPFound(request.route_url('send_email'), headers=headers)
        except:
            return {}
    return {'username': username}
Ejemplo n.º 45
0
class User(Base):
    __tablename__ = 'stucco_user'

    # When fallbacks are set, DelegatingPasswordManager will recognize
    # and automatically upgrade those password formats to the preferred
    # format when the correct password is provided:
    passwordmanager = DelegatingPasswordManager(
        preferred=BCRYPTPasswordManager(),
        fallbacks=(PlaceholderPasswordChecker(), ))

    user_id = Column(Integer, primary_key=True, nullable=False)
    username = Column(Unicode(32), unique=True, nullable=False, index=True)
    first_name = Column(Unicode(64))
    last_name = Column(Unicode(64))
    email = Column(Unicode(254))
    password = Column(String(80), default='*', nullable=False)
    is_active = Column(Boolean, default=True, nullable=False)
    last_login = Column(DateTime)
    last_password_change = Column(DateTime, default=datetime.date(2001, 1, 1))
    date_joined = Column(DateTime, default=sqlalchemy.func.current_timestamp())

    groups = relationship(Group, secondary=users_groups, backref="users")

    @property
    def is_anonymous(self):
        return False

    def set_password(self, raw_password):
        self.password = self.passwordmanager.encode(raw_password)
        self.last_password_change = sqlalchemy.func.current_timestamp()

    def check_password(self, raw_password):
        if not self.is_active:
            return False
        return self.passwordmanager.check(self.password,
                                          raw_password,
                                          setter=self.set_password)

    def __str__(self):
        # XXX self.user_id is None for new users
        return 'user:%s' % self.user_id
Ejemplo n.º 46
0
class User(Folder):
    """ Represents a user.  """

    pwd_manager = BCRYPTPasswordManager()

    groupids = multireference_sourceid_property(UserToGroup)
    groups = multireference_source_property(UserToGroup)

    def __init__(self, password, email):
        Folder.__init__(self)
        self.password = self.pwd_manager.encode(password)
        self.email = email

    def check_password(self, password):
        """ Checks if the plaintext password passed as ``password`` matches
        this user's stored, encrypted passowrd.  Returns ``True`` or
        ``False``."""
        return self.pwd_manager.check(self.password, password)

    def set_password(self, password):
        self.password = self.pwd_manager.encode(password)

    def email_password_reset(self, request):
        """ Sends a password reset email."""
        root = request.root
        sitename = getattr(root, 'title', None) or 'Substance D'
        principals = find_service(self, 'principals')
        resets = principals['resets']
        reset = resets.add_reset(self)
        reseturl = request.application_url + request.mgmt_path(reset)
        message = Message(subject='Account information for %s' % sitename,
                          recipients=[self.email],
                          body=render('templates/resetpassword_email.pt',
                                      dict(reseturl=reseturl)))
        mailer = get_mailer(request)
        mailer.send(message)
Ejemplo n.º 47
0
    def check_password(cls, **kwargs):
        if kwargs.has_key('id'):
            user = cls.get_by_id(kwargs['id'])
        if kwargs.has_key('login'):
            user = cls.get_by_login(kwargs['login'])

        if not user:
            return False
        try:
            if BCRYPTPasswordManager().check(user.password,
                '%s%s' % (kwargs['password'], user.salt)):
                return True
        except TypeError:
            pass

        request = get_current_request()
        fallback_auth = request.registry.settings.get('apex.fallback_auth')
        if fallback_auth:
            resolver = DottedNameResolver(fallback_auth.split('.', 1)[0])
            fallback = resolver.resolve(fallback_auth)
            return fallback().check(DBSession, request, user, \
                       kwargs['password'])

        return False
Ejemplo n.º 48
0
 def test_fail_1(self):
     def return_none(*args): return None
     bcrypt = BCRYPTPasswordManager()
     bcrypt.crypt_gensalt_rn = return_none
     bcrypt.encode('foo')
Ejemplo n.º 49
0
 def setup(self):
     self.manager = BCRYPTPasswordManager()
Ejemplo n.º 50
0
class TestBCRYPTPasswordManager(object):
    snowpass = "******"

    def setup(self):
        self.manager = BCRYPTPasswordManager()

    @raises(TypeError)
    def test_None1(self):
        self.manager.encode(None)

    @raises(TypeError)
    def test_None2(self):
        self.manager.check(None, 'xyzzy')

    @raises(TypeError)
    def test_None3(self):
        hash = self.manager.encode('xyzzy')
        self.manager.check(hash, None)

    def test_badhash(self):
        eq_(self.manager.check('$p5k2$400$ZxK4ZBJCfQg=$kBpklVI9kA13kP32HMZL0rloQ1M=', self.snowpass), False)

    @raises(ValueError)
    def test_shorthash(self):
        manager = BCRYPTPasswordManager()
        def match(hash):
            return True
        manager.match = match
        short_hash = manager.encode(self.snowpass)[:28]
        assert_true(manager.match(short_hash))
        manager.check(short_hash, self.snowpass)

    @raises(ValueError)
    def test_too_few_rounds(self):
        self.manager.encode(self.snowpass, rounds=1)

    @raises(ValueError)
    def test_too_many_rounds(self):
        self.manager.encode(self.snowpass, rounds=100)

    def test_emptypass(self):
        self.manager.encode('')

    def test_general(self):
        manager = self.manager
        hash = manager.encode(self.snowpass)
        eq_(manager.match(hash), True)
        eq_(len(hash), 60)
        assert_true(manager.check(hash, self.snowpass))
        password = "******"
        hash = manager.encode(password)
        assert_true(manager.check(hash, password))
        assert_true(manager.check(unicode(hash), password))
        assert_false(manager.check(password, password))
        assert_not_equal(manager.encode(password), manager.encode(password))
        hash = manager.encode(password, rounds=4)
        assert_true(manager.check(hash, password))
    
    @raises(ValueError)
    def test_fail_1(self):
        def return_none(*args): return None
        bcrypt = BCRYPTPasswordManager()
        bcrypt.crypt_gensalt_rn = return_none
        bcrypt.encode('foo')

    @raises(ValueError)
    def test_fail_2(self):
        def return_none(*args): return None
        bcrypt = BCRYPTPasswordManager()        
        bcrypt.crypt_rn = return_none
        bcrypt.encode('foo')

    @raises(ValueError)
    def test_fail_3(self):
        def return_none(*args): return None
        bcrypt = BCRYPTPasswordManager()
        pw = bcrypt.encode('foobar')
        bcrypt.crypt_rn = return_none
        bcrypt.check(pw, 'foo')
Ejemplo n.º 51
0
 def test_fail_2(self):
     def return_none(*args): return None
     bcrypt = BCRYPTPasswordManager()        
     bcrypt.crypt_rn = return_none
     bcrypt.encode('foo')
Ejemplo n.º 52
0
 def verify_password(self, password):
     manager = Manager()
     return manager.check(self.password, password)
Ejemplo n.º 53
0
 def test_fail_3(self):
     def return_none(*args): return None
     bcrypt = BCRYPTPasswordManager()
     pw = bcrypt.encode('foobar')
     bcrypt.crypt_rn = return_none
     bcrypt.check(pw, 'foo')
Ejemplo n.º 54
0
 def _set_password(self, password):
     self.salt = self.get_salt(24)
     password = password + self.salt
     self._password = BCRYPTPasswordManager().encode(password, rounds=12)