Example #1
0
    def client(self):
        """
        Lazily load the Stormpath Client object we need to access the raw
        Stormpath SDK.
        """
        ctx = stack.top
        if ctx is not None:
            if not hasattr(ctx, 'stormpath_client'):

                # If the user is specifying their credentials via a file path,
                # we'll use this.
                if self.app.config['STORMPATH_API_KEY_FILE']:
                    ctx.stormpath_client = Client(
                        api_key_file_location=self.app.
                        config['STORMPATH_API_KEY_FILE'], )

                # If the user isn't specifying their credentials via a file
                # path, it means they're using environment variables, so we'll
                # try to grab those values.
                else:
                    ctx.stormpath_client = Client(
                        id=self.app.config['STORMPATH_API_KEY_ID'],
                        secret=self.app.config['STORMPATH_API_KEY_SECRET'],
                    )

            return ctx.stormpath_client
Example #2
0
    def client(self):
        """
        Lazily load the Stormpath Client object we need to access the raw
        Stormpath SDK.
        """
        ctx = stack.top
        if ctx is not None:
            if not hasattr(ctx, 'stormpath_client'):

                # Create our custom user agent.  This allows us to see which
                # version of this SDK are out in the wild!
                user_agent = 'stormpath-flask/%s (flask %s)' % (__version__, flask_version)

                # If the user is specifying their credentials via a file path,
                # we'll use this.
                if self.app.config['STORMPATH_API_KEY_FILE']:
                    ctx.stormpath_client = Client(
                        api_key_file_location = self.app.config['STORMPATH_API_KEY_FILE'],
                        user_agent = user_agent,
                    )

                # If the user isn't specifying their credentials via a file
                # path, it means they're using environment variables, so we'll
                # try to grab those values.
                else:
                    ctx.stormpath_client = Client(
                        id = self.app.config['STORMPATH_API_KEY_ID'],
                        secret = self.app.config['STORMPATH_API_KEY_SECRET'],
                        user_agent = user_agent,
                    )

            return ctx.stormpath_client
Example #3
0
    def test_base_url(self):
        client = Client(id=self.api_key_id, secret=self.api_key_secret)
        self.assertEqual(client.BASE_URL, 'https://api.stormpath.com/v1')

        client = Client(id=self.api_key_id,
                        secret=self.api_key_secret,
                        base_url='https://example.com')
        self.assertEqual(client.BASE_URL, 'https://example.com')
Example #4
0
    def test_auth_method(self, session):
        tenant_return = MagicMock(
            status_code=200,
            json=MagicMock(
                return_value={'applications': {
                    'href': 'applications'
                }}))

        app_return = MagicMock(status_code=200,
                               json=MagicMock(return_value={'name': 'LCARS'}))

        with patch('stormpath.client.Auth.digest', new_callable=PropertyMock) \
                as digest:
            with patch('stormpath.client.Auth.basic',
                       new_callable=PropertyMock) as basic:

                client = Client(api_key={'id': 'MyId', 'secret': 'Shush!'})
                session.return_value.request.return_value = tenant_return
                application = client.applications.get('application_url')
                session.return_value.request.return_value = app_return
                application.name
                self.assertTrue(digest.called)
                self.assertFalse(basic.called)

                digest.reset_mock()
                client = Client(api_key={
                    'id': 'MyId',
                    'secret': 'Shush!'
                },
                                method='digest')
                session.return_value.request.return_value = tenant_return
                application = client.applications.get('application_url')
                session.return_value.request.return_value = app_return
                application.name
                self.assertTrue(digest.called)
                self.assertFalse(basic.called)

                digest.reset_mock()
                client = Client(api_key={'id': 'MyId', 'secret': 'Shush!'})
                session.return_value.request.return_value = tenant_return
                application = client.applications.get('application_url')
                session.return_value.request.return_value = app_return
                application.name
                self.assertTrue(digest.called)
                self.assertFalse(basic.called)

                digest.reset_mock()
                client = Client(api_key={
                    'id': 'MyId',
                    'secret': 'Shush!'
                },
                                method='basic')
                session.return_value.request.return_value = tenant_return
                application = client.applications.get('application_url')
                session.return_value.request.return_value = app_return
                application.name
                self.assertFalse(digest.called)
                self.assertTrue(basic.called)
