Exemplo n.º 1
0
 def authenticate(self):
     self.oauth2_token = self.redis_portal_session.get_oauth2_token(
         self.authenticated_on_backend())
     if not self.oauth2_token:
         authentication_results = super().authenticate(None)
         logger.debug(
             "OAUTH2_AUTH::authenticate: Oauth2 attributes : {}".format(
                 str(authentication_results['data'])))
         if authentication_results['data'].get('oauth2', None) is not None:
             self.oauth2_token = Uuid4().generate()
             self.register_authentication(
                 authentication_results['data']['oauth2'])
             authentication_results = authentication_results['data'][
                 'oauth2']
         elif self.application.enable_oauth2:
             authentication_results = {
                 'token_return_type': 'both',
                 'token_ttl': self.application.auth_timeout,
                 'scope': '{}'
             }
             self.oauth2_token = Uuid4().generate()
             self.register_authentication(authentication_results)
         else:
             raise AuthenticationError(
                 "OAUTH2_AUTH::authenticate: OAuth2 is not enabled on this app nor on this repository"
             )
     else:
         # REPLACE CREDENTIAL 'user"
         self.redis_oauth2_session = REDISOauth2Session(
             self.redis_base, "oauth2_" + self.oauth2_token)
         authentication_results = self.redis_oauth2_session.keys
     return authentication_results
def run_auth_server():
    try:
        client = MongoClient('localhost', 27017)

        db = client.test_database

        client_store = ClientStore(collection=db["clients"])

        token_store = AccessTokenStore(collection=db["access_tokens"])
        code_store = AuthCodeStore(collection=db["auth_codes"])

        provider = Provider(
            access_token_store=token_store,
            auth_code_store=code_store,
            client_store=client_store,
            token_generator=Uuid4())
        provider.add_grant(
            AuthorizationCodeGrant(site_adapter=TestSiteAdapter(), scopes=["basic", "big", "long"],
                                   unique_token=True,
                                   expires_in=20
                                   )
        )

        provider.add_grant(
            RefreshToken(scopes=["basic", "big", "long"], expires_in=2592000, reissue_refresh_tokens=True)
        )

        app = Application(provider=provider)

        httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler)

        print("Starting OAuth2 server on http://localhost:8080/...")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
def run_auth_server():
    try:
        client_store = ClientStore()
        client_store.add_client(
            client_id="abc",
            client_secret="xyz",
            redirect_uris=["http://localhost:8081/callback"])

        token_store = TokenStore()

        auth_controller = Provider(access_token_store=token_store,
                                   auth_code_store=token_store,
                                   client_store=client_store,
                                   site_adapter=TestSiteAdapter(),
                                   token_generator=Uuid4())
        auth_controller.add_grant(AuthorizationCodeGrant())

        app = Wsgi(server=auth_controller)

        httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler)

        print(
            "Starting implicit_grant oauth2 server on http://localhost:8080/..."
        )
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
Exemplo n.º 4
0
def create_auth_server():
    client_store = ClientStore()
    client_store.add_client(
        client_id="alexa.matsuoka",
        client_secret="xxxx",
        redirect_uris=[
            "https://layla.amazon.com/api/skill/link/M2Q7FOC6AVxxxx",
            "https://pitangui.amazon.com/api/skill/link/M2Q7FOC6AVxxxx",
            "https://alexa.amazon.co.jp/api/skill/link/M2Q7FOC6AVxxxx"
        ])

    token_store = TokenStore()
    token_store.save_token(
        AccessToken(client_id="alexa.matsuoka",
                    grant_type="authorization_code",
                    user_id="*****@*****.**",
                    token="xxxx"))

    provider = Provider(access_token_store=token_store,
                        auth_code_store=token_store,
                        client_store=client_store,
                        token_generator=Uuid4(),
                        client_authentication_source=http_basic_auth)
    provider.add_grant(
        AuthorizationCodeGrant(site_adapter=TestSiteAdapter(),
                               unique_token=True))

    app = Application([
        url(provider.authorize_path, OAuth2Handler, dict(provider=provider)),
        url(provider.token_path, OAuth2Handler, dict(provider=provider)),
    ],
                      debug=False)

    return app
