Пример #1
0
def login(request):
    """
    login method is used either to load login page or to authenticate user.
    :param request:
    :return:
    """
    # in case if it's GET request redirect to login page.
    if request.method == constants.GET:
        return logout(request)

    # get values for domain, username and password
    domain = request.POST['domain']
    username = request.POST['username']
    password = request.POST['password']

    # pass credentials with domain to authenticate method
    try:
        sol_user = ad.sol_authentication(username, password, domain)
    except Exception as e:
        return render(request, constants.LOGIN_TEMPLATE,
                      {constants.ERROR_MESSAGE: e.message})

    # authenticate method return dict object, which contains "auth" flag to indicate successful authentication.
    if not domain:
        # login django_admin to session so that user can also visit admin site.
        django_login(request, sol_user)
        # set session variables.
        request.session[constants.IS_DJANGO_ADMIN] = True
        request.session[constants.USER] = {constants.USERNAME: username}
    else:
        # for SOL user, we should put first name in session, to show welcome message.
        name = sol_user.full_name.split()
        session_user = {
            constants.USERNAME: username,
            constants.USER_FIRST_NAME: name[0]
        }
        request.session[
            constants.USER_HYPERVISORS] = db_service.get_hypervisor_of_user(
                username)
        if sol_user.default_project:
            hypervisor = sol_user.default_project.hypervisor.host
            project_id = sol_user.default_project.project_id
            project_name = sol_user.default_project.name
            domain, username, password = db_service.get_user_creds(
                hypervisor, username)
            session_user[constants.DEFAULT_HYPERVISOR] = hypervisor
            session_user[constants.DEFAULT_PROJECT] = project_name
            request.session[constants.USER] = session_user
            lib.views.load_hypervisor_projects(request, hypervisor, domain,
                                               username, password)
            return lib.views.mark_project_selection(request, project_id)
        request.session[constants.USER] = session_user
    request.session['last_activity'] = datetime.now().isoformat()
    return load_dashboard(request)
Пример #2
0
def hypervisor_user_management(request,
                               username=None,
                               message=None,
                               error_message=None):
    if request.method == constants.POST:
        username = request.POST[constants.USERNAME]
        host = request.POST[constants.HOST]
        hypervisor = db_service.get_hypervisor(host)
        domain, sol_username, password = db_service.get_user_creds(
            host, constants.HYPERVISOR_SOLUSER_NAME)
        user = db_service.get_user(username)
        try:
            adapter = factory.get_adapter(
                hypervisor.type, {
                    constants.PROTOCOL: hypervisor.protocol,
                    constants.HOST: hypervisor.host,
                    constants.PORT: hypervisor.port,
                    constants.DOMAIN: domain,
                    constants.USERNAME: sol_username,
                    constants.PASSWORD: password
                })
            adapter.generate_admin_auth()
            if 'user_id' in request.POST:
                user_id = request.POST['user_id']
                adapter.delete_user(user_id)
                user_id = None
                message = "User deleted successfully."
            else:
                user_id = adapter.create_user(user.username,
                                              request.POST['password'],
                                              user.email_id, user.full_name)
                message = "User created successfully."
            db_service.update_hypervisor_user_id(username, host, user_id)
        except Exception as e:
            error_message = e.message

    return render(
        request, constants.HYPERVISOR_USER_MGMT_TEMPLATE, {
            'mappings': db_service.get_user_hypervisor_mapping(username),
            constants.USERNAME: username,
            constants.MESSAGE: message,
            constants.ERROR_MESSAGE: error_message
        })