Example #5
0
    def test_proxies(self, session, auth):
        proxies = {
            'https': 'https://i-am-so-secure.com',
            'http': 'http://i-want-to-be.secure.org'}
        client = Client(api_key={'id': 'MyId', 'secret': 'Shush!'},
            proxies=proxies)
        self.assertEqual(client.data_store.executor.session.proxies, proxies)

        client = Client(api_key={'id': 'MyId', 'secret': 'Shush!'})
        self.assertEqual(client.data_store.executor.session.proxies, {})
Example #6
0
    def test_digest_authentication(self):
        client = Client(id=self.api_key_id,
                        secret=self.api_key_secret,
                        scheme='SAuthc1')
        list(client.applications)

        client = Client(id=self.api_key_id + 'x',
                        secret=self.api_key_secret + 'x',
                        scheme='SAuthc1')
        with self.assertRaises(Error):
            list(client.applications)
Example #7
0
def index():
    if user.is_authenticated():
        return redirect(url_for('success'))
    client = Client(api_key_file_location=app.config['STORMPATH_API_KEY_FILE'])
    a = client.applications.search(app.config['STORMPATH_APPLICATION'])[0]

    html = ''
    # delete user if it already exists
    email = '*****@*****.**'
    for i in a.accounts:
        if i.email == email:
            html = html + 'deleting account ' + i.email + '<br>'
            i.delete()

    # create the account
    password = '******'
    username = '******'
    html = html + 'creating account ' + email + '<br>'
    account = a.accounts.create({
        'given_name': 'John',
        'surname': 'Doe',
        'username': username,
        'email': email,
        'password': password,
    })

    html = html + '''
        Login using these credentials:<br>
        <b>%s <br></b>
        <b>%s <br></b>
        <a href="/login">Login</a>
        ''' % (email, password)
    return html
Example #8
0
    def test_digest_authentication_fails(self):
        client = Client(id=self.api_key_id + 'x',
                        secret=self.api_key_secret + 'x',
                        scheme='SAuthc1')

        # force the SDK to make a call to the server
        with self.assertRaises(Error):
            list(client.applications)
Example #9
0
 def test_basic_authentication_with_api_key_succeeds(self):
     api_key = {
         'api_key_id': self.api_key_id,
         'api_key_secret': self.api_key_secret
     }
     client = Client(api_key=api_key, scheme='basic')
     # force the SDK to make a call to the server
     list(client.applications)
Example #10
0
def bootstrap_client():
    """
    Create a new Stormpath Client from environment variables.

    :rtype: obj
    :returns: A new Stormpath Client, fully initialized.
    """
    return Client(
        id=environ.get('STORMPATH_API_KEY_ID'),
        secret=environ.get('STORMPATH_API_KEY_SECRET'),
    )
    def test_cache_opts_with_different_cache_stores(self):
        cache_opts = {
            'regions': {
                'customData': {
                    'store': NullCacheStore,
                }
            }
        }

        client = Client(id=self.api_key_id,
                        secret=self.api_key_secret,
                        scheme=self.AUTH_SCHEME,
                        cache_options=cache_opts)

        app_name = self.get_random_name()
        app = client.applications.create({
            'name': app_name,
            'description': 'test app',
            'custom_data': {
                'a': 1
            }
        })
        href = app.href

        # this will cache application
        self.assertEqual(Application(client, href=href).name, app_name)

        # pretend that app name is changed elsewhere
        properties = app._get_properties()
        properties['name'] = 'changed %s' % app_name
        client.data_store.executor.post(app.href, properties)

        # we get stale, cached app name
        self.assertEqual(Application(client, href=href).name, app_name)

        # unless we refresh
        app.refresh()
        self.assertEqual(
            Application(client, href=href).name, properties['name'])

        # this will not cache custom data
        self.assertEqual(Application(client, href=href).custom_data['a'], 1)

        # pretend that app's custom data is changed elsewhere
        properties = app.custom_data._get_properties()
        properties['a'] = 2
        client.data_store.executor.post(app.custom_data.href, properties)

        # we get fresh custom data
        self.assertEqual(Application(client, href=href).custom_data['a'], 2)

        app.delete()