Exemplo n.º 5
0
    def test_create_access_token_data_no_expiration(self):
        generator = Uuid4()

        result = generator.create_access_token_data('test_grant_type')

        self.assertRegexpMatches(result["access_token"], self.uuid_regex)
        self.assertEqual(result["token_type"], "Bearer")
Exemplo n.º 6
0
def run_auth_server():
    try:
        client_store = ClientStore()
        client_store.add_client(client_id="abc", client_secret="xyz",
                                redirect_uris=[])

        token_store = TokenStore()
        token_gen = Uuid4()
        token_gen.expires_in['client_credentials'] = 3600

        auth_controller = Provider(
            access_token_store=token_store,
            auth_code_store=token_store,
            client_store=client_store,
            token_generator=token_gen)
        auth_controller.add_grant(ClientCredentialsGrant())

        app = Application(provider=auth_controller)

        httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler)

        print("Starting implicit_grant oauth2 server on http://localhost:8080/...")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
Exemplo n.º 7
0
    def register_user(self, authentication_results):
        oauth2_token = None
        # No OAuth2 disabled
        # if self.application.enable_oauth2:
        timeout = self.workflow.authentication.auth_timeout
        oauth2_token = Uuid4().generate()
        self.redis_oauth2_session = REDISOauth2Session(
            self.redis_base, "oauth2_" + oauth2_token)
        if authentication_results['data'].get('oauth2', None):
            self.redis_oauth2_session.register_authentication(
                authentication_results['data']['oauth2'],
                authentication_results['data']['oauth2']['token_ttl'])
        else:
            self.redis_oauth2_session.register_authentication(
                {
                    'scope': '{}',
                    'token_return_type': 'both',
                    'token_ttl': timeout
                }, timeout)
        logger.debug(
            "AUTH::register_user: Redis oauth2 session successfully written in Redis"
        )

        portal_cookie = self.redis_portal_session.register_authentication(
            str(self.workflow.id), str(self.workflow.name),
            str(self.backend_id), self.workflow.get_redirect_uri(),
            self.workflow.authentication.otp_repository, self.credentials[0],
            self.credentials[1], oauth2_token, authentication_results['data'],
            timeout)
        logger.debug(
            "AUTH::register_user: Authentication results successfully written in Redis portal session"
        )

        return portal_cookie, oauth2_token
Exemplo n.º 8
0
def main():
    client = MongoClient()

    db = client.testdb

    access_token_store = AccessTokenStore(collection=db["access_tokens"])
    auth_code_store = AuthCodeStore(collection=db["auth_codes"])
    client_store = ClientStore(collection=db["clients"])

    provider = Provider(access_token_store=access_token_store,
                        auth_code_store=auth_code_store,
                        client_store=client_store,
                        site_adapter=TestSiteAdapter(),
                        token_generator=Uuid4())

    provider.add_grant(AuthorizationCodeGrant())
    provider.add_grant(ImplicitGrant())
    provider.add_grant(ResourceOwnerGrant())
    provider.add_grant(ClientCredentialsGrant())
    provider.add_grant(RefreshToken(expires_in=600))

    provider.enable_unique_tokens()

    app = Wsgi(server=provider)

    try:
        httpd = make_server('', 8888, app)
        print("Starting test auth server on port 8888...")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
