#!/usr/bin/env python

from neutronclient.v2_0 import client as neutron_client
from keystoneclient.v3 import client as keystone_client
from novaclient.exceptions import NotFound as novaNotFoundException
from neutronclient.common.exceptions import NeutronClientException
from keystoneclient.apiclient.exceptions import NotFound as keystoneNotFoundException

from novaclient import client as nova_client

from setup_tenant import parse_config
from os_reststack_manager.app import logging

logger = logging.getLogger('erase_tenant')


class TenantNotFound(Exception):
    pass


def tenant_delete(tenant_name, credentials):
    credsc = parse_config(credentials)

    keystone = keystone_client.Client(username=credsc['os_user'],
                                      password=credsc['os_password'],
                                      tenant_name=credsc['os_tenant_name'],
                                      auth_url=credsc['os_auth_url_v3'])
    try:
        tenant = keystone.projects.find(name=tenant_name)
        logger.info("Tenant found %s " % tenant.id)
    except keystoneNotFoundException:
from jinja2 import Environment
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from neutronclient.v2_0 import client as neutron_client
from keystoneclient.v3 import client as keystone_client
from keystoneclient.apiclient.exceptions import Conflict as keystoneConflictException
from novaclient.exceptions import NotFound as novaNotFoundException
from neutronclient.common.exceptions import NeutronClientException
from novaclient import client as nova_client

from neutron_tenant_net import neutron_tenant_net
from tenant_password import password_random, tenant_password
from os_reststack_manager.app import logging

logger = logging.getLogger('setup_tenant')


def extract_keys(key):
    if key.startswith("lp:"):
        lp_id = key.split(':')[1]
        lp_url = "http://launchpad.net/%s/+sshkeys" % lp_id
        response = urllib2.urlopen(lp_url)
        return response.read().split("\n")
    else:
        return [key]


def gen_multipart_cloudconfig(config_dict, other_files, tenant_name, tenant_pass, tenant_id):
    msg = MIMEMultipart()
    sm = MIMEText("#cloud-config\n%s" % json.dumps(config_dict), "cloud-config", sys.getdefaultencoding())
#!/usr/bin/env python
from __future__ import print_function

from flask import Blueprint, Flask, jsonify, json, abort, request, g
from os_reststack_manager.app import credentials, db, Tenant, logging

from lib.setup_tenant import tenant_create, extract_keys
from lib.erase_tenant import tenant_delete

import re
import jwt
import os_reststack_manager.config as CONF

mod = Blueprint('tenant-manager', __name__)
logger = logging.getLogger('tenant_manager')


@mod.before_request
def authenticate():
    # logger.debug("endpoint request: %s" % request.endpoint)
    if re.search('tenant_provisioned', str(request.endpoint)):
        g.user = "******"
        logger.info("Authentication bypassed: tenant_provisioned")
        return

    try:
        decoded = jwt.decode(request.headers['X-Auth-Token'], credentials['tenant_secret'], algorithms=['HS256'])
        g.user = decoded['user']
    except KeyError:
        logger.error("Error: key error.")
        abort(401)