Example #12
0
    def test_client(self):

        # get the client
        print 'STORMPATH_API_KEY_FILE =', STORMPATH_API_KEY_FILE
        print 'STORMPATH_APPLICATION =', STORMPATH_APPLICATION
        client = Client(api_key_file_location=STORMPATH_API_KEY_FILE)

        # get the app
        apps = client.applications.search(STORMPATH_APPLICATION)
        assert len(apps) == 1
        app = apps[0]

        # delete user if it already exists
        email = '*****@*****.**'
        for i in app.accounts:
            print 'email', i.email
            if i.email == email:
                print 'deleting existing account', i
                i.delete()

        # create the account
        password = '******'
        print 'creating account', email
        account = app.accounts.create({
            'given_name': 'John',
            'surname': 'Doe',
            'username': '******',
            'email': email,
            'password': password,
        })

        # authenticate
        app.authenticate_account(email, password)

        # bad authentication
        caught_bad_password = False
        try:
            app.authenticate_account(email, 'badpassword')
        except Error as re:
            # Will output: 400
            print 'caught error', re.status
            # Will output: "Invalid username or password."
            print 'caught error', re.message
            # Will output: "mailto:[email protected]"
            print 'caught error', re.more_info
            caught_bad_password = True

        assert caught_bad_password

        # cleanup
        account.delete()
Example #13
0
    def setUp(self):
        self.apiKeyId = os.getenv("STORMPATH_SDK_TEST_API_KEY_ID")
        self.apiKeySecret = os.getenv("STORMPATH_SDK_TEST_API_KEY_SECRET")
        self.client = Client(api_key={
            'id': self.apiKeyId,
            'secret': self.apiKeySecret
        })

        self.created_accounts = []
        self.created_applications = []
        self.created_directories = []
        self.created_group_memberships = []
        self.created_groups = []
        self.created_account_stores = []
Example #14
0
    def test_cache_options(self):
        client = Client(id=self.api_key_id,
                        secret=self.api_key_secret,
                        cache_options={
                            'regions': {
                                'customData': {
                                    'store': NullCacheStore
                                }
                            }
                        })

        self.assertIsInstance(
            client.data_store.cache_manager.caches['customData'].store,
            NullCacheStore)
Example #15
0
    def test_basic_authentication(self):
        client = Client(id=self.api_key_id,
                        secret=self.api_key_secret,
                        scheme='basic')
        list(client.applications)

        api_key = {
            'api_key_id': self.api_key_id,
            'api_key_secret': self.api_key_secret
        }
        client = Client(api_key=api_key, scheme='basic')
        list(client.applications)

        client = Client(api_key_id=self.api_key_id,
                        api_key_secret=self.api_key_secret,
                        scheme='basic')
        list(client.applications)

        client = Client(id=self.api_key_id + 'x',
                        secret=self.api_key_secret + 'x',
                        scheme='basic')
        with self.assertRaises(Error):
            list(client.applications)
Example #16
0
def pytest_keyboard_interrupt(excinfo):
    collection_resources = ['applications', 'organizations', 'directories']
    test_prefix = 'stormpath-sdk-python-test'
    auth_scheme = 'basic'
    base_url = getenv('STORMPATH_BASE_URL')
    api_key_id = getenv('STORMPATH_API_KEY_ID')
    api_key_secret = getenv('STORMPATH_API_KEY_SECRET')

    client = Client(id=api_key_id,
                    secret=api_key_secret,
                    base_url=base_url,
                    scheme=auth_scheme)
    for collection in collection_resources:
        for resource in list(getattr(client, collection).search(test_prefix)):
            resource.delete()
    def save(self):
        super(ChirperCreateForm, self).save()
        client = Client(api_key={
            'id': settings.STORMPATH_ID,
            'secret': settings.STORMPATH_SECRET
        })
        account_type = self.cleaned_data['account_type']
        if account_type == 'Admins':
            admin_group = client.groups.get(settings.STORMPATH_ADMINISTRATORS)
            self.account.add_group(admin_group)
            self.account.save()

        elif account_type == 'Premiums':
            premium_group = client.groups.get(settings.STORMPATH_PREMIUMS)
            self.account.add_group(premium_group)
            self.account.save()
    def test_resource_init_with_partial_href(self, session):
        session.return_value.request.return_value = MagicMock(
            status_code=200,
            json=MagicMock(return_value={'name': 'My Application'}))

        self.client = Client(api_key={
            'id': 'MyId',
            'secret': 'Shush!'
        },
                             base_url='https://enterprise.stormpath.io/v1')
        r = Resource(self.client, href='/application/APP_UID')

        self.assertEqual(r.name, 'My Application')
        session.return_value.request.assert_called_once_with(
            'GET',
            'https://enterprise.stormpath.io/v1/application/APP_UID',
            params=None,
            allow_redirects=False,
            data=None)