Exemplo n.º 9
0
        def run_provider(queue):
            try:

                redirect_uri = "http://127.0.0.1:15487/callback"

                stores = store_factory(client_identifier="abc",
                                       client_secret="xyz",
                                       redirect_uris=[redirect_uri])

                provider = Provider(
                    access_token_store=stores["access_token_store"],
                    auth_code_store=stores["auth_code_store"],
                    client_store=stores["client_store"],
                    site_adapter=TestSiteAdapter(),
                    token_generator=Uuid4())

                provider.add_grant(AuthorizationCodeGrant(expires_in=120))
                provider.add_grant(RefreshToken(expires_in=60))

                app = Wsgi(server=provider)

                httpd = make_server('',
                                    15486,
                                    app,
                                    handler_class=NoLoggingHandler)

                queue.put({"result": 0})

                httpd.serve_forever()
            except Exception as e:
                queue.put({"result": 1, "error_message": str(e)})
Exemplo n.º 10
0
def run_auth_server():
    client_store = ClientStore()
    client_store.add_client(client_id="abc", client_secret="xyz",
                            redirect_uris=["http://10.10.112.59:8081/callback"])
    client_store.add_client(client_id="bcd", client_secret="fff",
                            redirect_uris=["http://10.10.112.59:50000/callback"])
    client_store.add_client(client_id="9fdc2c7a1cee0cca54c150e3e0b822eb", client_secret="zzz",
                            redirect_uris=["http://10.10.112.59:8888/callback"])

    token_store = TokenStore()

    provider = Provider(access_token_store=token_store,
                        auth_code_store=token_store, client_store=client_store,
                        token_generator=Uuid4())
    provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter()))

    settings = dict(
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        cookie_secret='61oETzKXQAGaYdkL5gEmGEJJFuYh7EQnp2XdTP1o/Vo=',
    )
    try:
        app = Application([
            url(provider.authorize_path, OAuth2Handler, dict(provider=provider)),
            url(provider.token_path, OAuth2Handler, dict(provider=provider)),
            url("/", MainHandler),
        ], **settings)

        app.listen(8080)
        print "Starting OAuth2 server on http://10.10.112.59:8080/..."
        IOLoop.current().start()

    except KeyboardInterrupt:
        IOLoop.close()
def run_auth_server():
    try:
        client_store = ClientStore()
        client_store.add_client(client_id="abc",
                                client_secret="xyz",
                                redirect_uris=["http://localhost:8081/"])

        token_store = TokenStore()

        provider = Provider(access_token_store=token_store,
                            auth_code_store=token_store,
                            client_store=client_store,
                            token_generator=Uuid4())
        provider.add_grant(ImplicitGrant(site_adapter=TestSiteAdapter()))

        app = Application(provider=provider)

        httpd = make_server('', 8080, app)

        print(
            "Starting implicit_grant oauth2 server on http://localhost:8080/..."
        )
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
Exemplo n.º 12
0
def run_auth_server():
    client_store = ClientStore()
    # client_store.add_client(client_id="abc", client_secret="xyz",
    #                         redirect_uris=["http://localhost:8081/callback"])
    client_store.add_client(client_id="abc", client_secret="xyz",
                            redirect_uris=["http://localhost:8080/auth/realms/keycloak-express/broker/oidc/endpoint"])

    token_store = TokenStore()

    provider = Provider(access_token_store=token_store,
                        auth_code_store=token_store, client_store=client_store,
                        token_generator=Uuid4())
    provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter()))

    try:
        app = Application([
            url(provider.authorize_path, OAuth2Handler, dict(provider=provider)),
            url(provider.token_path, OAuth2Handler, dict(provider=provider)),
        ])

        app.listen(8090)
        print("Starting OAuth2 server on http://localhost:8090/...")
        IOLoop.current().start()

    except KeyboardInterrupt:
        IOLoop.close()