Пример #3
0
def mark_project_selection(request, project_id=None):
    selected_project = project_id if project_id else request.POST[
        'hypervisor_project']
    if selected_project == '--select--':
        clear_session_variables(request, [
            constants.SELECTED_PROJECT, constants.IS_ADMIN,
            constants.ENDPOINT_URLS, constants.TOKEN
        ])
        return render(request, constants.DASHBOARD_TEMPLATE)
    for project in request.session[constants.PROJECTS]:
        if project['id'] == selected_project:
            request.session[constants.SELECTED_PROJECT] = project
            hypervisor = request.session[constants.SELECTED_HYPERVISOR_OBJ]
            hypervisor[constants.PROJECT_ID] = project['id']
            adapter = factory.get_adapter(hypervisor[constants.TYPE],
                                          hypervisor)
            adapter.keystone_client = None
            token, endpoint_urls, is_admin = adapter.is_admin_for_project()
            request.session[constants.TOKEN] = token
            hypervisor[constants.TOKEN] = token
            request.session[constants.SELECTED_HYPERVISOR_OBJ] = hypervisor
            if not endpoint_urls:
                domain, username, password = db_service.get_user_creds(
                    hypervisor[constants.HOST],
                    constants.HYPERVISOR_SOLUSER_NAME)
                sol_adapter = factory.get_adapter(
                    hypervisor[constants.TYPE], {
                        constants.PROTOCOL: hypervisor[constants.PROTOCOL],
                        constants.HOST: hypervisor[constants.HOST],
                        constants.PORT: hypervisor[constants.PORT],
                        constants.DOMAIN: domain,
                        constants.USERNAME: username,
                        constants.PASSWORD: password
                    })
                _, _, endpoint_urls = sol_adapter.generate_admin_auth()
            request.session[constants.ENDPOINT_URLS] = endpoint_urls
            if is_admin:
                request.session[constants.IS_ADMIN] = True
            break
    return render(request, constants.DASHBOARD_TEMPLATE)
Пример #4
0
def auto_vm_deletion():
    logger.info('Running delete expired instace @ ' +
                str(datetime_obj.datetime.now()))
    try:
        instances = db_service.get_created_instances(all_created=True)
        if not instances:
            logger.info("No instances found. Exiting vm deletion job.")
            return

        for instance in instances:
            logger.info('Checking expiry details for : ' +
                        instance.instance_name)
            expiry_date = datetime.strptime(str(instance.doe), '%Y-%m-%d')
            today_date = datetime.strptime(str(datetime_obj.date.today()),
                                           '%Y-%m-%d')
            if expiry_date <= today_date:
                domain, username, password = db_service.get_user_creds(
                    instance.project.hypervisor.host,
                    constants.HYPERVISOR_SOLUSER_NAME)
                if not domain:
                    logger.error("Unable to delete instance : " +
                                 instance.instance_name +
                                 "as SOLUSER for hypervisor : " +
                                 instance.project.hypervisor.host +
                                 " Does not exist.")
                    continue
                hypervisor = {
                    constants.TYPE: instance.project.hypervisor.type,
                    constants.PROTOCOL: instance.project.hypervisor.protocol,
                    constants.HOST: instance.project.hypervisor.host,
                    constants.PORT: instance.project.hypervisor.port,
                    constants.DOMAIN: domain,
                    constants.USERNAME: username,
                    constants.PASSWORD: password,
                    constants.PROJECT_ID: instance.project.project_id
                }
                logger.debug(
                    "virtual machine '" + instance.instance_name +
                    "' has expired. Hence, deleting the virtual machine.")
                adapter = factory.get_adapter(hypervisor[constants.TYPE],
                                              hypervisor)
                adapter.generate_admin_auth()
                user_roles = adapter.get_user_roles_project(
                    hypervisor[constants.PROJECT_ID])
                for user in user_roles:
                    if user[constants.
                            USERNAME] == constants.HYPERVISOR_SOLUSER_NAME:
                        break
                else:
                    sol_user_id = db_service.get_sol_user_id(
                        hypervisor[constants.HOST])
                    role_ids = []
                    roles = adapter.get_roles()
                    for role in roles:
                        role_ids.append(role[constants.ROLE_ID])
                    adapter.assign_roles(role_ids, sol_user_id,
                                         hypervisor[constants.PROJECT_ID])

                adapter.delete_instance(instance.instance_id)

                subject = 'SOL (deleted): Instance ' + instance.instance_name + ' has deleted.'
                vm_information_table = tabulate(
                    [["Instance Name : ", instance.instance_name],
                     ["Hypervisor : ", instance.project.hypervisor.host],
                     ["Project : ", instance.project.name],
                     ["Date of Creation:", instance.doc],
                     ["Expiry Date:", instance.doe],
                     ["Deleted by:", "Service Online"]])
                message = "Hi " + instance.user.full_name + ", \n\tYour virtual machine " + \
                          instance.instance_name + " has deleted. Please, check Virtual " \
                                                   "machine Details below,\n\n" + vm_information_table + \
                          "\n\nFor any issue, please get in touch with Administrator."
                sol_email.send_mail(receiver=instance.user.email_id,
                                    subject=subject,
                                    message=message)
                db_service.remove_instance(instance_id=instance.instance_id)
                logger.debug('Instance ' + instance.instance_name +
                             ' has deleted')
    except Exception as e:
        logger.error(
            'Exception while executing deleting expired instances job: ' +
            e.message)
        logger.error(e)