Example #19
0
def init(args):
    """Downloads and installs a Stormpath sample project for the given platform."""
    from .main import USER_AGENT

    try:
        auth_args = init_auth(args)
        client = Client(user_agent=USER_AGENT, **auth_args)
    except ValueError as ex:
        get_logger().error(str(ex))
        exit(1)

    type = args.get('<resource>')
    name = args.get('<attributes>')

    if name and len(name) > 0:
        name = name[0].split('name=')[1]

    sample_project = Project.create_from_type(type, name)
    sample_project.download()
    sample_project.create_app(client)
    sample_project.install()
Example #20
0
        'account': acc,
        'group': group
    })

def render_nginx_conf(app, group):
    tpl = open(NGINX_CONF_IN).read()
    conf = tpl % {
        'app_href': app.href,
        'group_href': group.href
    }
    with open(NGINX_CONF, 'w') as fp:
        fp.write(conf)

def render_apikey_properties():
    tpl = open(APIKEY_PROPERTIES_IN).read()
    prop = tpl % os.environ
    with open(APIKEY_PROPERTIES, 'w') as fp:
        fp.write(prop)

# if id/secret are not in environment, this will terminate the setup script
c = Client()

app = ensure_test_app(c)
group = ensure_test_group(app)
primary = ensure_test_account(app, PRIMARY_ACC_NAME)
secondary = ensure_test_account(app, SECONDARY_ACC_NAME)
ensure_account_in_group(c, group, primary)

render_nginx_conf(app, group)
render_apikey_properties()
Example #21
0
from django.db import models
from django.conf import settings
from django_stormpath.models import StormpathUser
from stormpath.client import Client

CLIENT = Client(id=settings.STORMPATH_ID, secret=settings.STORMPATH_SECRET)