Exemplo n.º 13
0
    def send_lost_mail(self, request, email):

        # """ Generate an UUID64 and store it in redis """
        reset_key = Uuid4().generate()

        redis_key = 'password_reset_' + reset_key
        """ Store the reset-key in Redis """
        # The 'a' is for Redis stats, to make a distinction with Token entries
        self.redis_base.hmset(redis_key, {'email': email, 'a': 1})
        """ The key will expire in 10 minutes """
        self.redis_base.expire(redis_key, 600)
        """ Send the email with the link """
        reset_link = self.application.get_redirect_uri() + str(
            self.token_name) + '/self/change?rdm=' + reset_key

        msg = MIMEMultipart('alternative')
        email_from = self.application.template.email_from
        msg['From'] = email_from
        msg['To'] = email
        obj = {
            'name': self.application.name,
            'url': self.application.get_redirect_uri()
        }
        env = Environment(
            loader=FileSystemLoader("/home/vlt-gui/vulture/portal/templates/"))
        msg['subject'] = env.get_template(
            "portal_%s_email_subject.conf" %
            (str(self.application.template.id))).render({'app': obj})
        email_body = env.get_template(
            "portal_%s_email_body.conf" %
            (str(self.application.template.id))).render({
                'resetLink': reset_link,
                'app': obj
            })
        msg.attach(MIMEText(email_body, "html"))

        node = self.cluster.get_current_node()
        if hasattr(node.system_settings, 'smtp_settings') and getattr(
                node.system_settings, 'smtp_settings'):
            settings = getattr(node.system_settings, 'smtp_settings')
        else:
            """ Not found, use cluster settings for configuration """
            settings = getattr(self.cluster.system_settings, 'smtp_settings')

        try:
            logger.debug("Sending link '{}' to '{}'".format(reset_link, email))
            smtpObj = SMTP(settings.smtp_server)
            # message = "Subject: " + unicode (email_subject) + "\n\n" + unicode (email_body)
            smtpObj.sendmail(email_from, email, msg.as_string())
        except Exception as e:
            logger.error(
                "SELF::Lost: Failed to send email to '{}' : ".format(email))
            logger.exception(e)
            raise SMTPException(
                "<b>Send mail failure</b> <br> Please contact your administrator"
            )

        return "Mail successfully sent to '{}'".format(email)
Exemplo n.º 14
0
    def test_create_access_token_data_with_expiration(self):
        generator = Uuid4()
        generator.expires_in = {'test_grant_type': 600}

        result = generator.create_access_token_data('test_grant_type')

        self.assertRegexpMatches(result["access_token"], self.uuid_regex)
        self.assertEqual(result["token_type"], "Bearer")
        self.assertRegexpMatches(result["refresh_token"], self.uuid_regex)
        self.assertEqual(result["expires_in"], 600)
Exemplo n.º 15
0
    def test_generate(self):
        generator = Uuid4()

        result = generator.generate()

        regex = re.compile(self.uuid_regex)

        match = regex.match(result)

        self.assertEqual(result, match.group())
Exemplo n.º 16
0
    def __init__(self, request, site_adapter):
        self.request = Request(request)
        self.site_adapter = site_adapter
        self.token_generator = Uuid4()

        self.client_store = self._get_client_store()
        self.access_token_store = self._get_token_store()

        self.client_authenticator = ClientAuthenticator(
                                        client_store=self.client_store,
                                        source=request_body
                                    )

        self.grant_types = [];
Exemplo n.º 17
0
def main():
    parser = argparse.ArgumentParser(description="python-oauth2 test provider")
    parser.add_argument("--store", dest="store", type=str, default="mongodb",
                        help="The store adapter to use. Can one of 'mongodb'"\
                             "(default), 'mysql'")
    args = parser.parse_args()

    if args.store == "mongodb":
        print("Using mongodb stores...")
        client = MongoClient()

        db = client.testdb

        access_token_store = AccessTokenStore(collection=db["access_tokens"])
        auth_code_store = AuthCodeStore(collection=db["auth_codes"])
        client_store = ClientStore(collection=db["clients"])
    elif args.store == "mysql":
        print("Using mysql stores...")
        connection = mysql.connector.connect(host="127.0.0.1",
                                             user="******",
                                             passwd="",
                                             db="testdb")

        access_token_store = MysqlAccessTokenStore(connection=connection)
        auth_code_store = MysqlAuthCodeStore(connection=connection)
        client_store = MysqlClientStore(connection=connection)
    else:
        raise Exception("Unknown store")

    provider = Provider(access_token_store=access_token_store,
                        auth_code_store=auth_code_store,
                        client_store=client_store,
                        site_adapter=TestSiteAdapter(),
                        token_generator=Uuid4())

    provider.add_grant(AuthorizationCodeGrant(expires_in=120))
    provider.add_grant(ImplicitGrant())
    provider.add_grant(ResourceOwnerGrant())
    provider.add_grant(ClientCredentialsGrant())
    provider.add_grant(RefreshToken(expires_in=60))

    app = Wsgi(server=provider)

    try:
        httpd = make_server('', 8888, app)
        print("Starting test auth server on port 8888...")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