Пример #5
0
def hypervisor_preference(request, host=None, remove=False):
    user = request.session[constants.USER]
    if host == 'remove_default':
        db_service.remove_default_hypervisor(user)
        del user[constants.DEFAULT_HYPERVISOR]
        del user[constants.DEFAULT_PROJECT]
        request.session[constants.USER] = user
        return render(
            request, constants.HYPERVISOR_PREFERENCE_TEMPLATE,
            {constants.MESSAGE: "Default setting removed successfully."})

    if request.method == constants.GET and not host:
        clear_session_variables(request, [
            constants.HYPERVISOR_PREFERENCE_PROJECTS,
            constants.HYPERVISOR_PREFERENCE_SELECTED_HOST
        ])
        return render(request, constants.HYPERVISOR_PREFERENCE_TEMPLATE)

    domain, username, password = None, None, None

    if host:
        request.session[constants.HYPERVISOR_PREFERENCE_SELECTED_HOST] = host
        domain, username, password = db_service.get_user_creds(
            host, user[constants.USERNAME])
        if not domain:
            return render(
                request, constants.HYPERVISOR_ADMIN_LOGIN_TEMPLATE, {
                    'redirect': "/hypervisor_admin/hypervisor_preference/",
                    'button_name': 'Load Projects'
                })

    if 'selected_project' in request.POST:
        selected_project_id = request.POST['selected_project']
        selected_project = None
        for project in request.session[
                constants.HYPERVISOR_PREFERENCE_PROJECTS]:
            if project['id'] == selected_project_id:
                selected_project = project
                break
        db_service.set_default_project(
            request.session[constants.HYPERVISOR_PREFERENCE_SELECTED_HOST],
            user, selected_project)
        user[constants.DEFAULT_PROJECT] = selected_project['name']
        user[constants.DEFAULT_HYPERVISOR] = request.session[
            constants.HYPERVISOR_PREFERENCE_SELECTED_HOST]
        request.session[constants.USER] = user
        return render(
            request, constants.HYPERVISOR_PREFERENCE_TEMPLATE,
            {constants.MESSAGE: "Default project updated successfully."})

    hypervisor = get_selected_hypervisor(
        request,
        request.session[constants.HYPERVISOR_PREFERENCE_SELECTED_HOST])
    hypervisor[constants.DOMAIN] = domain if domain else request.POST[
        constants.DOMAIN]
    hypervisor[constants.USERNAME] = username if username else request.POST[
        constants.USERNAME]
    hypervisor[constants.PASSWORD] = password if password else request.POST[
        constants.PASSWORD]
    adapter = factory.get_adapter(hypervisor[constants.TYPE], hypervisor)
    request.session[
        constants.
        HYPERVISOR_PREFERENCE_PROJECTS], _ = adapter.get_projects_using_unscoped_login(
        )
    db_service.save_user_credentials(user[constants.USERNAME],
                                     hypervisor[constants.HOST],
                                     hypervisor[constants.DOMAIN],
                                     hypervisor[constants.USERNAME],
                                     hypervisor[constants.PASSWORD])
    return render(
        request, constants.HYPERVISOR_ADMIN_LOGIN_TEMPLATE, {
            'redirect': "/hypervisor_admin/hypervisor_preference/",
            'button_name': 'Save',
            'domain': hypervisor[constants.DOMAIN],
            'username': hypervisor[constants.USERNAME],
            'password': hypervisor[constants.PASSWORD]
        })