class Chirp(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    message = models.TextField(max_length=160, verbose_name='')
    created_at = models.DateTimeField(auto_now_add=True)
    owner_is_admin = models.BooleanField(default=False)
    owner_is_premium = models.BooleanField(default=False)

    class Meta:
        ordering = ['-created_at']


class ChirperUser(StormpathUser):
    def is_admin(self):
        admin_group = CLIENT.groups.get(settings.STORMPATH_ADMINISTRATORS)
        return len(admin_group.accounts.search({'email': self.email}))

    def is_premium(self):
        premium_group = CLIENT.groups.get(settings.STORMPATH_PREMIUMS)
        return len(premium_group.accounts.search({'email': self.email}))
Example #22
0
from stormpath.client import Client

client = Client(id='xxx', secrety='yyy', scheme='basic')
Example #23
0
from stormpath.cache.redis_store import RedisStore
from stormpath.client import Client

client = Client(id='xxx',
                secret='xxx',
                cache_options={
                    'store': RedisStore,
                    'store_opts': {
                        'host': 'localhost',
                        'port': 6739,
                    },
                    'ttl': 300,
                    'tti': 300,
                })
Example #24
0
def main():
    arguments = docopt(__doc__)
    action = arguments.get('<action>')
    resource = arguments.get('<resource>')

    log = setup_output(arguments.get('--verbose'))

    arguments.update(get_context_dict())
    arguments, resource, action = find_non_dash_arguments_and_default_action(
        arguments, resource, action)
    arguments = properly_support_boolean_values(arguments)
    arguments = check_primary_identifier_without_flags(arguments, resource,
                                                       action)

    if not action:
        log.error(__doc__.strip('\n'))
        return -1

    if action == 'help':
        log.error(__doc__.strip('\n'))
        return -1

    if action not in AVAILABLE_ACTIONS:
        log.error(
            "Unknown action '{}'. See 'stormpath --help' for list of available actions."
            .format(action))
        return -1

    if action in LOCAL_ACTIONS:
        return 0 if AVAILABLE_ACTIONS[action](arguments) else -1

    if not resource and action != STATUS_ACTION:
        if action == SET_ACTION:
            log.error(
                "A resource type is required. Available resources for the set command are: application, directory. Please see 'stormpath --help'"
            )
            return -1

        log.error(
            "A resource type is required. Available resources: {}. Please see 'stormpath --help'"
            .format(', '.join(sorted(AVAILABLE_RESOURCES.keys()))))
        return -1

    if resource not in AVAILABLE_RESOURCES and action != STATUS_ACTION:
        log.error(
            "Unknown resource type '{}'. See 'stormpath --help' for list of available resource types."
            .format(resource))
        return -1

    try:
        auth_args = init_auth(arguments)
        client = Client(user_agent=USER_AGENT, **auth_args)
    except ValueError as ex:
        log.error(str(ex))
        return -1

    if action == STATUS_ACTION:
        return 0 if AVAILABLE_ACTIONS[action](client, arguments) else -1

    try:
        res = AVAILABLE_RESOURCES[resource](client, arguments)
    except ValueError as ex:
        log.error(str(ex))
        return -1

    act = AVAILABLE_ACTIONS[action]

    try:
        result = act(res, arguments)
    except (StormpathError, ValueError) as ex:
        log.error(str(ex))
        return -1

    if result is not None and (isinstance(result, list) or isinstance(
            result, dict) or isinstance(result, types.GeneratorType)):
        output(result,
               show_links=arguments.get('--show-links', False),
               show_headers=arguments.get('--show-headers', False),
               output_json=arguments.get('--output-json', False))
    return 0
Example #25
0
import traceback
from stormpath.client import Client
from os import environ, path

from Connector import Database
from Validater import Validate
from CustomException import ValidatorException

DEBUG = True

abspath = path.dirname(path.abspath(__file__))

# Create a new Stormpath Client.
apiKeys = path.join(abspath, '../security/apiKey.properties')
client = Client(api_key_file_location=apiKeys)
href = environ['STORMPATH_APPLICATION_HREF']

# Retrieve our application
stormApp = client.applications.get(href)


class Registration(Database):
    """ A class that registers new student accounts

	To create a student account for a user, include this module
	and use methods to insert account information about user.
	"""
    def __init__(self):
        super(Registration, self).__init__()
        # Get connection & cursor from Database
Example #26
0
    def test_tenant_expansion(self):
        e = Expansion()
        e.add_property('bar', limit=5)
        client = Client(api_key={'id': 'MyId', 'secret': 'Shush!'}, expand=e)

        self.assertIsInstance(client.tenant._expand, Expansion)
from stormpath.cache.null_cache_store import NullCacheStore
from stormpath.client import Client

client = Client(id='xxx',
                secret='yyy',
                cache_options={'store': NullCacheStore})
Example #28
0
from os.path import expanduser, join

from stormpath.client import Client

# This is the absolute path to the file ~/.stormpath/apiKey.properties
# downloaded in the previous section.  This will work on any OS.
API_KEY_FILE = join(expanduser('~'), '.stormpath', 'apiKey.properties')

client = Client(api_key_file=API_KEY_FILE)
Example #29
0
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.signals import pre_save, pre_delete
from django.contrib.auth.models import Group
from django.dispatch import receiver
from django import VERSION as django_version

from stormpath.client import Client
from stormpath.error import Error as StormpathError

from django_stormpath import __version__

USER_AGENT = 'stormpath-django/%s django/%s' % (__version__, django_version)

CLIENT = Client(id=settings.STORMPATH_ID,
                secret=settings.STORMPATH_SECRET,
                user_agent=USER_AGENT,
                cache_options=getattr(settings, 'STORMPATH_CACHE_OPTIONS',
                                      None))

APPLICATION = CLIENT.applications.get(
    settings.STORMPATH_APPLICATION) if settings.STORMPATH_APPLICATION else None


class StormpathPermissionsMixin(PermissionsMixin):
    pass


class StormpathUserManager(BaseUserManager):
    def create(self, *args, **kwargs):
        return self.create_user(*args, **kwargs)
Example #30
0
"""


from os import environ
from sys import exit

from flask import Flask, jsonify, request
from stormpath.client import Client


##### GLOBALS
app = Flask(__name__)

try:
    stormpath_app = Client(
        id = environ.get('STORMPATH_API_KEY_ID'),
        secret = environ.get('STORMPATH_API_KEY_SECRET'),
    ).applications.search('flask-api-sample')[0]
except:
    print "Error! Couldn't find the Stormpath application."
    exit(1)


##### API
@app.route('/')
def api():
    """Simple API endpoint which requires user authention to access.

    Users can access this endpoint by using HTTP Basic Authentication when
    making their HTTP request to the service.

    We'll then use Stormpath's API to authenticate the user securely.