Exemplo n.º 18
0
def create_provider():
    redirect_uri = "http://127.0.0.1:15487/callback"

    stores = store_factory(client_identifier="abc",
                           client_secret="xyz",
                           redirect_uris=[redirect_uri])

    provider = Provider(access_token_store=stores["access_token_store"],
                        auth_code_store=stores["auth_code_store"],
                        client_store=stores["client_store"],
                        token_generator=Uuid4())

    provider.add_grant(
        AuthorizationCodeGrant(expires_in=120, site_adapter=TestSiteAdapter()))

    provider.add_grant(RefreshToken(expires_in=60))

    return provider
Exemplo n.º 19
0
def run_auth_server():
    try:
        client = MongoClient('localhost', 27017)

        db = client.test_database

        client_store = ClientStore(collection=db["clients"])

        # memory
        # client_store = ClientStore()
        # client_store.add_client(client_id="abc", client_secret="xyz",
        #                         redirect_uris=["http://localhost:8081/callback"])
        #
        # token_store = TokenStore()

        token_store = AccessTokenStore(collection=db["access_tokens"])
        code_store = AuthCodeStore(collection=db["auth_codes"])

        provider = Provider(access_token_store=token_store,
                            auth_code_store=code_store,
                            client_store=client_store,
                            token_generator=Uuid4())
        provider.add_grant(
            AuthorizationCodeGrant(site_adapter=TestSiteAdapter(),
                                   scopes=["test", "test2"],
                                   unique_token=True,
                                   expires_in=1))
        # auth_controller.add_grant_type(ResourceOwnerGrant(tokens_expire=600))
        provider.add_grant(
            RefreshToken(scopes=["test", "test2"],
                         expires_in=2592000,
                         reissue_refresh_tokens=True))
        # auth_controller.add_grant_type(RefreshToken(tokens_expire=1200))
        app = Application(provider=provider)

        httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler)

        print("Starting OAuth2 server on http://localhost:8080/...")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
Exemplo n.º 20
0
def run_auth_server(port=8282):
    print("Starting OAuth2 server on port:" + str(port))

    client_store = ClientStore()
    client_store.add_client(client_id="abc",
                            client_secret="xyz",
                            redirect_uris=["http://0.0.0.0:5000/"])

    token_store = TokenStore()

    provider = Provider(access_token_store=token_store,
                        auth_code_store=token_store,
                        client_store=client_store,
                        token_generator=Uuid4())
    provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter()))

    app = Application(provider=provider)

    httpd = make_server('', port, app, handler_class=OAuthRequestHandler)

    httpd.serve_forever()
Exemplo n.º 21
0
def run_auth_server():
	try:
		client_store = ClientStore()
		client_store.add_client(client_id="abc", client_secret="xyz",
								redirect_uris=["http://localhost:8081/callback"])

		token_store = TokenStore()

		provider = TestProvider(
			access_token_store=token_store,
			auth_code_store=token_store,
			client_store=client_store,
			token_generator=Uuid4())

		app = OAuthApplication(provider=provider)

		httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler)

		print("Starting OAuth2 server on http://localhost:8080/...")
		httpd.serve_forever()
	except KeyboardInterrupt:
		httpd.server_close()
Exemplo n.º 22
0
def main():
    token_store = AccessTokenStore()
    provider = Provider(access_token_store=token_store,
                        auth_code_store=token_store,
                        client_store=AuthUserStore(),
                        token_generator=Uuid4())
    provider.add_grant(
        ResourceOwnerGrant(site_adapter=AuthSiteAdapter(),
                           unique_token=True,
                           expires_in=ACCESS_TOKEN_REDIS_TTL))
    provider.add_grant(RefreshToken(expires_in=REFRESH_TOKEN_REDIS_TTL))

    app = Application(handlers=[
        url(provider.token_path, OAuth2Handler, dict(provider=provider)),
        url('/validate-token', AuthValidationHandler)
    ],
                      template_path=TEMPLATE_PATH,
                      static_path=STATIC_PATH,
                      cookie_secret=COOKIE_SECRET)

    print 'Starting OAuth Server on port %d' % options.port
    server = HTTPServer(app)
    server.listen(options.port)
    IOLoop.current().start()
Exemplo n.º 23
0
    def __init__(self, dbconnection):
        self.templates = os.path.join(os.path.dirname(__file__),
                                      "../templates")
        self.static = os.path.join(os.path.dirname(__file__), "../static")

        # DataBase connection
        self.dbconnection = dbconnection

        ##
        # OAuth authentication service (token provider)
        # Client Store (will be taken from db)
        client_store = ClientStore()
        client_store.add_client(client_id="abc",
                                client_secret="xyz",
                                redirect_uris=["http://localhost:8111"])

        ##
        # OAuth Token Store (in memory)
        token_store = TokenStore()

        # Generator of tokens
        token_generator = Uuid4()
        #token_generator.expires_in[ClientCredentialsGrant.grant_type] = 3600

        ##
        # OAuth Provider
        provider = Provider(access_token_store=token_store,
                            auth_code_store=token_store,
                            client_store=client_store,
                            token_generator=token_generator)

        #provider.token_path = '/oauth/token'

        # Support for the authorization code grant
        provider.add_grant(
            AuthorizationCodeGrant(site_adapter=CodeGrant(self.templates)))
        # provider.add_grant(
        #     ImplicitGrant(site_adapter=Authentication())
        # )

        logger.debug(provider.authorize_path)
        logger.debug(provider.token_path)
        ##
        # Auth handlers
        auth_handlers = [
            web.url(provider.authorize_path, OAuth2Handler,
                    dict(provider=provider)),
            web.url(provider.token_path, OAuth2Handler,
                    dict(provider=provider))
        ]

        ##
        # Web
        web_handlers = [
            web.url(r"/login", login.Index),
            web.url(r"/logout", logout.Index),
            web.url(r"/password/(.*)", password.Index),
            web.url(r"/forgot_password", password.Forgot),
            web.url(r"/registration", registration.Index),
            web.url(r'/', home.Index),
            web.url(r'/settings', home.User),
            web.url(r'/projects', projects.Projects),
            web.url(r'/slices/([a-z0-9\._\-]+)', slices.Slices),
            web.url(r'/users', users.Users),
            web.url(r'/users/?(' + self.urn_regex + ')', users.Users),
            web.url(r'/activity', activity.Index),
            web.url(r'/confirm/(' + self.uuid_regex + ')?', confirm.Index),
            web.url(r'/status', status.Index),
            web.url(r'/static/(.*)', web.StaticFileHandler,
                    {'path': self.static}),
            web.url(r'/test', test.Index),
            web.url(r"/addOrganization", addOrganization.Index)
        ]

        ##
        # REST API

        rest_handlers = [
            web.url(r'/api/v1/activity?([A-Za-z0-9-]+)?', ActivityHandler),
            web.url(r'/api/v1/activity/(' + self.uuid_regex + ')?',
                    ActivityHandler),
            web.url(r'/api/v1/confirm/(' + self.uuid_regex + ')?',
                    ConfirmHandler),
            web.url(r'/api/v1/requests?([A-Za-z0-9-]+)?', RequestsHandler),
            web.url(r'/api/v1/requests/(' + self.uuid_regex + ')?',
                    RequestsHandler),
            web.url(r'/api/v1/usertoken?', UserTokenHandler),
            web.url(r'/api/v1/login', LoginHandler),
            web.url(r'/api/v1/password', PasswordHandler),
            web.url(r'/api/v1/password/(.*)', PasswordHandler),
            web.url(r'/api/v1/resources$', ResourcesHandler),
            web.url(r'/api/v1/resources/(' + self.urn_regex + ')?$',
                    ResourcesHandler),
            web.url(r'/api/v1/resources/(' + self.urn_regex + ')?/?(leases)?$',
                    ResourcesHandler),
            web.url(r'/api/v1/resources/(' + self.urn_regex + ')?/?(slices)?$',
                    ResourcesHandler),
            web.url(
                r'/api/v1/resources/(' + self.urn_regex + ')?/?(testbeds)?$',
                ResourcesHandler),
            # leases
            web.url(r'/api/v1/leases$', LeasesHandler),
            web.url(r'/api/v1/leases/([A-Za-z0-9-]+)?', LeasesHandler),
            web.url(r'/api/v1/profile$', ProfileHandler),
            # testbeds
            web.url(
                r'/api/v1/testbeds/?(' + self.urn_regex + ')?/?(resources)?$',
                TestbedsHandler),
            web.url(r'/api/v1/testbeds/?(' + self.urn_regex + ')?/?(leases)?$',
                    TestbedsHandler),
            # users
            web.url(r'/api/v1/users$', UsersHandler),
            web.url(r'/api/v1/users/(' + self.email_regex + ')$',
                    UsersHandler),
            web.url(
                r'/api/v1/users/?(' + self.urn_regex +
                ')?/?(authorities|projects|slices)?$', UsersHandler),
            web.url(r'/api/v1/users/?(authorities|projects|slices)?$',
                    UsersHandler),
            # authorities
            web.url(r'/api/v1/authorities$', AuthoritiesHandler),
            web.url(
                r'/api/v1/authorities/?(' + self.urn_regex +
                ')?/?(users|projects)?$', AuthoritiesHandler),
            # projects
            web.url(
                r'/api/v1/projects/?(' + self.urn_regex +
                ')?/?(users|slices)?$', ProjectsHandler),
            # slices
            web.url(
                r'/api/v1/slices/?(' + self.hrn_regex +
                ')?/?(users|resources)?$', SlicesHandler),
            web.url(
                r'/api/v1/slices/?(' + self.urn_regex +
                ')?/?(users|resources)?$', SlicesHandler),

            # F-Interop sessions
            # security based on the slice id
            web.url(
                r'/api/v1/finterop/sessions/?(' + self.urn_regex +
                ')?/?(start|stop)?$', FinteropSessionsHandler),
            web.url(
                r'/api/v1/finterop/sessions/?(' + self.hrn_regex +
                ')?/?(start|stop)?$', FinteropSessionsHandler),
            web.url(
                r'/api/v1/finterop/sessions/?([a-zA-Z0-9]+)?/?(start|stop)?$',
                FinteropSessionsHandler),
            #web.url(r'/api/v1/finterop/sessions/?([a-zA-Z0-9]+)?/resources$', ResourceRepoHandler),
        ]

        ##
        # Websockets API
        # SockJSRouter: configure Websocket
        WebsocketRouter = SockJSRouter(WebsocketsHandler, '/api/v1/live')

        ##
        # URLs handlers
        handlers = auth_handlers + web_handlers + rest_handlers + WebsocketRouter.urls

        settings = dict(
            cookie_secret=config.web["cookie_secret"],
            login_url="/login",
            token_secret=config.web["token_secret"],
            template_path=self.templates,
            static_path=self.static,
            #xsrf_cookies=True,
            debug=True)

        web.Application.__init__(self, handlers, **settings)
Exemplo n.º 24
0
def start_auth_server(port, token_expiry, connection, oauth_connection):
    """
	Start the authorization server on the given port.

	:param port: The port on which the server listens.
	:type port: int
	:param token_expiry: The time taken for an access token delivered by the authorization server to expire.
	:type token_expiry: int
	:param connection: The database connection to use.
	:type connection: :class:`connection.connection.Connection`
	:param oauth_connection: The database connection to use for OAuth.
	:type oauth_connection: :class:`connection.connection.Connection`
	"""

    try:
        client_store = PostgresqlClientStore(oauth_connection)
        client_store.add_client(client_id=oauth.client_id,
                                client_secret=oauth.client_secret)
        """
		Create a token store.
		"""
        token_store = PostgresqlAccessTokenStore(oauth_connection)
        """
		Create the authentication and resource servers.
		The resource server is given the access token store to validate requests.
		The routes and their handler are also passed on as arguments.
		"""
        blockchain_handler = hyperledger.HyperledgerAPI(
            blockchain.admin_host, blockchain.admin_port,
            blockchain.multiuser_host, blockchain.multiuser_port, connection)
        """
		Create a thread manager since some functionality uses threading.
		This thread manager routinely checks for dead threads.
		"""
        thread_list = []
        thread_manager = ThreadManager(thread_list)
        thread = Thread(target=thread_manager.run)
        thread.start()
        """
		The route handlers are a set of classes that handle different requests.
		"""
        route_handlers = {
            handler_class: handler_class(connection, blockchain_handler,
                                         thread_list)
            for handler_class in routes.handler_classes
        }
        route_handlers[hyperledger.HyperledgerAPI] = blockchain_handler

        resource_provider = ResourceServer(
            connection=connection,
            access_token_store=token_store,
            auth_code_store=PostgresqlAuthCodeStore(oauth_connection),
            client_store=PostgresqlClientStore(oauth_connection),
            token_generator=Uuid4(),
            routes=routes.routes,
            route_handlers=route_handlers)
        """
		The authorization server gives out access tokens.
		"""
        authorization_server = AuthorizationServer(
            access_token_store=token_store,
            auth_code_store=token_store,
            client_store=client_store,
            token_generator=Uuid4(),
        )

        client_credentials_grant = CustomClientCredentialsGrant(
            expires_in=token_expiry,
            scopes=oauth.scopes,
            default_scope=oauth.default_scope)
        authorization_server.add_grant(client_credentials_grant)

        app = OAuthApplication(resource_provider=resource_provider,
                               authorization_server=authorization_server)

        if port is not None:
            port = int(port)
            httpd = make_server('',
                                port,
                                app,
                                handler_class=OAuthRequestHandler)

            print("Starting OAuth2 server on http://localhost:%d/..." % (port))
            httpd.serve_forever()
        return app
    except KeyboardInterrupt:
        httpd.server_close()
Exemplo n.º 25
0
# -*- coding: utf-8 -*-

import cherrypy
from . import verify, client_credentials, password
from oauth2.tokengenerator import Uuid4
from oauth2.store.memory import ClientStore, TokenStore

tokens = TokenStore()
clients = ClientStore()
clients.add_client(client_id="novareto", client_secret="test",
                        redirect_uris=[])

tickets = Uuid4()
tickets.expires_in['client_credentials'] = 7200


def run():
    cherrypy.config.update({
        'server.socket_host': '0.0.0.0',
        'server.socket_port': 8085,
    })

    cherrypy.tree.graft(
        client_credentials.make_application(tokens, clients, tickets),
        '/auth.client')

    cherrypy.tree.graft(
        password.make_application(tokens, clients, tickets),
        '/auth.passwd')

    cherrypy.tree.graft(