From 5f1f239f1c409d8ddaa69b781fc23b75c882d117 Mon Sep 17 00:00:00 2001 From: SILVA Ricardo <silvari@lab-silvari.dev.snmc.cec.eu.int> Date: Thu, 22 Feb 2024 15:08:56 +0100 Subject: [PATCH] Vault public git migration --- README | 49 + SNET/t.pl | 11 - ansible/.keep | 0 ansible/ansible-gen-role | 1 - ansible/ansible-json.cfg | 1 - ansible/ansible.cfg | 1 - ansible/ansible_tmp.cfg | 1 - ansible/bin | 1 - ansible/cache_plugins | 1 - ansible/callback_plugins | 1 - ansible/connection_plugins | 1 - ansible/filter_plugins | 1 - ansible/group_vars/.keep | 0 ansible/host_vars/.keep | 0 ansible/library | 1 - ansible/lookup_plugins | 1 - ansible/playbook-auth-usersldap.yml | 274 -- ansible/roles/.keep | 0 bin/check_password_expiration.pl | 618 ---- bin/ldap2sid.pl | 380 -- bin/ldap_NS.pl | 4197 ---------------------- bin/leankit_mindmap.py | 163 - bin/leankit_user.py | 474 --- bin/redmine_create_issue | 217 -- bin/redmine_create_repo.py | 104 - bin/redmine_create_sc_projects.py | 760 ---- bin/redmine_fetch_changeset.py | 94 - bin/redmine_issue | 226 -- bin/redmine_leankit_create_issue | 570 --- bin/sid_groups.py | 215 -- bin/sid_user.py | 1352 ------- bin/synchronize_home_Users.pl | 422 --- bin/synchronize_proteus_Users.pl | 567 --- bin/synchronize_redmine_projects.py | 760 ---- bin/synchronize_redmine_users.py | 80 - bin/synchronize_users.pl | 133 - cgi-bin/check_users_in_AD_group.pl | 262 -- cgi-bin/get_groups_content_from_AD.pl | 356 -- cgi-bin/get_users_in_AD_group.pl | 344 -- cgi-bin/ldap_NS.pl | 5 - cgi-bin/ldap_NS_adduser.pl | 515 --- htdocs/css/ldapns.css | 468 --- htdocs/css/zboub.css | 64 - library/leankit/__init__.py | 196 - library/leankit/connector.py | 135 - library/leankit/env_user.py | 10 - library/leankit/models/ApiObjBase.py | 18 - library/leankit/models/Board.py | 83 - library/leankit/models/BoardLevel.py | 24 - library/leankit/models/Board_bad.py | 203 -- library/leankit/models/Card.py | 137 - library/leankit/models/CardType.py | 14 - library/leankit/models/ClassOfService.py | 12 - library/leankit/models/Lane.py | 73 - library/leankit/models/ListResponse.py | 93 - library/leankit/models/Priority.py | 9 - library/leankit/models/User.py | 36 - library/leankit/models/__init__.py | 0 library/servicenow/__init__.py | 57 - library/servicenow/connector.py | 159 - library/servicenow/env_user.py | 91 - library/vault/examples/alternative.py | 15 - library/vault/examples/configure_jwt.py | 17 - library/vault/examples/main.py | 21 - library/vault/examples/requirement.txt | 8 - requirements.txt | 6 + templates/addgroup.tmpl | 64 - templates/addpolicy.tmpl | 58 - templates/adduser.tmpl | 113 - templates/adduserprofile.tmpl | 117 - templates/blank.tmpl | 11 - templates/delgroup.tmpl | 41 - templates/deluser.tmpl | 60 - templates/fields_policy.tmpl | 348 -- templates/groupinfos.tmpl | 21 - templates/ldapns_footer.tmpl | 57 - templates/ldapns_header.tmpl | 25 - templates/left_groups.tmpl | 50 - templates/left_home.tmpl | 30 - templates/left_pannel.tmpl | 35 - templates/left_policy.tmpl | 50 - templates/left_users.tmpl | 86 - templates/login.tmpl | 51 - templates/modgroup.tmpl | 72 - templates/modpolicy.tmpl | 46 - templates/passwd.tmpl | 50 - templates/policyinfos.tmpl | 29 - templates/reset.tmpl | 46 - templates/selectgroup.tmpl | 36 - templates/selectgroupclass.tmpl | 34 - templates/selectpolicy.tmpl | 34 - templates/selectppolicy.tmpl | 34 - templates/selectuser.tmpl | 34 - templates/tab.tmpl | 59 - templates/userinfos.tmpl | 29 - {library/vault => vault}/client.py | 28 +- 96 files changed, 76 insertions(+), 16780 deletions(-) create mode 100644 README delete mode 100755 SNET/t.pl delete mode 100644 ansible/.keep delete mode 120000 ansible/ansible-gen-role delete mode 120000 ansible/ansible-json.cfg delete mode 120000 ansible/ansible.cfg delete mode 120000 ansible/ansible_tmp.cfg delete mode 120000 ansible/bin delete mode 120000 ansible/cache_plugins delete mode 120000 ansible/callback_plugins delete mode 120000 ansible/connection_plugins delete mode 120000 ansible/filter_plugins delete mode 100644 ansible/group_vars/.keep delete mode 100644 ansible/host_vars/.keep delete mode 120000 ansible/library delete mode 120000 ansible/lookup_plugins delete mode 100644 ansible/playbook-auth-usersldap.yml delete mode 100644 ansible/roles/.keep delete mode 100755 bin/check_password_expiration.pl delete mode 100755 bin/ldap2sid.pl delete mode 100755 bin/ldap_NS.pl delete mode 100755 bin/leankit_mindmap.py delete mode 100755 bin/leankit_user.py delete mode 100755 bin/redmine_create_issue delete mode 100755 bin/redmine_create_repo.py delete mode 100755 bin/redmine_create_sc_projects.py delete mode 100755 bin/redmine_fetch_changeset.py delete mode 100755 bin/redmine_issue delete mode 100755 bin/redmine_leankit_create_issue delete mode 100755 bin/sid_groups.py delete mode 100755 bin/sid_user.py delete mode 100755 bin/synchronize_home_Users.pl delete mode 100755 bin/synchronize_proteus_Users.pl delete mode 100755 bin/synchronize_redmine_projects.py delete mode 100755 bin/synchronize_redmine_users.py delete mode 100755 bin/synchronize_users.pl delete mode 100755 cgi-bin/check_users_in_AD_group.pl delete mode 100755 cgi-bin/get_groups_content_from_AD.pl delete mode 100755 cgi-bin/get_users_in_AD_group.pl delete mode 100755 cgi-bin/ldap_NS.pl delete mode 100755 cgi-bin/ldap_NS_adduser.pl delete mode 100644 htdocs/css/ldapns.css delete mode 100644 htdocs/css/zboub.css delete mode 100755 library/leankit/__init__.py delete mode 100755 library/leankit/connector.py delete mode 100755 library/leankit/env_user.py delete mode 100755 library/leankit/models/ApiObjBase.py delete mode 100755 library/leankit/models/Board.py delete mode 100755 library/leankit/models/BoardLevel.py delete mode 100755 library/leankit/models/Board_bad.py delete mode 100755 library/leankit/models/Card.py delete mode 100755 library/leankit/models/CardType.py delete mode 100755 library/leankit/models/ClassOfService.py delete mode 100755 library/leankit/models/Lane.py delete mode 100755 library/leankit/models/ListResponse.py delete mode 100755 library/leankit/models/Priority.py delete mode 100755 library/leankit/models/User.py delete mode 100755 library/leankit/models/__init__.py delete mode 100755 library/servicenow/__init__.py delete mode 100755 library/servicenow/connector.py delete mode 100755 library/servicenow/env_user.py delete mode 100755 library/vault/examples/alternative.py delete mode 100755 library/vault/examples/configure_jwt.py delete mode 100755 library/vault/examples/main.py delete mode 100644 library/vault/examples/requirement.txt create mode 100644 requirements.txt delete mode 100644 templates/addgroup.tmpl delete mode 100644 templates/addpolicy.tmpl delete mode 100644 templates/adduser.tmpl delete mode 100644 templates/adduserprofile.tmpl delete mode 100644 templates/blank.tmpl delete mode 100644 templates/delgroup.tmpl delete mode 100644 templates/deluser.tmpl delete mode 100644 templates/fields_policy.tmpl delete mode 100644 templates/groupinfos.tmpl delete mode 100644 templates/ldapns_footer.tmpl delete mode 100644 templates/ldapns_header.tmpl delete mode 100644 templates/left_groups.tmpl delete mode 100644 templates/left_home.tmpl delete mode 100644 templates/left_pannel.tmpl delete mode 100644 templates/left_policy.tmpl delete mode 100644 templates/left_users.tmpl delete mode 100644 templates/login.tmpl delete mode 100644 templates/modgroup.tmpl delete mode 100644 templates/modpolicy.tmpl delete mode 100644 templates/passwd.tmpl delete mode 100644 templates/policyinfos.tmpl delete mode 100644 templates/reset.tmpl delete mode 100644 templates/selectgroup.tmpl delete mode 100644 templates/selectgroupclass.tmpl delete mode 100644 templates/selectpolicy.tmpl delete mode 100644 templates/selectppolicy.tmpl delete mode 100644 templates/selectuser.tmpl delete mode 100644 templates/tab.tmpl delete mode 100644 templates/userinfos.tmpl rename {library/vault => vault}/client.py (61%) diff --git a/README b/README new file mode 100644 index 0000000..1fecd4c --- /dev/null +++ b/README @@ -0,0 +1,49 @@ +Project Name: Vault Data Retrieval Tool + +Description: +This tool is designed to retrieve secrets and secret metadata from HashiCorp Vault using the AppRole authentication method. It provides functions to fetch passwords and key data from a specified path within the Vault. + +Requirements: +- Python 3.x +- pip (Python package manager) + +Installation: +1. Clone the repository from https://code.europa.eu/digit-c4/dev/ansible-vault. +2. Navigate to the project directory. +3. Create a virtual environment (optional but recommended): + ``` + python3 -m venv venv + source venv/bin/activate + ``` +4. Install dependencies using the provided requirements.txt file: + ``` + pip install -r requirements.txt + ``` + +Usage: +1. Ensure you have the necessary permissions and access to the HashiCorp Vault. +2. Set up the AppRole authentication method in your Vault instance. Refer to the provided links for detailed instructions. +3. Modify the code to provide your Vault URL, namespace, role ID, secret ID, mount point, and engine details. +4. EXAMPLE +sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) +sys.path.append('/opt/auth') +from ansible-vault.vault.client import clientV +password = clientV.getPasswordByAppRole("dev/SNOW/csui", "https://sam-hcavault.cec.eu.int", "EC/DIGIT_C4_SNET_ADMIN-ACC", "role_id", "secret_id", "apps-kv", "dev") + + +Functionality: +- `getPasswordByAppRole(key, vault_url, namespace_used, role_id, secret_id, mount_point, engine)`: This function retrieves a password from the specified key path in the Vault. +- `getKeysData(key, vault_url, namespace_used, role_id, secret_id, mount_point, engine)`: This function retrieves key data (secret metadata) from the specified key path in the Vault. + +Notes: +- Ensure that the AppRole authentication method is correctly configured and enabled in your Vault instance. +- Modify the code according to your specific Vault configuration and requirements. +- Handle errors and exceptions appropriately in your code to ensure smooth operation. + +References: +- HashiCorp Vault Documentation: [https://www.vaultproject.io/docs](https://www.vaultproject.io/docs) +- HVAC Documentation: [https://hvac.readthedocs.io](https://hvac.readthedocs.io) + +Author: +Marcelo teixeira +Ricardo Silva \ No newline at end of file diff --git a/SNET/t.pl b/SNET/t.pl deleted file mode 100755 index d1e8fbc..0000000 --- a/SNET/t.pl +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env perl - -use strict; -use warnings; -use diagnostics; -use LdapNS; - -my $zboub = SNET::LdapNS::PPControls->new("blah"); - -exit 0; - diff --git a/ansible/.keep b/ansible/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/ansible/ansible-gen-role b/ansible/ansible-gen-role deleted file mode 120000 index 337b9a2..0000000 --- a/ansible/ansible-gen-role +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/ansible-gen-role \ No newline at end of file diff --git a/ansible/ansible-json.cfg b/ansible/ansible-json.cfg deleted file mode 120000 index dc2ac1f..0000000 --- a/ansible/ansible-json.cfg +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/ansible-json.cfg \ No newline at end of file diff --git a/ansible/ansible.cfg b/ansible/ansible.cfg deleted file mode 120000 index e45d717..0000000 --- a/ansible/ansible.cfg +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/ansible.cfg \ No newline at end of file diff --git a/ansible/ansible_tmp.cfg b/ansible/ansible_tmp.cfg deleted file mode 120000 index e45d717..0000000 --- a/ansible/ansible_tmp.cfg +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/ansible.cfg \ No newline at end of file diff --git a/ansible/bin b/ansible/bin deleted file mode 120000 index 063a441..0000000 --- a/ansible/bin +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/bin \ No newline at end of file diff --git a/ansible/cache_plugins b/ansible/cache_plugins deleted file mode 120000 index a0114f0..0000000 --- a/ansible/cache_plugins +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/cache_plugins \ No newline at end of file diff --git a/ansible/callback_plugins b/ansible/callback_plugins deleted file mode 120000 index 7633f72..0000000 --- a/ansible/callback_plugins +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/callback_plugins \ No newline at end of file diff --git a/ansible/connection_plugins b/ansible/connection_plugins deleted file mode 120000 index 37d495d..0000000 --- a/ansible/connection_plugins +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/connection_plugins \ No newline at end of file diff --git a/ansible/filter_plugins b/ansible/filter_plugins deleted file mode 120000 index 536baf0..0000000 --- a/ansible/filter_plugins +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/filter_plugins \ No newline at end of file diff --git a/ansible/group_vars/.keep b/ansible/group_vars/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/ansible/host_vars/.keep b/ansible/host_vars/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/ansible/library b/ansible/library deleted file mode 120000 index 8815b0a..0000000 --- a/ansible/library +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/library \ No newline at end of file diff --git a/ansible/lookup_plugins b/ansible/lookup_plugins deleted file mode 120000 index cf5171d..0000000 --- a/ansible/lookup_plugins +++ /dev/null @@ -1 +0,0 @@ -/opt/ansible/lookup_plugins \ No newline at end of file diff --git a/ansible/playbook-auth-usersldap.yml b/ansible/playbook-auth-usersldap.yml deleted file mode 100644 index 881d95d..0000000 --- a/ansible/playbook-auth-usersldap.yml +++ /dev/null @@ -1,274 +0,0 @@ -# https://intragate.ec.europa.eu/snet/wiki/index.php/Service_Support/Application_Management_Service/Snet_AAA/Account_creation_and_deletion_of_Snet_members -# ansible-playbook-4.7 playbook-auth-usersldap.yml --extra-vars "username=xxx scrat_user=xxx" -kK --tags "add_user/rm_user, mandatory" -u snet -# To run specific task: -# ansible-playbook-4.7 playbook-auth-usersldap.yml --extra-vars "username=xxx" -kK --tags "propagate" -u snet ---- - -- hosts: localhost - gather_facts: false - connection: local - - vars: - whoami: 'unknown' - - vars_prompt: - - name: username - prompt: "Username not specified. Please enter it" - private: no - - pre_tasks: - - name: check the playbook run with ansible >= 2.9 - assert: - that: - - ansible_version.major >= 2 - - ansible_version.minor >= 9 - fail_msg: "Please run this playbook with at least ansible 2.9." - - tasks: - - - name: CHECK | User is in LDAP - block: - - - name: debug - debug: - msg: "The username is {{ username }}" - - # getent passwd will return an non zero exit code (2), if the account do not exist in the system (ldap) - - name: grab passwd - shell: "/usr/bin/getent passwd {{ username }}" - register: register_username - delegate_to: localhost - changed_when: False - ignore_errors: yes - - - name: check that user is known - fail: - msg: "Account {{ username }} is not resolved by the system. Is it created on the LDAP? Did you make a typo?" - when: register_username.rc != 0 - - - name: debug - debug: - msg: "The username is {{ register_username }}" - - tags: add_user - - - name: Check | Whoami - block: - - - name: grab whoami - shell: /usr/bin/whoami - register: register_whoami - delegate_to: localhost - changed_when: False - - - name: set whoami var - set_fact: - whoami: "{{register_whoami.stdout}}" - changed_when: False - - - name: debug - debug: - msg: "The whoami is {{ whoami }}" - - tags: always - -########## -#Add user# -########## - - name: Add user on Vshare - block: - - name: set /opt/home_nas - ansible.builtin.file: - path: /opt/home_nas - state: directory - mode: '0755' - owner: root - group: root - - - name: mount /opt/home_nas - mount: - path: /opt/home_nas - state: mounted - src: unityspb-vshare-lu.snmc.cec.eu.int:/fs_home - opts: defaults,rw,soft,nolock,tcp,vers=3 - boot: false - fstype: nfs - - - name: Create user directory in home - ansible.builtin.file: - path: /opt/home_nas/{{username}} - state: directory - mode: '0755' - owner: "{{username}}" - group: snmc - - - name: Unmount /opt/home_nas - mount: - path: /opt/home_nas - state: unmounted - - become: true - delegate_to: vshare-bx.snmc.cec.eu.int - tags: - - add_user - - add_user_vshare - -############# -#Remove user# -############# - - - name: Remove user on Vshare - block: - - name: set /opt/home_nas - ansible.builtin.file: - path: /opt/home_nas - state: directory - mode: '0755' - owner: root - group: root - - - name: mount /opt/home_nas - mount: - path: /opt/home_nas - state: mounted - src: unityspb-vshare-lu.snmc.cec.eu.int:/fs_home - opts: defaults,rw,soft,nolock,tcp,vers=3 - boot: false - fstype: nfs - - - name: stat /opt/home_nas/{{username}} - stat: - path: /opt/home_nas/{{username}} - register: user_folder - - - name: Compress and archive - shell: - cmd: tar -jcf /opt/home_nas/_OLD/{{username}}.tbz /opt/home_nas/{{username}} - when: user_folder.stat.exists - - - name: Delete user directory in home - file: - path: /opt/home_nas/{{username}} - state: absent - - - name: Unmount /opt/home_nas - mount: - path: /opt/home_nas - state: unmounted - - become: true - delegate_to: vshare-bx.snmc.cec.eu.int - tags: - - rm_user - - rm_user_vshare - - - name: Launch propagate users from Snet LDAP to SID - # 25/07 - # as seen with Jeremy on 25/07 and confirmed by Ricardo on 25/08, user creation/deletion is ok , but the update fails - # -> while update of users is implemented, the flag --error-stop must not usedi - # richeju: changed var whoami to scrat_user, needs to be set in command - shell: - cmd: "/opt/auth/bin/sid_user.py -e prod --rw-user {{ scrat_user }}" - #cmd: "/opt/auth/bin/sid_user.py -e prod --rw-user {{ whoami }} --error-stop" - delegate_to: vworker4-lu.snmc.cec.eu.int - ignore_errors: yes - tags: - - mandatory - - propagate - #when: false - - - name: Launch propagate SID groups from EC LDAP to SID - shell: - cmd: "/opt/auth/bin/sid_groups.py -e prod --rw-user {{ scrat_user }}" - #cmd: "/opt/auth/bin/sid_user.py -e prod --rw-user {{ whoami }} --error-stop" - delegate_to: vworker4-lu.snmc.cec.eu.int - ignore_errors: yes - tags: - - mandatory - - propagate - - - name: Launch propagate users on leankit - shell: - cmd: "/opt/auth/bin/leankit_user.py" - delegate_to: vworker4-lu.snmc.cec.eu.int - ignore_errors: yes - tags: - - mandatory - - propagate - - - name: Create user on Proteus - shell: - cmd: "/opt/auth/bin/synchronize_proteus_Users.pl" - delegate_to: vworker4-lu.snmc.cec.eu.int - ignore_errors: yes - tags: - - mandatory - - propagate - - - name: Launch redmine LDAP sync - shell: - cmd: /usr/local/sbin/sync_users - become: true - become_method: sudo - delegate_to: "{{ item }}" - loop: "{{ groups['vredmine_prd'] }}" - tags: - - mandatory - - redmine - - - name: Sync SID users with Wiki phonebook - command: "python3 {{item}}" - args: - chdir: /export/home/snet/ - with_items: - - sid_2_wiki_NMT_users_single_page.py - - sid_2_wiki_NTX_users_single_page.py - - sid_2_wiki_user.py - delegate_to: vworker0-lu.snmc.cec.eu.int - become: "{{ whoami }}" - become: true - tags: - - mandatory - - sync_phonebook - -####### -#EJBCA# -####### - - - name: Remove user from EJBCA - block: - - name: test presence of entity in ejbca - shell: /opt/SNet/EJBCA/ejbca/bin/ejbca.sh ra findendentity --username {{username}} - delegate_to: vcertserv-lu.snmc.cec.eu.int - become: yes - become_user: snet-pki - ignore_errors: yes - register: result_ejbca - - - name: Cert found - debug: - msg: "There is a certificate, Let's remove it" - when: result_ejbca.rc == 0 - - - name: No cert - debug: - msg: "No entity/cert found, Skipping this action" - when: result_ejbca.rc != 0 - - - name: Revocation - shell: /opt/SNet/EJBCA/ejbca/bin/ejbca.sh ra revokeendentity --username {{username}} -r 5 - delegate_to: vcertserv-lu.snmc.cec.eu.int - become: yes - become_user: snet-pki - when: result_ejbca.rc == 0 - - - name: Deletion - shell: /opt/SNet/EJBCA/ejbca/bin/ejbca.sh ra delendentity --username {{username}} -force - delegate_to: vcertserv-lu.snmc.cec.eu.int - become: yes - become_user: snet-pki - when: result_ejbca.rc == 0 - - tags: - - rm_user - - rm_EJBCA diff --git a/ansible/roles/.keep b/ansible/roles/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/bin/check_password_expiration.pl b/bin/check_password_expiration.pl deleted file mode 100755 index 668a46c..0000000 --- a/bin/check_password_expiration.pl +++ /dev/null @@ -1,618 +0,0 @@ -#!/usr/bin/perl - -# ------------------------------------------------------------------------------ -# $Id$ -# -# ------------------------------------------------------------------------------ - -use strict; -use warnings; -use Getopt::Long; -use Data::Dumper; -use Config::IniFiles; -use Net::LDAP; -use File::Copy; -use File::Basename; -use Sys::Hostname; -use DateTime; -use MIME::Lite; - -# unbuffered output: -$| = 1; - -use lib ( new Config::IniFiles( -file => "/opt/etc/ini/global.ini" )->val( 'APPLICATION', 'LIBRARY' ) ); - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} - -use SNET::common; -use SNET::snmpd; -use SNET::LdapNS qw(:all); -use DateTime::Format::LDAP; - -use vars qw($verbose $debug $help $force $cli_mode $dry_run ); -$verbose = 0; -$debug = 0; -$cli_mode = 1; - -my $PROGNAME = basename( $0 ); -$PROGNAME =~ s/\.p[lm]$//; - -my %options = ( - "help" => \$help, - "debug" => \$debug, - "verbose" => \$verbose, - "force" => \$force, - "dry-run" => \$dry_run, -); - -my $SNMP_ENTERPRISEOID = "53"; -my $SNMP_OID = "1.3.6.1.4.1.99999.$SNMP_ENTERPRISEOID"; -my $SNMP_GEN = "6"; -my $SNMP_SPE = "1"; -my $msg = ''; -my $title = "Check Password"; - -help() if !GetOptions( %options ) or $help; -$verbose = 1 if $debug; - -metaprint( 'warning', "Dry-run is activated, no email." ) if $dry_run; - -# ldap_find_users_and_groups() -# -# Read users and groups from SNet LDAP. - -sub ldap_find_users_in_group ($$$$$$$$$$) -{ - my ( - $cfg_ldap_server, $cfg_ldap_user, $cfg_ldap_passwd, $cfg_ldap_group_search, $cfg_ldap_search_scope, - $cfg_ldap_group_search_filter, $cfg_ldap_group_attribute, $cfg_ldap_groupname, $hostname, $cfg_ldap_cafile - ) = @_; - - my %users; - - # Connect to the LDAP server - metaprint( 'verbose', "Initiating connection to LDAP server <$cfg_ldap_server>:" ) if $verbose; - my $ldap = Net::LDAP->new( - $cfg_ldap_server, - async => 0, - onerror => ( - ( $debug == 0 ) ? sub { return $_[0] } : sub { - my $message = shift; - my $error = defined( $message->error_desc ) ? $message->error_desc : $message->error(); - $msg = "Ldap: Unable to process request: $error."; - metaprint( 'error', $title . ": " . $msg ); - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - return $message; - } - ), - ); - if ( !$ldap ) { - $msg = "LDAP connection to <$cfg_ldap_server> failed."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - metaprint( 'verbose', "* LDAP connection completed successfully." ) if $verbose; - - my $message; - eval { - print STDERR 'Starting tls' . "\n" if ( $debug ); - $message = $ldap->start_tls( verify => 'require', - cafile => $cfg_ldap_cafile, ); - if ( $message->is_error() ) { - $msg = "Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - }; - if ( $@ ) { - $msg = "Crash - Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - eval { - print STDERR 'binding' . "\n" if ( $debug ); - $message = $ldap->bind( - $cfg_ldap_user, - password => $cfg_ldap_passwd, - version => 3, - ); - if ( $message->is_error() ) { - $msg = "LDAP bind error occurred."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - }; - if ( $@ ) { - $msg = "Crash - LDAP bind error occurred ('" . $message->error_name . "')."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - metaprint( 'verbose', "* LDAP bind operation completed successfully." ) if $verbose; - - # Search AD for objects in a particular group using LDAP - - metaprint( 'info', "Getting the LDAP member with expiration." ) if $verbose; - my %searchargs; - $searchargs{base} = $cfg_ldap_group_search; - $searchargs{scope} = $cfg_ldap_search_scope; - $searchargs{filter} = $cfg_ldap_group_search_filter; - $searchargs{attrs} = $cfg_ldap_group_attribute; - - print Dumper( \%searchargs ) if $verbose; - - my $results; - eval { $results = $ldap->search( %searchargs ); }; - if ( $@ ) { - my $title = "Check Password"; - my $msg = "Crash - LDAP Users Search."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); - } elsif ( $results->count() == 0 ) { - metaprint( 'error', 'no result' ); - } else { - metaprint( 'verbose', "* Search returned " . $results->count . " object." ) if $verbose; - print Dumper( $results->as_struct() ) if $verbose; - my $ldap_hash = $results->as_struct(); - - my $attribute = $searchargs{attrs}[0]; - if ( defined( $ldap_hash->{ "cn=$cfg_ldap_groupname," . $searchargs{base} }{$attribute} ) ) { - foreach my $url ( @{ $ldap_hash->{ "cn=$cfg_ldap_groupname," . $searchargs{base} }{$attribute} } ) { - - print "$url\n" if $verbose; - push( @{ $users{$url}{'groups'} }, $cfg_ldap_groupname ); - - } - } else { - metaprint( 'error', "Could not parse the hash result: {" . "cn=$cfg_ldap_groupname," . $searchargs{base} . "} { " . $attribute . " }" ); - } - } - - print "\nClosing LDAP connection.\n" if $verbose; - $ldap->unbind; - return %users; -} - -sub gen_filter -{ - my ( $warningtime ) = @_; - my $dt = DateTime->now; - $dt->subtract( seconds => $warningtime ); - my $filtertime = $dt->strftime( '%Y%m%d%H%M%SZ' ); - return $filtertime; -} - -sub send_email_template ($$$;$) -{ - my ( $uid, $email, $status, $days ) = @_; - - return if $dry_run; - - my $subject = 'Your SNet LDAP password is '; - my $template_file = '/opt/etc/template/InfoTemplate.htm'; - - my $text = ''; - - if ( $status !~ /^LOCKED|EXPIRATION$/ ) { - return 1; - } elsif ( $status eq 'LOCKED' ) { - $subject .= 'expired.'; - $text = - 'Please note that your SNet LDAP account \'' - . $uid - . '\' is expired. Please change your password using the following URL: <ul><li><a href="https://intragate.ec.europa.eu/snet/">SNet Portal</a></li><li> -> Authentication</li><li> -> SNet LDAP Manager</li></ul> Without this step, your SNet account is not usable.'; - } elsif ( ( $status eq 'EXPIRATION' ) && ( $days eq 0 ) ) { - $subject .= 'going to expire TODAY.'; - $text = - 'Please note that your SNet LDAP account \'' - . $uid - . '\' is going to <b>expire TODAY</b>. Please change your password now using the following URL: <ul><li><a href="https://intragate.ec.europa.eu/snet/">SNet Portal</a></li><li> -> Authentication</li><li> -> SNet LDAP Manager</li></ul> Without this step, your SNet account will become not usable <b>Today</b>.'; - } elsif ( $status eq 'EXPIRATION' ) { - $subject .= 'going to expire soon.'; - $text = - 'Please note that your SNet LDAP account \'' - . $uid - . '\' is going to <b>expire in ' - . $days . ' day' - . ( $days > 1 ? 's' : '' ) - . '</b>. Please change your password, before it\'s expiration using the following URL: <ul><li><a href="https://intragate.ec.europa.eu/snet/">SNet Portal</a></li><li> -> Authentication</li><li> -> SNet LDAP Manager</li></ul> Without this step, your SNet account will become not usable in a few days.'; - } - my $real_subject = 'Information - ' . $subject; - - # Open email template. - die "Session date files not found\n" if !-f "$template_file"; - open( TEMPL, "<$template_file" ); - my $htmltext = ''; - while ( my $l = <TEMPL> ) { - $l =~ s/\r*//g; - chomp( $l ); - if ( $l =~ /##TITLE##/ ) { - $l =~ s/##TITLE##/$subject/; - } elsif ( $l =~ /##DESCRIPTION##/ ) { - $l =~ s/##DESCRIPTION##/$text/; - } - - $htmltext .= $l; - } - - # - my $msg = MIME::Lite->new( - From => 'snet@ec.europa.eu', - To => $email, - Subject => $real_subject, - Type => 'multipart/related' - ); - - $msg->attach( - Type => 'text/html', - Data => $htmltext, - Encoding => 'quoted-printable' - ); - - $msg->attach( - Encoding => 'base64', - Type => 'image/jpg', - Path => "/opt/etc/template/snet-banner.jpg", - Id => "image", - Disposition => 'inline', - ); - - $msg->scrub( [ 'x-mailer', 'Content-Disposition' ] ); - - print $msg->as_string if $verbose; - $msg->send(); -} - -# -# Global Declarations -# -# load the INI -metaprint( "info", "Loading INI file Parameters" ); -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -my $CiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'RME' ) ); -metaprint( "error", "error value of CiniFile is undefined" ) if ( !defined( $CiniFile ) ); - -my $outpath = $CiniFile->val( 'GLOBAL', 'OUTPATH' ); -metaprint( "error", "The defined outpath is not valid, please correct-it" ) if ( !defined( $outpath ) ); - -my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); -metaprint( "error", "error value of AiniFile is undefined" ) if ( !defined( $AiniFile ) ); - -my $cfg_ldap_server = $AiniFile->val( 'LDAP_SNET_NG', 'SERVER' ); -metaprint( "error", "error value of cfg_ldap_server is undefined" ) if ( !defined( $cfg_ldap_server ) ); -my $cfg_ldap_user = $AiniFile->val( 'LDAP_SNET_NG', 'USER' ); -metaprint( "error", "error value of cfg_ldap_user is undefined" ) if ( !defined( $cfg_ldap_user ) ); -my $cfg_ldap_passwd = $AiniFile->val( 'LDAP_SNET_NG', 'PASSWORD' ); -metaprint( "error", "error value of cfg_ldap_passwd is undefined" ) if ( !defined( $cfg_ldap_passwd ) ); -my $cfg_ldap_people_base = $AiniFile->val( 'LDAP_SNET_NG', 'PEO_SEARCH' ); -metaprint( "error", "error value of cfg_ldap_people_base is undefined" ) if ( !defined( $cfg_ldap_people_base ) ); -my $cfg_ldap_group_base = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_SEARCH' ); -metaprint( "error", "error value of cfg_ldap_group_base is undefined" ) if ( !defined( $cfg_ldap_group_base ) ); - -my $cfg_ldap_group_search_filter = $AiniFile->val( 'LDAP_SNET_NG', 'FILTER' ); -metaprint( "error", "error value of cfg_ldap_group_search_filter is undefined" ) if ( !defined( $cfg_ldap_group_search_filter ) ); -my $cfg_ldap_group_attribute = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_ATTRIBUTE' ); -metaprint( "error", "error value of cfg_ldap_group_attribute is undefined" ) if ( !defined( $cfg_ldap_group_attribute ) ); -my $cfg_ldap_search_scope = $AiniFile->val( 'LDAP_SNET_NG', 'SEARCH_SCOPE' ); -metaprint( "error", "error value of cfg_ldap_search_scope is undefined" ) if ( !defined( $cfg_ldap_search_scope ) ); -my $cfg_ldap_cafile = $AiniFile->val( 'LDAP_SNET_NG', 'CA' ); -metaprint( "error", "error value of cfg_ldap_cafile is undefined" ) if ( !defined( $cfg_ldap_cafile ) ); - -my $hostname = hostname(); - -# Main Application -metaprint( 'info', "Starting password policy check." ); - -my $date_now = DateTime->now()->set_time_zone( "Europe/Luxembourg" ); - -########### - -my $filter = 'bcp'; -$cfg_ldap_group_attribute = ['memberuid']; -$cfg_ldap_group_search_filter = "(&(objectclass=posixGroup)(cn=REPLACE))"; -$cfg_ldap_group_base = 'ou=posix,' . $cfg_ldap_group_base; -my $cfg_ldap_group_search_f = $cfg_ldap_group_search_filter; -$cfg_ldap_group_search_f =~ s/REPLACE/$filter/; -print "$cfg_ldap_group_search_f\n" if $verbose; -metaprint( 'info', "Checking account '$cfg_ldap_group_base'." ) if $verbose; -my %ldap_bcp_users = ldap_find_users_in_group( $cfg_ldap_server, $cfg_ldap_user, $cfg_ldap_passwd, $cfg_ldap_group_base, $cfg_ldap_search_scope, - $cfg_ldap_group_search_f, $cfg_ldap_group_attribute, $filter, $hostname, $cfg_ldap_cafile ); -metaprint( 'debug', "BCP Users:" . Dumper( \%ldap_bcp_users ) ) if $verbose; - -########### - -# -- Create the import file -my $email_to_send = (); - -metaprint( 'info', "Getting all user with expiration." ) if $verbose; - -my %policies; - -# Connect to the LDAP server -metaprint( 'verbose', "Initiating connection to LDAP server <$cfg_ldap_server>:" ) if $verbose; -my $ldap = Net::LDAP->new( - $cfg_ldap_server, - async => 0, - onerror => ( - ( $debug == 0 ) ? sub { return $_[0] } : sub { - my $message = shift; - my $error = defined( $message->error_desc ) ? $message->error_desc : $message->error(); - $msg = "Ldap: Unable to process request: $error."; - metaprint( 'error', $title . ": " . $msg ); - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - return $message; - } - ), - - # debug => 15, -); -if ( !$ldap ) { - $msg = "LDAP connection to <$cfg_ldap_server> failed."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; -} -metaprint( 'verbose', "* LDAP connection completed successfully." ) if $verbose; - -my $message; -eval { - print STDERR 'Starting tls' . "\n" if ( $debug ); - $message = $ldap->start_tls( verify => 'require', - cafile => $cfg_ldap_cafile, ); - if ( $message->is_error() ) { - $msg = "Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } -}; -if ( $@ ) { - $msg = "Crash - Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; -} - -eval { - print STDERR 'binding' . "\n" if ( $debug ); - $message = $ldap->bind( - $cfg_ldap_user, - password => $cfg_ldap_passwd, - version => 3, - ); - if ( $message->is_error() ) { - $msg = "LDAP bind error occurred."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } -}; -if ( $@ ) { - $msg = "Crash - LDAP bind error occurred ('" . $message->error_name . "')."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; -} - -metaprint( 'verbose', "* LDAP bind operation completed successfully." ) if $verbose; - -# Search AD for objects in a particular group using LDAP - -my $basedn = "dc=ec,dc=europa,dc=eu"; - -# TODO: get defaultpolicy from the cn:config -my %config = ( - 'basedn' => $basedn, - 'defaultpolicy' => "documentIdentifier=default,ou=policies,dc=ec,dc=europa,dc=eu", - 'interval' => '86400', # 1d -); - -metaprint( 'info', "Getting the all password policies." ) if $verbose; -my %searchargs; -$searchargs{base} = $basedn; -$searchargs{scope} = $cfg_ldap_search_scope; -$searchargs{filter} = "(objectclass=pwdPolicy)"; -$searchargs{attrs} = [ 'documentIdentifier', 'pwdMaxAge', 'pwdExpireWarning', 'pwdGraceAuthnLimit' ]; - -print Dumper( \%searchargs ) if $verbose; - -my $results; -eval { $results = $ldap->search( %searchargs ); }; -if ( $@ ) { - my $title = "Check Password"; - my $msg = "Crash - LDAP Password Policy Search."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; -} - -if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); -} elsif ( $results->count() == 0 ) { - metaprint( 'error', 'no result' ); -} else { - metaprint( 'verbose', "* Search returned " . $results->count . " objects 'Password Policy'." ) if $verbose; - - foreach my $entry ( $results->entries ) { - my $pmaxage = $entry->get_value( 'pwdMaxAge' ) ? $entry->get_value( 'pwdMaxAge' ) : 0; - my $pmaxage_d = $pmaxage / 60 / 60 / 24; - my $pexpire = $entry->get_value( 'pwdExpireWarning' ) ? $entry->get_value( 'pwdExpireWarning' ) : 0; - my $pexpire_d = $pexpire / 60 / 60 / 24; - my $pgrace = $entry->get_value( 'pwdGraceAuthnLimit' ) ? $entry->get_value( 'pwdGraceAuthnLimit' ) : 0; - my $warnage = $pmaxage - $pexpire; - my $warnage_d = $warnage / 60 / 60 / 24; - my $policyname = $entry->get_value( 'documentIdentifier' ); - my $policydn = $entry->dn; - metaprint( 'info_ok', "Found password policy '" . $policydn . "'." ); - metaprint( - 'info', - "Policy $policyname with MaxAge:'$pmaxage:$pmaxage_d" - . ( $pmaxage / 60 / 60 / 24 ) - . "d' ExpireWarning:'$pexpire:$pexpire_d" - . ( $pexpire / 60 / 60 / 24 ) - . "d' PwdLife:'$warnage:$warnage_d" - . ( $warnage / 60 / 60 / 24 ) . "d'." - ); - - if ( $warnage <= 0 ) { - metaprint( 'warn', "Policy $policyname has no warning time set, or no expiry." ); - next; - } - my $filterwarn = gen_filter( $warnage ); - my $filterexpire = gen_filter( $pmaxage + $config{'interval'} ); - my $filter; - if ( $policydn eq $config{'defaultpolicy'} ) { - - # objectClass = simpleSecurityObject - # - $filter = "(&(|(&(objectClass=simpleSecurityObject)(!(pwdPolicySubEntry=*)))(pwdPolicySubEntry=$policydn))(|(!(pwdChangedTime=*))(pwdChangedTime<=$filterwarn)))"; - } else { - $filter = "(&(pwdPolicySubEntry=$policydn)(pwdChangedTime<=$filterwarn))"; - } - - metaprint( 'info', "Policy $policyname searching for users about to expire." ); - - my %searchargs; - $searchargs{base} = "ou=SNet,ou=snmc,o=DIGIT,dc=ec,dc=europa,dc=eu"; - $searchargs{scope} = $cfg_ldap_search_scope; - $searchargs{filter} = $filter; - $searchargs{attrs} = [ 'cn', 'uid', 'mail', 'pwdChangedTime', 'pwdGraceUseTime', 'pwdReset', 'createTimestamp' ]; - - print Dumper( \%searchargs ) if $verbose; - - my $mesg; - eval { $mesg = $ldap->search( %searchargs ); }; - if ( $@ ) { - my $title = "Check Password"; - my $msg = "Crash - LDAP Password Policy Search."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - if ( $mesg->is_error() ) { - metaprint( 'error', 'search failed: ' . $mesg->error_text ); - metaprint( 'error', 'search failed: ' . $mesg->code ); - metaprint( 'error', 'search failed: ' . $mesg->error ); - } elsif ( $mesg->count() == 0 ) { - metaprint( 'error', 'no result' ); - } else { - metaprint( 'verbose', "* Search returned " . $mesg->count . " object users." ); - - foreach my $entry ( $mesg->entries ) { - my $changedtime = $entry->get_value( 'pwdChangedTime' ) ? $entry->get_value( 'pwdChangedTime' ) : 0; - my $createtime = $entry->get_value( 'createTimestamp' ) ? $entry->get_value( 'createTimestamp' ) : 0; - my @graceuses = $entry->get_value( 'pwdGraceUseTime' ) ? $entry->get_value( 'pwdGraceUseTime' ) : 0; - my $willexpire = $filterexpire; - my $graceleft = $pgrace - $#graceuses; - my $uid = $entry->get_value( 'uid' ); - my $email = $entry->get_value( 'mail' ) ? $entry->get_value( 'mail' ) : 'digit-snet-sup@ec.europa.eu'; - my $pwdreset = $entry->get_value( 'pwdReset' ); - - if ( lc( $email ) ne $email ) { - metaprint( 'error', "Email '$email' is not lowercase '" . $email . "'." ); - } - - # TODO: Overwrigth for DVE test - # $email = 'david.vernazobres@ext.ec.europa.eu'; - - if ( defined( $ldap_bcp_users{$uid} ) ) { - metaprint( 'info', "'$uid': This is a BCP account, skipping." ); - next; - } elsif ( defined( $pwdreset ) - && ( $pwdreset eq 'TRUE' ) ) { - - if ( $createtime =~ m/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\w+)$/x ) { - my $pass_date = DateTime->new( - year => $1, - month => $2, - day => $3, - hour => $4, - minute => $5, - second => $6, - time_zone => $7, - )->set_time_zone( 'Europe/Luxembourg' ); - my $date_days = $pmaxage_d - ( ( $date_now->local_rd_values )[0] - ( $pass_date->local_rd_values )[0] ); - - # Activate email for lock accounts every 30 days, based on account creation date. - if ( ( $date_days % 30 ) == 0 ) { - metaprint( 'info', "'$uid': Accound is pwdreset enabled, send email ($date_days)." ); - send_email_template( $uid, $email, 'LOCKED' ); - } else { - metaprint( 'info', "'$uid': no email has there is not yet 30 days since the last time ($date_days)." ); - } - - } else { - metaprint( 'info', "'$uid': Accound is pwdreset enabled and in createTimestamp is not valid, this should never happends." ); - } - next; - - } elsif ( $changedtime =~ m/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\w+)$/x ) { - my $pass_date = DateTime->new( - year => $1, - month => $2, - day => $3, - hour => $4, - minute => $5, - second => $6, - time_zone => $7, - )->set_time_zone( 'Europe/Luxembourg' ); - my $date_days = $pmaxage_d - ( ( $date_now->local_rd_values )[0] - ( $pass_date->local_rd_values )[0] ); - if ( $date_days > 0 ) { - metaprint( 'info', "'$uid': Accound validity is positiv ($date_days)." ); - if ( ( $date_days == 30 ) || ( $date_days == 25 ) || ( $date_days == 20 ) ) { - send_email_template( $uid, $email, 'EXPIRATION', $date_days ); - } elsif ( $date_days <= 10 ) { - send_email_template( $uid, $email, 'EXPIRATION', $date_days ); - } - } elsif ( $date_days == 0 ) { - metaprint( 'info', "'$uid': Accound validity is zero ($date_days)." ); - send_email_template( $uid, $email, 'EXPIRATION', $date_days ); - } elsif ( $date_days < 0 ) { - - # If the expiration is bigger than 5, do not worry, nobody care. - if ( $date_days > -5 ) { - metaprint( 'info', "'$uid': Accound validity is negativ ($date_days), still trying." ); - send_email_template( $uid, $email, 'LOCKED' ); - } elsif ( ( $date_days % 10 ) == 0 ) { - metaprint( 'info', "'$uid': Accound validity is negativ ($date_days), today is going to be a good day!" ); - send_email_template( $uid, $email, 'LOCKED' ); - } else { - metaprint( 'info', "'$uid': Accound validity is negativ ($date_days), but no email." ); - } - } else { - metaprint( 'info', "'$uid': Accound validity error, this should never happends ($date_days)." ); - } - next; - } - metaprint( 'error', "'$uid': Accound has no changedtime, so account is locked." ); - send_email_template( $uid, $email, 'LOCKED' ); - } - } - } -} - -print "\nClosing LDAP connection.\n" if $verbose; -$ldap->unbind; - -metaprint( "info", "--- Process Done ---" ); -exit( 0 ); diff --git a/bin/ldap2sid.pl b/bin/ldap2sid.pl deleted file mode 100755 index f6daa4b..0000000 --- a/bin/ldap2sid.pl +++ /dev/null @@ -1,380 +0,0 @@ -#!/usr/bin/perl -# -use strict; -use warnings; - -# -use Data::Dumper; -use Config::IniFiles; -use File::Basename; -use CGI qw/:standard/; -use Spreadsheet::WriteExcel; -use Getopt::Long; -use JSON; -use utf8; - -# Remove non-breaking space char -binmode( STDOUT, ":utf8" ); - -use Net::LDAP; -use Cache::FileCache; - -# unbuffered output: -$| = 1; - -BEGIN { - my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $global_iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} -use SNET::access; -use SNET::common; -use SNET::dumper; -use SNET::html; -use SNET::libdb; -use SNET::ActiveDirectory; - -use vars qw($verbose $debug $help $env $script $force $cli_mode $stderr); -$debug = 0; -$verbose = 0; -( $script ) = split( /\./, basename( $0 ) ); -$stderr = 1; - -my $title = "LDAP Group User Check"; -my $function = $title; -$function =~ s/\s/_/g; -my $href = ""; -my $header = h1( a( { href => "/cgi-bin/nCheck/$script.pl" }, $title ) ); -my $html_msg = ""; - -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -$env = "test"; -( $html_msg ) = Access_snet_script_head( $script, $global_iniFile, $ENV, $env ); - -# -# Global Declarations -# -my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); -$html_msg .= "error value of AiniFile is undefined" . "\n" if ( !defined( $AiniFile ) ); -my $ldapserver = $AiniFile->val( 'LDAP_EC', 'SERVER' ); -$html_msg .= "error value of ldapserver is undefined" . "\n" if ( !defined( $ldapserver ) ); -my $basedn = $AiniFile->val( 'LDAP_EC', 'BASE' ); -$html_msg .= "error value of basedn is undefined" . "\n" if ( !defined( $basedn ) ); -my $ldapuser = $AiniFile->val( 'LDAP_EC', 'USER' ); -$html_msg .= "error value of ldapuser is undefined" . "\n" if ( !defined( $ldapuser ) ); -my $ldappasswd = $AiniFile->val( 'LDAP_EC', 'PASSWORD' ); -$html_msg .= "error value of ldappasswd is undefined" . "\n" if ( !defined( $ldappasswd ) ); - -my $cfg_ldap_server = $AiniFile->val( 'LDAP_SNET_NG', 'SERVER' ); -$html_msg .= "error value of cfg_ldap_server is undefined" . "\n" if ( !defined( $cfg_ldap_server ) ); -my $cfg_ldap_user = $AiniFile->val( 'LDAP_SNET_NG', 'USER' ); -$html_msg .= "error value of cfg_ldap_user is undefined" . "\n" if ( !defined( $cfg_ldap_user ) ); -my $cfg_ldap_passwd = $AiniFile->val( 'LDAP_SNET_NG', 'PASSWORD' ); -$html_msg .= "error value of cfg_ldap_passwd is undefined" . "\n" if ( !defined( $cfg_ldap_passwd ) ); -my $cfg_ldap_group_search = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_SEARCH' ); -$html_msg .= "error value of cfg_ldap_group_search is undefined" . "\n" if ( !defined( $cfg_ldap_group_search ) ); -my $cfg_ldap_group_search_filter = $AiniFile->val( 'LDAP_SNET_NG', 'FILTER_posix' ); -$html_msg .= "error value of cfg_ldap_group_search_filter is undefined" . "\n" if ( !defined( $cfg_ldap_group_search_filter ) ); -my $cfg_ldap_group_attribute = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_ATTRIBUTE' ); -$html_msg .= "error value of cfg_ldap_group_attribute is undefined" . "\n" if ( !defined( $cfg_ldap_group_attribute ) ); -my $cfg_ldap_search_scope = $AiniFile->val( 'LDAP_SNET_NG', 'SEARCH_SCOPE' ); -$html_msg .= "error value of cfg_ldap_search_scope is undefined" . "\n" if ( !defined( $cfg_ldap_search_scope ) ); -my $cfg_ldap_cafile = $AiniFile->val( 'LDAP_SNET_NG', 'CA' ); -$html_msg .= "error value of cfg_ldap_cafile is undefined" . "\n" if ( !defined( $cfg_ldap_cafile ) ); - -my $all_ldap_group = $AiniFile->val( 'LDAP_EC', 'SID_GROUP' ); -$html_msg .= "error value of all_ldap_group is undefined" . "\n" if ( !defined( $all_ldap_group ) ); - -###### - -my $groups = (); -@$groups = split( ',', $all_ldap_group ); - -my $colnames = [ 'uid', 'cn', 'departmentNumber', 'physicalDeliveryOfficeName', 'building', 'dg', 'telephoneNumber' ]; - -# Get all the SNet member of NS. -my $snet_member = {}; -my $off_member = {}; - -my $group = ''; - -my $cache_report = new Cache::FileCache( - { - 'namespace' => 'nCheck_ldap_group_check', - 'cache_root' => '/opt/resources_SNet/DGtools', - 'default_expires_in' => '1h', - 'auto_purge_interval' => '1h' - } -); - -metaprint( 'info', "init_cache cache_report" ) if $verbose; - -$force = 0; -$force = 1 if ( ( defined( param( 'force' ) ) ) && ( param( 'force' ) !~ /^$/ ) && ( param( 'force' ) =~ /^Reload$/ ) ); -$verbose = 1 if ( ( defined( param( 'verbose' ) ) ) && ( param( 'verbose' ) !~ /^$/ ) && ( param( 'verbose' ) =~ /^[\d\w]+$/ ) && ( param( 'verbose' ) eq 'godmode1' ) ); - -my $res = $cache_report->get( 'snet_member' ); -if ( ( !defined $res ) || $force ) { - - undef( $res ); - - # do action - my $ldap = Net::LDAP->new( - $cfg_ldap_server, - async => 0, - onerror => ( - ( $debug == 0 ) ? sub { return $_[0] } : sub { - my $message = shift; - my $error = defined( $message->error_desc ) ? $message->error_desc : $message->error(); - print STDERR 'Ldap: Unable to process request: ' . $error . "\n"; - return $message; - } - ), - ); - - if ( !$ldap ) { - metaprint 'error', "Could not connect to LDAP: $cfg_ldap_server!"; - exit 1; - } - - metaprint( 'info', "LDAP connection completed successfully." ) if $verbose; - - my $message; - eval { - print STDERR 'Starting tls' . "\n" if ( $debug ); - $message = $ldap->start_tls( verify => 'require', - cafile => $cfg_ldap_cafile, ); - if ( $message->is_error() ) { - metaprint( 'error', "Could not encrypt LDAP connection." ); - exit 1; - } - }; - if ( $@ ) { - metaprint( 'error', "Crash - Could not encrypt LDAP connection." ); - exit 1; - } - - eval { - print STDERR 'binding' . "\n" if ( $debug ); - $message = $ldap->bind( - $cfg_ldap_user, - password => $cfg_ldap_passwd, - version => 3, - ); - if ( $message->is_error() ) { - metaprint( 'error', "LDAP bind error occurred." ); - exit 1; - } - }; - if ( $@ ) { - metaprint( 'error', "Crash - LDAP bind error occurred" ); - exit 1; - } - - metaprint( 'info', "LDAP bind operation completed successfully." ) if $verbose; - - my $snetcol = [ 'memberUid', 'cn' ]; - $cfg_ldap_group_attribute = [ 'memberUid', 'cn' ]; - $group = '|(cn=com)(cn=ss)(cn=sd)(cn=pm)(cn=net)(cn=sec)(cn=tda)(cn=mgt)(cn=pi)(cn=bcp)'; - - my %searchargs; - my $cfg_ldap_group_search_f = $cfg_ldap_group_search_filter; - $cfg_ldap_group_search_f =~ s/cn=REPLACE/$group/; - - $searchargs{base} = $cfg_ldap_group_search; - $searchargs{scope} = $cfg_ldap_search_scope; - $searchargs{filter} = $cfg_ldap_group_search_f; - $searchargs{attrs} = $cfg_ldap_group_attribute; - - metaprint( 'info', Dumper( \%searchargs ) ) if $verbose; - - my $results; - eval { - print STDERR 'searching' . "\n" if ( $debug ); - $results = $ldap->search( %searchargs ); - if ( $results->is_error() ) { - metaprint( 'error', "LDAP search error occurred:" . $results->code . " : " . $results->error ); - exit 1; - } - }; - if ( $@ ) { - metaprint( 'error', "Crash - LDAP Users Search." ); - exit 1; - } - - my $count = $results->count; - if ( $count >= 1 ) { - foreach my $entry ( $results->entries ) { - foreach my $key ( $entry->get_value( $snetcol->[0] ) ) { - push( @{ $snet_member->{"$key"} }, $entry->get_value( $snetcol->[1] ) ); - } - } - } else { - $html_msg .= "$group is an empty group.\n" . br; - } - AD_disconnect( $ldap ); - print Dumper ( $snet_member ) if ( $debug ); - - $cache_report->set( 'snet_member', $snet_member ); -} else { - $snet_member = $res; -} - -# print html_rendering (Dumper ( $snet_member ) ); - -###### - -my $fromcache = 1; -my $data = []; - -foreach my $group ( @{$groups} ) { - - my $gdata = $cache_report->get( $group ); - if ( ( !defined $gdata ) || $force ) { - - undef( $gdata ); - - # do action - my $ldap = AD_connect( $ldapserver, $ldapuser, $ldappasswd ); - - my $searchquery = "(&(objectclass=*)(cudgroup=$group))"; - - my $filter = "cudgroup=$group"; - - my $results = $ldap->search( base => $basedn, filter => $filter, attrs => $colnames ); - my $count = $results->count; - $html_msg .= "Total entries returned for $group: $count." . "\n" if $main::debug; - - if ( $count >= 1 ) { - foreach my $entry ( $results->entries ) { - my $tmp = (); - push( @{$tmp}, $group ); - foreach my $cln ( @{$colnames} ) { - push( @{$tmp}, ( $entry->get_value( $cln ) ? $entry->get_value( $cln ) : '' ) ); - } - push( @{$gdata}, $tmp ); - } - } else { - $html_msg .= "$group is an empty group." . br; - } - - AD_disconnect( $ldap ); - - $cache_report->set( $group, $gdata ); - } - - foreach my $dd ( @{$gdata} ) { - push( @{$data}, $dd ); - } -} - -# taking LDAP group 'DIGIT_NS_TEAM' as reference, for the official list members. - -$group = 'DIGIT_NS_TEAM'; -foreach my $member ( - grep { !/^$/ } map { - if ( $_->[0] eq $group ) { $_->[1] } - } map { - $_ - } @$data - ) { - $off_member->{$member} = 1; -} - -###### - -# print Dumper ( $data ); -my $data_users = (); -my $data_groups = (); - -my $cln = (); -for ( my $i = 0 ; $i <= $#{$colnames} ; $i++ ) { - $cln->{ $colnames->[$i] } = ( $i + 1 ); -} -print Dumper ( $cln ); - -for my $group ( @{$groups} ) { - print( "Group is $group\n" ); - $data_groups->{$group} = (); - foreach my $d ( @$data ) { - next if ( $d->[0] ne $group ); - - # if ( $d->[1] eq 'alogin' ) { - # print Dumper( $d ); - # } - - #$VAR1 = [ - # 'DIGIT_UNIX', group - # 'gabrigr', uid - # 'GABRIEL Gregory', cn - # 'DIGIT.C.3.004', departement - # 'DRB- D1/007E' physical delivry Office - # ]; - # colnames: 'uid', 'cn', 'departmentNumber', 'physicalDeliveryOfficeName', 'building', 'dg', 'telephoneNumber' - my $member = $d->[ $cln->{'uid'} ]; - if ( $group eq 'DIGIT_SNET' ) { - - # Could not be part of official and SNet at the same time - next if ( defined( $off_member->{$member} ) && ( $off_member->{$member} ) ); - - # Should be declared in Snet LDAP system. - next if ( !defined( $snet_member->{$member} ) ); - - foreach my $g ( @{ $snet_member->{$member} } ) { - next if ( $g eq 'bcp' ); - push( @{ $data_groups->{ $group . '_' . uc( $g ) }{'contains'} }, $member ); - push( @{ $data_users->{$member}{'is_members_of'} }, $group . '_' . uc( $g ) ); - } - } elsif ( $group eq 'DIGIT_SNET_PROX' ) { - if ( ( $member !~ /^j/ ) && ( $member !~ /^x/ ) ) { - - # TODO open a ticket to request removal.... - next; - } - } - push( @{ $data_groups->{$group}{'contains'} }, $member ); - push( @{ $data_users->{$member}{'is_members_of'} }, $group ); - $data_users->{$member}{'departement'} = $d->[ $cln->{'departmentNumber'} ]; - $data_users->{$member}{'office'} = $d->[ $cln->{'physicalDeliveryOfficeName'} ]; - $data_users->{$member}{'cn'} = $d->[ $cln->{'cn'} ]; - $data_users->{$member}{'building'} = $d->[ $cln->{'building'} ]; - $data_users->{$member}{'dg'} = $d->[ $cln->{'dg'} ]; - $data_users->{$member}{'telephoneNumber'} = $d->[ $cln->{'telephoneNumber'} ]; - - # cleaning stuff - $data_users->{$member}{'building'} =~ s/\-$//; - $data_users->{$member}{'office'} =~ s/^.+\s//; - - # 'office' => 'D2/058',$ - if ( $data_users->{$member}{'office'} =~ /\// ) { - $data_users->{$member}{'nop'} = $data_users->{$member}{'office'}; - if ( $data_users->{$member}{'office'} =~ /^([A-Za-z])/ ) { - $data_users->{$member}{'aisle'} = $1; - } - if ( $data_users->{$member}{'office'} =~ /^[A-Za-z]?(\d+)\// ) { - $data_users->{$member}{'floor'} = $1; - $data_users->{$member}{'floor'} =~ s/^0//; - } - $data_users->{$member}{'office'} =~ s/^.*\///; - } - } -} -print Dumper( $data_users ); - -my $json; -my $cert_data; -print Dumper ( $data_groups ); -$json = JSON->new->allow_nonref; -$cert_data = $json->pretty->canonical->encode( $data_groups ); -open( OUTFILE, ">/tmp/groups.json" ); -print OUTFILE $cert_data; -close( OUTFILE ); - -print Dumper ( $data_users ); -$json = JSON->new->allow_nonref; -$cert_data = $json->pretty->canonical->encode( $data_users ); -open( OUTFILE, ">/tmp/users.json" ); -print OUTFILE $cert_data; -close( OUTFILE ); - -exit 0; diff --git a/bin/ldap_NS.pl b/bin/ldap_NS.pl deleted file mode 100755 index 7fe541b..0000000 --- a/bin/ldap_NS.pl +++ /dev/null @@ -1,4197 +0,0 @@ -#!/usr/bin/perl -T - -# -use strict; -use warnings FATAL => 'all'; -use diagnostics; - -use Data::Dumper; -use Config::IniFiles; -use File::Basename; -use Sys::Hostname; - -use Net::LDAP; - -use CHI; -use CGI; -use CGI::Ajax; -use CGI::Cookie; -use CGI::FormBuilder; -use CGI::Session::ID::md5; -use CGI::Session qw/-ip_match/; -use CGI::Untaint; -use HTML::Template; - -use Crypt::CBC; -use Crypt::Blowfish; -use Crypt::SmbHash; -use MIME::Base64; -use DateTime; - -# unbuffered output: -$| = 1; - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} - -use SNET::access; -use SNET::common; -use SNET::html; -use SNET::ActiveDirectory; -use SNET::LdapNS qw(:all); - -use Net::LDAP::Constant qw( - LDAP_CONTROL_PASSWORDPOLICY - LDAP_PP_PASSWORD_EXPIRED - LDAP_PP_ACCOUNT_LOCKED - LDAP_PP_CHANGE_AFTER_RESET -); - -use SNET::Magic::MagicHash; - -my $stderr = 1; -my $cli_mode = 0; -my $ldap_snmc; -my $redis_hostport; - -my $htmlbasedir = '/snet/cgi-bin/auth'; -my $homepage = $htmlbasedir . '/ldap_NS.pl'; -my $templatedir = '/opt/auth/templates'; - -my ( $cgi, $params, $error, $message, $sid, $session, $key ); -my ( $connected, $isAdmin, $userMustChange, $audit_user ); -my $debug; - -my $LOGIN; -my ( $TAB_HOME, $INFO, $PASSWD, $EXPIRED ); -my ( $TAB_USERS, $USERINFOS, $DELUSER, $ADDUSER, $ADDUSERPROFILE, $MODUSER, $RESET ); -my ( $TAB_GROUPS, $GROUPINFOS, $DELGROUP, $ADDGROUP, $MODGROUP ); -my ( $TAB_POLICY, $POLICYINFOS, $DELPOLICY, $ADDPOLICY, $MODPOLICY ); - -sub reconnect_ldap_snmc(); -sub refresh_posixGroups(); -sub refresh_userInfos(); -sub reset_tab_actions(); -sub display_passwd(); - -# used by check_remote_infos -my $authorized_ip = [qw(158.167.133.90 158.166.133.90 158.166.133.6 158.167.133.6 158.166.164.6 158.167.134.6 192.168.46.46)]; -my $authorized_ip_regex = [qw(^(10\.215\.4[0123]\.|10\.134\.240\.|10\.226\.(49|50)\.))]; - -# if != 0, synchronize change with snmc-ldapns and nms-nls -my $mod_synchro; - -INIT { - - # unbuffered output: - $| = 1; - - # turn on/off debug - # if isAdmin is set, will be automatically set to 2 - $debug = 1; - $stderr = 1; - $cli_mode = 0; - - $mod_synchro = 0; - - ( $connected, $isAdmin, $userMustChange ) = ( 0, 0, 0 ); - - my $local_server = 'vldap-jmo.snmc.cec.eu.int'; - my $hostname = hostname(); - if ( $hostname =~ /-dev$/ ) { - $local_server = 'vldap01.dev.snmc.cec.eu.int'; - } - - my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - my $cache_env = 'prod-cache'; - if ( $hostname =~ /-dev$/ ) { - $cache_env = 'dev-cache'; - } - $redis_hostport = $global_iniFile->val( $cache_env, 'Url' ); - - $ldap_snmc = { - - #'server' => 'ldap.snmc.cec.eu.int', - 'server' => $local_server, - 'label' => 'ldap_snmc', - 'starttls' => 1, - 'debug' => $debug, - 'verbose' => $debug, - }; - - reset_tab_actions; - - # add and overwrite some FormBuilder validation methods - my $validate = \%CGI::FormBuilder::Field::VALIDATE; - - $validate->{'IM'} = '/^IM[0-9]{10}$/'; - - my $uid = '[a-zA-Z][\-a-zA-Z0-9]{6,16}'; - $validate->{'UID'} = '/^' . $uid . '$/'; - - my $word = '[a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9]'; - my $anchored_word = '/^' . $word . '$/'; - - my $peopletree = $SNET::LdapNS::PEOPLE . ',' . $SNET::LdapNS::SNET; - $validate->{'USERDN'} = '/^(?i)uid=' . $uid . ',' . $peopletree . '$/'; - - $validate->{'GROUP'} = $anchored_word; - - $validate->{'UIDNUMBER'} = '/^[2-9][0-9]{3}$/'; - $validate->{'GIDNUMBER'} = '/^[2-9][0-9]{3}$/'; - $validate->{'EMAIL'} = '/^[\w\-\+\._]+\@[a-zA-Z0-9][-a-zA-Z0-9\.]*(\.[a-zA-Z]+)+$/'; - $validate->{'GECOS'} = '/^\w+(\s+\w+)+$/'; - $validate->{'FIRSTNAME'} = '/^\w+(\s+\w+)*$/'; - $validate->{'DESCRIPTION'} = '/^\w+(\s+\w+)*$/'; - $validate->{'GROUPCLASS'} = '/^(posixGroup|groupOfNames|groupOfUniqueNames)$/'; - $validate->{'PROFILE'} = '/^(Architect|Compliance|Development|Managment|Network|Noca|Officials|Ois|ProjectManager|Security|System|Videoconference)$/'; - $validate->{'STATE'} = '/^(Luxembourg|Belgium)$/'; - - $validate->{'PPOLICY'} = $anchored_word; - $validate->{'PPOLICYDN'} = '/^(?i)documentIdentifier=' . $word . ',' . $SNET::LdapNS::POLICIES . '/'; - - while ( my ( $k, $v ) = each %{$SNET::LdapNS::pwdPolicyAttributes} ) { - my $type = ${$v}[0]; - if ( $type eq 'bool' ) { - $validate->{$k} = '/^(true|false)$/'; - } elsif ( $type eq 'nbool' ) { - $validate->{$k} = '/^(counted|forbidden)$/'; - } elsif ( $type eq 'extbool' ) { - $validate->{$k} = '/^(on|off|strict)$/'; - } elsif ( ( $type eq 'int' ) || ( $type eq 'second' ) ) { - $validate->{$k} = '/^[0-9]+$/'; - } - } - -} - -sub reset_actions() -{ - ( $INFO, $PASSWD ) = ( 0, 0 ); - ( $USERINFOS, $DELUSER, $ADDUSER, $ADDUSERPROFILE, $MODUSER, $RESET ) = ( 0, 0, 0, 0, 0, 0 ); - ( $GROUPINFOS, $DELGROUP, $ADDGROUP, $MODGROUP ) = ( 0, 0, 0, 0 ); - ( $POLICYINFOS, $DELPOLICY, $ADDPOLICY, $MODPOLICY ) = ( 0, 0, 0, 0 ); -} - -sub reset_tab_actions() -{ - $LOGIN = 0; - $TAB_HOME = 0; - $TAB_USERS = 0; - $TAB_GROUPS = 0; - $TAB_POLICY = 0; - reset_actions(); -} - -sub parse_messages() -{ - if ( defined( $session ) && defined( $session->param( 'error' ) ) ) { - $error = $session->param( 'error' ); - $session->clear( ['error'] ); - } - if ( defined( $session ) && defined( $session->param( 'message' ) ) ) { - $message = $session->param( 'message' ); - $session->clear( ['message'] ); - } - $error =~ s/\s+at\s+(\/|ldap).*//i if ( defined( $error ) && ( $debug < 2 ) ); -} - -sub redirect($) -{ - my $params = shift; - $params = '?tab=home' unless ( defined( $params ) && ( $params =~ m/^\?.+=.+/ ) ); - if ( $params =~ m/\?tab=([[:alnum:]]+)/ ) { - $session->param( 'tab', $1 ); - } - print $cgi->redirect( $homepage . $params, -status => 302 ); - exit 0; -} - -sub redirect_login() -{ - redirect( '?login=1' ); -} - -sub redirect_homepage() -{ - redirect( '?tab=home' ); -} - -sub ldapns_logout() -{ - $session->delete(); - redirect_login; -} - -sub synchronize_del_users($$) -{ - - my ( $uid, $synchronize ) = @_; - - print STDERR "synchronize_del_users($mod_synchro/$synchronize)\n"; - - return unless ( $mod_synchro && $synchronize ); - - my $error_msg = "unable to delete user from old database: "; - my $error = 0; - my $binddn; - - eval { - - die "invalid uid" unless ( defined( $uid ) ); - - my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - my $ldap_iniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); - - my $binddn = $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'USER' ); - my $passwd = $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'PASSWORD' ); - my @servers = split( /,/, $ldap_iniFile->val( 'LDAP_SNET_SERVER_LIST', 'SERVERS' ) ); - - SNET::LdapNS::ldapns_add_dn_exception( $binddn ); - - foreach my $server ( @servers ) { - - my $host = $ldap_iniFile->val( $server, 'SERVER' ); - my $base = $ldap_iniFile->val( $server, 'BASE' ); - - die "invalid host `$host'" unless ( $host =~ m/^(?:ldap:\/\/)?([^:]+)(?::389)?$/i ); - my $fqdn = $1; - - SNET::LdapNS::ldapns_bind( $fqdn, $binddn, $passwd, $host, 'LDAPISS', 0, 0, 0 ); - - my $connection = SNET::LdapNS::get_connection( $host ); - - $uid = $connection->clean_dn( $uid ); - my $res; - - eval { $res = SNET::LdapNS::getPosixAccount( $host, $uid, 'ou=People,' . $base ); }; - if ( $@ ) { - $error++; - $error_msg .= "[uid=$uid]: skipping missing user; "; - print STDERR "synchronize_del_users: skipping non-existing user `$uid'\n"; - next; - } - - print STDERR "synchronize_del_users: deleting user `$uid'\n"; - my @keys = keys( %{$res} ); - my $dn = shift( @keys ); - die "invalid uid `$uid'" unless ( lc( $dn ) eq lc( 'uid=' . $uid . ',ou=People,' . $base ) ); - - eval { - - my $entry = Net::LDAP::Entry->new( $dn ); - $entry->delete(); - my $result = $entry->update( $connection->{'connection'} ); - die "[uid=$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - # update automount - $entry = Net::LDAP::Entry->new( 'automountKey=' . $uid . ',automountMapName=auto_home,' . $base, ); - $entry->delete(); - $result = $entry->update( $connection->{'connection'} ); - die "[homedir=$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - # update cn=snmc - $entry = Net::LDAP::Entry->new( 'cn=snmc,ou=group,' . $base, ); - $entry->changetype( 'modify' ); - $entry->delete( 'memberUid' => [$uid] ); - $result = $entry->update( $connection->{'connection'} ); - die "[cn=snmc:$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - # update cn=NS - $entry = Net::LDAP::Entry->new( 'cn=NS,ou=group,' . $base, ); - $entry->changetype( 'modify' ); - $entry->delete( 'memberUid' => [$uid] ); - $result = $entry->update( $connection->{'connection'} ); - die "[cn=snmc:$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - }; - if ( $@ ) { - $error_msg .= '[' . $host . '] ' . $@ . ';'; - $error++; - } - - } - - }; - if ( $@ ) { - $error++; - $error_msg .= $@; - } - SNET::LdapNS::ldapns_del_dn_exception( $binddn ) if ( defined( $binddn ) ); - $session->param( 'error', $error_msg ) if ( $error ); - -} - -sub synchronize_add_users($$) -{ - - my ( $entry, $synchronize ) = @_; - return unless ( $mod_synchro && $synchronize ); - - my $error_msg = "unable to synchronize user with old database: "; - my $error = 0; - my $binddn; - - eval { - - my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - my $ldap_iniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); - - my $binddn = $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'USER' ); - my $passwd = $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'PASSWORD' ); - my @servers = split( /,/, $ldap_iniFile->val( 'LDAP_SNET_SERVER_LIST', 'SERVERS' ) ); - my $homeserver = $ldap_iniFile->val( 'LDAP_SNET_HOMESERVER', 'SERVER' ); - - SNET::LdapNS::ldapns_add_dn_exception( $binddn ); - - die "invalid entry" unless ( defined( $entry ) - && ( ref( $entry ) eq 'HASH' ) ); - - my %nocasehash; - tie %nocasehash, 'MagicHash', { 'KEY' => sub { return lc( $_[0] ) }, }; - - while ( my ( $k, $v ) = each %{$entry} ) { - - die 'entry uid undefined' unless ( ( ref( $v ) eq 'HASH' ) && ( defined( $v->{'uid'} ) ) ); - - my %nocasehash_v; - tie %nocasehash_v, 'MagicHash', { 'KEY' => sub { return lc( $_[0] ) }, }; - while ( my ( $kk, $vv ) = each %{$v} ) { - $nocasehash_v{$kk} = $vv; - } - $nocasehash{$k} = \%nocasehash_v; - - $nocasehash{$k}->{'homeDirectory'} = [ '/home/' . ${ $v->{'uid'} }[0] ]; - $nocasehash{$k}->{'shadowLastChange'} = ['11640']; - $nocasehash{$k}->{'shadowFlag'} = [0]; - $nocasehash{$k}->{'loginShell'} = ['/bin/ksh']; - $nocasehash{$k}->{'cn'} = [ ${ $v->{'uid'} }[0] ]; - - } - - foreach my $server ( @servers ) { - - my $host = $ldap_iniFile->val( $server, 'SERVER' ); - my $base = $ldap_iniFile->val( $server, 'BASE' ); - my $class = $ldap_iniFile->val( $server, 'MAILCLASS' ); - - die "invalid host `$host'" unless ( $host =~ m/^(?:ldap:\/\/)?([^:]+)(?::389)?$/i ); - my $fqdn = $1; - - SNET::LdapNS::ldapns_bind( $fqdn, $binddn, $passwd, $host, 'LDAPISS', 0, 0, 0 ); - - my $connection = SNET::LdapNS::get_connection( $host ); - - while ( my ( $k, $v ) = each %nocasehash ) { - - my $uid = $connection->clean_dn( ${ $v->{'uid'} }[0] ); - my $res; - - eval { $res = SNET::LdapNS::getPosixAccount( $host, $uid, 'ou=People,' . $base ); }; - if ( !$@ ) { - if ( defined( $res ) && ( keys( %{$res} ) >= 1 ) ) { - $error++; - $error_msg .= "[uid=$uid]: skipping existing user; "; - print STDERR "synchronize_add_users: skipping existing user `$uid'\n"; - next; - } - } - - print STDERR "synchronize_add_users: synchronizing user `$uid'\n"; - - delete( $v->{'objectclass'} ); - delete( $v->{'auditinformation'} ); - delete( $v->{'pwdreset'} ); - - $v->{'objectClass'} = [ qw(top posixAccount shadowAccount account), $class ]; - - my $dn = 'uid=' . $uid . ',ou=People,' . $base; - - eval { - - my $entry = Net::LDAP::Entry->new( $dn ); - while ( my ( $kk, $vv ) = each %{$v} ) { - $entry->add( $kk => $vv ); - } - $entry->changetype( 'add' ); - - #print STDERR 'uid='.$uid.',ou=People,'.$base.' => '.Dumper($entry)."\n"; - - my $result = $entry->update( $connection->{'connection'} ); - die "[uid=$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - # update automount - $entry = Net::LDAP::Entry->new( - 'automountKey=' . $uid . ',automountMapName=auto_home,' . $base, - 'automountkey' => [$uid], - 'objectClass' => [ 'automount', 'top' ], - 'automountInformation' => [ $homeserver . ':/opt/home/&' ], - ); - $entry->changetype( 'add' ); - $result = $entry->update( $connection->{'connection'} ); - die "[homedir=$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - # update cn=snmc - $entry = Net::LDAP::Entry->new( 'cn=snmc,ou=group,' . $base, ); - $entry->changetype( 'modify' ); - $entry->add( 'memberUid' => [$uid] ); - $result = $entry->update( $connection->{'connection'} ); - die "[cn=snmc=$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - # update cn=NS - $entry = Net::LDAP::Entry->new( 'cn=NS,ou=group,' . $base, ); - $entry->changetype( 'modify' ); - $entry->add( 'memberUid' => [$uid] ); - $result = $entry->update( $connection->{'connection'} ); - die "[cn=snmc=$uid]: " . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . '; ' if ( $result->is_error() ); - - }; - if ( $@ ) { - $error_msg .= '[' . $host . '] ' . $@ . ';'; - $error++; - } - - } - - } - - }; - if ( $@ ) { - $error++; - $error_msg .= $@; - } - SNET::LdapNS::ldapns_del_dn_exception( $binddn ) if ( defined( $binddn ) ); - $session->param( 'error', $error_msg ) if ( $error ); - -} - -sub synchronize_samba_password($$;$) -{ - - my $error_msg = "unable to synchronize password with samba credential: "; - my $error = 0; - - eval { - my ( $label, $new, $uid ) = @_; - - die 'missing parameters' unless ( defined( $label ) && defined( $new ) ); - - my $ldap = SNET::LdapNS::get_connection( $label ) - or die "invalid connection's label `$label'"; - - if ( defined( $uid ) ) { - $uid = $ldap->clean_dn( $uid ); - } else { - $uid = $ldap->clean_dn( $ldap->{'user'} ); - } - - $error_msg .= '[uid=' . $uid . '] : '; - - ### If user NOT is SAMBA compliant: - SNET::LdapNS::check_user_smb_ready( $label, $uid ); - - # TODO: inject SAMBA schema. - - my ( $lm, $nt ) = ntlmgen $new; - my $dt = DateTime->now()->set_time_zone( "Europe/Luxembourg" ); - my $current_epoch = $dt->epoch(); - - SNET::LdapNS::smb_passwd( $label, $lm, $nt, $current_epoch, $uid ); - - }; - if ( $@ ) { - $error++; - $error_msg .= $@; - } - - $session->param( 'error', $error_msg ) if ( $error ); - -} - -sub synchronize_passwords($$$;$$) -{ - - my $error_msg = "unable to synchronize password with old database: "; - my $error = 0; - - eval { - - my ( $synchronize, $label, $new, $uid, $old ) = @_; - return unless ( $mod_synchro && $synchronize ); - - die 'missing parameters' unless ( defined( $label ) && defined( $new ) ); - - my $ldap = SNET::LdapNS::get_connection( $label ) - or die "invalid connection's label `$label'"; - - if ( defined( $uid ) ) { - $uid = $ldap->clean_dn( $uid ); - } else { - $uid = $ldap->clean_dn( $ldap->{'user'} ); - } - - $error_msg .= '[uid=' . $uid . '] : '; - - my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - my $ldap_iniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); - - my $salt = join '', ( '.', '/', 0 .. 9, 'A' .. 'Z', 'a' .. 'z' )[ rand 64, rand 64 ]; - my $crypt = '{CRYPT}' . crypt( $new, $salt ); - - my @servers = split( /,/, $ldap_iniFile->val( 'LDAP_SNET_SERVER_LIST', 'SERVERS' ) ); - - foreach my $server ( @servers ) { - - my $host = $ldap_iniFile->val( $server, 'SERVER' ); - my $base = $ldap_iniFile->val( $server, 'BASE' ); - - eval { - - die "invalid host `$host'" unless ( $host =~ m/^(?:ldap:\/\/)?([^:]+)(?::389)?$/i ); - my $fqdn = $1; - - my $dn = 'uid=' . $uid . ',ou=People,' . $base; - my $binddn; - my $passwd; - - if ( defined( $old ) ) { - $binddn = 'uid=' . $uid . ',ou=People,' . $base; - $passwd = $old; - } else { - $binddn = $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'USER' ); - $passwd = $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'PASSWORD' ); - die "not going to reset $binddn password" if ( lc( $dn ) eq lc( $binddn ) ); - SNET::LdapNS::ldapns_add_dn_exception( $binddn ); - } - - SNET::LdapNS::ldapns_bind( $fqdn, $binddn, $passwd, $host, 'LDAPISS', 0, 0, 0 ); - - my $connection = SNET::LdapNS::get_connection( $host ); - - if ( defined( $old ) ) { - $connection->passwd2( $dn, $old, $crypt ); - } else { - $connection->passwd2( $dn, $salt, $crypt ); - } - - }; - if ( $@ ) { - $error_msg .= '[' . $host . '] ' . $@ . ';'; - $error++; - } - - } - - }; - if ( $@ ) { - $error++; - $error_msg .= $@; - } - - $session->param( 'error', $error_msg ) if ( $error ); - -} - -sub fetch_net1_userinfos($) -{ - - my $uid = shift; - - my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'AD' ) ); - - my $ldap_ad = { - 'server' => $AiniFile->val( 'AD_NET1', 'SERVER' ), - 'user' => $AiniFile->val( 'AD_NET1', 'USER' ), - 'password' => $AiniFile->val( 'AD_NET1', 'PASSWORD' ), - 'label' => 'ad', - 'starttls' => 0, - 'debug' => 0, - 'verbose' => 0, - }; - - die 'missing parameters' unless ( defined( $uid ) && ( $uid =~ m/^[a-z0-9]+$/i ) ); - - SNET::LdapNS::ldapns_bind( $ldap_ad->{'server'}, $ldap_ad->{'user'}, $ldap_ad->{'password'}, $ldap_ad->{'label'}, 'LDAPISS', $ldap_ad->{'starttls'}, $ldap_ad->{'debug'}, $ldap_ad->{'verbose'} ); - - my $connection = SNET::LdapNS::get_connection( $ldap_ad->{'label'} ); - - my $userInfos = $connection->search( - base => 'OU=DIGIT,OU=Users,OU=ITIC,DC=net1,DC=cec,DC=eu,DC=int', - scope => 'sub', - filter => '(sAMAccountName=' . $uid . ')', - attrs => [ 'mail', 'displayName', 'givenName', 'sn', 'co' ] - ); - - die "user `$uid' not found in Net1 AD" unless defined( $userInfos ); - die 'More than 1 entries fetched from the AD Net1' unless ( scalar( keys( %{$userInfos} ) ) == 1 ); - - return $userInfos; - -} - -sub encode_sessionauth($) -{ - - my $password = shift; - - my $cipher = Crypt::CBC->new( -key => $key, - -cipher => 'Blowfish' ); - my $sessionauth = encode_base64( $cipher->encrypt( $password ) ); - chomp( $sessionauth ); - $session->param( 'sessionauth', $sessionauth ); - -} - -sub decode_sessionauth() -{ - - my $cipher = Crypt::CBC->new( -key => $key, - -cipher => 'Blowfish' ); - my $password = $cipher->decrypt( decode_base64( $session->param( 'sessionauth' ) ) ); - return $password; - -} - -sub connect_ldap_snmc($$$) -{ - - my ( $user, $password, $isAdmin ) = @_; - - # overwrite debug for admin - $ldap_snmc->{'debug'} = $isAdmin; - - return if ( $connected ); - - $ldap_snmc->{'user'} = $user; - $ldap_snmc->{'password'} = $password; - - print STDERR "ldap_NS.pl: creating connection to " . $ldap_snmc->{'server'} . " ...\n" if ( $debug > 2 ); - - my $pp = SNET::LdapNS::ldapns_bind( $ldap_snmc->{'server'}, $ldap_snmc->{'user'}, $ldap_snmc->{'password'}, $ldap_snmc->{'label'}, - $audit_user, $ldap_snmc->{'starttls'}, $ldap_snmc->{'debug'}, $ldap_snmc->{'verbose'} ); - - print STDERR "ldap_NS.pl: connection established\n" if ( $debug > 2 ); - - if ( !defined( $session ) ) { - - $session = new CGI::Session( 'driver:chi', undef, { 'driver' => 'Redis', 'namespace' => 'ldapcgi', 'server' => $redis_hostport, } ) or die CGI::Session->errstr; - $sid = $session->id(); - print STDERR "ldap_NS:connect_ldap_snmc: no session, creating a new one:$sid.\n" if ( $debug > 2 ); - } - - $connected = 1; - - $session->param( 'user', $user ); - - # $error could have been set to 'invalid empty session' - # after a logout/login - undef $error; - $session->clear( ['error'] ); - - if ( defined( $pp->{'error'} ) ) { - - print STDERR "ldap_NS.pl: ppolicy error!\n" if ( $debug > 2 ); - - if ( $pp->{'error'} == LDAP_PP_PASSWORD_EXPIRED ) { - $session->param( 'error', 'Your password has expired' ); - $session->param( 'userMustChange', 1 ); - $userMustChange = 1; - $session->param( 'isAdmin', 0 ); - $session->clear( ['userInfos'] ); - } elsif ( $pp->{'error'} == LDAP_PP_CHANGE_AFTER_RESET ) { - $session->param( 'error', 'You must change your password immediately' ); - $session->param( 'userMustChange', 1 ); - $userMustChange = 1; - $session->param( 'isAdmin', 0 ); - $session->clear( ['userInfos'] ); - } else { - $session->param( 'error', 'Undefined password policy error(' . $pp->{'error'} . ')' ); - $session->param( 'isAdmin', 0 ); - } - } else { - - if ( defined( $pp->{'warning'} ) ) { - - print STDERR "ldap_NS.pl: ppolicy warning!\n" if ( $debug > 2 ); - - if ( defined( $pp->{'warning'}->{'graceAuthNsRemaining'} ) ) { - $session->param( 'error', 'Grace authentications remaining: ' . $pp->{'warning'}->{'graceAuthNsRemaining'} ); - } elsif ( defined( $pp->{'warning'}->{'timeBeforeExpiration'} ) ) { - - if ( $pp->{'warning'}->{'timeBeforeExpiration'} > 0 ) { - - my ( $days, $hours, $minutes ) = ( gmtime( $pp->{'warning'}->{'timeBeforeExpiration'} ) )[ 7, 2, 1 ]; - my @values = (); - my @formats = (); - - if ( $days == 1 ) { - push( @formats, 'one day' ); - } elsif ( $days > 1 ) { - push( @values, $days ); - push( @formats, '%d days' ); - } - - if ( $hours == 1 ) { - push( @formats, 'one hour' ); - } elsif ( $hours > 1 ) { - push( @values, $hours ); - push( @formats, '%d hours' ); - } - - if ( $minutes <= 1 ) { - push( @formats, 'one minute' ); - } elsif ( $minutes > 1 ) { - push( @values, $minutes ); - push( @formats, '%d minutes' ); - } - - my $message = sprintf( 'Your password will expire in ' . join( ', ', @formats ), @values ); - - if ( $days < 7 ) { - $session->param( 'error', $message ); - } else { - $session->param( 'message', $message ); - } - - } else { - - # no ppolicy, or no pwdChangedTime - $session->param( 'message', 'Your password never expires' ); - } - - } - - } - - $session->param( 'userMustChange', 0 ); - refresh_userInfos; - - } - - encode_sessionauth( $password ); - - if ( $userMustChange ) { - reset_tab_actions; - display_passwd; - } - - $session->param( 'tab', 'home' ) unless ( defined( $session->param( 'tab' ) ) ); - -} - -sub reconnect_ldap_snmc() -{ - return if ( $connected ); - my $user = $session->param( 'user' ); - my $password = decode_sessionauth(); - connect_ldap_snmc( $user, $password, $isAdmin ); -} - -sub refresh_ppolicy() -{ - return if defined( $session->param( 'pwdPolicies' ) ); - eval { - - reconnect_ldap_snmc(); - my $pwdPolicies = SNET::LdapNS::getAllPwdPolicies( $ldap_snmc->{'label'} ); - if ( 1 ) { - my $defaultPwdPolicy = SNET::LdapNS::getPwdPolicy( $ldap_snmc->{'label'}, $SNET::LdapNS::defaultPwdPolicy ); - my @keys = keys( %{$defaultPwdPolicy} ); - $pwdPolicies->{ $keys[0] } = $defaultPwdPolicy->{ $keys[0] }; - } - $session->param( 'pwdPolicies', $pwdPolicies ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - redirect_homepage(); - } -} - -sub refresh_posixAccounts() -{ - return if defined( $session->param( 'posixAccounts' ) ); - eval { - reconnect_ldap_snmc(); - my $posixAccounts = SNET::LdapNS::getAllPosixAccounts( $ldap_snmc->{'label'} ); - $session->param( 'posixAccounts', $posixAccounts ); - }; - if ( $@ ) { - $session->param( 'error', $@ ); - redirect_homepage(); - } -} - -sub refresh_posixGroups() -{ - return if defined( $session->param( 'posixGroups' ) ); - eval { - reconnect_ldap_snmc(); - my $posixGroups = SNET::LdapNS::getAllPosixGroups( $ldap_snmc->{'label'} ); - $session->param( 'posixGroups', $posixGroups ); - }; - if ( $@ ) { - $session->param( 'error', $@ ); - redirect_homepage(); - } -} - -sub refresh_groupOfNames() -{ - return if defined( $session->param( 'groupOfNames' ) ); - eval { - reconnect_ldap_snmc(); - my $groupOfNames = SNET::LdapNS::getAllGroupOfNames( $ldap_snmc->{'label'} ); - $session->param( 'groupOfNames', $groupOfNames ); - }; - if ( $@ ) { - $session->param( 'error', $@ ); - redirect_homepage(); - } -} - -sub refresh_userInfos() -{ - - print STDERR "ldap_NS.pl: entering refresh_userInfos\n" if ( $debug > 2 ); - - reconnect_ldap_snmc(); - - eval { - return if ( $session->param( 'userMustChange' ) > 0 ); - print STDERR "ldap_NS.pl: fetching `" . $session->param( 'user' ) . "' posixAccount\n" if ( $debug > 2 ); - my $userInfos = SNET::LdapNS::getPosixAccount( $ldap_snmc->{'label'}, $session->param( 'user' ) ); - $session->param( 'userInfos', $userInfos ); - - print STDERR "ldap_NS.pl: checking user privileges ...\n" if ( $debug > 2 ); - $isAdmin = SNET::LdapNS::isAdmin( $ldap_snmc->{'label'} ); - $session->param( 'isAdmin', $isAdmin ); - print STDERR "ldap_NS.pl: user " . ( $isAdmin ? "is admin" : "is not admin" ) . "\n" if ( $debug > 2 ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - redirect_homepage(); - } - -} - -sub getsize_multipleselect($) -{ - - my $options = $_[0]; - my $size = 0; - - if ( defined( $options ) ) { - if ( ref( $options ) eq 'ARRAY' ) { - $size = scalar( @{$options} ); - } elsif ( ref( $options ) eq 'HASH' ) { - $size = scalar( keys( %{$options} ) ); - } - } - - if ( $size > 10 ) { - $size = 10; - } elsif ( $size < 5 ) { - $size = 5; - } - - return $size; - -} - -sub print_ns_headers($) -{ - - my $title = shift; - my $header_title = $cgi->h1( $cgi->a( { href => $homepage }, "SNet LdapNS" ) ); - - my $cookies = []; - push( - @{$cookies}, - $cgi->cookie( - -name => "SESSION_ID", - -value => $session->id(), - -path => $htmlbasedir, - -secure => 1, - ) - ) if ( defined( $session ) ); - - push( - @{$cookies}, - $cgi->cookie( - -name => "SESSION_KEY", - -value => $key, - -path => $htmlbasedir, - -secure => 1, - ) - ); - - my $template_header = HTML::Template->new( filename => $templatedir . '/ldapns_header.tmpl' ); - - $template_header->param( 'login', $LOGIN ); - - $template_header->param( 'tab_home', $TAB_HOME ); - $template_header->param( 'isAdmin', $isAdmin ); - $template_header->param( 'userMustChange', $userMustChange ); - $template_header->param( 'info', $INFO ); - $template_header->param( 'passwd', $PASSWD ); - - $template_header->param( 'tab_users', $TAB_USERS ); - $template_header->param( 'userinfos', $USERINFOS ); - $template_header->param( 'adduser', $ADDUSER ); - $template_header->param( 'adduserprofile', $ADDUSERPROFILE ); - $template_header->param( 'deluser', $DELUSER ); - $template_header->param( 'moduser', $MODUSER ); - $template_header->param( 'reset', $RESET ); - - $template_header->param( 'tab_groups', $TAB_GROUPS ); - $template_header->param( 'groupinfos', $GROUPINFOS ); - $template_header->param( 'addgroup', $ADDGROUP ); - $template_header->param( 'delgroup', $DELGROUP ); - $template_header->param( 'modgroup', $MODGROUP ); - - $template_header->param( 'tab_policy', $TAB_POLICY ); - $template_header->param( 'policyinfos', $POLICYINFOS ); - $template_header->param( 'addpolicy', $ADDPOLICY ); - $template_header->param( 'delpolicy', $DELPOLICY ); - $template_header->param( 'modpolicy', $MODPOLICY ); - - print $cgi->header( -charset => 'UTF-8', - -cookie => $cookies, ); - - # $title; $js_enable, $xport, $html, $header_title, $jsarray, $cssarray - dg_header_html( $title, 0, 0, undef, $header_title, undef, ['/snet/auth/css/ldapns.css'] ); - print $template_header->output; - -} - -sub print_ns_footers() -{ - - my $template_footer = HTML::Template->new( filename => $templatedir . '/ldapns_footer.tmpl' ); - $template_footer->param( 'login', $LOGIN ); - - parse_messages(); - $template_footer->param( 'error' => defined( $error ) ); - $template_footer->param( 'error_msg' => $error ); - $template_footer->param( 'message' => defined( $message ) ); - $template_footer->param( 'message_msg' => $message ); - - print $template_footer->output; - print $cgi->end_html; - exit 0; - -} - -sub render_ppolicyinfos($;$) -{ - - my ( $policyInfos, $audit ) = @_; - $audit = 0 unless defined( $audit ); - - my $template = HTML::Template->new( filename => $templatedir . '/policyinfos.tmpl' ); - - foreach my $dn ( sort { $a cmp $b } keys( %{$policyInfos} ) ) { - my $attrs = $policyInfos->{$dn}; - my @attrs; - delete( $attrs->{'auditinformation'} ) unless ( $audit ); - $attrs->{'objectclass'} = [qw(pwdPolicy)]; - foreach my $attr ( sort { $a cmp $b } keys( %{$attrs} ) ) { - my $value = $attrs->{$attr}; - foreach my $val ( @{$value} ) { - - if ( defined( $SNET::LdapNS::pwdPolicyAttributes->{$attr} ) ) { - my $type = ${ $SNET::LdapNS::pwdPolicyAttributes->{$attr} }[0]; - if ( $type eq 'bool' ) { - $val = lc( "$val" ); - } elsif ( $type eq 'extbool' ) { - if ( $val <= 0 ) { - $val = 'false'; - } elsif ( $val == 1 ) { - $val = 'true'; - } else { - $val = 'strict'; - } - } elsif ( $type eq 'second' ) { - $val = $val . "s"; - } - - # elsif ($type eq 'int') { - # } - elsif ( $type eq 'string' ) { - next; - } elsif ( $type eq 'nbool' ) { - $val = ( $val > 0 ) ? 'counted' : 'forbidden'; - } - } - push( @attrs, { 'attr' => $attr, 'value' => $val } ); - } - } - $template->param( 'policydn' => $dn ); - $template->param( 'attrs' => \@attrs ); - print $template->output; - } - -} - -sub render_userinfos($;$) -{ - - my ( $userInfos, $audit ) = @_; - $audit = 0 unless defined( $audit ); - - my $template = HTML::Template->new( filename => $templatedir . '/userinfos.tmpl' ); - - foreach my $dn ( sort { $a cmp $b } keys( %{$userInfos} ) ) { - my $attrs = $userInfos->{$dn}; - my @attrs; - if ( defined( $attrs->{'pwdreset'} ) ) { - delete( $attrs->{'pwdreset'} ); - $template->param( 'reset' => 1 ); - } else { - $template->param( 'reset' => 0 ); - } - delete( $attrs->{'auditinformation'} ) unless ( $audit ); - foreach my $attr ( sort { $a cmp $b } keys( %{$attrs} ) ) { - my $value = $attrs->{$attr}; - foreach ( @{$value} ) { - push( @attrs, { 'attr' => $attr, 'value' => $_ } ); - } - } - $template->param( 'userdn' => $dn ); - $template->param( 'attrs' => \@attrs ); - print $template->output; - } - -} - -sub render_groupinfos($;$) -{ - - my ( $groupInfos, $audit ) = @_; - $audit = 0 unless defined( $audit ); - - my $template = HTML::Template->new( filename => $templatedir . '/groupinfos.tmpl' ); - - foreach my $dn ( sort { $a cmp $b } keys( %{$groupInfos} ) ) { - my $attrs = $groupInfos->{$dn}; - my $objectClass; - if ( defined( $attrs->{'objectClass'} ) ) { - $objectClass = ${ $attrs->{'objectClass'} }[0]; - delete( $attrs->{'objectClass'} ); - } - delete( $attrs->{'auditinformation'} ) unless ( $audit ); - my @attrs; - foreach my $attr ( sort { $a cmp $b } keys( %{$attrs} ) ) { - my $value = $attrs->{$attr}; - foreach ( @{$value} ) { - push( @attrs, { 'attr' => $attr, 'value' => $_ } ); - } - } - if ( defined( $objectClass ) ) { - unshift( @attrs, { 'attr' => 'objectclass', 'value' => $objectClass } ); - } - $template->param( 'groupdn' => $dn ); - $template->param( 'attrs' => \@attrs ); - print $template->output; - } - -} - -sub get_default_description($) -{ - - my $group = shift; - my @description; - - # if ( $group eq 'sup' ) { - # push( @description, 'CWRA' ); - #} elsif ( $group eq 'network' ) { - # push( @description, 'CWRW' ); - #} elsif ( $group eq 'security' ) { - # push( @description, 'CWRW' ); - #} elsif ( $group eq 'official' ) { - # push( @description, 'CWRO' ); - #} else { - return undef; - - #} - #return \@description; -} - -sub display_userinfos() -{ - - $USERINFOS = 1; - - refresh_posixAccounts(); - - my $userInfos; - my $options = {}; - - my $validate = { uid => 'UID', }; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_userinfos_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Display user', - fields => [qw(uid audit)], - template => $templatedir . '/selectuser.tmpl', - method => 'post', - javascript => 1, - validate => $validate, - required => 'uid', - submit => 'Display', - ); - - my $posixAccounts = $session->param( 'posixAccounts' ); - foreach my $values ( values( %{$posixAccounts} ) ) { - my $uid = ${ $values->{'uid'} }[0]; - my $gecos = ${ $values->{'gecos'} }[0]; - $options->{$uid} = $uid . ' - ' . $gecos; - } - - if ( $form->submitted eq 'Display' ) { - eval { - die 'invalid parameters' unless $form->validate; - my @uids = $form->field( name => 'uid' ); - die 'You must select at least one user' unless ( scalar( @uids ) > 0 ); - - map { die "invalid uid `$_'" unless defined( $options->{$_} ) } @uids; - - reconnect_ldap_snmc(); - - foreach my $uid ( @uids ) { - my $infos = SNET::LdapNS::getPosixAccount( $ldap_snmc->{'label'}, $uid ); - while ( my ( $k, $v ) = each( %{$infos} ) ) { - $userInfos->{$k} = $v; - } - } - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - undef $userInfos; - } - } - - $form->field( - name => 'audit', - type => 'checkbox', - comment => 'Display auditInformation?', - options => 'yes', - selected => 0, - ); - - $form->field( - name => 'uid', - options => $options, - sortopts => 'NAME', - type => 'select', - size => getsize_multipleselect( $options ), - multiple => 1, - ); - - my $audit = ( defined( $form->field( name => 'audit' ) ) ); - - print_ns_headers( "LdapNS display users" ); - print $form->render; - render_userinfos( $userInfos, $audit ) if defined( $userInfos ); - print_ns_footers(); - -} - -sub display_adduser() -{ - - $ADDUSER = 1; - - refresh_posixAccounts; - refresh_posixGroups; - - my $options = {}; - - my $jsfunc = <<'EOJS'; - // skip js validation if fetching userInfos from Net1 - if (form._submitted_value.value.match(/^Refresh/)) { - var uid = form.elements['uid'].value; - var group = form.elements['group'].value; - if ((uid == null) && (group == null)) { - alert('Please fill uid and/or group prior to Refresh'); - } - return true; - } -EOJS - - my $validate = { - IM => 'IM', - uid => 'UID', - uidNumber => 'UIDNUMBER', - mail => 'EMAIL', - gecos => 'GECOS', - firstname => 'FIRSTNAME', - group => 'GIDNUMBER', - description => 'DESCRIPTION', - }; - - my $fields = [qw(IM uid mail gecos firstname group)]; - - my $form_fields = [qw(_submitted_value IM uid uidNumber mail gecos firstname group description)]; - push( @{$form_fields}, 'synchronize' ) if ( $mod_synchro ); - - my $form = CGI::FormBuilder->new( - name => 'ldapns_adduser_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Add user', - fields => $form_fields, - template => $templatedir . '/adduser.tmpl', - method => 'post', - javascript => 1, - jsfunc => $jsfunc, - validate => $validate, - required => $fields, - reset => 1, - ); - - if ( $mod_synchro ) { - $form->field( - name => 'synchronize', - type => 'checkbox', - comment => 'Synchronize with old LDAP database?', - options => 'yes', - ); - $form->field( - name => 'synchronize', - value => 'yes' - ) unless ( $form->submitted ); - } - $form->tmpl_param( 'mod_synchro' => $mod_synchro ); - - $form->field( - name => 'description', - comment => 'optional', - growable => 1, - ); - $form->field( name => '_submitted_value', - type => 'hidden', ); - $form->field( name => 'uidNumber', - comment => 'optional [2000..9999]', ); - $form->field( name => 'IM', - comment => 'SMT ticket number', ); - $form->field( name => 'gecos', - comment => 'LASTNAME Firstname', ); - $form->field( name => 'firstname', - comment => 'Firstname', ); - $form->field( name => 'group', - comment => 'refresh Description', ); - $form->field( name => 'uid', - comment => 'fetch Mail & Gecos', ); - - my $posixGroups = $session->param( 'posixGroups' ); - foreach my $values ( values( %{$posixGroups} ) ) { - my $cn = ${ $values->{'cn'} }[0]; - my $gidNumber = ${ $values->{'gidnumber'} }[0]; - $options->{$gidNumber} = $cn; - } - - if ( scalar( keys( %{$options} ) ) == 0 ) { - $session->param( 'error', 'Unable to fetch available posixGroups' ); - redirect( '?tab=groups&action=addgroup' ); - } - - if ( ( $form->submitted eq 'Uid' ) || ( $form->submitted eq 'Group' ) ) { - - eval { - - foreach my $field ( @{$fields} ) { - $form->field( 'name' => $field, - required => 0 ); - } - my $valid = 0; - $form->field( 'name' => 'uid', required => 1 ); - $valid += $form->validate; - $form->field( 'name' => 'uid', required => 0 ); - $form->field( 'name' => 'group', required => 1 ); - $valid += $form->validate; - - die 'invalid parameters' unless $valid; - - my $uid = $form->field( name => 'uid' ); - if ( defined( $uid ) && length( $uid ) ) { - my $userInfos = fetch_net1_userinfos( $uid ); - my @keys = keys( %{$userInfos} ); - my $dn = $keys[0]; - - $form->field( - name => 'mail', - force => 1, - value => lc( ${ $userInfos->{$dn}->{'mail'} }[0] ), - ) if defined( $userInfos->{$dn}->{'mail'} ); - - if ( defined( $userInfos->{$dn}->{'displayname'} ) ) { - my $gecos = ${ $userInfos->{$dn}->{'displayname'} }[0]; - $gecos =~ s/\s+\(.*$//; - $form->field( - name => 'gecos', - force => 1, - value => $gecos, - ); - } - - $form->field( - name => 'firstname', - force => 1, - value => ucfirst( ${ $userInfos->{$dn}->{'givenname'} }[0] ), - ) if defined( $userInfos->{$dn}->{'givenname'} ); - - } - - my $group = $form->field( name => 'group' ); - if ( defined( $group ) && length( $group ) ) { - my $description = get_default_description( $options->{$group} ); - $form->field( - name => 'description', - force => 1, - value => $description, - ); - } - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } - - } elsif ( $form->submitted eq 'Add' ) { - - my $entry; - - eval { - - die 'invalid parameters' unless $form->validate( $validate ); - - my $uidNumber = $form->field( name => 'uidNumber' ) || undef; - my $uid = $form->field( name => 'uid' ); - - my $posixAccounts = $session->param( 'posixAccounts' ); - foreach my $values ( values( %{$posixAccounts} ) ) { - die "user `$uid' already exists" if ( $uid eq ${ $values->{'uid'} }[0] ); - next unless defined( $uidNumber ); - die "user id `$uidNumber' already exists" if ( $uidNumber == ${ $values->{'uidnumber'} }[0] ); - } - - my $group = $form->field( name => 'group' ); - my $description = get_default_description( $options->{$group} ); - $description = [] unless defined( $description ); - - if ( defined( $form->field( name => 'description' ) ) ) { - push( @{$description}, $form->field( name => 'description' ) ); - } - - my %uniq_description; - foreach my $desc ( @{$description} ) { - $uniq_description{$desc}++; - } - $description = []; - foreach my $desc ( keys( %uniq_description ) ) { - push( @{$description}, $desc ) if ( defined( $desc ) - && length( $desc ) ); - } - undef $description unless ( scalar( @{$description} ) ); - - print STDERR "description is defined: " . ( defined( $description ) ) . "\n"; - - reconnect_ldap_snmc(); - $entry = SNET::LdapNS::addPosixAccount( - $ldap_snmc->{'label'}, $form->field( name => 'IM' ), $uid, $group, - $form->field( name => 'gecos' ), $form->field( name => 'mail' ), $form->field( name => 'firstname' ), $uidNumber, - $description, - ) or die "Unable to create LDAP entry for `$uid'"; - - $session->clear( ['posixAccounts'] ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } else { - - my @attributes = $entry->attributes( nooptions => 1 ); - my $dn = $entry->dn; - my $userInfos; - - eval { $userInfos = SNET::LdapNS::getPosixAccount( $ldap_snmc->{'label'}, $dn ); }; - if ( $@ ) { - print STDERR "unable to fetch userInfos for `$dn': $@\n"; - $userInfos = { $dn => {}, }; - foreach my $attr ( @attributes ) { - next if ( $attr =~ m/objectclass/i ); - next if ( $attr =~ m/shadow/i ); - next if ( $attr =~ m/^cn|sn$/i ); - $userInfos->{$dn}->{ lc( $attr ) } = $entry->get_value( $attr, asref => 1 ); - } - } else { - print STDERR "looking good, fetched userInfos for `$dn'\n"; - foreach my $attr ( @attributes ) { - next unless ( ( $attr =~ m/userPassword/i ) - || ( $attr =~ m/auditinformation/i ) ); - $userInfos->{$dn}->{ lc( $attr ) } = $entry->get_value( $attr, asref => 1 ); - } - } - - synchronize_add_users( $userInfos, defined( $form->field( name => 'synchronize' ) ) ); - - $session->param( 'message', 'user added successfully' ); - print_ns_headers( "LdapNS add users" ); - render_userinfos( $userInfos ); - print_ns_footers(); - - } - - } - - $form->field( - name => 'group', - options => $options, - type => 'select', - size => getsize_multipleselect( $options ), - sortopts => 'NAME', - selectname => 0, - multiple => 0, - ); - - print_ns_headers( "LdapNS add users" ); - print $form->render; - print_ns_footers(); - -} - -sub display_adduserprofile() -{ - - $ADDUSERPROFILE = 1; - - refresh_posixAccounts(); - refresh_posixGroups(); - refresh_groupOfNames(); - - my $options = (); - - my $jsfunc = <<'EOJS'; - // skip js validation if fetching userInfos from Net1 - if (form._submitted_value.value.match(/^Refresh/)) { - var uid = form.elements['uid'].value; - if (uid == null) { - alert('Please fill uid prior to Refresh'); - } - return true; - } -EOJS - - my $validate = { - IM => 'IM', - uid => 'UID', - uidNumber => 'UIDNUMBER', - mail => 'EMAIL', - gecos => 'GECOS', - firstname => 'FIRSTNAME', - description => 'DESCRIPTION', - profile => 'PROFILE', - state => 'STATE', - }; - - my $fields = [qw(IM uid mail gecos firstname profile state)]; - - my $form_fields = [qw(_submitted_value IM uid uidNumber mail gecos firstname profile state bcp description)]; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_adduserprofile_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Add user profile based', - fields => $form_fields, - template => $templatedir . '/adduserprofile.tmpl', - method => 'post', - javascript => 1, - jsfunc => $jsfunc, - validate => $validate, - required => $fields, - reset => 1, - ); - - $form->field( - name => 'description', - comment => 'optional', - growable => 1, - ); - $form->field( name => '_submitted_value', - type => 'hidden', ); - $form->field( name => 'uidNumber', - comment => 'optional [2000..9999]', ); - $form->field( name => 'IM', - comment => 'SMT ticket number', ); - $form->field( name => 'gecos', - comment => 'LASTNAME Firstname', ); - $form->field( name => 'firstname', - comment => 'Firstname', ); - $form->field( - name => 'bcp', - comment => 'Is the user belonging to the BCP team', - options => 'yes', - selected => 0, - ); - $form->field( name => 'uid', - comment => 'fetch Mail & Gecos', ); - - $options->{'Architect'} = 'Architect'; - $options->{'Compliance'} = 'Compliance'; - $options->{'Development'} = 'Development'; - $options->{'Managment'} = 'Managment'; - $options->{'Network'} = 'Network'; - $options->{'Officials'} = 'Officials'; - $options->{'Ois'} = 'Ois'; - $options->{'ProjectManager'} = 'ProjectManager'; - $options->{'Security'} = 'Security'; - $options->{'Noca'} = 'Noca'; - $options->{'System'} = 'System'; - $options->{'Videoconference'} = 'Videoconference'; - - my $options_profile = (); - $options_profile->{'Architect'}{'description'} = 'profile:Architect'; - $options_profile->{'Architect'}{'arc'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - $options_profile->{'Architect'}{'bindhg'} = 'posixGroup'; - $options_profile->{'Architect'}{'logs'} = 'posixGroup'; - - $options_profile->{'Compliance'}{'description'} = 'profile:compliance'; - $options_profile->{'Compliance'}{'com'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - - $options_profile->{'Development'}{'description'} = 'profile:development'; - $options_profile->{'Development'}{'dev'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - $options_profile->{'Development'}{'logs'} = 'posixGroup'; - - $options_profile->{'Managment'}{'description'} = 'profile:managment'; - $options_profile->{'Managment'}{'mgt'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - - $options_profile->{'Network'}{'description'} = 'profile:network'; - $options_profile->{'Network'}{'net'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - - $options_profile->{'Noca'}{'description'} = 'profile:noca'; - $options_profile->{'Noca'}{'noca'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - $options_profile->{'Noca'}{'logs'} = 'posixGroup'; - - $options_profile->{'Officials'}{'description'} = 'profile:officials'; - $options_profile->{'Officials'}{'officials'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - - $options_profile->{'Ois'}{'description'} = 'profile:ois'; - $options_profile->{'Ois'}{'ois'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - - $options_profile->{'ProjectManager'}{'description'} = 'profile:projectmanager'; - $options_profile->{'ProjectManager'}{'pm'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - - $options_profile->{'Security'}{'description'} = 'profile:security'; - $options_profile->{'Security'}{'sec'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - $options_profile->{'Security'}{'bindhg'} = 'posixGroup'; - $options_profile->{'Security'}{'logs'} = 'posixGroup'; - - $options_profile->{'System'}{'description'} = 'profile:system'; - $options_profile->{'System'}{'sys'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - $options_profile->{'System'}{'logs'} = 'posixGroup'; - - $options_profile->{'Videoconference'}{'description'} = 'profile:videoconference'; - $options_profile->{'Videoconference'}{'vc'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - - $form->field( - name => 'profile', - comment => 'Select the right profile', - options => $options, - sortopts => 'NAME', - linebreaks => 1, - type => 'select', - multiple => 0, - ); - - my $options_st = (); - $options_st->{'Luxembourg'} = 'Luxembourg'; - $options_st->{'Belgium'} = 'Belgium'; - - $form->field( - name => 'state', - comment => 'Select the right state', - options => $options_st, - type => 'select', - multiple => 0, - - ); - - if ( $form->submitted eq 'Uid' ) { - - eval { - - foreach my $field ( @{$fields} ) { - $form->field( 'name' => $field, - required => 0 ); - } - my $valid = 0; - $form->field( 'name' => 'uid', required => 1 ); - $valid += $form->validate; - - die 'invalid parameters' unless $valid; - - my $uid = $form->field( name => 'uid' ); - if ( defined( $uid ) && length( $uid ) ) { - my $userInfos = fetch_net1_userinfos( $uid ); - my @keys = keys( %{$userInfos} ); - my $dn = $keys[0]; - - $form->field( - name => 'mail', - force => 1, - value => lc( ${ $userInfos->{$dn}->{'mail'} }[0] ), - ) if defined( $userInfos->{$dn}->{'mail'} ); - - if ( defined( $userInfos->{$dn}->{'displayname'} ) ) { - my $gecos = ${ $userInfos->{$dn}->{'displayname'} }[0]; - $gecos =~ s/\s+\(.*$//; - $form->field( - name => 'gecos', - force => 1, - value => $gecos, - ); - } - - $form->field( - name => 'firstname', - force => 1, - value => ucfirst( ${ $userInfos->{$dn}->{'givenname'} }[0] ), - ) if defined( $userInfos->{$dn}->{'givenname'} ); - - $form->field( - name => 'state', - force => 1, - value => ( ucfirst( ${ $userInfos->{$dn}->{'co'} }[0] ) eq 'LU' ? 'Luxembourg' : 'Belgium' ), - ) if defined( $userInfos->{$dn}->{'co'} ); - - } - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } - - } elsif ( $form->submitted eq 'Add' ) { - - my $entry; - my $tmp_message_string = ''; - - eval { - - die 'invalid parameters validate' . html_rendering( Dumper( $validate ) ) unless $form->validate( $validate ); - - my $uidNumber = $form->field( name => 'uidNumber' ) || undef; - my $uid = $form->field( name => 'uid' ); - - my $posixAccounts = $session->param( 'posixAccounts' ); - foreach my $values ( values( %{$posixAccounts} ) ) { - die "user `$uid' already exists" if ( $uid eq ${ $values->{'uid'} }[0] ); - next unless defined( $uidNumber ); - die "user id `$uidNumber' already exists" if ( $uidNumber == ${ $values->{'uidnumber'} }[0] ); - } - - my $profile = $form->field( name => 'profile' ); - my $group = 'snmc'; - my $group_id = 3500; - if ( $options->{$profile} eq 'Officials' ) { - $group = 'officials'; - $group_id = 3800; - } - my $description; - $description = [] unless defined( $description ); - - push( @{$description}, 'profile:' . $options->{$profile} ); - - if ( defined( $form->field( name => 'description' ) ) ) { - push( @{$description}, $form->field( name => 'description' ) ); - } - - my %uniq_description; - foreach my $desc ( @{$description} ) { - $uniq_description{$desc}++; - } - $description = []; - foreach my $desc ( keys( %uniq_description ) ) { - push( @{$description}, $desc ) if ( defined( $desc ) - && length( $desc ) ); - } - undef $description unless ( scalar( @{$description} ) ); - - print STDERR "description is defined: " . ( defined( $description ) ) . "\n"; - - reconnect_ldap_snmc(); - $entry = SNET::LdapNS::addPosixAccount( - $ldap_snmc->{'label'}, $form->field( name => 'IM' ), $uid, $group_id, - $form->field( name => 'gecos' ), $form->field( name => 'mail' ), $form->field( name => 'firstname' ), $uidNumber, - $description, undef, $form->field( name => 'state' ), - ) or die "Unable to create LDAP entry for `$uid'"; - - $session->clear( ['posixAccounts'] ); - - $tmp_message_string = " -Dear, - -Please find as requested the new temp password. - -new password for `$uid': " . " - -Please note, that the password is not valid, but allow you to change your -password on the interface (Authentication > SNet LDAP Manager): - https://intragate.ec.europa.eu/snet - -If you need more information from my side, please do not hesitate to contact the Supporting team,"; - - }; - if ( $@ ) { - print STDERR "error: $@\n"; - $session->param( 'error', $@ ); - } else { - - my @attributes = $entry->attributes( nooptions => 1 ); - my $dn = $entry->dn; - my $userInfos; - - eval { $userInfos = SNET::LdapNS::getPosixAccount( $ldap_snmc->{'label'}, $dn ); }; - if ( $@ ) { - print STDERR "unable to fetch userInfos for `$dn': $@\n"; - $userInfos = { $dn => {}, }; - foreach my $attr ( @attributes ) { - next if ( $attr =~ m/objectclass/i ); - next if ( $attr =~ m/shadow/i ); - next if ( $attr =~ m/^cn|sn$/i ); - $userInfos->{$dn}->{ lc( $attr ) } = $entry->get_value( $attr, asref => 1 ); - } - } else { - print STDERR "looking good, fetched userInfos for `$dn'\n"; - foreach my $attr ( @attributes ) { - next unless ( ( $attr =~ m/userPassword/i ) - || ( $attr =~ m/auditinformation/i ) ); - $userInfos->{$dn}->{ lc( $attr ) } = $entry->get_value( $attr, asref => 1 ); - } - } - - synchronize_add_users( $userInfos, defined( $form->field( name => 'synchronize' ) ) ); - - $session->param( 'message', 'user added successfully' ); - print STDERR "user added successfully\n"; - print_ns_headers( "LdapNS add users" ); - render_userinfos( $userInfos ); - $tmp_message_string = CGI::escapeHTML( $tmp_message_string ); - $tmp_message_string =~ s/\r\n|\r|\n/<br\/>\n/g; - $tmp_message_string =~ s/^(\s+)/" " x length($1)/meg; - - $session->param( 'message', $tmp_message_string ); - - # user parameters - - refresh_posixAccounts(); - - # TODO add profile to the group - - undef $entry; - - my $profile = $form->field( name => 'profile' ); - my $IM = $form->field( name => 'IM' ); - my $objectClass = ''; - - my $posix_group_to_exclude = 'snmc'; - if ( $options->{$profile} eq 'Officials' ) { - $posix_group_to_exclude = 'officials'; - } - - if ( defined( $form->field( name => 'bcp' ) ) ) { - print Dumper ( $form->field( name => 'bcp' ) ); - $options_profile->{$profile}{'bcp'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - } - - # $options_profile->{'XX'}{'sd'} = [ 'groupOfNames', 'posixGroup', 'groupOfUniqueNames' ]; - foreach my $group ( keys %{ $options_profile->{$profile} } ) { - - next if ( $group eq 'description' ); - - if ( $options_profile->{$profile}{$group} !~ /^ARRAY/ ) { - my $tmp = $options_profile->{$profile}{$group}; - undef( $options_profile->{$profile}{$group} ); - push( @{ $options_profile->{$profile}{$group} }, $tmp ); - } - foreach $objectClass ( @{ $options_profile->{$profile}{$group} } ) { - - next if ( ( $group eq $posix_group_to_exclude ) && ( $objectClass eq 'posixGroup' ) ); - - print STDERR "Searching the $objectClass group '$group' existance.\n"; - if ( $objectClass eq 'posixGroup' ) { - print STDERR Dumper( $session->param( 'posixGroups' ) ); - } elsif ( $objectClass eq 'groupOfNames' ) { - print STDERR Dumper( $session->param( 'groupOfNames' ) ); - } elsif ( $objectClass eq 'groupOfUniqueNames' ) { - print STDERR Dumper( $session->param( 'groupOfUniqueNames' ) ); - } else { - print STDERR "Bad objectClass '$objectClass'\n"; - next; - } - - my $notfound = 1; - if ( $objectClass eq 'posixGroup' ) { - foreach my $values ( values( %{ $session->param( 'posixGroups' ) } ) ) { - if ( ${ $values->{'cn'} }[0] eq $group ) { - $notfound = 0; - last; - } - } - - } elsif ( $objectClass eq 'groupOfNames' ) { - - foreach my $values ( values( %{ $session->param( 'groupOfNames' ) } ) ) { - if ( ${ $values->{'cn'} }[0] eq $group ) { - $notfound = 0; - last; - } - } - - } elsif ( $objectClass eq 'groupOfUniqueNames' ) { - - foreach my $values ( values( %{ $session->param( 'groupOfNames' ) } ) ) { - if ( ${ $values->{'cn'} }[0] eq $group ) { - $notfound = 0; - last; - } - } - } - if ( $notfound ) { - print STDERR "The $objectClass group '$group' doesnot exist, skipping.\n"; - next; - } - - eval { - - my @to_add = (); - push( @to_add, $form->field( name => 'uid' ) ); - - my $add_function; - my $get_function; - - if ( $objectClass eq 'posixGroup' ) { - $add_function = \&SNET::LdapNS::addToPosixGroup; - $get_function = \&SNET::LdapNS::getPosixGroup; - } elsif ( $objectClass eq 'groupOfNames' ) { - $add_function = \&SNET::LdapNS::addToGroupOfNames; - $get_function = \&SNET::LdapNS::getGroupOfNames; - } elsif ( $objectClass eq 'groupOfUniqueNames' ) { - $add_function = \&SNET::LdapNS::addToGroupOfUniqueNames; - $get_function = \&SNET::LdapNS::getGroupOfUniqueNames; - } - - reconnect_ldap_snmc(); - print STDERR "user to add '" . Dumper( \@to_add ) . "'.\n"; - - if ( scalar( @to_add ) ) { - my $rtrn_sts = &{$add_function}( $ldap_snmc->{'label'}, $IM, $group, \@to_add ) or die SNET::LdapNS::error( $ldap_snmc->{'label'} ); - print STDERR "after calling '$add_function'.\n"; - if ( $rtrn_sts eq '1' ) { - print STDERR "something wrong with the '$add_function'.\n"; - } - } - - $session->param( 'message', 'group modification successful' ); - print STDERR "The user was added successful to the group '$group'.\n"; - $entry = &{$get_function}( $ldap_snmc->{'label'}, $group, ); - - }; - if ( $@ ) { - print STDERR "error: $@\n"; - $session->param( 'error', $@ ); - } - if ( defined( $entry ) ) { - render_groupinfos( $entry ); - } - - } - } - - } - } - - print_ns_headers( "LdapNS add users" ); - print $form->render; - print_ns_footers(); - -} - -sub display_deluser() -{ - - $DELUSER = 1; - - refresh_posixAccounts(); - - my $options = {}; - my $deluser = $session->param( 'deluser' ); - my $type = 'select'; - - my $jsfunc = <<'EOJS'; - // skip on Cancel - if (form._submitted_value.value == 'Cancel') { - return true; - } -EOJS - - my $validate = { - IM => 'IM', - uid => 'UID', - }; - - my $form_fields = [qw(_submitted_value IM uid)]; - push( @{$form_fields}, 'synchronize' ) if ( $mod_synchro ); - - my $form = CGI::FormBuilder->new( - name => 'ldapns_deluser_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Delete user', - fields => $form_fields, - template => $templatedir . '/deluser.tmpl', - method => 'post', - required => [qw(IM uid)], - javascript => 1, - sticky => 1, - selectname => 0, - jsfunc => $jsfunc, - validate => $validate, - ); - - if ( $mod_synchro ) { - $form->field( - name => 'synchronize', - type => 'checkbox', - comment => 'Synchronize with old LDAP database?', - options => 'yes', - ); - $form->field( - name => 'synchronize', - value => 'yes' - ) unless ( $form->submitted ); - } - $form->tmpl_param( 'mod_synchro' => $mod_synchro ); - - $form->field( name => '_submitted_value', - type => 'hidden', ); - $form->field( name => 'IM', - comment => 'SMT ticket number', ); - - if ( $form->submitted eq 'Delete' ) { - - eval { - - die 'invalid parameters' unless $form->validate( $validate ); - my @uids = $form->field( name => 'uid' ); - die 'You must select a single user' unless ( scalar( @uids ) == 1 ); - - $deluser->{'IM'} = $form->field( name => 'IM' ); - foreach my $uid ( @uids ) { - $options->{$uid} = $deluser->{'options'}->{$uid} - or die "invalid uid `$uid'"; - } - $deluser->{'options'} = $options; - $session->param( 'deluser', $deluser ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - display_blank( "LdapNS delete users" ); - } - - $type = 'checkbox'; - $form->field( name => 'uid', disabled => 1 ); - $form->field( name => 'IM', disabled => 1 ); - - $form->tmpl_param( 'submit1' => 'Confirm' ); - $form->tmpl_param( 'submit2' => 1 ); - $form->tmpl_param( 'submit2_value' => 'Cancel' ); - - } elsif ( $form->submitted eq 'Confirm' ) { - my $deluser = $session->param( 'deluser' ); - my @uids = keys( %{ $deluser->{'options'} } ); - my $IM = $deluser->{'IM'}; - my @deleted_uid; - my $uid; - eval { - reconnect_ldap_snmc(); - foreach $uid ( @uids ) { - SNET::LdapNS::deletePosixAccount( $ldap_snmc->{'label'}, $IM, $uid ); - push( @deleted_uid, $uid ); - synchronize_del_users( $uid, defined( $form->field( name => 'synchronize' ) ) ); - } - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } - if ( scalar( @deleted_uid ) ) { - print STDERR 'Successful deletion of ' . join( ', ', @deleted_uid ) . "\n"; - $session->param( 'message', 'Successful deletion of ' . join( ', ', @deleted_uid ) ); - $session->clear( ['posixAccounts'] ); - } - $session->clear( ['deluser'] ); - display_blank( "LdapNS delete users" ); - } elsif ( $form->submitted eq 'Cancel' ) { - $session->param( 'error', 'delete operation cancelled' ); - $session->clear( ['deluser'] ); - display_blank( "LdapNS delete users" ); - } else { - my $posixAccounts = $session->param( 'posixAccounts' ); - foreach my $values ( values( %{$posixAccounts} ) ) { - my $uid = ${ $values->{'uid'} }[0]; - next if ( $uid eq $session->param( 'user' ) ); - my $gecos = ${ $values->{'gecos'} }[0]; - $options->{$uid} = $uid . ' - ' . $gecos; - } - $deluser->{'options'} = $options; - $session->param( 'deluser', $deluser ); - $form->tmpl_param( 'submit1' => 'Delete' ); - } - - if ( scalar( keys( %{$options} ) ) == 0 ) { - $session->param( 'error', 'Unable to fetch available posixAccounts' ); - display_blank( "LdapNS delete users" ); - } - - $form->field( - name => 'uid', - options => $options, - sortopts => 'NAME', - linebreaks => 1, - type => $type, - multiple => 0, - ); - - if ( $type eq 'select' ) { - $form->field( size => getsize_multipleselect( $options ), ); - } - - print_ns_headers( "LdapNS delete users" ); - print $form->render(); - print_ns_footers(); - -} - -sub display_moduser() -{ - $MODUSER = 1; - $session->param( 'error', 'Not yet implemented' ); - display_blank( "LdapNS modify users" ); -} - -sub display_reset() -{ - - $RESET = 1; - - refresh_posixAccounts(); - - my $options = {}; - my $reset = $session->param( 'reset' ); - my $type = 'select'; - - my $jsfunc = <<'EOJS'; - // skip on Cancel - if (form._submitted_value.value == 'Cancel') { - return true; - } -EOJS - - my $validate = { uid => 'UID', }; - - my $form_fields = [qw(_submitted_value uid)]; - push( @{$form_fields}, 'synchronize' ) if ( $mod_synchro ); - - my $form = CGI::FormBuilder->new( - name => 'ldapns_reset_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Reset password', - fields => $form_fields, - template => $templatedir . '/reset.tmpl', - method => 'post', - required => [qw(uid)], - javascript => 1, - selectname => 0, - jsfunc => $jsfunc, - validate => $validate, - ); - - if ( $mod_synchro ) { - $form->field( - name => 'synchronize', - type => 'checkbox', - comment => 'Synchronize with old LDAP database?', - options => 'yes', - ); - $form->field( - name => 'synchronize', - value => 'yes' - ) unless ( $form->submitted ); - } - $form->tmpl_param( 'mod_synchro' => $mod_synchro ); - - $form->field( name => '_submitted_value', - type => 'hidden', ); - - if ( $form->submitted eq 'Reset' ) { - eval { - - die 'invalid parameters' unless $form->validate( $validate ); - my @uids = $form->field( name => 'uid' ); - die 'You must select a single user' unless ( scalar( @uids ) == 1 ); - - my $uid = shift( @uids ); - $options->{$uid} = $reset->{'options'}->{$uid} - or die "invalid uid `$uid'"; - - $reset->{'options'} = $options; - $session->param( 'reset', $reset ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - display_blank( "LdapNS reset passwords" ); - } - - $type = 'checkbox'; - $form->field( name => 'uid', disabled => 1 ); - - $form->tmpl_param( 'submit1' => 'Confirm' ); - $form->tmpl_param( 'submit2' => 1 ); - $form->tmpl_param( 'submit2_value' => 'Cancel' ); - - } elsif ( $form->submitted eq 'Confirm' ) { - my $reset = $session->param( 'reset' ); - my @uids = keys( %{ $reset->{'options'} } ); - my $uid = shift( @uids ); - eval { - - reconnect_ldap_snmc(); - my $pwdinfos = SNET::LdapNS::pwdReset( $ldap_snmc->{'label'}, $uid ) or die "Unable to reset password for `$uid'"; - - synchronize_passwords( defined( $form->field( name => 'synchronize' ) ), $ldap_snmc->{'label'}, $pwdinfos->{'value'}, $uid ); - - $session->param( 'error', $pwdinfos->{'error'} ) if ( defined( $pwdinfos->{'error'} ) ); - if ( defined( $pwdinfos->{'value'} ) ) { - my $tmp_message_string = " -Dear, - -Please find as requested by your new temp password. - -new password for `$uid': " . $pwdinfos->{'value'} . " - -Please note, that the password is not valid, but allow you to change your -password on the interface (Authentication > SNet LDAP Manager): - https://intragate.ec.europa.eu/snet - -If you need more information from my side, please do not hesitate to contact the Supporting team,"; - $tmp_message_string = CGI::escapeHTML( $tmp_message_string ); - $tmp_message_string =~ s/\r\n|\r|\n/<br\/>\n/g; - $tmp_message_string =~ s/^(\s+)/" " x length($1)/meg; - - $session->param( 'message', $tmp_message_string ); - - } - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } else { - print STDERR "Password resetted for `$uid'\n"; - } - $session->clear( ['reset'] ); - display_blank( "LdapNS reset passwords" ); - } elsif ( $form->submitted eq 'Cancel' ) { - $session->param( 'error', 'reset operation cancelled' ); - $session->clear( ['reset'] ); - display_blank( "LdapNS reset passwords" ); - } else { - my $posixAccounts = $session->param( 'posixAccounts' ); - foreach my $values ( values( %{$posixAccounts} ) ) { - my $uid = ${ $values->{'uid'} }[0]; - next if ( $uid eq $session->param( 'user' ) ); - my $gecos = ${ $values->{'gecos'} }[0]; - $options->{$uid} = $uid . ' - ' . $gecos; - } - $reset->{'options'} = $options; - $session->param( 'reset', $reset ); - $form->tmpl_param( 'submit1' => 'Reset' ); - } - - if ( scalar( keys( %{$options} ) ) == 0 ) { - $session->param( 'error', 'Unable to fetch available posixAccounts' ); - display_blank( "LdapNS reset passwords" ); - } - - $form->field( - name => 'uid', - options => $options, - sortopts => 'NAME', - linebreaks => 1, - type => $type, - multiple => 0, - ); - - if ( $type eq 'select' ) { - $form->field( size => getsize_multipleselect( $options ), ); - } - - print_ns_headers( "LdapNS reset passwords" ); - print $form->render(); - print_ns_footers(); - -} - -sub select_group() -{ - - my $modgroup = $session->param( 'modgroup' ); - my $objectClass = $modgroup->{'objectClass'}; - my $groups; - my $options; - - return 1 if ( defined( $modgroup->{'group'} ) ); - - if ( $objectClass eq 'posixGroup' ) { - $groups = $session->param( 'posixGroups' ); - } else { - $groups = $session->param( 'groupOfNames' ); - } - - my $addoptions = {}; - my $deloptions = {}; - - my $validate = { group => 'GROUP', }; - - my $jsfunc = <<'EOJS'; - // skip on back - if (form._submitted_value.value == 'Previous') { - return true; - } -EOJS - - my $form = CGI::FormBuilder->new( - name => 'ldapns_selectgroup_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => "Select group", - fields => [qw(group)], - template => $templatedir . '/selectgroup.tmpl', - submit => [qw(Previous Next)], - method => 'post', - selectname => 0, - javascript => 1, - jsfunc => $jsfunc, - required => 'ALL', - validate => $validate, - ); - - if ( $form->submitted eq 'Previous' ) { - $session->clear( ['modgroup'] ); - redirect( '?tab=groups&action=modgroup' ); - } - - foreach my $values ( values( %{$groups} ) ) { - my $cn = ${ $values->{'cn'} }[0]; - $options->{$cn} = $cn; - } - - if ( scalar( keys( %{$options} ) ) == 0 ) { - $session->clear( ['modgroup'] ); - $session->param( 'error', 'Unable to fetch available groups' ); - redirect( '?tab=groups&action=addgroup' ); - } - - $form->field( - name => 'group', - options => $options, - sortopts => 'NAME', - type => 'select', - size => getsize_multipleselect( $options ), - multiple => 0, - ); - - if ( $form->submitted eq 'Next' ) { - - eval { - - die 'invalid parameters' unless $form->validate( $validate ); - - my $posixAccounts = $session->param( 'posixAccounts' ); - my $cn = $form->field( name => 'group' ); - my $member_attr; - my $group; - - reconnect_ldap_snmc(); - if ( $objectClass eq 'posixGroup' ) { - $group = SNET::LdapNS::getPosixGroup( $ldap_snmc->{'label'}, $cn ); - $member_attr = 'memberuid'; - } else { - $group = SNET::LdapNS::getGroupOfNames( $ldap_snmc->{'label'}, $cn ); - $member_attr = 'member'; - } - die 'invalid group' unless ( keys( %{$group} ) == 1 ); - - my @keys = keys( %{$group} ); - my $group_dn = shift( @keys ); - - while ( my ( $dn, $attrs ) = each( %{$posixAccounts} ) ) { - my $uid = ${ $attrs->{'uid'} }[0]; - my $gecos = ${ $attrs->{'gecos'} }[0]; - if ( $member_attr eq 'memberuid' ) { - $addoptions->{$uid} = $uid . ' - ' . $gecos; - } else { - $addoptions->{ lc( $dn ) } = $uid . ' - ' . $gecos; - } - } - - foreach my $member ( @{ $group->{$group_dn}->{$member_attr} } ) { - $member = lc( $member ) if ( $member_attr eq 'member' ); - my $userinfos = $addoptions->{$member}; - if ( defined( $userinfos ) ) { - delete( $addoptions->{$member} ); - $deloptions->{$member} = $userinfos; - } else { - $deloptions->{$member} = $member; - } - } - - $modgroup->{'addoptions'} = $addoptions; - $modgroup->{'deloptions'} = $deloptions; - $modgroup->{'group'} = $cn; - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - display_blank( "LdapNS modify groups" ); - } - $session->param( 'modgroup', $modgroup ); - return 1; - - } - - print_ns_headers( "LdapNS modify groups" ); - print $form->render; - print_ns_footers(); - -} - -sub select_group_objectclass($) -{ - - my $title = shift; - my $sessionparam = $session->param( 'action' ); - - if ( ( $sessionparam ne 'addgroup' ) - && ( $sessionparam ne 'delgroup' ) - && ( $sessionparam ne 'modgroup' ) ) { - $session->param( 'error', "invalid action $sessionparam" ); - redirect_homepage(); - } - - if ( defined( $session->param( $sessionparam ) ) ) { - - my $objectClass = $session->param( $sessionparam )->{'objectClass'}; - if ( $objectClass eq 'posixGroup' ) { - refresh_posixGroups; - } else { - refresh_groupOfNames; - } - return -1; - } - - my $validate = { - IM => 'IM', - objectClass => 'GROUPCLASS', - }; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_selectgroupclass_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'select group type', - fields => [qw(IM objectClass)], - template => $templatedir . '/selectgroupclass.tmpl', - method => 'post', - submit => 'Select', - javascript => 1, - required => 'ALL', - validate => $validate, - ); - $form->field( - name => 'objectClass', - options => { - 'posixGroup' => 'posixGroups', - 'groupOfNames' => 'groupOfNames' - }, - linebreaks => 1, - comment => 'posixGroups or groupOfNames', - multiple => 0, - ); - $form->field( name => 'IM', - comment => 'SMT ticket number', ); - - if ( $form->submitted eq 'Select' ) { - - my $IM = $form->field( name => 'IM' ); - my $objectClass = ( $form->field( name => 'objectClass' ) eq 'posixGroup' ) ? 'posixGroup' : 'groupOfNames'; - - eval { - die 'invalid parameters' unless $form->validate( $validate ); - $session->param( - $sessionparam, - { - IM => $IM, - objectClass => $objectClass, - } - ); - }; - if ( $@ ) { - $session->param( 'error', $@ ); - display_blank( $title ); - } - - if ( $objectClass eq 'posixGroup' ) { - refresh_posixGroups; - } else { - refresh_groupOfNames; - } - - return 1; - - } - - print_ns_headers( $title ); - print $form->render; - print_ns_footers(); - -} - -sub display_groupinfos() -{ - - $GROUPINFOS = 1; - - refresh_posixGroups; - refresh_groupOfNames; - - my $groupInfos; - my $options = []; - - my $validate = { group => 'GROUP', }; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_groupinfos_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Display group', - fields => [qw(group audit)], - template => $templatedir . '/selectgroup.tmpl', - method => 'post', - javascript => 1, - validate => $validate, - required => 'group', - submit => 'Display', - ); - - $form->tmpl_param( "audit" => 1 ); - - my $groupClass = {}; - - foreach my $values ( values( %{ $session->param( 'groupOfNames' ) } ) ) { - my $cn = ${ $values->{'cn'} }[0]; - $groupClass->{$cn} = 'groupOfNames'; - } - - foreach my $k ( sort( keys( %{$groupClass} ) ) ) { - push( @{$options}, [ $k, $k, $groupClass->{$k} ] ); - } - - foreach my $values ( values( %{ $session->param( 'posixGroups' ) } ) ) { - my $cn = ${ $values->{'cn'} }[0]; - $groupClass->{$cn} = 'posixGroup'; - } - - foreach my $k ( sort( keys( %{$groupClass} ) ) ) { - push( @{$options}, [ $k, $k, $groupClass->{$k} ] ) unless ( $groupClass->{$k} eq 'groupOfNames' ); - } - - if ( $form->submitted eq 'Display' ) { - eval { - die "invalid parameters" unless $form->validate( $validate ); - my @groups = $form->field( name => 'group' ); - die 'You must select at least one group' unless ( scalar( @groups ) > 0 ); - - map { die "invalid group `$_'" unless defined( $groupClass->{$_} ) } @groups; - - reconnect_ldap_snmc(); - - foreach my $group ( @groups ) { - my $infos; - my $class; - if ( $groupClass->{$group} eq 'posixGroup' ) { - $infos = SNET::LdapNS::getPosixGroup( $ldap_snmc->{'label'}, $group ); - $class = ['posixGroup']; - } else { - $infos = SNET::LdapNS::getGroupOfNames( $ldap_snmc->{'label'}, $group ); - $class = ['groupOfNames']; - } - while ( my ( $k, $v ) = each( %{$infos} ) ) { - $v->{'objectClass'} = $class; - $groupInfos->{$k} = $v; - } - } - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - undef $groupInfos; - } - } - - $form->field( - name => 'audit', - type => 'checkbox', - options => 'yes', - comment => 'Display auditInformation?', - selected => 0, - ); - - $form->field( - name => 'group', - options => $options, - optgroups => 1, - type => 'select', - size => getsize_multipleselect( $options ), - multiple => 1, - ); - - my $audit = ( defined( $form->field( name => 'audit' ) ) ); - - print_ns_headers( "LdapNS display groups" ); - print $form->render; - render_groupinfos( $groupInfos, $audit ) if defined( $groupInfos ); - print_ns_footers(); - -} - -sub display_addgroup() -{ - - $ADDGROUP = 1; - select_group_objectclass( "LdapNS add groups" ); - - my $addgroup = $session->param( 'addgroup' ); - my $objectClass = $addgroup->{'objectClass'}; - my $IM = $addgroup->{'IM'}; - my $groups; - my $options = {}; - - if ( $objectClass eq 'posixGroup' ) { - $groups = $session->param( 'posixGroups' ); - } else { - $groups = $session->param( 'groupOfNames' ); - refresh_posixAccounts(); - } - - my $jsfunc = <<'EOJS'; - // skip on back - if (form._submitted_value.value == 'Back') { - return true; - } -EOJS - - my $fields = [qw(_submitted_value IM objectClass group)]; - my @required; - push( @required, @{$fields} ); - - my $validate = { - IM => 'IM', - group => 'GROUP', - }; - if ( $objectClass eq 'posixGroup' ) { - push( @{$fields}, 'gidNumber' ); - $validate->{'gidNumber'} = 'GIDNUMBER'; - } else { - push( @{$fields}, 'member' ); - push( @required, 'member' ); - $validate->{'member'} = 'USERDN'; - } - - my $form = CGI::FormBuilder->new( - name => 'ldapns_addgroup_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => "Add $objectClass", - fields => $fields, - template => $templatedir . '/addgroup.tmpl', - method => 'post', - javascript => 1, - jsfunc => $jsfunc, - required => \@required, - validate => $validate, - ); - - if ( $form->submitted eq 'Back' ) { - $session->clear( ['addgroup'] ); - redirect( '?tab=groups&action=addgroup' ); - } - - $form->field( - name => 'IM', - value => $IM, - label => 'IM', - comment => 'SMT ticket number', - disabled => 1, - ); - $form->field( - name => 'objectClass', - value => $objectClass, - label => 'objectClass', - comment => 'posixGroups or groupOfNames', - disabled => 1, - ); - $form->field( name => '_submitted_value', - type => 'hidden', ); - $form->field( name => 'gidNumber', - comment => 'optional [2000..9999]', ); - $form->field( name => 'member', - comment => 'required', ); - - if ( $objectClass ne 'posixGroup' ) { - my $posixAccounts = $session->param( 'posixAccounts' ); - while ( my ( $dn, $values ) = each( %{$posixAccounts} ) ) { - my $uid = ${ $values->{'uid'} }[0]; - my $gecos = ${ $values->{'gecos'} }[0]; - $options->{$dn} = $uid . ' - ' . $gecos; - } - if ( scalar( keys( %{$options} ) ) == 0 ) { - $session->param( 'error', 'Unable to fetch available posixAccounts' ); - redirect( '?tab=users&action=adduser' ); - } - $form->field( - name => 'member', - options => $options, - selectname => 0, - sortopts => 'NAME', - label => 'member', - multiple => 1, - ); - } else { - $form->field( - name => 'gidNumber', - options => $options, - label => 'gidNumber', - ); - } - - $form->tmpl_param( "posix" => ( $objectClass eq 'posixGroup' ) ); - - if ( $form->submitted eq 'Add' ) { - my $entry; - eval { - - die 'invalid parameters' unless $form->validate( $validate ); - print STDERR "addgroup validation ok\n"; - - my $group = $form->field( name => 'group' ); - foreach my $dn ( keys( %{$groups} ) ) { - $dn =~ s/,.*//; - $dn =~ s/^.*=//; - die "group `$group' already exists" if ( $group eq $dn ); - } - - my $get_function; - reconnect_ldap_snmc(); - if ( $objectClass eq 'posixGroup' ) { - - $get_function = \&SNET::LdapNS::getPosixGroup; - my $gidNumber; - if ( defined( $form->field( name => 'gidNumber' ) ) - && length( $form->field( name => 'gidNumber' ) ) ) { - $gidNumber = $form->field( name => 'gidNumber' ); - } - - SNET::LdapNS::addPosixGroup( $ldap_snmc->{'label'}, $form->field( name => 'IM' ), $group, $gidNumber, ) or die "Unable to create LDAP entry for `$group'"; - } else { - - $get_function = \&SNET::LdapNS::getGroupOfNames; - - my @members = $form->field( name => 'member' ); - die 'You must select at least one member' unless ( scalar( @members ) ); - - map { die "invalid member `$_'" unless defined( $options->{$_} ) } @members; - - SNET::LdapNS::addGroupOfNames( $ldap_snmc->{'label'}, $form->field( name => 'IM' ), $group, \@members, ) or die "Unable to create LDAP entry for `$group'"; - - } - $session->param( 'message', "Group added" ); - if ( $objectClass eq 'posixGroup' ) { - $session->clear( [qw(addgroup posixGroups)] ); - } else { - $session->clear( [qw(addgroup groupOfNames)] ); - } - - $entry = &{$get_function}( $ldap_snmc->{'label'}, $group, ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } - reset_actions(); - if ( defined( $entry ) ) { - print_ns_headers( "LdapNS add group" ); - render_groupinfos( $entry ); - print_ns_footers(); - } else { - display_blank( "LdapNS add group" ); - } - } - - print_ns_headers( "LdapNS add group" ); - print $form->render; - print_ns_footers(); - -} - -sub display_delgroup() -{ - - $DELGROUP = 1; - select_group_objectclass( "LdapNS delete groups" ); - - my $delgroup = $session->param( 'delgroup' ); - my $objectClass = $delgroup->{'objectClass'}; - my $IM = $delgroup->{'IM'}; - my $options = {}; - my $type = 'select'; - my $groups; - - if ( $objectClass eq 'posixGroup' ) { - $groups = $session->param( 'posixGroups' ); - } else { - $groups = $session->param( 'groupOfNames' ); - } - - my $jsfunc = <<'EOJS'; - // skip js validation if on refresh or on cancel - if (form._submitted_value.value == 'Refresh') { - return true; - } - if (form._submitted_value.value == 'Cancel') { - return true; - } -EOJS - - my $validate = { - IM => 'IM', - objectClass => 'GROUPCLASS', - group => 'GROUP', - }; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_delgroup_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Delete group', - fields => [qw(_submitted_value IM group objectClass)], - template => $templatedir . '/delgroup.tmpl', - method => 'post', - javascript => 1, - jsfunc => $jsfunc, - required => 'ALL', - validate => $validate, - ); - - if ( $form->submitted eq 'Back' ) { - $session->clear( ['delgroup'] ); - redirect( '?tab=groups&action=delgroup' ); - } - $form->field( name => '_submitted_value', - type => 'hidden', ); - $form->field( - name => 'IM', - value => $IM, - disabled => 1, - ); - $form->field( - name => 'objectClass', - value => $objectClass, - disabled => 1, - ); - - if ( $form->submitted eq 'Delete' ) { - eval { - - die 'invalid parameters' unless $form->validate( $validate ); - - my @groups = $form->field( name => 'group' ); - die 'You must select at least one group' unless ( scalar( @groups ) > 0 ); - foreach my $group ( @groups ) { - - $group = lc( $group ); - - eval { - foreach my $dn ( keys( %{$groups} ) ) { - $dn =~ s/,.*//; - $dn =~ s/^.*=//; - die 'found' if ( lc( $group ) eq lc( $dn ) ); - } - }; - die "invalid group `$group'" unless ( $@ ); - die "read-only group `$group'" if ( lc( $group ) eq 'admin' ); - - $options->{$group} = $group; - } - $delgroup->{'options'} = $options; - $session->param( 'delgroup', $delgroup ); - }; - if ( $@ ) { - $session->param( 'error', $@ ); - display_blank( "LdapNS delete groups" ); - } - $type = 'checkbox'; - $form->field( name => 'group', disabled => 1 ); - $form->tmpl_param( 'submit1' => 'Confirm' ); - $form->tmpl_param( 'submit2' => 'Cancel' ); - } elsif ( $form->submitted eq 'Confirm' ) { - my @groups = keys( %{ $delgroup->{'options'} } ); - my @deleted_groups; - my $group; - eval { - reconnect_ldap_snmc(); - if ( $objectClass eq 'posixGroup' ) { - foreach $group ( @groups ) { - SNET::LdapNS::deletePosixGroup( $ldap_snmc->{'label'}, $IM, $group ); - push( @deleted_groups, $group ); - } - } elsif ( $objectClass eq 'groupOfNames' ) { - foreach $group ( @groups ) { - SNET::LdapNS::deleteGroupOfNames( $ldap_snmc->{'label'}, $IM, $group ); - push( @deleted_groups, $group ); - } - } else { - die "invalid objectClass `$objectClass'"; - } - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } - if ( scalar( @deleted_groups ) ) { - print STDERR 'Successful deletion of ' . join( ', ', @deleted_groups ) . "\n"; - $session->param( 'message', 'Successful deletion of ' . join( ', ', @deleted_groups ) ); - if ( $objectClass eq 'posixGroup' ) { - $session->clear( ['posixGroups'] ); - } else { - $session->clear( ['groupOfNames'] ); - } - } - $session->clear( ['delgroup'] ); - display_blank( "LdapNS delete groups" ); - } elsif ( $form->submitted eq 'Cancel' ) { - $session->param( 'error', 'delete operation cancelled' ); - $session->clear( ['delgroup'] ); - display_blank( "LdapNS delete groups" ); - } else { - my $groups; - if ( $objectClass eq 'posixGroup' ) { - $groups = $session->param( 'posixGroups' ); - } else { - $groups = $session->param( 'groupOfNames' ); - } - foreach my $values ( values( %{$groups} ) ) { - my $cn = ${ $values->{'cn'} }[0]; - $options->{$cn} = $cn; - } - $form->tmpl_param( 'submit1' => 'Delete' ); - $form->tmpl_param( 'submit2' => 'Back' ); - } - - if ( scalar( keys( %{$options} ) ) == 0 ) { - $session->param( 'error', 'Unable to fetch available groups' ); - display_blank( "LdapNS delete groups" ); - } - - $form->field( - name => 'group', - options => $options, - sortopts => 'NAME', - linebreaks => 1, - type => $type, - selectname => 0, - multiple => 0, - ); - - if ( $type eq 'select' ) { - $form->field( size => getsize_multipleselect( $options ), ); - } - - print_ns_headers( "LdapNS delete groups" ); - print $form->render(); - print_ns_footers(); - -} - -sub display_modgroup() -{ - - $MODGROUP = 1; - - refresh_posixAccounts(); - - my $next_step = select_group_objectclass( "LdapNS modify groups" ); - - if ( $next_step < 0 ) { - select_group(); - } else { - select_group() if ( $next_step > 0 ); - } - - my $modgroup = $session->param( 'modgroup' ); - my $IM = $modgroup->{'IM'}; - my $objectClass = $modgroup->{'objectClass'}; - my $group = $modgroup->{'group'}; - my $deloptions; - my $addoptions; - my $type = 'select'; - - my $jsfunc = <<'EOJS'; - // skip on back - if (form._submitted_value.value == 'Back') { - return true; - } - if (form._submitted_value.value == 'Cancel') { - return true; - } -EOJS - - my $user_validate = ( $objectClass eq 'posixGroup' ) ? 'UID' : 'USERDN'; - my $validate = { - IM => 'IM', - group => 'GROUP', - objectClass => 'GROUPCLASS', - uid => $user_validate, - }; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_modgroup_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => "Modify $objectClass", - fields => [qw(_submitted_value IM objectClass group deluser adduser)], - template => $templatedir . '/modgroup.tmpl', - method => 'post', - javascript => 1, - jsfunc => $jsfunc, - required => [qw(IM objectClass group)], - validate => $validate, - ); - $form->field( name => '_submitted_value', - type => 'hidden', ); - - if ( $form->submitted eq 'Back' ) { - delete( $modgroup->{'group'} ); - $session->param( 'modgroup', $modgroup ); - redirect( '?tab=groups&action=modgroup' ); - } - - if ( $form->submitted eq 'Cancel' ) { - $session->param( 'error', 'modify operation cancelled' ); - $session->clear( ['modgroup'] ); - display_blank( "LdapNS modify groups" ); - } - - $form->field( - name => 'IM', - value => $IM, - disabled => 1, - ); - $form->field( - name => 'objectClass', - value => $objectClass, - disabled => 1, - ); - $form->field( - name => 'group', - value => $group, - disabled => 1, - ); - - if ( $form->submitted eq 'Modify' ) { - - eval { - - my $deluser = []; - my $adduser = []; - $deloptions = {}; - $addoptions = {}; - - push( @{$deluser}, $form->field( name => 'deluser' ) ) if ( defined( $form->field( name => 'deluser' ) ) ); - push( @{$adduser}, $form->field( name => 'adduser' ) ) if ( defined( $form->field( name => 'adduser' ) ) ); - - die 'You must select at least one user' unless ( scalar( @{$deluser} ) || scalar( @{$adduser} ) ); - - foreach my $user ( @{$deluser} ) { - $deloptions->{$user} = $modgroup->{'deloptions'}->{$user} - or die "invalid user `$user'"; - } - foreach my $user ( @{$adduser} ) { - $addoptions->{$user} = $modgroup->{'addoptions'}->{$user} - or die "invalid user `$user'"; - } - - if ( $objectClass eq 'groupOfNames' ) { - my $members = scalar( keys( %{ $modgroup->{'deloptions'} } ) ); - $members += scalar( keys( %{$addoptions} ) ); - $members -= scalar( keys( %{$deloptions} ) ); - die "groupOfNames must contain at least one member" unless ( $members ); - } - - $modgroup->{'deloptions'} = $deloptions; - $modgroup->{'addoptions'} = $addoptions; - $session->param( 'modgroup', $modgroup ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - display_blank( "LdapNS modify groups" ); - } - $type = 'checkbox'; - $form->field( name => 'adduser', disabled => 1 ); - $form->field( name => 'deluser', disabled => 1 ); - $form->tmpl_param( 'submit1' => 'Cancel' ); - $form->tmpl_param( 'submit2' => 'Confirm' ); - } elsif ( $form->submitted eq 'Confirm' ) { - - my $entry; - - eval { - - $deloptions = $modgroup->{'deloptions'}; - $addoptions = $modgroup->{'addoptions'}; - my @to_delete = keys( %{$deloptions} ); - my @to_add = keys( %{$addoptions} ); - - my $add_function; - my $del_function; - my $get_function; - - if ( $objectClass eq 'posixGroup' ) { - $add_function = \&SNET::LdapNS::addToPosixGroup; - $del_function = \&SNET::LdapNS::removeFromPosixGroup; - $get_function = \&SNET::LdapNS::getPosixGroup; - } else { - $add_function = \&SNET::LdapNS::addToGroupOfNames; - $del_function = \&SNET::LdapNS::removeFromGroupOfNames; - $get_function = \&SNET::LdapNS::getGroupOfNames; - } - - reconnect_ldap_snmc(); - - if ( scalar( @to_add ) ) { - &{$add_function}( $ldap_snmc->{'label'}, $IM, $group, \@to_add ) or die SNET::LdapNS::error( $ldap_snmc->{'label'} ); - } - - if ( scalar( @to_delete ) ) { - &{$del_function}( $ldap_snmc->{'label'}, $IM, $group, \@to_delete ) or die SNET::LdapNS::error( $ldap_snmc->{'label'} ); - } - - $session->param( 'message', 'group modification successful' ); - if ( $objectClass eq 'posixGroup' ) { - $session->clear( [qw(modgroup posixGroups)] ); - } else { - $session->clear( [qw(modgroup groupOfNames)] ); - } - - $entry = &{$get_function}( $ldap_snmc->{'label'}, $group, ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } - reset_actions(); - if ( defined( $entry ) ) { - print_ns_headers( "LdapNS modify group" ); - render_groupinfos( $entry ); - print_ns_footers(); - } else { - display_blank( "LdapNS modify groups" ); - } - - } else { - $deloptions = $modgroup->{'deloptions'}; - $addoptions = $modgroup->{'addoptions'}; - $form->tmpl_param( 'submit1' => 'Back' ); - $form->tmpl_param( 'submit2' => 'Modify' ); - } - - if ( keys %{$deloptions} ) { - $form->field( - name => 'deluser', - options => $deloptions, - sortopts => 'NAME', - linebreaks => 1, - type => $type, - multiple => 1, - disable => ( scalar( keys( %{$deloptions} ) ) == 0 ), - ); - - if ( $type eq 'select' ) { - $form->field( size => getsize_multipleselect( $deloptions ), ); - } - - } else { - $form->tmpl_param( 'disable_deluser' => 1 ); - } - - if ( keys( %{$addoptions} ) ) { - $form->field( - name => 'adduser', - options => $addoptions, - sortopts => 'NAME', - linebreaks => 1, - type => $type, - multiple => 1, - disable => ( scalar( keys( %{$addoptions} ) ) == 0 ), - ); - - if ( $type eq 'select' ) { - $form->field( size => getsize_multipleselect( $addoptions ), ); - } - - } else { - $form->tmpl_param( 'disable_adduser' => 1 ); - } - - print_ns_headers( "LdapNS modify groups" ); - print $form->render(); - print_ns_footers(); - -} - -sub display_passwd() -{ - - $PASSWD = 1; - - my $form_fields = [qw(old new repeat)]; - push( @{$form_fields}, 'synchronize' ) if ( $mod_synchro ); - - my $form = CGI::FormBuilder->new( - name => 'ldapns_passwd_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Password change', - fields => $form_fields, - template => $templatedir . '/passwd.tmpl', - method => 'post', - required => [qw(old new repeat)], - submit => 'Change password', - javascript => 0, - ); - - if ( $mod_synchro ) { - $form->field( - name => 'synchronize', - type => 'checkbox', - comment => 'Synchronize with old LDAP database?', - options => 'yes', - ); - $form->field( - name => 'synchronize', - value => 'yes' - ) unless ( $form->submitted ); - } - $form->tmpl_param( 'mod_synchro' => $mod_synchro ); - - $form->field( name => 'new', - type => 'password', ); - $form->field( name => 'old', - type => 'password', ); - $form->field( name => 'repeat', - type => 'password', ); - - $session->param( 'message', "password must be [10..64] characters long, and must contains 3 different character classes" ); - - if ( $form->submitted ) { - - eval { - unless ( $form->validate() ) { - print STDERR 'display_passwd: missing parameters'; - die 'missing parameters'; - } - unless ( $form->field( name => 'new' ) eq $form->field( name => 'repeat' ) ) { - print STDERR 'display_passwd: password mismatch'; - die 'password mismatch'; - } - - reconnect_ldap_snmc(); - SNET::LdapNS::passwd( $ldap_snmc->{'label'}, $form->field( name => 'old' ), $form->field( name => 'new' ) ); - $session->param( 'message', 'password changed successfully' ); - $session->clear( [ 'action', 'error' ] ); - - # synchronize_samba_password( - # $ldap_snmc->{'label'}, - # $form->field(name => 'new') - # ); - - synchronize_passwords( defined( $form->field( name => 'synchronize' ) ), $ldap_snmc->{'label'}, $form->field( name => 'new' ), undef, $form->field( name => 'old' ) ); - - encode_sessionauth( $form->field( name => 'new' ) ); - $session->param( 'userMustChange', 0 ); - $userMustChange = 0; - refresh_userInfos; - redirect_homepage(); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } else { - display_blank( "LdapNS homepage" ); - } - } - - print_ns_headers( "LdapNS homepage" ); - print $form->render; - print_ns_footers(); - -} - -sub display_blank($) -{ - - my $title = shift; - my $template_blank = HTML::Template->new( filename => $templatedir . '/blank.tmpl' ); - - parse_messages(); - - $template_blank->param( 'br' => ( !( defined( $error ) || defined( $message ) ) ) ); - - reset_actions(); - - print_ns_headers( $title ); - print $template_blank->output; - print_ns_footers(); - -} - -sub display_users() -{ - - print STDERR "ldap_NS.pl: entering display_users\n" if ( $debug > 2 ); - - if ( defined( $params->{'action'} ) ) { - if ( $params->{'action'} eq 'reset' ) { - $session->param( 'action', 'reset' ); - } elsif ( $params->{'action'} eq 'deluser' ) { - $session->param( 'action', 'deluser' ); - } elsif ( $params->{'action'} eq 'adduser' ) { - $session->param( 'action', 'adduser' ); - } elsif ( $params->{'action'} eq 'adduserprofile' ) { - $session->param( 'action', 'adduserprofile' ); - } elsif ( $params->{'action'} eq 'moduser' ) { - $session->param( 'action', 'moduser' ); - } elsif ( $params->{'action'} eq 'userinfos' ) { - $session->param( 'action', 'userinfos' ); - } - } - - if ( defined( $session->param( 'action' ) ) ) { - if ( $session->param( 'action' ) eq 'adduser' ) { - display_adduser; - } elsif ( $session->param( 'action' ) eq 'adduserprofile' ) { - display_adduserprofile; - } elsif ( $session->param( 'action' ) eq 'moduser' ) { - display_moduser; - } elsif ( $session->param( 'action' ) eq 'deluser' ) { - display_deluser; - } elsif ( $session->param( 'action' ) eq 'reset' ) { - display_reset; - } elsif ( $session->param( 'action' ) eq 'userinfos' ) { - display_userinfos; - } else { - $session->clear( ['action'] ); - } - } - - display_blank( "LdapNS users management" ); - -} - -sub display_groups() -{ - - print STDERR "ldap_NS.pl: entering display_groups\n" if ( $debug > 2 ); - - if ( defined( $params->{'action'} ) ) { - if ( $params->{'action'} eq 'modgroup' ) { - $session->param( 'action', 'modgroup' ); - } elsif ( $params->{'action'} eq 'delgroup' ) { - $session->param( 'action', 'delgroup' ); - } elsif ( $params->{'action'} eq 'addgroup' ) { - $session->param( 'action', 'addgroup' ); - } elsif ( $params->{'action'} eq 'groupinfos' ) { - $session->param( 'action', 'groupinfos' ); - } - } - - if ( defined( $session->param( 'action' ) ) ) { - if ( $session->param( 'action' ) eq 'addgroup' ) { - display_addgroup(); - } elsif ( $session->param( 'action' ) eq 'delgroup' ) { - display_delgroup(); - } elsif ( $session->param( 'action' ) eq 'modgroup' ) { - display_modgroup(); - } elsif ( $session->param( 'action' ) eq 'groupinfos' ) { - display_groupinfos(); - } else { - $session->clear( ['action'] ); - } - } - - display_blank( "LdapNS groups management" ); - -} - -sub select_policy($) -{ - - my $title = shift; - my $sessionparam = $session->param( 'action' ); - - if ( ( $sessionparam ne 'modpolicy' ) - && ( $sessionparam ne 'delpolicy' ) ) { - $session->param( 'error', "invalid action $sessionparam" ); - redirect_homepage(); - } - - refresh_ppolicy(); - - if ( defined( $session->param( $sessionparam ) ) ) { - return 1 if ( defined( $session->param( $sessionparam )->{'policy'} ) ); - } - - my $policies; - my $options; - - my $validate = { - IM => 'IM', - policy => 'PPOLICYDN', - }; - - my $jsfunc = <<'EOJS'; - // skip on back - if (form._submitted_value.value == 'Cancel') { - return true; - } -EOJS - - my $form = CGI::FormBuilder->new( - name => 'ldapns_selectpolicy_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => "Select policy", - fields => [qw(IM policy)], - template => $templatedir . '/selectpolicy.tmpl', - submit => [qw(Cancel Select)], - method => 'post', - selectname => 0, - javascript => 1, - jsfunc => $jsfunc, - required => 'ALL', - validate => $validate, - ); - - if ( $form->submitted eq 'Cancel' ) { - $session->clear( ["$sessionparam"] ); - $session->clear( ['action'] ); - redirect( '?tab=ppolicies' ); - } - - my $pwdPolicies = $session->param( 'pwdPolicies' ); - while ( my ( $dn, $values ) = each( %{$pwdPolicies} ) ) { - my $did = ${ $values->{'documentidentifier'} }[0]; - if ( defined( $values->{'description'} ) - && scalar( @{ $values->{'description'} } ) ) { - $options->{$dn} = $did . ' - ' . ${ $values->{'description'} }[0]; - } else { - $options->{$dn} = $did; - } - } - - if ( scalar( keys( %{$options} ) ) == 0 ) { - $session->clear( ["$sessionparam"] ); - $session->param( 'error', 'Unable to fetch available policies' ); - redirect( '?tab=ppolicies&action=addpolicy' ); - } - - $form->field( name => 'IM', - comment => 'SMT ticket number', ); - - $form->field( - name => 'policy', - options => $options, - sortopts => 'NAME', - type => 'select', - size => getsize_multipleselect( $options ), - multiple => 0, - ); - - if ( $form->submitted eq 'Select' ) { - - my $IM = $form->field( name => 'IM' ); - my $policy = $form->field( name => 'policy' ); - - eval { - - die 'invalid parameters' unless $form->validate( $validate ); - - reconnect_ldap_snmc(); - my $infos = SNET::LdapNS::getPwdPolicy( $ldap_snmc->{'label'}, $policy ); - - $session->param( - $sessionparam, - { - 'IM' => $IM, - 'policy' => $policy, - 'infos' => $infos->{$policy}, - } - ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - display_blank( $title ); - } - - return 1; - - } - - print_ns_headers( $title ); - print $form->render; - print_ns_footers(); - -} - -sub display_addpolicy() -{ - - $ADDPOLICY = 1; - refresh_ppolicy(); - - $session->param( 'error', 'Not yet implemented' ); - - display_blank( "LdapNS passwords policies management" ); - -} - -sub display_delpolicy() -{ - - $DELPOLICY = 1; - refresh_ppolicy(); - - $session->param( 'error', 'Not yet implemented' ); - - display_blank( "LdapNS passwords policies management" ); - -} - -sub display_modpolicy() -{ - - $MODPOLICY = 1; - - select_policy( "LdapNS modify policy" ); - - my $modpolicy = $session->param( 'modpolicy' ); - my $IM = $modpolicy->{'IM'}; - my $policy = $modpolicy->{'policy'}; - my $infos = $modpolicy->{'infos'}; - my $deloptions; - my $addoptions; - my $type = 'select'; - - my $add = {}; - my $del = {}; - - my $jsfunc = <<'EOJS'; - // skip on back - if (form._submitted_value.value == 'Back') { - return true; - } - if (form._submitted_value.value == 'Cancel') { - return true; - } -EOJS - - my $validate = { - 'IM' => 'IM', - 'policy' => 'PPOLICYDN', - description => 'DESCRIPTION', - }; - - my $fields = [qw(_submitted_value IM description)]; - my $pwdconstraint_fields = []; - my @keys = keys( %{$SNET::LdapNS::pwdPolicyAttributes} ); - foreach my $k ( sort { $a cmp $b } @keys ) { - next if ( $k =~ m/checkmodule|constraint.*length|constraintcheckquality/i ); - if ( $k =~ m/pwdconstraint/i ) { - if ( $k =~ m/quality/i ) { - unshift( @{$pwdconstraint_fields}, $k ); - } else { - push( @{$pwdconstraint_fields}, $k ); - } - } else { - push( @{$fields}, $k ); - } - $validate->{$k} = $CGI::FormBuilder::Field::VALIDATE{$k}; - } - push( @{$fields}, @{$pwdconstraint_fields} ); - - my $form = CGI::FormBuilder->new( - name => 'ldapns_modpolicy_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => "Modify policy", - fields => $fields, - template => $templatedir . '/modpolicy.tmpl', - method => 'post', - javascript => 1, - sticky => 1, - jsfunc => $jsfunc, - required => [qw(IM policy)], - validate => $validate, - ); - - $form->field( name => '_submitted_value', - type => 'hidden', ); - - if ( $form->submitted eq 'Back' ) { - delete( $modpolicy->{'policy'} ); - $session->param( 'modpolicy', $modpolicy ); - redirect( '?tab=ppolicies&action=modpolicy' ); - } - - if ( $form->submitted eq 'Cancel' ) { - $session->param( 'error', 'modify operation cancelled' ); - $session->clear( ['modpolicy'] ); - display_blank( "LdapNS modify policies" ); - } - - $form->field( - name => 'IM', - value => $IM, - disabled => 1, - ); - $form->field( - name => 'policy', - value => $policy, - disabled => 1, - ); - - $form->field( name => 'description', - comment => 'optional', ); - $form->field( name => 'description', value => $infos->{'description'} ) - if defined( $infos->{'description'} ); - - foreach my $k ( @{$fields} ) { - - next unless ( defined( $SNET::LdapNS::pwdPolicyAttributes->{$k} ) ); - my $type = ${ $SNET::LdapNS::pwdPolicyAttributes->{$k} }[0]; - - my $val = ( defined( $infos->{$k} ) ? ${ $infos->{$k} }[0] : 0 ); - $form->tmpl_param( 'if_' . $k, 1 ); - - if ( $type eq 'bool' ) { - $form->field( - name => $k, - comment => ${ $SNET::LdapNS::pwdPolicyAttributes->{$k} }[1], - type => 'checkbox', - options => 'true', - ); - if ( $form->submitted ne 'Modify' ) { - $form->field( name => $k, value => 'true' ) if ( "$val" =~ m/true/i ); - } - } elsif ( $type eq 'extbool' ) { - $form->field( - name => $k, - comment => ${ $SNET::LdapNS::pwdPolicyAttributes->{$k} }[1], - type => 'checkbox', - options => 'strict', - ); - if ( $form->submitted ne 'Modify' ) { - $form->field( name => $k, value => 'strict' ) if ( $val > 0 ); - } - } elsif ( $type eq 'nbool' ) { - $form->field( - name => $k, - comment => ${ $SNET::LdapNS::pwdPolicyAttributes->{$k} }[1], - type => 'checkbox', - options => 'counted', - ); - if ( $form->submitted ne 'Modify' ) { - $form->field( name => $k, value => 'counted' ) if ( $val > 0 ); - } - } else { - $form->field( name => $k, - comment => ${ $SNET::LdapNS::pwdPolicyAttributes->{$k} }[1], ); - if ( $form->submitted ne 'Modify' ) { - $form->field( name => $k, value => $val ); - } - } - $form->field( name => $k, disabled => ( $form->submitted eq 'Modify' ) ); - } - - if ( $form->submitted eq 'Modify' ) { - - foreach my $k ( @{$fields} ) { - - next if ( $k eq '_submitted_value' ); - next if ( $k eq 'IM' ); - next if ( $k eq 'policy' ); - - if ( $k eq 'description' ) { - my $v = $form->field( name => $k ) || undef; - if ( defined( $v ) ) { - $add->{$k} = $v; - } else { - $del->{$k}++; - } - next; - } elsif ( $k =~ m/pwdCheckQuality/i ) { - my $checkquality = $form->field( name => $k ) || undef; - if ( defined( $checkquality ) ) { - $add->{'pwdConstraintCheckQuality'} = 2; - } else { - $del->{'pwdConstraintCheckQuality'}++; - } - } - - next unless ( defined( $SNET::LdapNS::pwdPolicyAttributes->{$k} ) ); - - my $v = $form->field( name => $k ) || undef; - if ( !defined( $v ) ) { - $del->{$k}++; - $form->tmpl_param( 'if_' . $k, 0 ); - next; - } - - $form->tmpl_param( 'if_' . $k, 1 ); - my $type = ${ $SNET::LdapNS::pwdPolicyAttributes->{$k} }[0]; - - if ( $type eq 'bool' ) { - $add->{$k} = ( ( $v =~ m/true/i ) ? 'TRUE' : 'FALSE' ); - } elsif ( $type eq 'extbool' ) { - $add->{$k} = 2; - } elsif ( $type eq 'nbool' ) { - $add->{$k} = 1; - } else { - $add->{$k} = $v; - } - - } - - $modpolicy->{'add'} = $add; - $modpolicy->{'del'} = $del; - - $form->tmpl_param( 'submit1' => 'Cancel' ); - $form->tmpl_param( 'submit2' => 'Confirm' ); - - } elsif ( $form->submitted eq 'Confirm' ) { - - my $entry; - - eval { - - reconnect_ldap_snmc(); - - SNET::LdapNS::updatePwdPolicy( $ldap_snmc->{'label'}, $IM, $policy, $modpolicy->{'add'}, $modpolicy->{'del'}, ) or die SNET::LdapNS::error( $ldap_snmc->{'label'} ); - - $session->param( 'message', 'policy modification successful' ); - $session->clear( [qw(modpolicy pwdPolicies)] ); - - $entry = SNET::LdapNS::getPwdPolicy( $ldap_snmc->{'label'}, $policy, ); - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - } - reset_actions(); - if ( defined( $entry ) ) { - print_ns_headers( "LdapNS modify policies" ); - render_ppolicyinfos( $entry, 1 ); - print_ns_footers(); - } else { - display_blank( "LdapNS modify policies" ); - } - - } else { - $form->tmpl_param( 'submit1' => 'Back' ); - $form->tmpl_param( 'submit2' => 'Modify' ); - } - - print_ns_headers( "LdapNS modify policies" ); - print $form->render(); - print_ns_footers(); - -} - -sub display_policyinfos() -{ - - $POLICYINFOS = 1; - - refresh_ppolicy(); - - my $policyInfos; - my $options = {}; - - my $validate = { policy => 'PPOLICYDN', }; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_policyinfos_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Display ppolicy', - fields => [qw(policy audit)], - template => $templatedir . '/selectppolicy.tmpl', - method => 'post', - javascript => 1, - validate => $validate, - required => 'policy', - submit => 'Display', - ); - - my $pwdPolicies = $session->param( 'pwdPolicies' ); - while ( my ( $dn, $values ) = each( %{$pwdPolicies} ) ) { - my $did = ${ $values->{'documentidentifier'} }[0]; - if ( defined( $values->{'description'} ) - && scalar( @{ $values->{'description'} } ) ) { - $options->{$dn} = $did . ' - ' . ${ $values->{'description'} }[0]; - } else { - $options->{$dn} = $did; - } - } - - if ( $form->submitted eq 'Display' ) { - eval { - die 'invalid parameters' unless $form->validate; - my @dids = $form->field( name => 'policy' ); - die 'You must select at least one policy' unless ( scalar( @dids ) > 0 ); - - map { die "invalid policy `$_'" unless defined( $options->{$_} ) } @dids; - - reconnect_ldap_snmc(); - - foreach my $did ( @dids ) { - my $infos = SNET::LdapNS::getPwdPolicy( $ldap_snmc->{'label'}, $did ); - while ( my ( $k, $v ) = each( %{$infos} ) ) { - $policyInfos->{$k} = $v; - } - } - - }; - if ( $@ ) { - $session->param( 'error', $@ ); - undef $policyInfos; - } - } - - $form->field( - name => 'audit', - type => 'checkbox', - comment => 'Display auditInformation?', - options => 'yes', - selected => 0, - ); - - $form->field( - name => 'policy', - options => $options, - sortopts => 'NAME', - type => 'select', - size => getsize_multipleselect( $options ), - multiple => 1, - ); - - my $audit = ( defined( $form->field( name => 'audit' ) ) ); - - print_ns_headers( "LdapNS display password policies" ); - print $form->render; - render_ppolicyinfos( $policyInfos, $audit ) if defined( $policyInfos ); - print_ns_footers(); - -} - -sub display_policies() -{ - - print STDERR "ldap_NS.pl: entering display_policies\n" if ( $debug > 2 ); - - if ( defined( $params->{'action'} ) ) { - if ( $params->{'action'} eq 'modpolicy' ) { - $session->param( 'action', 'modpolicy' ); - } elsif ( $params->{'action'} eq 'delpolicy' ) { - $session->param( 'action', 'delpolicy' ); - } elsif ( $params->{'action'} eq 'addpolicy' ) { - $session->param( 'action', 'addpolicy' ); - } elsif ( $params->{'action'} eq 'policyinfos' ) { - $session->param( 'action', 'policyinfos' ); - } - } - - if ( defined( $session->param( 'action' ) ) ) { - if ( $session->param( 'action' ) eq 'addpolicy' ) { - display_addpolicy(); - } elsif ( $session->param( 'action' ) eq 'delpolicy' ) { - display_delpolicy(); - } elsif ( $session->param( 'action' ) eq 'modpolicy' ) { - display_modpolicy(); - } elsif ( $session->param( 'action' ) eq 'policyinfos' ) { - display_policyinfos(); - } else { - $session->clear( ['action'] ); - } - } - - display_blank( "LdapNS passwords policies management" ); - -} - -sub display_homepage() -{ - - print STDERR "ldap_NS.pl: entering display_homepage\n" if ( $debug > 2 ); - - if ( defined( $params->{'action'} ) ) { - if ( $params->{'action'} eq 'passwd' ) { - $session->param( 'action', 'passwd' ); - } elsif ( $params->{'action'} eq 'info' ) { - $session->param( 'action', 'info' ); - } - } - - if ( defined( $session->param( 'action' ) ) ) { - if ( $session->param( 'action' ) eq 'passwd' ) { - display_passwd(); - } elsif ( $session->param( 'action' ) eq 'info' ) { - $INFO = 1; - print_ns_headers( "LdapNS homepage" ); - render_userinfos( $session->param( 'userInfos' ) ); - print_ns_footers(); - } else { - $session->clear( ['action'] ); - } - } - display_blank( "LdapNS homepage" ); -} - -sub dispatch() -{ - - print STDERR "ldap_NS.pl: entering dispatch\n" if ( $debug > 2 ); - - $session->expire( '+1h' ); - $LOGIN = 0; - - $isAdmin = $session->param( 'isAdmin' ); - $debug = 1 if ( ( $isAdmin ) && ( $debug < 2 ) ); - - if ( defined( $params->{'tab'} ) ) { - $session->param( 'tab', $params->{'tab'} ); - } - - if ( defined( $session->param( 'tab' ) ) ) { - if ( $session->param( 'tab' ) eq 'users' ) { - $TAB_USERS = 1; - display_users(); - } elsif ( $session->param( 'tab' ) eq 'groups' ) { - $TAB_GROUPS = 1; - display_groups(); - } elsif ( $session->param( 'tab' ) eq 'ppolicies' ) { - $TAB_POLICY = 1; - display_policies(); - } elsif ( $session->param( 'tab' ) eq 'home' ) { - $TAB_HOME = 1; - display_homepage(); - } - } - - display_blank( "LdapNS homage" ); - -} - -sub display_login() -{ - - $LOGIN = 1; - - my $form = CGI::FormBuilder->new( - name => 'ldapns_login_form', - header => 0, - stylesheet => 1, - styleclass => 'ldapns_fb', - text => 'Sign in', - fields => [qw(uid password action)], - template => $templatedir . '/login.tmpl', - method => 'post', - required => 'ALL', - sticky => 1, - submit => 'Sign-up', - ); - $form->field( - name => 'password', - type => 'password', - label => 'password', - required => 1, - ); - $form->field( - name => 'uid', - label => 'login', - comment => 'uid of full dn', - required => 1, - ); - $form->field( - name => 'action', - type => 'hidden', - value => 'login' - ); - - if ( defined( $session ) ) { - if ( defined( $session->param( 'user' ) ) ) { - $form->field( name => 'uid', - value => $session->param( 'user' ), ); - } - } elsif ( defined( $ENV{"HTTP_AUTHUSER"} ) ) { - my $AuthUser = $ENV{"HTTP_AUTHUSER"}; - $AuthUser =~ s/uid=//; - $AuthUser =~ s/,.*$//g; - $form->field( name => 'uid', - value => $AuthUser, ); - } - - if ( $form->submitted ) { - - eval { - - die "missing required field `login'" unless ( defined( $form->field( name => 'uid' ) ) && ( length( $form->field( name => 'uid' ) ) > 0 ) ); - $ldap_snmc->{'user'} = $form->field( name => 'uid' ); - - die "missing required field `password'" unless ( defined( $form->field( name => 'password' ) ) && ( length( $form->field( name => 'password' ) ) > 0 ) ); - $ldap_snmc->{'password'} = $form->field( name => 'password' ); - - die 'invalid or missing parameters' unless $form->validate(); - - connect_ldap_snmc( $ldap_snmc->{'user'}, $ldap_snmc->{'password'}, 0 ); - - }; - if ( $@ ) { - $error = $@; - } else { - dispatch(); - } - } - - $key = CGI::Session::ID::md5::generate_id(); - - print_ns_headers( "LdapNS authentication" ); - parse_messages(); - $form->tmpl_param( 'error' => defined( $error ) ); - $form->tmpl_param( 'error_msg' => $error ); - print $form->render( sticky => ( $form->submitted ? 1 : 0 ) ); - print_ns_footers(); - -} - -sub check_remote_infos() -{ - - eval { - - die 'Unauthorized access from unknown source' unless ( defined( $ENV{'REMOTE_ADDR'} ) && defined( $ENV{"HTTP_AUTHUSER"} ) ); - - my $remote_addr = $ENV{'REMOTE_ADDR'} || ''; - $audit_user = $ENV{"HTTP_AUTHUSER"} || ''; - - my $auth_ok = 0; - - foreach my $auth_ip ( @{$authorized_ip} ) { - $auth_ok = 1, last if ( $auth_ip eq $remote_addr ); - } - unless ( $auth_ok ) { - foreach my $auth_ip ( @{$authorized_ip_regex} ) { - $auth_ok = 1, last if ( $remote_addr =~ /$auth_ip/ ); - } - } - - die "Unauthorized access from `$remote_addr'" unless $auth_ok; - - my $client_ip = $ENV{'HTTP_CLIENT_IP'}; - $ENV{'REMOTE_ADDR'} = $client_ip, return if ( defined( $client_ip ) ); - - my $x_forwarded_for = $ENV{'HTTP_X_FORWARDED_FOR'}; - $ENV{'REMOTE_ADDR'} = $x_forwarded_for, return if ( defined( $x_forwarded_for ) ); - - }; - if ( $@ ) { - $error = $@; - display_login; - } - -} - -eval { - - $cgi = CGI->new; - $params = $cgi->Vars; - - if ( $debug > 2 ) { - - foreach my $hash ( \%ENV, $params ) { - while ( my ( $k, $v ) = each( %{$hash} ) ) { - $v =~ s/./*/g if ( $k =~ m/password|old|new|repeat/ ); - print STDERR 'ldap_NS.pl: ' . $k . ', ' . $v . "\n"; - } - } - - } - - check_remote_infos(); - - my $hash = {}; - if ( defined( $cgi->cookie( "SESSION_ID" ) ) ) { - $hash->{'sid'} = $cgi->cookie( "SESSION_ID" ); - } - if ( defined( $cgi->cookie( "SESSION_KEY" ) ) ) { - $hash->{'key'} = $cgi->cookie( "SESSION_KEY" ); - } - my $handler = CGI::Untaint->new( $hash ); - - # no key = no session at all - $key = $handler->extract( -as_printable => 'key' ); - unless ( defined( $key ) ) { - print STDERR 'ldap_NS.pl: ' . 'no session key readable from cookies' . "\n"; - display_login(); - } - - # sid is created after successful connection to ldap - $sid = $handler->extract( -as_printable => 'sid' ); - unless ( defined( $sid ) ) { - print STDERR 'ldap_NS.pl: ' . 'no session id readable from cookies' . "\n"; - display_login(); - } - - # we must load the session before checking logout - # for cleaning purpose - $session = CGI::Session->load( 'driver:chi', $sid, { 'driver' => 'Redis', 'namespace' => 'ldapcgi', 'server' => $redis_hostport, } ) or die CGI::Session->errstr; - - if ( defined( $params->{'logout'} ) ) { - print STDERR 'ldap_NS.pl: ' . 'You have been logged out' . "\n"; - $error = 'You have been logged out' unless ( $session->is_empty ); - $session->delete(); - undef $session; - display_login(); - } - - if ( $session->is_expired ) { - print STDERR 'ldap_NS.pl: ' . 'Your session is no longer valid' . "\n"; - $session->delete(); - undef $session; - $error = 'Your session is no longer valid'; - display_login(); - } - - # session is empty in 2 cases: - # - cookies sent by ua are plain wrong - # - user is relogin after logout, thus is sending - # expired cookies - # - # BUG: - # Here is also, when logging with expired account, - # the session is not created, or not valid. - if ( $session->is_empty ) { - print STDERR 'ldap_NS.pl: ' . 'Invalid empty session' . "\n"; - print STDERR 'ldap_NS.pl: ' . Dumper( $session ); - $error = 'Invalid empty session'; - $session->delete(); - undef $session; - display_login(); - } - - # from here we should have a valid session object - $userMustChange = $session->param( 'userMustChange' ); - - if ( defined( $session->param( 'userInfos' ) ) ) { - $session->expires( 'userInfos', '+15m' ); - } elsif ( $userMustChange ) { - display_passwd(); - } else { - if ( defined( $session->param( 'isAdmin' ) ) ) { - $session->param( 'error', 'Your session has expired' ); - print STDERR 'ldap_NS.pl: Invalid expired session: ' . Dumper( $session ); - $error = 'Invalid expired session'; - $session->delete(); - undef $session; - } - display_login(); - } - - dispatch(); - -}; -if ( $@ ) { - print STDERR 'ldap_NS.pl: ' . $@ . "\n"; -} - -exit 0; - -END { - - if ( defined( $session ) ) { - $session->flush(); - } - CGI::Session->find( - 'driver:chi', - sub { - my ( $session ) = @_; - my $id = $session->id(); - if ( $session->is_expired ) { - print STDERR "cleaning expired session `$id'\n" if ( defined( $id ) ); - $session->delete(); - } - }, - { 'driver' => 'Redis', 'namespace' => 'ldapcgi', 'server' => $redis_hostport, } - ); - -} - diff --git a/bin/leankit_mindmap.py b/bin/leankit_mindmap.py deleted file mode 100755 index a95d407..0000000 --- a/bin/leankit_mindmap.py +++ /dev/null @@ -1,163 +0,0 @@ - -#!/opt/gvenv/venv_leankit/bin/python3 -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import logging -import argparse -import inspect -import traceback -import shlex -import re -from subprocess import check_output, STDOUT, CalledProcessError -from json import dumps as json_dumps - -hostname = os.uname()[1] -whoami = sys._getframe().f_code.co_name -script = os.path.basename(__file__).split(".")[0] - -for pylib in list(sys.path): - if '/usr/local/lib' in pylib: - sys.path.remove(pylib) - continue - elif '/export/home/snet/.local' in pylib: - sys.path.remove(pylib) - continue - -''' BASE CONFIG ''' -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -import snet.sloggly - -sys.path.append('/opt/auth/') -import library.leankit as leankit - -try: - logger = snet.sloggly.setup_custom_logger(script, logging.INFO) -except Exception as e: - print("\n=======\n") - title = "Something went wrong. Please inform SS team." - msg = "Error initializing the snet logger: " + str(e) + " :: " + traceback.format_exc(5) - print(msg) - whoami = sys._getframe().f_code.co_name - messages = [hostname, script, title, whoami, msg] - traceback.print_exc() - sys.exit(1) - - -def obj_dump(obj): - ''' - Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - print("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - except: # noqa: E722 - print("obj.%s = %s" % (attr, getattr(obj, attr))) - - for name, data in inspect.getmembers(obj): - if inspect.isclass(data): - print('name:%s' % (name)) - print(data) - - -def obj_dump_r(obj, level=0, deepth=2): - ''' - Recursive Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - msg = 2 * level * ' ' - msg += ("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - print(msg) - except: # noqa: E722 - msg = 2 * level * ' ' - msg += ("obj.%s = %s" % (attr, getattr(obj, attr))) - print(msg) - - if level >= deepth: - continue - - try: - obj_dump_r(getattr(obj, attr), level=level + 1) - except: # noqa: E722 - msg = 2 * level * ' ' - msg = 2 * level * ' ' - msg += "Dump is stinking... crashed." - print(msg) - - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -parser = argparse.ArgumentParser() -parser.add_argument('--leankit-board', type=str, required=False, - help='The leankit board name for the card creation', dest='leankit_board') -parser.add_argument('--leankit-board-id', type=int, required=False, - help='The leankit board id for the card creation', dest='leankit_board_id') -args = parser.parse_args() - -# leankit validation: -if args.leankit_board is None and args.leankit_board_id is None: - logger.error("leankit_board or leankit_board_id is not provided.") - logger.error("This is incompatible.") - print(parser.format_help()) - sys.exit(1) - -leankit_board_id = None - -if args.leankit_board_id is not None: - leankit_board_id = args.leankit_board_id - -elif args.leankit_board is not None: - leankit_res = leankit.get_board(args.leankit_board) - # print(leankit_res) - ''' - {'pageMeta': {'totalRecords': 2, 'offset': 0, 'limit': 100, 'startRow': 1, 'endRow': 2}, 'boards': [{'id': '31512088856393', 'title': 'DEV', 'description': '', 'boardRoleId': 4, 'isWelcome': False, 'boardRole': 'boardAdministrator', 'level': {'id': '31512085971730', 'depth': 3, 'maxDepth': 3, 'label': 'Team', 'color': '#ff841f'}}, {'id': '31512088544453', 'title': 'DEV-NMS3-phasein', 'description': '', 'boardRoleId': 4, 'isWelcome': False, 'boardRole': 'boardAdministrator'}]} - ''' - if leankit_res is None: - logger.error("Leankit board '%s': id is not found. Check the board name parameter." % args.leankit_board) - sys.exit(1) - - leankit_board_id = leankit_res['id'] - -# check lane -leankit_res = leankit.get_board_detail(leankit_board_id) -# print(json_dumps(leankit_res, sort_keys=True, indent=4)) - -leankit_lanes = dict() -for ll in leankit_res['lanes']: - leankit_lanes[ll['id']] = ll['name'] - -# Get Users -leankit_users = dict() -for ll in leankit_res['users']: - leankit_users[ll['id']] = ll['fullName'] - -# Get board contents -leankit_cards = dict() -# leankit_res = leankit.get_board_detail(leankit_board_id) -# limit 500 is max. -leankit_res = leankit.get_cards(board_id=leankit_board_id, limit=500, offset=0) -print(json_dumps(leankit_res, sort_keys=True, indent=4)) -# print(leankit_res) diff --git a/bin/leankit_user.py b/bin/leankit_user.py deleted file mode 100755 index 3ec49e8..0000000 --- a/bin/leankit_user.py +++ /dev/null @@ -1,474 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -from ldap3 import Server, Connection -import sys -import os -import configparser as ConfigParser -import logging -# import argparse -from pprint import pformat -import traceback -import string -import random - - -hostname = os.uname()[1] -whoami = sys._getframe().f_code.co_name -script = os.path.basename(__file__) - -for pylib in list(sys.path): - if '/usr/local/lib' in pylib: - sys.path.remove(pylib) - continue - elif '/export/home/snet/.local' in pylib: - sys.path.remove(pylib) - continue - -''' BASE CONFIG ''' -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) -sys.path.append('/opt/gvenv/venv_changemanagement/lib/python3.7/site-packages') -import snet.sloggly - -sys.path.append('/opt/auth/') -import library.leankit as leankit - -try: - logger = snet.sloggly.setup_custom_logger(script, logging.INFO) -except Exception as e: - print("\n=======\n") - title = "Something went wrong. Please inform SS team." - msg = "Error initializing the snet logger: " + str(e) + " :: " + traceback.format_exc(5) - print(msg) - whoami = sys._getframe().f_code.co_name - messages = [hostname, script, title, whoami, msg] - traceback.print_exc() - sys.exit(1) - - -def gen_password_leankit(length): - - # define data - lower = string.ascii_lowercase - upper = string.ascii_uppercase - num = string.digits - # symbols = string.punctuation - # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ - # symbols = '(){}_-!*@,:=$?' - symbols = '_-!@*?' - - # combine the data - all = lower + upper + num + symbols - the_dummy = lower + upper - - # use random - temp = random.sample(the_dummy, 1) + random.sample(all, length - 2) + random.sample(the_dummy, 1) - - # create the password - password = "".join(temp) - - # print the password - # print(password) - - return password - - -def snet_ldap_get(): - - ldap_config_file = config_global.get('INI', 'LDAP') - ldap_config = ConfigParser.RawConfigParser() - ldap_config.optionxform(str()) - ldap_config.optionxform = str - ldap_config.read(ldap_config_file) - - server_name = ldap_config.get('LDAP_SNET_NG', 'SERVER') - server_port = int(ldap_config.get('LDAP_SNET_NG', 'SSL_PORT')) - user = ldap_config.get('LDAP_SNET_NG', 'USER') - password = ldap_config.get('LDAP_SNET_NG', 'PASSWORD') - basedn = ldap_config.get('LDAP_SNET_NG', 'BASE') - bfilter = ldap_config.get('LDAP_SNET_NG', 'FILTER') - - groups = ldap_config.get('LDAP_SNET_NG', 'LEANKIT_GROUP').split(',') - attributes = ['uid', 'cn', 'member'] - uattributes = ['uid', 'gecos', 'givenName', 'mail', 'st', 'description'] - - ldap_server = Server(server_name, port=server_port, use_ssl=True) - ldap_con = Connection(ldap_server, user, password, auto_bind=True) - - results = dict() - results['groups'] = dict() - users = list() - gcn = list() - for group in groups: - - filter = bfilter.replace('REPLACE', group) - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=attributes) - - results['groups'][group] = dict() - results['groups'][group]['users'] = list() - - for entry in ldap_con.response: - if attributes[2] in entry['attributes']: - gcn.append(entry['dn']) - for g in entry['attributes'][attributes[2]]: - u = g.split(',')[0].replace('uid=', '') - results['groups'][group]['users'].append(u) - if u not in users: - users.append(u) - - results['users'] = dict() - bfilter = '(&(objectClass=posixAccount)(|' - for g in gcn: - bfilter += '(memberOf=' + g + ')' - bfilter += '))' - filter = bfilter - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=uattributes) - - for entry in ldap_con.response: - if uattributes[0] in entry['attributes']: - if isinstance(entry['attributes'][uattributes[0]], list): - uid = entry['attributes'][uattributes[0]][0] - else: - uid = entry['attributes'][uattributes[0]] - - results['users'][uid] = dict() - for g in uattributes: - if g not in entry['attributes']: - continue - if isinstance(entry['attributes'][g], list): - results['users'][uid][g] = entry['attributes'][g][0] - else: - results['users'][uid][g] = entry['attributes'][g] - if 'lastname' not in results['users'][uid]: - results['users'][uid]['lastname'] = results['users'][uid]['gecos'].replace(' ' + results['users'][uid]['givenName'], '') - results['users'][uid]['membership'] = list() - - ldap_con.unbind() - - for group in results['groups']: - for user in results['groups'][group]['users']: - results['users'][user]['membership'].append(group) - - return results - - -def ec_ldap_get_user(users=[]): - - ldap_config_file = config_global.get('INI', 'LDAP') - ldap_config = ConfigParser.RawConfigParser() - ldap_config.optionxform(str()) - ldap_config.optionxform = str - ldap_config.read(ldap_config_file) - - server_name = ldap_config.get('LDAP_EC', 'SERVER_NAME') - server_port = int(ldap_config.get('LDAP_EC', 'SERVER_PORT')) - user = ldap_config.get('LDAP_EC', 'USER') - password = ldap_config.get('LDAP_EC', 'PASSWORD') - basedn = ldap_config.get('LDAP_EC', 'BASE') - uattributes = ['uid', 'building', 'c', 'departmentNumber', 'dg', 'ecInternationalTelephoneNumber', 'employeeType', 'euEmployeeStatusDetail', 'euEmployeeSubtype', 'floor', 'givenName', 'l', 'mail', 'physicalDeliveryOfficeName', 'roomNumber', 'telephoneNumber', 'title', 'sn', 'cn'] - - ldap_server = Server(server_name, port=server_port, use_ssl=False) - ldap_con = Connection(ldap_server, user, password, auto_bind=True) - - results = dict() - results['users'] = dict() - for user in users: - - filter = "(&(objectclass=cudperson)(uid=%s))" % (user) - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=uattributes) - - for entry in ldap_con.response: - if uattributes[0] in entry['attributes']: - if isinstance(entry['attributes'][uattributes[0]], list): - uid = entry['attributes'][uattributes[0]][0] - else: - uid = entry['attributes'][uattributes[0]] - - results['users'][uid] = dict() - for g in uattributes: - if g not in entry['attributes']: - continue - if isinstance(entry['attributes'][g], list): - if len(entry['attributes'][g]) == 0: - continue - results['users'][uid][g] = entry['attributes'][g][0] - else: - results['users'][uid][g] = entry['attributes'][g] - - ldap_con.unbind() - return results - - -def ec_ldap_get(): - - ldap_config_file = config_global.get('INI', 'LDAP') - ldap_config = ConfigParser.RawConfigParser() - ldap_config.optionxform(str()) - ldap_config.optionxform = str - ldap_config.read(ldap_config_file) - - server_name = ldap_config.get('LDAP_EC', 'SERVER_NAME') - server_port = int(ldap_config.get('LDAP_EC', 'SERVER_PORT')) - user = ldap_config.get('LDAP_EC', 'USER') - password = ldap_config.get('LDAP_EC', 'PASSWORD') - basedn = ldap_config.get('LDAP_EC', 'BASE') - - groups = ldap_config.get('LDAP_EC', 'LEANKIT_GROUP').split(',') - attributes = ['uid', 'cn'] - - ldap_server = Server(server_name, port=server_port, use_ssl=False) - ldap_con = Connection(ldap_server, user, password, auto_bind=True) - - results = dict() - results['groups'] = dict() - for group in groups: - - filter = "(&(objectclass=*)(cudgroup=%s))" % (group) - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=attributes) - - results['groups'][group] = dict() - results['groups'][group]['description'] = "nothing" - results['groups'][group]['mapped-ldap-users'] = list() - results['groups'][group]['mapped-ldap-groups'] = list() - - for entry in ldap_con.response: - if attributes[0] in entry['attributes']: - for g in entry['attributes'][attributes[0]]: - results['groups'][group]['mapped-ldap-users'].append(g) - - ldap_con.unbind() - return results - - -def main(): - - dryrun = True - - # note com is no inside for now - snet_groups = 'officials,mgt,net,pm,sd,sec,sup,com,tda'.split(',') - - devnull_user = ['geirnal', 'lehonan', 'perreja', 'rotchri'] - donotdelete = ['wim.oyen@global.ntt', 'david.deveen@global.ntt'] - - extra_leankit_results = list() - ''' - extra_leankit_results.append({ - 'emailAddress': 'dbox1495@gmail.com', - 'firstName': 'Daniel', - 'lastName': 'BOX' - }) - extra_leankit_results.append( - { - 'emailAddress': 'koen.hauwaert@global.ntt', - 'firstName': 'Koen', - 'lastName': 'Hauwaert' - }) - ''' - - extra_leankit_results_idx = list() - for uu in extra_leankit_results: - extra_leankit_results_idx.append(uu['emailAddress']) - - snet_results = dict() - snet_results = snet_ldap_get() - print(pformat(snet_results)) - - ec_results = dict() - ec_results = ec_ldap_get_user(list(snet_results['users'].keys())) - print(pformat(ec_results)) - ''' - 'yildmes': {'building': 'B-28', - 'c': 'BE', - 'departmentNumber': 'DIGIT.C.4.006', - 'dg': 'DIGIT', - 'ecInternationalTelephoneNumber': '+32 229-68623', - 'employeeType': 'E', - 'euEmployeeStatusDetail': 'A', - 'euEmployeeSubtype': 'PPW', - 'floor': '01', - 'givenName': 'Mesut', - 'sn': 'YILDIRIM', - 'cn': 'YILDIRIM Mesut', - 'l': 'BRU', - 'mail': 'Mesut.YILDIRIM@ext.ec.europa.eu', - 'physicalDeliveryOfficeName': 'B-28 01/P051', - 'roomNumber': 'P051', - 'telephoneNumber': '68623', - 'title': 'Mr', - 'uid': 'yildmes'}, - ''' - - snet_mail_index = dict() - bad_user = list() - for user in snet_results['users']: - # print(user) - if user not in ec_results['users']: - bad_user.append(user) - continue - if 'dg' not in ec_results['users'][user]: - logger.error("%s do not have a dg" % (user)) - bad_user.append(user) - continue - if ec_results['users'][user]['dg'] != 'DIGIT': - bad_user.append(user) - continue - if ec_results['users'][user]['departmentNumber'] not in ['DIGIT.C.4', 'DIGIT.C.4.002', 'DIGIT.C.4.003', 'DIGIT.C.4.006', 'DIGIT.C.4.008']: - # this is not declared as snet - print('skipping ' + user + ' dpt: ' + ec_results['users'][user]['departmentNumber']) - continue - - real_member = False - for gr in snet_results['users'][user]['membership']: - if gr in snet_groups: - real_member = True - break - - if real_member is False: - # this is not declared as snet - continue - - if 'mail' not in ec_results['users'][user]: - print('Houston no mail, no mail...') - print(pformat(ec_results['users'][user])) - bad_user.append(user) - continue - - snet_mail_index[ec_results['users'][user]['mail']] = user - - print('Bad User: ' + pformat(bad_user)) - print('Snet User: ' + pformat(snet_mail_index)) - - leankit_global = list() - leankit_results = leankit.get_users() - # print(pformat(leankit_results)) - ''' - { - 'accountOwner': False, - 'administrator': False, - 'boardCreator': False, - 'dateFormat': 'dd/MM/yyyy', - 'deleted': False, - 'emailAddress': 'Mesut.YILDIRIM@ext.ec.europa.eu', - 'enabled': True, - 'externalUserName': None, - 'firstName': 'Mesut', - 'fullName': 'Mesut YILDIRIM', - 'lastAccess': None, - 'lastName': 'YILDIRIM', - 'timeZone': 'Europe/Paris', - 'username': 'Mesut.YILDIRIM@ext.ec.europa.eu' - } - ''' - try: - leankit_inv_results = leankit.get_invitations() - except Exception as e: - leankit_inv_results = None - logger.error(e) - # print(pformat(leankit_inv_results)) - ''' - { - 'acceptDate': None, - 'creationDate': '2021-10-18T12:32:19.000Z', - 'emailAddress': 'mihai.stoian@ec.europa.eu', - 'emailDateSent': '2021-10-18T12:32:19.000Z', - 'emailSendStatus': 'success', - 'id': '31512089806391', - 'invitedUser': None, - 'invitingUser': {'emailAddress': 'Romain.WISNIEWSKI@ext.ec.europa.eu', - 'enabled': True, - 'firstName': 'Romain', - 'fullName': 'Romain WISNIEWSKI', - 'id': '31512085836484', - 'isDeleted': False, - 'lastName': 'WISNIEWSKI'}, - 'isExpired': False, - 'isRevoked': False - }, - ''' - - snet_mail_index_lc = {k.lower(): v for k, v in snet_mail_index.items()} - print(snet_mail_index_lc) - - leankit_account = list() - for duser in leankit_results['users']: - # print(duser) - if 'enabled' in duser and duser['enabled'] is False: - continue - - if duser['emailAddress'] not in snet_mail_index and duser['emailAddress'].lower() not in snet_mail_index_lc and duser['emailAddress'] not in donotdelete and duser['emailAddress'].lower() not in donotdelete and duser['emailAddress'].lower() not in extra_leankit_results_idx: - print('Leankit user ' + duser['emailAddress'] + ' should be deleted. Doing nothing for now.') - continue - leankit_account.append(duser['emailAddress']) - - if leankit_inv_results is not None: - for duser in leankit_inv_results['invitations']: - # print(duser) - if 'isExpired' in duser and duser['isExpired'] is True: - continue - if 'isRevoked' in duser and duser['isRevoked'] is True: - continue - - if duser['emailAddress'] not in snet_mail_index and duser['emailAddress'].lower() not in snet_mail_index_lc and duser['emailAddress'] not in donotdelete and duser['emailAddress'].lower() not in donotdelete and duser['emailAddress'].lower() not in extra_leankit_results_idx: - print('Leankit user ' + duser['emailAddress'] + ' should be deleted.') - continue - leankit_account.append(duser['emailAddress']) - - for usermail in snet_mail_index: - usermail_lc = usermail.lower() - if usermail not in leankit_account and usermail_lc not in leankit_account: - print('Leankit user ' + snet_mail_index[usermail] + ' : ' + usermail + ' should be added.') - if snet_mail_index[usermail] in devnull_user: - continue - leankit_user = dict() - leankit_user['emailAddress'] = usermail - leankit_user['firstName'] = ec_results['users'][snet_mail_index[usermail]]['givenName'] - leankit_user['lastName'] = ec_results['users'][snet_mail_index[usermail]]['sn'] - leankit_user['timeZone'] = 'Europe/Paris' - leankit_user['password'] = gen_password_leankit(10) - leankit_user['dateFormat'] = 'dd/MM/yyyy' - - print(leankit_user) - if not dryrun: - leankit_new_result = leankit.create_user(leankit_user) - print(pformat(leankit_new_result)) - else: - print('dryrun mode: should be creating the user ' + leankit_user['emailAddress']) - - for user in extra_leankit_results: - usermail = user['emailAddress'] - usermail_lc = usermail.lower() - if usermail not in leankit_account and usermail_lc not in leankit_account: - print('Leankit user ' + usermail + ' should be added.') - leankit_user = dict() - leankit_user['emailAddress'] = usermail - leankit_user['firstName'] = user['firstName'] - leankit_user['lastName'] = user['lastName'] - leankit_user['timeZone'] = 'Europe/Paris' - leankit_user['password'] = gen_password_leankit(10) - leankit_user['dateFormat'] = 'dd/MM/yyyy' - - print(leankit_user) - if not dryrun: - leankit_new_result = leankit.create_user(leankit_user) - print(pformat(leankit_new_result)) - else: - print('dryrun mode: should be creating the user ' + usermail) - - -if __name__ == '__main__': - main() diff --git a/bin/redmine_create_issue b/bin/redmine_create_issue deleted file mode 100755 index 6f39fda..0000000 --- a/bin/redmine_create_issue +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import argparse -import pprint -# import inspect -# import traceback -import shlex -import re -# import requests -from subprocess import check_output, STDOUT, CalledProcessError - -pp = pprint.PrettyPrinter(indent=4) - -PROGNAME = os.path.basename(sys.argv[0]).split(".")[0] -script = os.path.basename(__file__).split(".")[0] - -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -basedir = '/opt/SNet/scm' - -Tracker_List = ['Bug', 'Feature', 'Service Improvement'] - - -parser = argparse.ArgumentParser() -parser.add_argument('-p', '--project', type=str, default='local', - help='The project to restrict: ALL for all', - dest='project') -parser.add_argument('-t', '--title', '--title', type=str, required=True, - help='The issue title and description', - dest='title') -parser.add_argument('-o', '--owner', type=str, required=True, - help='The owner of the new issue', - dest='owner') -parser.add_argument('--type', type=str, required=True, choices=Tracker_List, - help='The type of issue', dest='tracker') -args = parser.parse_args() - -# project_filter = 'ALL' -project_filter = args.project - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') -REDMINE_WS_KEY = redmine_config_global.get('GLOBAL', 'WS_KEY') -REDMINE_VERSION = redmine_config_global.get('GLOBAL', 'VERSION') -redmine = None - -if project_filter == 'local': - # cmd = ("pwd") - # cmd = ("hg config paths.default || git config --get remote.origin.url") - cmds = [] - # cmds.append('git rev-parse --show-toplevel 2>/dev/null || hg root 2>/dev/null || echo "$PWD"') - # cmds.append('git rev-parse --show-toplevel || hg root || echo "$PWD"') - # cmds.append("hg config paths.default || git config --get remote.origin.url") - cmds.append("hg config paths.default") - cmds.append("git config --get remote.origin.url") - - vcs = '' - for cmd in cmds: - # print("hg-git cmd: %s" % (cmd)) - # print("hg-git cmd: %s" % (shlex.split(cmd))) - - try: - output = check_output((shlex.split(cmd)), - stderr=None, - shell=True) - except CalledProcessError as ex: - output = ex.output - - # print("hg-git output: '%s'" % (output)) - # print('-----------------') - # continue - - if output == '': - continue - if ':/' in output and '.git' in output: - vcs = 'git' - break - elif '//' in output: - vcs = 'hg' - break - # sys.exit(1) - - if vcs == '': - print("bad repo: %s, abort." % (output)) - sys.exit(1) - if vcs == 'hg': - match = re.search(r'^.*/(/.*)$', output) - elif vcs == 'git': - match = re.search(r'^.*:(/.*)$', output) - if match: - repo = match.group(1) - else: - print("bad repo: %s, abort." % (output)) - sys.exit(1) - - print("repo: %s" % (repo)) - - redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), - key=REDMINE_KEY, requests={'verify': CA_bundle}, - version=REDMINE_VERSION) - - red_projects = redmine.project.all(offset=0, limit=1000, include='repositories') - for u in red_projects: - # print(u) - # print('%s' % (u.id)) - # print('%s' % (u.name)) - # print('%s' % (u.identifier)) - if len(u.repositories) == 0: - continue - - elif str(repo) == u.repositories[0]['url']: - print("found project %s" % (u.name)) - project_filter = u.name - break - -if redmine is None: - redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), - key=REDMINE_KEY, requests={'verify': CA_bundle}, - version=REDMINE_VERSION) - -status_id = None -statuses = redmine.issue_status.all() -for st in statuses: - # print(st.id, st) - if str(st) == 'Assigned': - # print(st.id, st) - status_id = st.id - break - -if status_id is None: - print("status not found.") - sys.exit(1) - -tracker_id = None -trackers = redmine.tracker.all() -for tr in trackers: - # print(tr.id, tr) - if str(tr) == args.tracker: - # print(tr.id, tr) - tracker_id = tr.id - break - -if tracker_id is None: - print("tracker not found.") - sys.exit(1) - -#priority_id = None -#priorities = redmine.priority.all() -#for pr in priorities: -# print(pr.id, pr) -# continue -# if str(pr) == args.priority: -# # print(tr.id, tr) -# priority_id = tr.id -# break - -#if priority_id is None: -# print("priority not found.") -# sys.exit(1) - -# user = redmine.user.get(args.owner) -user_id = None -users = redmine.user.filter(name=args.owner) -for usr in users: - # print(usr.id, usr, usr.login) - if str(usr.login) == args.owner: - # print(usr.id, usr) - user_id = usr.id - break - -if user_id is None: - print("user not found.") - sys.exit(1) - -# issues = redmine.issue.filter(status_id='open', sort='project:asc,id:asc') -# >>> project = redmine.project.get('vacation') -# >>> project.issues -issue = redmine.issue.new() -issue.project_id = project_filter -issue.subject = args.title -issue.description = args.title -issue.tracker_id = tracker_id -issue.status_id = status_id -# issue.priority_id = 7 -issue.assigned_to_id = user_id -issue.save() - -print('#%s' % (str(issue.id))) -print('%s fixes #%s' % (str(args.title), str(issue.id))) -sys.exit(0) diff --git a/bin/redmine_create_repo.py b/bin/redmine_create_repo.py deleted file mode 100755 index 28570c1..0000000 --- a/bin/redmine_create_repo.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import pprint -import inspect -import traceback -import shlex -import re -import requests -import time -from subprocess import check_output, STDOUT, CalledProcessError - -pp = pprint.PrettyPrinter(indent=4) - -PROGNAME = os.path.basename(sys.argv[0]).split(".")[0] -script = os.path.basename(__file__).split(".")[0] - -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -# find /opt/SNet/scm -path '*/.hg' -prune -o -type d -path '*/.hg' | grep -v '^.hg$' | sed 's/\/\.hg$//' | xargs -n1 -P1 -I% echo % && sudo -u www-data RAILS_ENV=production bundle exec rails runner "Repository.find_by_url('%').fetch_changesets" - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') -REDMINE_WS_KEY = redmine_config_global.get('GLOBAL', 'WS_KEY') - -redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), key=REDMINE_KEY, requests={'verify': CA_bundle}, version='3.4.4') - -project_name = "bind9-bindhg-snet" -repo_url = "/opt/SNet/scm/pkg/bind9-snet/bind9-bindhg-snet" - -# -u = redmine.project.get(project_name, include='enabled_modules,repositories') - -print('%s:%s:%s' % (u.id, u.identifier, u.name)) - -if 'repository' not in u.enabled_modules: - print("Repository is not activated for repo %s:%s (%s)" % (u.id, u.identifier, u.name)) - sys.exit(1) -# continue - -elif len(u.repositories) > 0: - print("Repository is not defined for repo %s:%s (%s)" % (u.id, u.identifier, u.name)) - sys.exit(1) -# continue - -redmine_url = "%s://%s/sys/projects/%s/repository?key=%s" % (REDMINE_PROTO, REDMINE_HOSTNAME, u.id, REDMINE_WS_KEY) -# print('curl -s "%s"' % (redmine_url)) -# curl -v -H "Content-Type: application/json" -X POST -d '{"id": "3581", "vendor": "Mercurial", "repository": {"url": "/opt/SNet/scm/pkg/bind9-snet/bind9-bindhg-snet", "identifier":"bind9-bindhg-snet"}}' "https://redmine.snmc.cec.eu.int/sys/projects/3581/repository?key=tU0LvEthIX4cMzCI9YPI" - -print('curl -v -H "Content-Type: application/json" -X POST -d \'{"id": "%s", "vendor": "Mercurial", "repository": {"identifier": "%s", "url": "%s"}}\' "%s"' % (u.id, u.name, repo_url, redmine_url)) - -''' - time.sleep(120) - - try: - response = requests.get(redmine_url, - allow_redirects=True, - # headers=headers, - verify=CA_bundle) - except requests.exceptions.SSLError as e: - print('%s: %s' % (redmine_url, str(e))) - time.sleep(360) - continue - except Exception as e: - print('Generic: %s' % (str(e))) - time.sleep(360) - continue - - if response.status_code == 200: - print(response.content) - else: - print('ERROR') - print(response.status_code) - print(response.content) - time.sleep(360) -''' - -sys.exit(0) diff --git a/bin/redmine_create_sc_projects.py b/bin/redmine_create_sc_projects.py deleted file mode 100755 index e5395c4..0000000 --- a/bin/redmine_create_sc_projects.py +++ /dev/null @@ -1,760 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import pprint -import inspect -import traceback -import shlex -import re -import requests -from subprocess import check_output, STDOUT, CalledProcessError - -pp = pprint.PrettyPrinter(indent=4) - -PROGNAME = os.path.basename(sys.argv[0]).split(".")[0] -script = os.path.basename(__file__).split(".")[0] - -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -basedir = '/opt/SNet/scm' - -wanted_membership = {} -wanted_membership['com'] = 'Reporter' -wanted_membership['mgt'] = 'Reporter' -wanted_membership['officials'] = 'Reporter' -wanted_membership['net'] = 'Developer' -wanted_membership['pi'] = 'Developer' -wanted_membership['sd'] = 'Developer' -wanted_membership['sec'] = 'Developer' -wanted_membership['sup'] = 'Developer' -wanted_membership['tda'] = 'Developer' -wanted_membership['pm'] = 'Manager' - -cmd = ("ssh vcodebox-lu find %s -path '\*/.hg' -prune -o -type d -path '\*/.hg' | grep -v '^.hg$'" % (basedir)) - -try: - output = check_output((shlex.split(cmd)), stderr=STDOUT, shell=False) -except CalledProcessError as ex: - output = ex.output -# print(output) - -folder_projects = [] -for l in output.splitlines(): - if not l.startswith(basedir): - continue - if not l.endswith('/.hg'): - continue - if l == basedir + '/.hg': - continue - if 'archive_' in l: - continue - pat = l.replace('/.hg', '').replace(basedir + '/', '') - - # print("%s %s" % (l, pat)) - folder_projects.append(pat) - - -def obj_dump(obj): - ''' - Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - print("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - except: - print("obj.%s = %s" % (attr, getattr(obj, attr))) - - for name, data in inspect.getmembers(obj): - if inspect.isclass(data): - print('name:%s' % (name)) - print(data) - - -def obj_dump_r(obj, level=0, deepth=2): - ''' - Recursive Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - msg = 2*level*' ' - msg += ("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - print(msg) - except: - msg = 2*level*' ' - msg += ("obj.%s = %s" % (attr, getattr(obj, attr))) - print(msg) - - if level >= deepth: - continue - - try: - obj_dump_r(getattr(obj, attr), level=level+1) - except: - msg = 2*level*' ' - msg += "Dump is stinking... crashed." - print(msg) - - -def redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, pj_id, pj_ident, repository_url): - - ''' - curl -v -H "Content-Type: application/json" -X POST -d '{"id": "3581", "vendor": "Mercurial", "repository": {"url": "/opt/SNet/scm/pkg/bind9-snet/bind9-bindhg-snet", "identifier":"bind9-bindhg-snet"}}' "https://redmine.snmc.cec.eu.int/sys/projects/3581/repository?key=tU0LvEthIX4cMzCI9YPI" - ''' - - redmine_url = "%s://%s/sys/projects/%s/repository?key=%s" % (REDMINE_PROTO, REDMINE_HOSTNAME, pj_id, REDMINE_WS_KEY) - playload = {} - playload['id'] = pj_id - playload['vendor'] = 'Mercurial' - playload['repository'] = {} - playload['repository']['identifier'] = pj_ident - playload['repository']['url'] = repository_url - - try: - response = requests.post(redmine_url, - json=playload, - allow_redirects=True, - verify=CA_bundle) - - except requests.exceptions.SSLError as e: - self.logger.error('%s: %s' % (redmine_url, str(e))) - return None - except Exception as e: - self.logger.error('Generic: %s' % (str(e))) - return None - - if response.status_code == 201: - print('OK') - print(response.content) - return None - else: - print('ERROR') - print(response.status_code) - print(response.content) - return None - - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') -REDMINE_WS_KEY = redmine_config_global.get('GLOBAL', 'WS_KEY') - -redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), key=REDMINE_KEY, requests={'verify': CA_bundle}, version='3.4.4') - -all_red_parent = {} -all_red_pj = {} -all_red_cross_pj = {} -red_projects = redmine.project.all(offset=0, limit=1000, include='enabled_modules,repositories,trackers') - -for u in red_projects: - # print(u) - # print('%s' % (u.id)) - # print('%s' % (u.name)) - # print('%s' % (u.identifier)) - all_red_pj[u.identifier] = {} - all_red_pj[u.identifier]['id'] = u.id - all_red_pj[u.identifier]['name'] = u.name - all_red_pj[u.identifier]['identifier'] = u.identifier - all_red_pj[u.identifier]['enabled_modules'] = u.enabled_modules - all_red_pj[u.identifier]['repositories'] = u.repositories - if hasattr(u, 'is_public'): - all_red_pj[u.identifier]['is_public'] = u.is_public - else: - all_red_pj[u.identifier]['is_public'] = False - - if 'parent' in dir(u): - # print('parent:%s' % (u.parent)) - all_red_pj[u.identifier]['parent'] = {} - all_red_pj[u.identifier]['parent']['name'] = u.parent.name - all_red_pj[u.identifier]['parent']['id'] = u.parent.id - # all_red_pj[u.identifier]['parent']['identifier'] = u.parent.identifier - all_red_parent[u.parent.name+'/'+u.name] = u.identifier - - if u.identifier == 'refconfig': - pp.pprint(all_red_pj[u.identifier]) - # obj_dump(u) - # obj_dump_r(u, level=0, deepth=1) - print(u.enabled_modules) - print(u.repositories) - print(u.is_public) - print(list(u)) - # sys.exit(0) - - if u.name != u.identifier: - all_red_cross_pj[u.name] = u.identifier - # pp.pprint(all_red_cross_pj[u.name]) - - continue - print('%s' % (u.id)) - print('%s' % (u.name)) - print('%s' % (u.identifier)) - if 'parent' in u: - print('%s' % (u.parent)) - -pp.pprint(all_red_parent) - -red_groups = redmine.group.all() -all_red_grp = {} -for g in red_groups: - all_red_grp[g.name] = {} - all_red_grp[g.name]['id'] = g.id - all_red_grp[g.id] = {} - all_red_grp[g.id]['name'] = g.name -# print(pp.pformat(all_red_grp)) - -red_roles = redmine.role.all() -all_red_rl = {} -for r in red_roles: - all_red_rl[r.name] = {} - all_red_rl[r.name]['id'] = r.id - all_red_rl[r.id] = {} - all_red_rl[r.id]['name'] = r.name -# print(pp.pformat(all_red_rl)) - -# sys.exit(1) - -limit = 3000 -cpt = 0 -for pj in sorted(folder_projects): - if cpt > limit: - break - cpt += 1 - - print("----%s" % (pj)) - if '/' in pj: - (parent, pjj) = pj.rsplit('/', 1) - if '/' in parent: - cnt = parent.count('/') - if cnt == 1: - if parent in all_red_parent: - parent = all_red_parent[parent] - else: - print("Parent '%s' with 1/ but not found (%s), creating pre-parent" % (parent, pj)) - - prepa, ppa = parent.split('/') - prepa_ident = prepa.lower().replace('.', '-') - ppa_ident = ppa.lower().replace('.', '-') - ''' Pre-parent check-up. ''' - if prepa_ident in all_red_pj: - print("Pre-Parent '%s' is found" % (prepa)) - prepa_id = all_red_pj[prepa_ident]['id'] - elif prepa in all_red_cross_pj: - print("Pre-Parent '%s' is found in the bad list" % (prepa)) - prepa_id = all_red_pj[all_red_cross_pj[prepa]]['id'] - else: - print("Pre-Parent '%s:%s' need to be created" % (prepa, prepa_ident)) - - try: - project = redmine.project.new() - project.name = prepa - project.identifier = prepa_ident - project.description = prepa - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = None - project.enabled_module_names = [] - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (parent, str(e))) - print(traceback.format_exc(5)) - sys.exit(1) - prepa_id = project.id - - all_red_pj[project.identifier] = {} - all_red_pj[project.identifier]['id'] = project.id - all_red_pj[project.identifier]['name'] = project.name - all_red_pj[project.identifier]['identifier'] = project.identifier - all_red_pj[project.identifier]['enabled_modules'] = project.enabled_modules - all_red_pj[project.identifier]['repositories'] = project.repositories - if hasattr(project, 'is_public'): - all_red_pj[project.identifier]['is_public'] = project.is_public - else: - all_red_pj[project.identifier]['is_public'] = False - - # Preparent membership - - print("membership prepa_id is %s." % (prepa_id)) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=prepa_id) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = prepa_id - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(prepa_id) - membership.delete(mb) - - ''' Parent check-up. ''' - if ppa_ident in all_red_pj: - print("Parent '%s' is found" % (ppa)) - ppa_id = all_red_pj[ppa_ident]['id'] - elif ppa in all_red_cross_pj: - print("Parent '%s' is found in the bad list" % (ppa)) - ppa_id = all_red_pj[all_red_cross_pj[ppa]]['id'] - else: - print("Parent '%s:%s' need to be created" % (ppa, ppa_ident)) - - try: - project = redmine.project.new() - project.name = ppa - project.identifier = ppa_ident - project.description = ppa - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = prepa_id - project.enabled_module_names = [] - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (ppa, str(e))) - print(traceback.format_exc(5)) - sys.exit(1) - ppa_id = project.id - - all_red_pj[project.identifier] = {} - all_red_pj[project.identifier]['id'] = project.id - all_red_pj[project.identifier]['name'] = project.name - all_red_pj[project.identifier]['identifier'] = project.identifier - all_red_pj[project.identifier]['enabled_modules'] = project.enabled_modules - if hasattr(project, 'is_public'): - all_red_pj[project.identifier]['is_public'] = project.is_public - else: - all_red_pj[project.identifier]['is_public'] = False - - all_red_pj[project.identifier]['parent'] = {} - all_red_pj[project.identifier]['parent']['name'] = project.parent.name - all_red_pj[project.identifier]['parent']['id'] = project.parent.id - all_red_parent[project.parent.name+'/'+project.name] = project.identifier - - else: - match = re.search(r'^.*/([^/]+/[^/]+)$', parent) - if match.group(1) in all_red_parent: - parent = all_red_parent[match.group(1)] - else: - print("Parent '%s' need to be decomposed for %s, skipping for now" % (parent, pj)) - continue - else: - parent = None - pjj = pj - - print("%s:%s" % (parent, pjj)) - if parent: - parent_ident = parent.lower().replace('.', '-') - pj_ident = pjj.lower().replace('.', '-') - - ''' - PARENT - ''' - - if parent and parent_ident in all_red_pj: - print("Parent '%s' is found" % (parent)) - parent_id = all_red_pj[parent_ident]['id'] - elif parent and parent in all_red_cross_pj: - print("Parent '%s' is found in the bad list" % (parent)) - parent_id = all_red_pj[all_red_cross_pj[parent]]['id'] - elif parent: - print("Parent '%s:%s' need to be created" % (parent, parent_ident)) - - try: - project = redmine.project.new() - project.name = parent - project.identifier = parent_ident - project.description = parent - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = None - project.enabled_module_names = [] - # project.enabled_modules = [] readonly attribute - # project.custom_fields = [{'id': 1, 'value': 'PE'}, {'id': 11, 'value': 'scm'}] - # list(project) - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (parent, str(e))) - print(traceback.format_exc(5)) - break - - all_red_pj[project.identifier] = {} - all_red_pj[project.identifier]['id'] = project.id - all_red_pj[project.identifier]['name'] = project.name - all_red_pj[project.identifier]['identifier'] = project.identifier - all_red_pj[project.identifier]['is_public'] = True - parent_id = project.id - - else: - parent_id = None - - if parent_id is not None: - - project = redmine.project.get(parent_id) - project.is_public = True - project.inherit_members = False - project.save() - - if 'enabled_modules' not in all_red_pj[parent_ident]: - print("No repository module activated for parent, OK") - - elif 'repository' not in all_red_pj[parent_ident]['enabled_modules']: - print("No repository for parent, OK") - - elif len(all_red_pj[parent_ident]['repositories']) == 0: - print("No repository for parent, OK") - - else: - print("repository activated for parent should not") - - print("membership parent_id is %s." % (parent_id)) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=parent_id) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = parent_id - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(parent_id) - membership.delete(mb) - - ''' - ITSELF - ''' - - if pjj in all_red_pj: - print("The project '%s' is found in all_red_pj." % (pjj)) - repository_url = os.path.join(basedir, pj) - print("hg:%s:%s" % (pj_ident, repository_url)) - pp.pprint(all_red_pj[pjj]) - - if parent and 'parent' in all_red_pj[pjj]: - if parent != all_red_pj[pjj]['parent']['name']: - print("Not the same parent %s:%s" % (parent, all_red_pj[pjj]['parent']['name'])) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.parent_id = parent_id - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.save() - - elif parent: - print("Not the same parent %s:None" % (parent)) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.parent_id = parent_id - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[pjj]['id'], pj_ident, repository_url) - - if 'repository' not in all_red_pj[pjj]['enabled_modules']: - print("Repository is not activated for repo %s:%s" % (pjj, pj_ident)) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[pjj]['id'], pj_ident, repository_url) - - elif len(all_red_pj[pjj]['repositories']) == 0: - print("Repository URL is empty for repo %s:%s (%s)" % (pjj, pj_ident, os.path.join(basedir, pj))) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[pjj]['id'], pj_ident, repository_url) - - elif os.path.join(basedir, pj) != all_red_pj[pjj]['repositories'][0]['url']: - print("Repository URL is bad for repo %s:%s (%s <> %s)" - % (pjj, pj_ident, os.path.join(basedir, pj), all_red_pj[pjj]['repositories'][0]['url'])) - - # if all_red_pj[pjj]['is_public']: - # reset verything to is_public false - project = redmine.project.get(all_red_pj[pjj]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - - print("membership all_red_pj id %s." % (all_red_pj[pjj]['id'])) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=all_red_pj[pjj]['id']) - # print('%s' % (pp.pprint(pj_wanted_membership))) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print(list(mb)) - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - if 'inherited' in mb: - if mb.inherited == True: - print("inherited = True") - else: - print("inherited = False") - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if mb.group.name in pj_wanted_membership and pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = all_red_pj[pjj]['id'] - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(all_red_pj[pjj]['id']) - membership.delete(mb) - - elif pjj in all_red_cross_pj: - print("The project '%s' is found in all_red_cross_pj." % (pjj)) - repository_url = os.path.join(basedir, pj) - print("hg:%s:%s" % (pj_ident, repository_url)) - pp.pprint(all_red_pj[all_red_cross_pj[pjj]]) - if parent and 'parent' in all_red_pj[all_red_cross_pj[pjj]]: - if parent != all_red_pj[all_red_cross_pj[pjj]]['parent']['name']: - print("Not the same parent %s:%s" % (parent, all_red_pj[all_red_cross_pj[pjj]]['parent']['name'])) - elif parent: - print("Not the same parent %s:None" % (parent)) - elif 'parent' in all_red_pj[all_red_cross_pj[pjj]]: - print("Not the same parent None:%s" % (all_red_pj[all_red_cross_pj[pjj]]['parent']['name'])) - - if 'repository' not in all_red_pj[all_red_cross_pj[pjj]]['enabled_modules']: - print("Repository is not activated for repo %s:%s" % (pjj, pj_ident)) - project = redmine.project.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[all_red_cross_pj[pjj]]['id'], pj_ident, repository_url) - - elif len(all_red_pj[all_red_cross_pj[pjj]]['repositories']) == 0: - print("Repository URL is empty for repo %s:%s (%s)" % (pjj, pj_ident, repository_url)) - project = redmine.project.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[all_red_cross_pj[pjj]]['id'], pj_ident, repository_url) - - elif os.path.join(basedir, pj) != all_red_pj[all_red_cross_pj[pjj]]['repositories'][0]['url']: - print("Repository URL is bad for repo %s:%s (%s <> %s)" - % (pjj, pj_ident, os.path.join(basedir, pj), all_red_pj[all_red_cross_pj[pjj]]['repositories'][0]['url'])) - - # if all_red_pj[pjj]['is_public']: - # reset verything to is_public false - project = redmine.project.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - - print("membership all_red_cross_pj id %s." % (all_red_pj[all_red_cross_pj[pjj]]['id'])) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=all_red_pj[all_red_cross_pj[pjj]]['id']) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = all_red_pj[all_red_cross_pj[pjj]]['id'] - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - membership.delete(mb) - - # break - - else: - print("The project '%s' need to be created." % (pj)) - print("hg:%s:%s" % (pj_ident, os.path.join(basedir, pj))) - - if parent and parent in all_red_pj: - print("Parent '%s' is found" % (parent)) - elif parent and parent in all_red_cross_pj: - print("Parent '%s' is found in the bad list" % (parent)) - - try: - print('id:%s' % (pj_ident)) - project = redmine.project.new() - project.name = pjj - project.identifier = pj_ident - project.description = pjj - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = parent_id - # project.enabled_modules = ['repository'] Readonly attribute - # project.custom_fields = [{'id': 1, 'value': 'PE'}, {'id': 11, 'value': 'scm'}] - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - # list(project) - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (pjj, str(e))) - print(traceback.format_exc(5)) - break - - # try: - # project = redmine.project.get(pjj) - # except ResourceNotFoundError as e: - # print('The ressources is not found') - -sys.exit(0) diff --git a/bin/redmine_fetch_changeset.py b/bin/redmine_fetch_changeset.py deleted file mode 100755 index b7883ea..0000000 --- a/bin/redmine_fetch_changeset.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import pprint -import inspect -import traceback -import shlex -import re -import requests -import time -from subprocess import check_output, STDOUT, CalledProcessError - -pp = pprint.PrettyPrinter(indent=4) - -PROGNAME = os.path.basename(sys.argv[0]).split(".")[0] -script = os.path.basename(__file__).split(".")[0] - -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -# find /opt/SNet/scm -path '*/.hg' -prune -o -type d -path '*/.hg' | grep -v '^.hg$' | sed 's/\/\.hg$//' | xargs -n1 -P1 -I% echo % && sudo -u www-data RAILS_ENV=production bundle exec rails runner "Repository.find_by_url('%').fetch_changesets" - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') -REDMINE_WS_KEY = redmine_config_global.get('GLOBAL', 'WS_KEY') - -redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), key=REDMINE_KEY, requests={'verify': CA_bundle}, version='3.4.4') - -red_projects = redmine.project.all(offset=0, limit=1000, include='enabled_modules,repositories,trackers') - -for u in red_projects: - print('%s:%s:%s' % (u.id, u.identifier, u.name)) - - if 'repository' not in u.enabled_modules: - print("Repository is not activated for repo %s:%s (%s)" % (u.id, u.identifier, u.name)) - continue - - elif len(u.repositories) == 0: - print("Repository is not defined for repo %s:%s (%s)" % (u.id, u.identifier, u.name)) - continue - - redmine_url = "%s://%s/sys/fetch_changesets?key=%s&id=%s" % (REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, u.id) - # print('curl -s "%s"' % (redmine_url)) - - time.sleep(120) - - try: - response = requests.get(redmine_url, - allow_redirects=True, - # headers=headers, - verify=CA_bundle) - except requests.exceptions.SSLError as e: - print('%s: %s' % (redmine_url, str(e))) - time.sleep(360) - continue - except Exception as e: - print('Generic: %s' % (str(e))) - time.sleep(360) - continue - - if response.status_code == 200: - print(response.content) - else: - print('ERROR') - print(response.status_code) - print(response.content) - time.sleep(360) - -sys.exit(0) diff --git a/bin/redmine_issue b/bin/redmine_issue deleted file mode 100755 index 088c67b..0000000 --- a/bin/redmine_issue +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import argparse -import pprint -import inspect -# import traceback -import shlex -import re -# import requests -from subprocess import check_output, STDOUT, CalledProcessError - -pp = pprint.PrettyPrinter(indent=4) - -PROGNAME = os.path.basename(sys.argv[0]).split(".")[0] -script = os.path.basename(__file__).split(".")[0] - -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -basedir = '/opt/SNet/scm' - -parser = argparse.ArgumentParser() -parser.add_argument('-p', '--project', type=str, default='local', - help='The project to restrict: ALL for all', - dest='project') -args = parser.parse_args() - -project_filter = 'ALL' -project_filter = args.project - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') -REDMINE_WS_KEY = redmine_config_global.get('GLOBAL', 'WS_KEY') -REDMINE_VERSION = redmine_config_global.get('GLOBAL', 'VERSION') -redmine = None - - -def obj_dump(obj): - ''' - Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - print("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - except: - print("obj.%s = %s" % (attr, getattr(obj, attr))) - - for name, data in inspect.getmembers(obj): - if inspect.isclass(data): - print('name:%s' % (name)) - print(data) - - -def obj_dump_r(obj, level=0, deepth=2): - ''' - Recursive Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - msg = 2*level*' ' - msg += ("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - print(msg) - except: - msg = 2*level*' ' - msg += ("obj.%s = %s" % (attr, getattr(obj, attr))) - print(msg) - - if level >= deepth: - continue - - if isinstance(getattr(obj, attr), (int, str, unicode)): - continue - - try: - obj_dump_r(getattr(obj, attr), level=level+1) - except: - msg = 2*level*' ' - msg += "Dump is stinking... crashed." - print(msg) - - -if project_filter == 'local': - # cmd = ("pwd") - # cmd = ("hg config paths.default || git config --get remote.origin.url") - cmds = [] - cmds.append("hg config paths.default") - cmds.append("git config --get remote.origin.url") - - vcs = '' - for cmd in cmds: - # print("hg-git cmd: %s" % (cmd)) - # print("hg-git cmd: %s" % (shlex.split(cmd))) - - try: - output = check_output((shlex.split(cmd)), - stderr=STDOUT, - shell=False) - except CalledProcessError as ex: - output = ex.output - - # print("hg-git output: '%s'" % (output)) - if output == '': - continue - if ':/' in output and '.git' in output: - vcs = 'git' - break - elif '//' in output: - vcs = 'hg' - break - - if vcs == '': - print("bad repo: %s, abort." % (output)) - sys.exit(1) - if vcs == 'hg': - match = re.search(r'^.*/(/.*)$', output) - elif vcs == 'git': - match = re.search(r'^.*:(/.*)$', output) - if match: - repo = match.group(1) - else: - print("bad repo: %s, abort." % (output)) - sys.exit(1) - - print("repo: %s" % (repo)) - - redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), - key=REDMINE_KEY, requests={'verify': CA_bundle}, - version='3.4.4') - - red_projects = redmine.project.all(offset=0, limit=1000, include='enabled_modules,repositories') - for u in red_projects: - if 'repository' not in u.enabled_modules: - continue - if 'issue_tracking' not in u.enabled_modules: - continue - - # if obj.trackers - # print(u) - pp.pprint(u) - # obj_dump(u) - # obj_dump_r(u, level=0, deepth=1) - print("'%s' '%s' '%s'" % (u.id, u.name, u.identifier)) - print(u.enabled_modules) - - try: - if len(u.repositories) == 0: - continue - except Exception as e: - print('no repository: %s' % (str(e))) - continue - - if str(repo) == u.repositories[0]['url']: - print("found project %s" % (u.name)) - project_filter = u.name - break - -if redmine is None: - redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), - key=REDMINE_KEY, requests={'verify': CA_bundle}, - version=REDMINE_VERSION) - -if project_filter == 'ALL': - issues = redmine.issue.filter(status_id='open', sort='project:asc,id:asc') -else: - issues = redmine.issue.filter(status_id='open', project_id=project_filter, sort='project:asc,id:asc') - -for i in issues: - msg = ('#%s' % (i.id)) - if project_filter == 'ALL': - msg += (' p:%s\n' % (i.project)) - msg += (' status_id:%s\n' % (i.status)) - msg += (' priority_id:%s\n' % (i.priority)) - msg += (' tracker_id:%s\n' % (i.tracker)) - else: - msg += (' subject:%s\n' % (i.subject)) - try: - msg += (' assigned:%s\n' % (i.assigned_to.name)) - except Exception as e: - pass - obj_dump(i) - print(dir(i)) - print(i.custom_fields) - obj_dump(i.custom_fields) - print(redmine.custom_field.all()) - print('cs:' + str(i.custom_fields.get(41))) - for cs in i.custom_fields: - print(cs) - # print('cs:' + str(i.custom_fields.['leankit'])) - print(msg) - - # print('project:%s' % (i.project)) - # print('category:%s' % (i.category)) - # i.url - # print('%s' % (u.identifier)) - -sys.exit(0) diff --git a/bin/redmine_leankit_create_issue b/bin/redmine_leankit_create_issue deleted file mode 100755 index 7b7771a..0000000 --- a/bin/redmine_leankit_create_issue +++ /dev/null @@ -1,570 +0,0 @@ -#!/opt/gvenv/venv_leankit/bin/python3 -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import logging -import argparse -import inspect -import traceback -import shlex -import re -from subprocess import check_output, STDOUT, CalledProcessError -from json import dumps as json_dumps - -hostname = os.uname()[1] -whoami = sys._getframe().f_code.co_name -script = os.path.basename(__file__).split(".")[0] - -for pylib in list(sys.path): - if '/usr/local/lib' in pylib: - sys.path.remove(pylib) - continue - elif '/export/home/snet/.local' in pylib: - sys.path.remove(pylib) - continue - -''' BASE CONFIG ''' -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine -import snet.sloggly - -sys.path.append('/opt/auth') -import library.leankit as leankit - -try: - logger = snet.sloggly.setup_custom_logger(script, logging.INFO) -except Exception as e: - print("\n=======\n") - title = "Something went wrong. Please inform SS team." - msg = "Error initializing the snet logger: " + str(e) + " :: " + traceback.format_exc(5) - print(msg) - whoami = sys._getframe().f_code.co_name - messages = [hostname, script, title, whoami, msg] - traceback.print_exc() - sys.exit(1) - - -def obj_dump(obj): - ''' - Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - print("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - except: # noqa: E722 - print("obj.%s = %s" % (attr, getattr(obj, attr))) - - for name, data in inspect.getmembers(obj): - if inspect.isclass(data): - print('name:%s' % (name)) - print(data) - - -def obj_dump_r(obj, level=0, deepth=2): - ''' - Recursive Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - msg = 2 * level * ' ' - msg += ("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - print(msg) - except: # noqa: E722 - msg = 2 * level * ' ' - msg += ("obj.%s = %s" % (attr, getattr(obj, attr))) - print(msg) - - if level >= deepth: - continue - - try: - obj_dump_r(getattr(obj, attr), level=level + 1) - except: # noqa: E722 - msg = 2 * level * ' ' - msg = 2 * level * ' ' - msg += "Dump is stinking... crashed." - print(msg) - - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -basedir = '/opt/SNet/scm' - -Tracker_List = ['Bug', 'Feature', 'Service Improvement'] -leankit_tracker_conversion = dict() -leankit_tracker_conversion['Bug'] = 'Task' -leankit_tracker_conversion['Feature'] = 'Task' -leankit_tracker_conversion['DEV'] = dict() -leankit_tracker_conversion['DEV']['Bug'] = 'Task' -leankit_tracker_conversion['DEV']['Feature'] = 'Task' -leankit_tracker_conversion['SEC'] = dict() -leankit_tracker_conversion['SEC']['Bug'] = 'Incident' -leankit_tracker_conversion['SEC']['Feature'] = 'Request' -leankit_tracker_conversion['SEC']['Service Improvement'] = 'Improvement' -leankit_tracker_conversion['NET'] = dict() -leankit_tracker_conversion['NET']['Bug'] = 'Incident' -leankit_tracker_conversion['NET']['Feature'] = 'Request' -leankit_tracker_conversion['NET']['Service Improvement'] = 'Improvement' - -leankit_lane_conversion = dict() -leankit_lane_conversion['DEV'] = "In Process" -leankit_lane_conversion['SEC'] = "INPUT" -leankit_lane_conversion['NET'] = "Input" - -parser = argparse.ArgumentParser() -parser.add_argument('-p', '--project', type=str, default='local', - help='The project to restrict: ALL for all', - dest='project') -parser.add_argument('-t', '--title', '--title', type=str, required=True, - help='The issue title and description', - dest='title') -parser.add_argument('-o', '--owner', type=str, required=True, - help='The owner of the new issue', - dest='owner') -parser.add_argument('--type', type=str, required=True, choices=Tracker_List, - help='The type of issue', dest='tracker') -parser.add_argument('--leankit-id', type=int, required=False, - help='The leankit card id', dest='leankit_id') -parser.add_argument('--leankit-url', type=str, required=False, - help='The leankit card url id', dest='leankit_url') -parser.add_argument('--leankit-create', action="store_true", default=False, - help='The leankit create a card', dest='leankit_create') -parser.add_argument('--leankit-board', type=str, required=False, - help='The leankit board name for the card creation', dest='leankit_board') -parser.add_argument('--leankit-board-id', type=int, required=False, - help='The leankit board id for the card creation', dest='leankit_board_id') -parser.add_argument('--leankit-story-point', type=int, required=False, default=1, - help='The leankit story point associated with the issue', dest='leankit_story_point') -parser.add_argument('--leankit-header', type=str, required=False, default='', - help='The leankit card header for the card creation', dest='leankit_header') -args = parser.parse_args() - -# leankit validation: -if (args.leankit_id is not None or args.leankit_url is not None) and (args.leankit_create is True or args.leankit_board is not None or args.leankit_board_id is not None): - logger.error("leankit_id is provided with one of th option leankit_create leankit_board leankit_board_id.") - logger.error("This is incompatible.") - print(parser.format_help()) - sys.exit(1) - -if args.leankit_id is None and args.leankit_url is None and args.leankit_create is False: - logger.error("leankit_id is not provided, but no card creation requested.") - logger.error("This is incompatible.") - print(parser.format_help()) - sys.exit(1) - -if args.leankit_id is None and args.leankit_url is None and args.leankit_create is True and args.leankit_board is None and args.leankit_board_id is None: - logger.error("leankit_id is not provided, the leankit_create requested, but the leankit_board or leankit_board_id is not provided.") - logger.error("This is incompatible.") - print(parser.format_help()) - sys.exit(1) - -if args.leankit_id is None and args.leankit_url is None and args.leankit_create is True and args.leankit_board is not None and args.leankit_board_id is not None: - logger.error("leankit_id is not provided, the leankit_create requested, but the leankit_board and leankit_board_id is provided.") - logger.error("This is incompatible.") - print(parser.format_help()) - sys.exit(1) - -leankit_board_id = None -leankit_card_id = None -leankit_card_type_id = None -leankit_user_id = None -leankit_board_lane_id = None - -if args.leankit_url is not None: - leankit_card_id = str(args.leankit_url).replace('https://globalntt.leankit.com/card/', '') - # https://globalntt.leankit.com/card/31512091272763 - -if args.leankit_id is not None: - leankit_card_id = str(args.leankit_id) - -if leankit_card_id is not None: - leankit_card_res = leankit.get_card(leankit_card_id) - print(leankit_card_res) - print(json_dumps(leankit_card_res, sort_keys=True, indent=4)) - if leankit_card_res['actualFinish'] is not None: - logger.error("Card is finished, so this is not possible") - sys.exit(1) - if leankit_card_res['lane']['laneClassType'] == "archive": - logger.error("Card is finished, so this is not possible") - sys.exit(1) - - # check assigned - ''' - - "assignedUsers": [ - { - "avatar": "https://globalntt.leankit.com/avatar/show/31512085826382/?s=25", - "emailAddress": "David.VERNAZOBRES@ext.ec.europa.eu", - "firstName": "David", - "fullName": "David VERNAZOBRES", - "id": "31512085826382", - "lastName": "VERNAZOBRES" - } - ], - - { - "cardIds": ["945202295", "945233018"], - "userIdsToAssign": ["478440842", "583458214"], - "wipOverrideComment": "This is needed if user WIP is violated on a board" - } - ''' - -if args.leankit_create is True and args.leankit_board_id is not None: - leankit_board_id = args.leankit_board_id - - leankit_res = leankit.get_board_detail(args.leankit_board_id) - # print(leankit_res) - ''' - {'pageMeta': {'totalRecords': 2, 'offset': 0, 'limit': 100, 'startRow': 1, 'endRow': 2}, 'boards': [{'id': '31512088856393', 'title': 'DEV', 'description': '', 'boardRoleId': 4, 'isWelcome': False, 'boardRole': 'boardAdministrator', 'level': {'id': '31512085971730', 'depth': 3, 'maxDepth': 3, 'label': 'Team', 'color': '#ff841f'}}, {'id': '31512088544453', 'title': 'DEV-NMS3-phasein', 'description': '', 'boardRoleId': 4, 'isWelcome': False, 'boardRole': 'boardAdministrator'}]} - ''' - if leankit_res is None: - logger.error("Leankit board '%s': id is not found. Check the board name parameter." % args.leankit_board) - sys.exit(1) - - leankit_board_id = leankit_res['id'] - leankit_board_name = leankit_res['title'] - -elif args.leankit_create is True and args.leankit_board is not None: - leankit_res = leankit.get_board(args.leankit_board) - # print(leankit_res) - ''' - {'pageMeta': {'totalRecords': 2, 'offset': 0, 'limit': 100, 'startRow': 1, 'endRow': 2}, 'boards': [{'id': '31512088856393', 'title': 'DEV', 'description': '', 'boardRoleId': 4, 'isWelcome': False, 'boardRole': 'boardAdministrator', 'level': {'id': '31512085971730', 'depth': 3, 'maxDepth': 3, 'label': 'Team', 'color': '#ff841f'}}, {'id': '31512088544453', 'title': 'DEV-NMS3-phasein', 'description': '', 'boardRoleId': 4, 'isWelcome': False, 'boardRole': 'boardAdministrator'}]} - ''' - if leankit_res is None: - logger.error("Leankit board '%s': id is not found. Check the board name parameter." % args.leankit_board) - sys.exit(1) - - leankit_board_id = leankit_res['id'] - leankit_board_name = leankit_res['title'] - -if args.leankit_create is True: - leankit_res = leankit.get_cardtype_from_board(leankit_board_id) - # print(leankit_res) - # print(json_dumps(leankit_res, sort_keys=True, indent=4)) - if args.tracker not in leankit_tracker_conversion or (leankit_board_name in leankit_tracker_conversion and args.tracker not in leankit_tracker_conversion[leankit_board_name]): - logger.error("%s is not a valid leankit type conversion." % (args.tracker)) - sys.exit(1) - for tt in leankit_res['cardTypes']: - if tt['name'] == leankit_tracker_conversion[args.tracker]: - leankit_card_type_id = tt['id'] - break - elif leankit_board_name in leankit_tracker_conversion and args.tracker in leankit_tracker_conversion[leankit_board_name] and tt['name'] == leankit_tracker_conversion[leankit_board_name][args.tracker]: - leankit_card_type_id = tt['id'] - break - - if leankit_card_type_id is None: - print(leankit_res) - print(json_dumps(leankit_res, sort_keys=True, indent=4)) - logger.error("%s is not found in the leankit card type id." % (args.tracker)) - sys.exit(1) - - # check lane - # leankit_board_lane_id - leankit_res = leankit.get_board_detail(leankit_board_id) - # print(json_dumps(leankit_res, sort_keys=True, indent=4)) - for ll in leankit_res['lanes']: - if ll['name'] == "In Process": - # print(ll) - leankit_board_lane_id = ll['id'] - break - elif leankit_board_name in leankit_lane_conversion and ll['name'] == leankit_lane_conversion[leankit_board_name]: - leankit_board_lane_id = ll['id'] - break - - if leankit_board_lane_id is None: - logger.error('Lane in process is not found') - sys.exit(1) - -# project_filter = 'ALL' -project_filter = args.project - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') -REDMINE_WS_KEY = redmine_config_global.get('GLOBAL', 'WS_KEY') -REDMINE_VERSION = redmine_config_global.get('GLOBAL', 'VERSION') -redmine = None - -if project_filter == 'local': - # cmd = ("pwd") - # cmd = ("hg config paths.default || git config --get remote.origin.url") - cmds = [] - # cmds.append('git rev-parse --show-toplevel 2>/dev/null || hg root 2>/dev/null || echo "$PWD"') - # cmds.append('git rev-parse --show-toplevel || hg root || echo "$PWD"') - # cmds.append("hg config paths.default || git config --get remote.origin.url") - cmds.append("hg config paths.default") - cmds.append("git config --get remote.origin.url") - - vcs = '' - for cmd in cmds: - # print("hg-git cmd: %s" % (cmd)) - # print("hg-git cmd: %s" % (shlex.split(cmd))) - - try: - output = check_output((shlex.split(cmd)), - stderr=None, - shell=True) - except CalledProcessError as ex: - output = ex.output - - # print("hg-git output: '%s'" % (output)) - # print('-----------------') - # continue - - if output == '': - continue - if ':/' in output and '.git' in output: - vcs = 'git' - break - elif '//' in output: - vcs = 'hg' - break - # sys.exit(1) - - if vcs == '': - print("bad repo: %s, abort." % (output)) - sys.exit(1) - if vcs == 'hg': - match = re.search(r'^.*/(/.*)$', output) - elif vcs == 'git': - match = re.search(r'^.*:(/.*)$', output) - if match: - repo = match.group(1) - else: - print("bad repo: %s, abort." % (output)) - sys.exit(1) - - print("repo: %s" % (repo)) - - redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), - key=REDMINE_KEY, requests={'verify': CA_bundle}, - version=REDMINE_VERSION) - - red_projects = redmine.project.all(offset=0, limit=1000, include='repositories') - for u in red_projects: - # print(u) - # print('%s' % (u.id)) - # print('%s' % (u.name)) - # print('%s' % (u.identifier)) - if len(u.repositories) == 0: - continue - - elif str(repo) == u.repositories[0]['url']: - print("found project %s" % (u.name)) - project_filter = u.name - break - -if redmine is None: - redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), - key=REDMINE_KEY, requests={'verify': CA_bundle}, - version=REDMINE_VERSION) - -status_id = None -statuses = redmine.issue_status.all() -for st in statuses: - # print(st.id, st) - if str(st) == 'Assigned': - # print(st.id, st) - status_id = st.id - break - -if status_id is None: - print("status not found.") - sys.exit(1) - -tracker_id = None -trackers = redmine.tracker.all() -for tr in trackers: - # print(tr.id, tr) - if str(tr) == args.tracker: - # print(tr.id, tr) - tracker_id = tr.id - break - -if tracker_id is None: - print("tracker not found.") - sys.exit(1) - -# priority_id = None -# priorities = redmine.priority.all() -# for pr in priorities: -# print(pr.id, pr) -# continue -# if str(pr) == args.priority: -# # print(tr.id, tr) -# priority_id = tr.id -# break - -# if priority_id is None: -# print("priority not found.") -# sys.exit(1) - -# user = redmine.user.get(args.owner) -user_id = None -user_email = None -users = redmine.user.filter(name=args.owner) -for usr in users: - # print(usr.id, usr, usr.login) - if str(usr.login) == args.owner: - # print(usr.id, usr) - user_id = usr.id - user_email = usr.mail - break - -if user_id is None: - logger.error("user not found.") - sys.exit(1) - -# print(user_email) - -leankit_res = leankit.get_user(user_email) -# print(leankit_res) -if leankit_res['pageMeta']['totalRecords'] != 1: - logger.error('user is not found uniquely in leankit') - sys.exit(1) - -leankit_user_id = leankit_res['users'][0]['id'] - -if leankit_card_id is not None: - # check assigned - ''' - - "assignedUsers": [ - { - "avatar": "https://globalntt.leankit.com/avatar/show/31512085826382/?s=25", - "emailAddress": "David.VERNAZOBRES@ext.ec.europa.eu", - "firstName": "David", - "fullName": "David VERNAZOBRES", - "id": "31512085826382", - "lastName": "VERNAZOBRES" - } - ], - - { - "cardIds": ["945202295", "945233018"], - "userIdsToAssign": ["478440842", "583458214"], - "wipOverrideComment": "This is needed if user WIP is violated on a board" - } - leankit.card_assign - leankit_user_id - - ''' - if leankit_card_res['assignedUsers'] is None: - logger.error('missing assigned user check') - sys.exit(1) - - assignee = False - logger.info(leankit_user_id) - for lean_user in leankit_card_res['assignedUsers']: - print(json_dumps(lean_user, sort_keys=True, indent=4)) - if lean_user['id'] == leankit_user_id: - assignee = True - break - if assignee is False: - logger.error('leankit card is not assigned to the current user.') - sys.exit(1) - -# issues = redmine.issue.filter(status_id='open', sort='project:asc,id:asc') -# >>> project = redmine.project.get('vacation') -# >>> project.issues -issue = redmine.issue.new() -issue.project_id = project_filter -issue.subject = args.title -issue.description = args.title -issue.tracker_id = tracker_id -issue.status_id = status_id -# issue.priority_id = 7 -issue.assigned_to_id = user_id -issue.save() - -redmine_id = str(issue.id) - -if args.leankit_create is True: - leankit_card = dict() - leankit_card["boardId"] = str(leankit_board_id) - leankit_card["title"] = args.title - leankit_card["typeId"] = leankit_card_type_id - leankit_card["assignedUserIds"] = list() - leankit_card["assignedUserIds"].append(leankit_user_id) - leankit_card["description"] = args.title - leankit_card["laneId"] = leankit_board_lane_id - leankit_card["priority"] = "normal" - leankit_card["size"] = args.leankit_story_point - - if leankit_board_name == 'DEV': - if args.tracker == 'Bug': - leankit_card["customIconId"] = "31512101365737" - - # leankit_card["customId"] = dict() - # leankit_card["customId"]["value"] = args.leankit_header - # leankit_card["customId"]["prefix"] = '[' + leankit_board_name + '] ' - # leankit_card["customId"]["url"] = None - leankit_card["customId"] = args.leankit_header - - leankit_card["customFields"] = list() - # Custums field redmine_id - if leankit_board_name == 'DEV': - t = dict() - t["fieldId"] = "31512088868633" - t["value"] = int(redmine_id) - leankit_card["customFields"].append(t) - - # print(json_dumps(leankit_card, sort_keys=True, indent=4)) - leankit_res = leankit.create_card(leankit_card) - print(leankit_res) - - leankit_id = leankit_res['id'] - print(leankit_id) - -else: - # if leankit_card_id is not None: - leankit_path = [ - {"op": "replace", - "path": "/customFields/0", - "value": { - "fieldId": "31512088868633", - "value": int(redmine_id) - } - }] - leankit_res = leankit.update_card(leankit_card_id, leankit_path) - print(leankit_res) - leankit_id = leankit_card_id - -issue = redmine.issue.get(int(redmine_id)) -# print('redmine_issue:' + str(issue)) -issue.custom_fields = [{'id': 41, 'value': leankit_id}] -issue.save() -# print('redmine_issue:' + str(issue.custom_fields)) -# print(issue.custom_field.all()) -# print(issue.custom_fields.get(41)) - -print('#Redmine %s' % (redmine_id)) -print('#Leankit %s' % (leankit_id)) -print('%s lk:%s fixes #%s' % (str(args.title), str(leankit_id), redmine_id)) -sys.exit(0) diff --git a/bin/sid_groups.py b/bin/sid_groups.py deleted file mode 100755 index d1da025..0000000 --- a/bin/sid_groups.py +++ /dev/null @@ -1,215 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -from ldap3 import Server, Connection -import sys -import os -import configparser as ConfigParser -import logging -import argparse -import socket -# import json -from pprint import pformat -import traceback - - -hostname = os.uname()[1] -whoami = sys._getframe().f_code.co_name -script = os.path.basename(__file__) - -for pylib in list(sys.path): - if '/usr/local/lib' in pylib: - sys.path.remove(pylib) - continue - elif '/export/home/snet/.local' in pylib: - sys.path.remove(pylib) - continue - -''' BASE CONFIG ''' -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -import snet.sloggly -from snet.diego import Diego -from snet.scrat import Scrat - -try: - logger = snet.sloggly.setup_custom_logger(script, logging.INFO) -except Exception as e: - print("\n=======\n") - title = "Something went wrong. Please inform SS team." - msg = "Error initializing the snet logger: " + str(e) + " :: " + traceback.format_exc(5) - print(msg) - whoami = sys._getframe().f_code.co_name - messages = [hostname, script, title, whoami, msg] - traceback.print_exc() - sys.exit(1) - - -def ec_ldap_get(): - - ldap_config_file = config_global.get('INI', 'LDAP') - ldap_config = ConfigParser.RawConfigParser() - ldap_config.optionxform(str()) - ldap_config.optionxform = str - ldap_config.read(ldap_config_file) - - server_name = ldap_config.get('LDAP_EC', 'SERVER_NAME') - server_port = int(ldap_config.get('LDAP_EC', 'SERVER_PORT')) - user = ldap_config.get('LDAP_EC', 'USER') - password = ldap_config.get('LDAP_EC', 'PASSWORD') - basedn = ldap_config.get('LDAP_EC', 'BASE') - - groups = ldap_config.get('LDAP_EC', 'SID_GROUP').split(',') - attributes = ['uid', 'cn'] - - ldap_server = Server(server_name, port=server_port, use_ssl=False) - ldap_con = Connection(ldap_server, user, password, auto_bind=True) - - results = dict() - results['groups'] = dict() - for group in groups: - - filter = "(&(objectclass=*)(cudgroup=%s))" % (group) - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=attributes) - - results['groups'][group] = dict() - results['groups'][group]['description'] = "nothing" - results['groups'][group]['mapped-ldap-users'] = list() - results['groups'][group]['mapped-ldap-groups'] = list() - - for entry in ldap_con.response: - if attributes[0] in entry['attributes']: - for g in entry['attributes'][attributes[0]]: - results['groups'][group]['mapped-ldap-users'].append(g) - - ldap_con.unbind() - return results - - -def sid_create_user_group(dfqdn, res_rw_user, block_to_update, verify=True, error_stop=False): - - scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify) - (scrat_json, scratres) = scrat_inst.scratQuery(block_to_update, Full=True) - - if str(scratres) != '200': - '''Scrat just add the vlan to the trunked list''' - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - to_print = '%s: %s' % (str(scratres), str(scrat_json)) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - if error_stop is True: - sys.exit(1) - else: - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.debug('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - -def main(): - - parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, - description='Script to synchronize the CUCM videoconference endpoints' - 'to SID') - - parser.add_argument('-v', '--verbose', action="store_true", default=False, - help="increase output verbosity", dest='verbose') - parser.add_argument('-d', '--debug', action="store_true", default=False, - help="increase output verbosity a lot", dest='debug') - parser.add_argument('--parameter', default=False, - help="the login parameter to debug", dest='param') - parser.add_argument('-e', '--env', default=False, help="Set the wanted env", dest='env', nargs='?', - choices=('dev', 'acc', 'prod')) - parser.add_argument('--dryrun', action="store_true", default=False, - help="print but do nothing", dest='dryrun') - parser.add_argument('--error-stop', action="store_true", default=False, - help="stop at the first errors", dest='error_stop') - parser.add_argument('--rw-user', default=False, required=True, help="Set the user doing the action in SID", dest='rw_user') - - args = parser.parse_args() - - dryrun = args.dryrun - debug = args.debug - logindebug = args.param - res_rw_user = args.rw_user - error_stop = args.error_stop - - if debug: - logger.setLevel(logging.DEBUG) - - verify = True - if args.env is False: - logger.debug('Using the automatic env.') - fqdn = socket.getfqdn() - - elif args.env == 'prod': - fqdn = '10.226.41.24:45789' - verify = False - - elif args.env == 'acc': - fqdn = 'vworker0-lu.acc.snmc.cec.eu.int' - - elif args.env == 'dev': - fqdn = 'vworker-dev.dev.snmc.cec.eu.int' - - else: - logger.error('should not happen') - sys.exit(1) - - print('Using the SID backend: ' + fqdn) - diego = Diego(fqdn=fqdn, verify=verify) - - snet_results = dict() - snet_results = ec_ldap_get() - - if debug: - logger.debug(pformat(snet_results)) - - context_uid = 666000002 - - (header,sid_groups) = diego.diego_run_dieget_by_name('list_user_groups', {}) - - if debug: - logger.debug(sid_groups) - - for group in snet_results['groups']: - need_to_create = False - block_to_update = { - 'name': group, - 'context': context_uid, - 'type': 'user group', - 'properties': { - } - } - if group not in sid_groups: - need_to_create = True - if debug: - logger.debug("GROUP -> " + group + " is to create: " + str(need_to_create)) - - if not dryrun and need_to_create is True: - sid_create_user_group(fqdn, res_rw_user, block_to_update, verify=verify, error_stop=error_stop) - else: - logger.debug('dryrun') - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - sys.exit(0) - -if __name__ == '__main__': - main() diff --git a/bin/sid_user.py b/bin/sid_user.py deleted file mode 100755 index 82c751c..0000000 --- a/bin/sid_user.py +++ /dev/null @@ -1,1352 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -from ldap3 import Server, Connection -import sys -import os -import configparser as ConfigParser -import logging -import argparse -import socket -# import json -from pprint import pformat -import traceback - - -hostname = os.uname()[1] -whoami = sys._getframe().f_code.co_name -script = os.path.basename(__file__) - -for pylib in list(sys.path): - if '/usr/local/lib' in pylib: - sys.path.remove(pylib) - continue - elif '/export/home/snet/.local' in pylib: - sys.path.remove(pylib) - continue - -''' BASE CONFIG ''' -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -import snet.sloggly -from snet.diego import Diego -from snet.scrat import Scrat - -try: - logger = snet.sloggly.setup_custom_logger(script, logging.INFO) -except Exception as e: - print("\n=======\n") - title = "Something went wrong. Please inform SS team." - msg = "Error initializing the snet logger: " + str(e) + " :: " + traceback.format_exc(5) - print(msg) - whoami = sys._getframe().f_code.co_name - messages = [hostname, script, title, whoami, msg] - traceback.print_exc() - sys.exit(1) - - -def snet_ldap_get(): - - ldap_config_file = config_global.get('INI', 'LDAP') - ldap_config = ConfigParser.RawConfigParser() - ldap_config.optionxform(str()) - ldap_config.optionxform = str - ldap_config.read(ldap_config_file) - - server_name = ldap_config.get('LDAP_SNET_NG', 'SERVER') - server_port = int(ldap_config.get('LDAP_SNET_NG', 'SSL_PORT')) - user = ldap_config.get('LDAP_SNET_NG', 'USER') - password = ldap_config.get('LDAP_SNET_NG', 'PASSWORD') - basedn = ldap_config.get('LDAP_SNET_NG', 'BASE') - bfilter = ldap_config.get('LDAP_SNET_NG', 'FILTER') - - groups = ldap_config.get('LDAP_SNET_NG', 'LEANKIT_GROUP').split(',') - attributes = ['uid', 'cn', 'member'] - uattributes = ['uid', 'gecos', 'givenName', 'mail', 'st', 'description'] - - ldap_server = Server(server_name, port=server_port, use_ssl=True) - ldap_con = Connection(ldap_server, user, password, auto_bind=True) - - results = dict() - results['groups'] = dict() - users = list() - gcn = list() - for group in groups: - - filter = bfilter.replace('REPLACE', group) - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=attributes) - - results['groups'][group] = dict() - results['groups'][group]['users'] = list() - - for entry in ldap_con.response: - if attributes[2] in entry['attributes']: - gcn.append(entry['dn']) - for g in entry['attributes'][attributes[2]]: - u = g.split(',')[0].replace('uid=', '') - results['groups'][group]['users'].append(u) - if u not in users: - users.append(u) - - results['users'] = dict() - bfilter = '(&(objectClass=posixAccount)(|' - for g in gcn: - bfilter += '(memberOf=' + g + ')' - bfilter += '))' - filter = bfilter - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=uattributes) - - for entry in ldap_con.response: - # print(entry) - if uattributes[0] in entry['attributes']: - if isinstance(entry['attributes'][uattributes[0]], list): - uid = entry['attributes'][uattributes[0]][0] - else: - uid = entry['attributes'][uattributes[0]] - - results['users'][uid] = dict() - for g in uattributes: - if g not in entry['attributes']: - continue - if isinstance(entry['attributes'][g], list): - results['users'][uid][g] = entry['attributes'][g][0] - else: - results['users'][uid][g] = entry['attributes'][g] - if 'lastname' not in results['users'][uid]: - results['users'][uid]['lastname'] = results['users'][uid]['gecos'].replace(' ' + results['users'][uid]['givenName'], '') - results['users'][uid]['membership'] = list() - - ldap_con.unbind() - - for group in results['groups']: - for user in results['groups'][group]['users']: - results['users'][user]['membership'].append(group) - - return results - - -def ec_ldap_get_user(users=[]): - - ldap_config_file = config_global.get('INI', 'LDAP') - ldap_config = ConfigParser.RawConfigParser() - ldap_config.optionxform(str()) - ldap_config.optionxform = str - ldap_config.read(ldap_config_file) - - server_name = ldap_config.get('LDAP_EC', 'SERVER_NAME') - server_port = int(ldap_config.get('LDAP_EC', 'SERVER_PORT')) - user = ldap_config.get('LDAP_EC', 'USER') - password = ldap_config.get('LDAP_EC', 'PASSWORD') - basedn = ldap_config.get('LDAP_EC', 'BASE') - uattributes = ['uid', 'building', 'c', 'departmentNumber', 'dg', 'ecInternationalTelephoneNumber', 'employeeType', 'euEmployeeStatusDetail', 'euEmployeeSubtype', 'floor', 'givenName', 'l', 'mail', 'physicalDeliveryOfficeName', 'roomNumber', 'telephoneNumber', 'title', 'sn', 'cn'] - - ldap_server = Server(server_name, port=server_port, use_ssl=False) - ldap_con = Connection(ldap_server, user, password, auto_bind=True) - - results = dict() - results['users'] = dict() - for user in users: - - filter = "(&(objectclass=cudperson)(uid=%s))" % (user) - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=uattributes) - - for entry in ldap_con.response: - if uattributes[0] in entry['attributes']: - if isinstance(entry['attributes'][uattributes[0]], list): - uid = entry['attributes'][uattributes[0]][0] - else: - uid = entry['attributes'][uattributes[0]] - - results['users'][uid] = dict() - for g in uattributes: - if g not in entry['attributes']: - continue - if isinstance(entry['attributes'][g], list): - if len(entry['attributes'][g]) == 0: - continue - results['users'][uid][g] = entry['attributes'][g][0] - else: - results['users'][uid][g] = entry['attributes'][g] - - ldap_con.unbind() - return results - - -def ec_ldap_get(): - - ldap_config_file = config_global.get('INI', 'LDAP') - ldap_config = ConfigParser.RawConfigParser() - ldap_config.optionxform(str()) - ldap_config.optionxform = str - ldap_config.read(ldap_config_file) - - server_name = ldap_config.get('LDAP_EC', 'SERVER_NAME') - server_port = int(ldap_config.get('LDAP_EC', 'SERVER_PORT')) - user = ldap_config.get('LDAP_EC', 'USER') - password = ldap_config.get('LDAP_EC', 'PASSWORD') - basedn = ldap_config.get('LDAP_EC', 'BASE') - - #groups = ldap_config.get('LDAP_EC', 'LEANKIT_GROUP').split(',') - groups = ldap_config.get('LDAP_EC', 'SID_GROUP').split(',') - attributes = ['uid', 'cn'] - - ldap_server = Server(server_name, port=server_port, use_ssl=False) - ldap_con = Connection(ldap_server, user, password, auto_bind=True) - - results = dict() - results['groups'] = dict() - for group in groups: - - filter = "(&(objectclass=*)(cudgroup=%s))" % (group) - ldap_con.search(search_base=basedn, - search_filter=filter, - attributes=attributes) - - results['groups'][group] = dict() - results['groups'][group]['description'] = "nothing" - results['groups'][group]['mapped-ldap-users'] = list() - results['groups'][group]['mapped-ldap-groups'] = list() - - for entry in ldap_con.response: - if attributes[0] in entry['attributes']: - for g in entry['attributes'][attributes[0]]: - results['groups'][group]['mapped-ldap-users'].append(g) - - ldap_con.unbind() - return results - - -def sid_create_user(diego, dfqdn, res_rw_user, user, block_to_update, context_uid=666000002, verify=True, error_stop=False): - - scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify, group="DIGIT_SNET_PROX") - try: - (scrat_json, scratres) = scrat_inst.scratQuery(block_to_update, Full=True) - except Exception as e: - scratres = '409' - scrat_json = 'Creation failed' - - if str(scratres) != '200': - '''Scrat just add the vlan to the trunked list''' - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - to_print = '%s: %s' % (str(scratres), str(scrat_json)) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - if error_stop is True: - sys.exit(1) - else: - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.debug('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - -def sid_associate_user_to_group(diego, user, ec_ldap_sid_results, scrat, logger): - """ - Function that happen one user to the member of any group. - - Args: - diego: Diego Object - user: User to assiciate - ec_ldap_sid_results: Data content related to LDAP - scrat: Scrat Object - logger: To print things. - - Returns: - Void - - Raises: - Scrat error, when appending wont work. - """ - context_uid = 779000000 - context_name = "AAA" - d_get = "auth_get_teams" - (h, d_grp_list) = diego._dieget(d_get, {}) - d_grp_list = list( - { - "uid": x[0], - "name": x[1], - "properties": { "has as description": x[3]} - } for x in d_grp_list - ) - # For non-existent group : Add-it manually or add the specific feature. - # Right to the top of this command. - for group in ec_ldap_sid_results['groups']: - if user in ec_ldap_sid_results['groups'][group]["mapped-ldap-users"]: - # Case : User in the current group. should be changed. - if list(x for x in d_grp_list if x["name"] == group): - # Case : Group exist in SID, ok for the edit. - group_uid = list(x["uid"] for x in d_grp_list if x["name"] == group)[0] - new_member = { - "uid": group_uid, - "name": group, - "type": "team", - "context": context_name, - "properties": { - "has as member": user - } - } - logger.info(f"Try to update {group}...") - (scrat_json, scratres) = scrat.scratUpdate(new_member, overwrite_mode=False, line_only=False, Full=True) - if str(scratres) != '200': - logger.error(f"Error when trying to add new member '{new_member}' in '{group}':") - logger.error(f"{scrat_json}") - else: - logger.info(f"Success !") - - -def sid_update_user(diego, dfqdn, res_rw_user, user, block_to_update, context_uid=666000002, verify=True, error_stop=False): - """ - Update (petjere) : Remove useless error print format to have quick and simple error returned. - Also: Block the script if error returned from Scrat (should not happen at all) - - 2nd update : Workaround of the input. - --> The usage of dict format as value is not stable, use simple string as much as possible ! - """ - - ''' delete: need to check the line exist if not 409''' - scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify, group="DIGIT_SNET_PROX") - try: - # logger.info(f"Before {block_to_update}...") - # logger.info('\n') - block_to_update = reformat_values(block_to_update, logger) - logger.info(f"Try to update {block_to_update}...") - (scrat_json, scratres) = scrat_inst.scratUpdate(block_to_update, overwrite_mode=True, Full=True) - except Exception as e: - scratres = '409' - scrat_json = 'Update Failed' - raise Exception(e) - - if str(scratres) != '200': - raise Exception(f"{scrat_json}") - else: - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.debug('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - -def reformat_values(scrat_req, logger): - """ - Reformat scrat request to use as much as possible values in string. - - Args: - scrat_req: Scrat request about to be reformat. - - Returns: - Reformatted scrat request. - - Raises: - Format error, if a case is not managed. - """ - new_format = dict() - if "properties" not in scrat_req: - raise Exception(f"Missing properties on scrat request : '{scrat_req}'") - new_format["properties"] = dict() - - for meta_prop in scrat_req: - if meta_prop == "properties": - continue - new_format[meta_prop] = scrat_req[meta_prop] - - for prop in scrat_req["properties"]: - if isinstance(scrat_req["properties"][prop], str): - if not scrat_req["properties"][prop].strip(): - continue - new_format["properties"][prop] = scrat_req["properties"][prop] - elif isinstance(scrat_req["properties"][prop], list): - if prop not in new_format["properties"]: - new_format["properties"][prop] = list() - for elt in scrat_req["properties"][prop]: - if isinstance(elt, str): - if not elt.strip(): - continue - new_format["properties"][prop].append(elt) - elif isinstance(elt, dict): - new_format["properties"][prop].append(elt["name"]) - else: - raise Exception(f"Unmanaged case, yet: {elt}") - # Info : To remove duplicate. - new_format["properties"][prop] = list(set(new_format["properties"][prop])) - elif isinstance(scrat_req["properties"][prop], dict): - new_format["properties"][prop] = scrat_req["properties"][prop]["name"] - else: - raise Exception(f"Unmanaged case, yet: {scrat_req['properties'][prop]}") - - return new_format - -def sid_add_user_to_department(diego, dfqdn, res_rw_user, user, uid, department, context_uid=666000002, verify=True, error_stop=False): - - results = diego.diegoGetObject(uid, context_uid) - logger.debug(results) - - '''Scrat just add the vlan to the trunked list''' - block_to_update = { - 'uid': uid, - 'name': department, - 'context': context_uid, - 'type': results['type'], - 'properties': {'has as member': user} - } - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - ''' delete: need to check the line exist if not 409''' - scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify, group="DIGIT_SNET_PROX") - try: - (scrat_json, scratres) = scrat_inst.scratUpdate(block_to_update, overwrite_mode=False, line_only=False, Full=True) - except Exception as e: - scrat_json = 'e' - scratres = '409' - - if str(scratres) != '200': - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - to_print = '%s: %s' % (str(scratres), str(scrat_json)) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - if error_stop is True: - sys.exit(1) - else: - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.debug('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - -def sid_update_user_to_resigned(diego, dfqdn, res_rw_user, user, uid, context_uid=666000002, verify=True, error_stop=False): - - results = diego.diegoGetObject(uid, context_uid) - logger.debug(results) - - '''Scrat just add the vlan to the trunked list''' - block_to_update = { - 'uid': uid, - 'name': user, - 'context': context_uid, - 'type': results['type'], - 'properties': {'has as status': 'resigned'} - } - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - ''' delete: need to check the line exist if not 409''' - scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify, group="DIGIT_SNET_PROX") - try: - (scrat_json, scratres) = scrat_inst.scratUpdate(block_to_update, overwrite_mode='exclusive', line_only=False, Full=True) - except Exception as e: - scrat_json = e - scratres = '409' - - if str(scratres) != '200': - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - to_print = '%s: %s' % (str(scratres), str(scrat_json)) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - if error_stop is True: - sys.exit(1) - else: - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.debug('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - -def sid_update_user_exlude_approver_scheduler_change_management(diego, dfqdn, res_rw_user, user, uid, typeExclude, context_uid=778000000, verify=True, error_stop=False): - - results = diego.diegoGetObject(uid, context_uid) - logger.debug(results) - logger.debug('Type: ' + typeExclude) - block_to_update = { - 'uid': uid, - 'name': user, - 'context': context_uid, - 'type': typeExclude, - 'properties': {'is a': typeExclude} - } - to_print = pformat(block_to_update) - #print(block_to_update) - #pass - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - ''' delete: need to check the line exist if not 409''' - scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify, group="DIGIT_SNET_PROX") - try: - (scratres) = scrat_inst.deleteLine(block_to_update) - except Exception as e: - scratres = '409' - if str(scratres) != '200': - print("not removed " + user + " from " + typeExclude) - if error_stop is True: - sys.exit(1) - else: - print("removed " + user + " from " + typeExclude) - -def sid_create_update_user_approver_scheduler_change_management(diego, dfqdn, res_rw_user, user, uid, typeAdd, need_to_update, context_uid=666000002, verify=True, error_stop=False): - create = True - results = diego.diegoGetObject(uid) - ty = [] - ty2 = [] - #print(results) 666060597 - if 'has as act' in results['properties'] : - if (isinstance(results['properties']['has as act'], list)): - for act in results['properties']['has as act'] : - ty.append(act['name']) - else : - ty.append(results['properties']['has as act']['name']) - - if typeAdd not in ty : - ty.append(typeAdd) - #new relation to workaround Polymorphism - if create : - block_to_update = { - 'uid': uid, - 'name': user, - 'context': 778000000, - "is applicable in the context of" : 778000000, - 'is a specialization of' : typeAdd, - 'type': typeAdd, - } - - #new version "has as act" - block_to_update = { - 'uid': uid, - 'name': user, - 'context': 666000002, - 'type': 'user', - 'properties': {'has as act': ty} - } - - to_print = pformat(block_to_update) - #print(to_print) - #pass - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - ''' delete: need to check the line exist if not 409''' - scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify, group="DIGIT_SNET_PROX") - #(scrat_json, scratres) = scrat_inst.scratUpdate(block_to_update, overwrite_mode=True, line_only=True, Full=True) - #(scrat_json, scratres) = scrat_inst.scratQuery(block_to_update, Full=True) - #(scrat_json, scratres) = scrat_inst.scratQuery(scratter, Full=True) - (scrat_json, scratres) = scrat_inst.scratUpdate(block_to_update, overwrite_mode='exclusive', line_only=False, Full=True) - if str(scratres) != '200': - '''Scrat add new user relation in diferent context''' - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - to_print = '%s: %s' % (str(scratres), str(scrat_json)) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.error('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - if error_stop is True: - sys.exit(1) - - else: - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.debug('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - else : - logger.error('the ' + typeAdd + ' role. is already defined for this user') - pass - - -def main(): - - parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, - description='Script to synchronize the CUCM videoconference endpoints' - 'to SID') - - parser.add_argument('-v', '--verbose', action="store_true", default=False, - help="increase output verbosity", dest='verbose') - parser.add_argument('-d', '--debug', action="store_true", default=False, - help="increase output verbosity a lot", dest='debug') - parser.add_argument('--parameter', default=False, - help="the login parameter to debug", dest='param') - parser.add_argument('-e', '--env', default=False, help="Set the wanted env", dest='env', nargs='?', - choices=('dev', 'acc', 'prod')) - parser.add_argument('--dryrun', action="store_true", default=False, - help="print but do nothing", dest='dryrun') - parser.add_argument('--error-stop', action="store_true", default=False, - help="stop at the first errors", dest='error_stop') - parser.add_argument('--rw-user', default=False, required=True, help="Set the user doing the action in SID", dest='rw_user') - - args = parser.parse_args() - - dryrun = args.dryrun - debug = args.debug - logindebug = args.param - res_rw_user = args.rw_user - error_stop = args.error_stop - - if debug: - logger.setLevel(logging.DEBUG) - - verify = True - if args.env is False: - logger.debug('Using the automatic env.') - fqdn = socket.getfqdn() - - elif args.env == 'prod': - fqdn = '10.226.41.24:45789' - verify = False - - elif args.env == 'acc': - fqdn = 'vworker0-lu.acc.snmc.cec.eu.int' - - elif args.env == 'dev': - fqdn = 'vworker-dev.dev.snmc.cec.eu.int' - - else: - logger.error('should not happen') - sys.exit(1) - - print('Using the SID backend: ' + fqdn) - snet_groups = 'com,mgt,net,pm,sd,sec,dev,sys,tda,sup'.split(',') - official_groups = ['officials'] - - devnull_del_user = ['systemac'] - devnull_user = ['geirnal', 'lehonan', 'perreja', 'rotchri', 'stoiama'] - - # DIGIT C4 Official satic whitelist, as they refuse to follow the PUMA process. - # They are all members of C4-TA. So do not add someone not member of C4-TA. The C4-TA is hard-coded below. - # first_request before 10/2021 - # last reminder request: 01/2022 - # last reminder request: 04/2022 : used to remove the relations for others users - official_broken_leg = ['tsigref', 'wagnejl', 'hautari', 'durmeda', 'stoiama'] - - departments = ['DIGIT.C.4', 'DIGIT.C.4.001', 'DIGIT.C.4.002', 'DIGIT.C.4.003', 'DIGIT.C.4.004','DIGIT.C.4.006', 'DIGIT.C.4.007', 'DIGIT.C.4.008'] - - # Suggestion done : Put a dieget instead. - diego = Diego(fqdn=fqdn, verify=verify, group="DIGIT_SNET_PROX") - approver_scheduler_list = ['ventufa', 'houinbe', 'devijea'] - - # Info : Scheduler should also be approver by default. - d_get = "auth_get_scheduler_users" - (h, scheduler_results) = diego.diego_run_dieget_by_name(d_get, dict()) - print(f"{scheduler_results}") - if scheduler_results: - approver_scheduler_list = list() - for sch in scheduler_results: - approver_scheduler_list.append(sch) - - print(f"{approver_scheduler_list}") - - snet_results = dict() - snet_results = snet_ldap_get() - - ec_ldap_sid_results = dict() - ec_ldap_sid_results = ec_ldap_get() - snet_prox = list() - - for group in ec_ldap_sid_results['groups']: - if group == "DIGIT_SNET_PROX": - snet_prox = ec_ldap_sid_results['groups'][group]['mapped-ldap-users'] - - - if debug: - if logindebug: - logger.debug("debuging " + logindebug) - if 'users' in snet_results and logindebug in snet_results['users']: - logger.debug(pformat(snet_results['users'][logindebug])) - else: - logger.debug(logindebug + " not found in snet_results.") - else: - logger.debug(pformat(snet_results)) - - ec_results = dict() - - ec_ldap_users = list(snet_results['users'].keys()) - ec_ldap_users += snet_prox - ec_ldap_users += official_broken_leg - ec_results = ec_ldap_get_user(ec_ldap_users) - if debug: - if logindebug: - logger.debug("debuging " + logindebug) - if 'users' in snet_results and logindebug in snet_results['users']: - logger.debug(pformat(ec_results['users'][logindebug])) - else: - logger.debug(logindebug + " not found in snet_results.") - else: - logger.debug(pformat(ec_results)) - - ''' - 'yildmes': {'building': 'B-28', - 'c': 'BE', - 'departmentNumber': 'DIGIT.C.4.006', - 'dg': 'DIGIT', - 'ecInternationalTelephoneNumber': '+32 229-68623', - 'employeeType': 'E', - 'euEmployeeStatusDetail': 'A', - 'euEmployeeSubtype': 'PPW', - 'floor': '01', - 'givenName': 'Mesut', - 'sn': 'YILDIRIM', - 'cn': 'YILDIRIM Mesut', - 'l': 'BRU', - 'mail': 'Mesut.YILDIRIM@ext.ec.europa.eu', - 'physicalDeliveryOfficeName': 'B-28 01/P051', - 'roomNumber': 'P051', - 'telephoneNumber': '68623', - 'title': 'Mr', - 'uid': 'yildmes'}, - ''' - - snet_mail_index = dict() - snet_account_index = dict() - bad_user = list() - for user in snet_results['users']: - # print(user) - if user not in ec_results['users']: - bad_user.append(user) - continue - if 'dg' not in ec_results['users'][user]: - logger.error("%s do not have a dg" % (user)) - bad_user.append(user) - continue - if ec_results['users'][user]['dg'] != 'DIGIT': - bad_user.append(user) - continue - if ec_results['users'][user]['departmentNumber'] not in departments: - # this is not declared as snet - logger.error('skipping ' + user + ' dpt: ' + ec_results['users'][user]['departmentNumber']) - continue - - real_member = False - for gr in snet_results['users'][user]['membership']: - if gr in snet_groups: - real_member = True - break - elif gr in official_groups: - real_member = True - break - - if real_member is False: - # this is not declared as snet - continue - - if 'mail' not in ec_results['users'][user]: - logger.error('Houston no mail, no mail...') - logger.error(pformat(ec_results['users'][user])) - bad_user.append(user) - continue - - snet_mail_index[ec_results['users'][user]['mail']] = user - snet_account_index[user] = ec_results['users'][user]['mail'] - - for user in official_broken_leg: - - if user not in snet_account_index: - if user not in ec_results['users']: - logger.error("user '%s' is a real broken leg, too bad for him. There is no rescue." % (user)) - else: - snet_mail_index[ec_results['users'][user]['mail']] = user - snet_account_index[user] = ec_results['users'][user]['mail'] - snet_results['users'][user] = dict() - snet_results['users'][user]['membership'] = list() - snet_results['users'][user]['membership'].append('officials') - - for user in snet_prox: - if user not in ec_results['users']: - logger.error("proxy user '%s' not found in ec ldap." % (user)) - else: - ec_results['users'][user]['mail'] = 'proxy user, no email' - snet_mail_index[ec_results['users'][user]['mail']] = user - snet_account_index[user] = ec_results['users'][user]['mail'] - snet_results['users'][user] = dict() - snet_results['users'][user]['membership'] = list() - snet_results['users'][user]['membership'].append('proxy') - - logger.info('Bad User: ' + pformat(bad_user)) - logger.info('Snet User snet_mail_index: ' + pformat(snet_mail_index)) - logger.info('Snet User snet_account_index: ' + pformat(snet_account_index)) - - - scrat = Scrat(res_rw_user, '', fqdn=fqdn, version=2, verify=verify, group="DIGIT_SNET_PROX") - params = {'name': '","'.join(departments)} - sid_results = diego.diego_run_dieget_by_name('sid_user_check', params) - params = {'name': '","'.join(departments)} - sid_resigned_results = diego.diego_run_dieget_by_name('sid_user_resigned_check', params) - - context_uid = 666000002 - - if debug: - if logindebug: - logger.debug("debuging " + logindebug) - if sid_results and logindebug in sid_results[1]: - logger.debug(pformat(sid_results[1][logindebug])) - else: - logger.debug(logindebug + " not found in sid_results.") - - if sid_resigned_results and logindebug in sid_resigned_results[1]: - logger.debug(pformat(sid_resigned_results[1][logindebug])) - else: - logger.debug(logindebug + " not found in sid_resigned_results.") - else: - logger.debug('SID User: ' + pformat(sid_results[1])) - - ''' - 'yildmes': {'belongs to': 'SNet NET', - 'has as directorate general': 'DIGIT', - 'has as long name': 'Mesut YILDIRIM', - 'has as role': 'Network Engineer', - 'has as short name': 'MYI', - 'has as status': 'active', - 'has e-mail address': 'Mesut.YILDIRIM@ext.ec.europa.eu', - 'has telephone number': '+32 229-68623', - 'is a member of': 'DIGIT.C.4.006', - 'is located in': 'Brussels', - 'type': 'user', - 'uid': 666060176, - 'value': 'yildmes'}}) - ''' - for user in sid_results[1]: - if user in devnull_del_user: - continue - if debug and logindebug and logindebug != user: - continue - if user not in snet_account_index: - logger.info('SID user ' + user + ' should be updated to resigned. User missing from the snet_account_index.') - if not dryrun: - sid_update_user_to_resigned(diego, fqdn, res_rw_user, user, sid_results[1][user]['uid'], verify=verify) - else: - logger.debug('dry run, user not updated to resigned.') - continue - - sid_need_approver = list() - sid_need_scheduler = list() - - for user in snet_account_index: - if user in devnull_user: - continue - if debug and logindebug and logindebug != user: - continue - - params = {'name': user} - user_exists = diego.diego_run_dieget_by_name('sid_check_user_exists', params) - - need_to_create = False - need_to_update = False - if user in sid_results[1]: - logger.debug('SID user ' + user + ' should be updated.') - need_to_update = True - block_to_update = diego.diegoGetObject(sid_results[1][user]['uid'], context_uid) - elif user in user_exists[1] and user not in sid_results[1] and user not in sid_resigned_results[1]: - logger.debug('SID user ' + user + ' is incomplete and should be updated.') - need_to_update = True - block_to_update = diego.diegoGetObject(user_exists[1][user]['uid'], context_uid) - elif user not in sid_results[1] and user not in sid_resigned_results[1] and user not in user_exists[1]: - need_to_create = True - logger.debug('SID user ' + user + ' should be addded.') - logger.debug(pformat(snet_results['users'][user])) - - block_to_update = { - 'name': user, - 'context': context_uid, - 'type': 'user', - 'properties': { - } - } - - elif user in sid_resigned_results[1]: - logger.error('user %s in in resigned, skipping.' % user) - continue - - if need_to_update is False and need_to_create is True: - if 'has as role' not in block_to_update['properties']: - block_to_update['properties']['has as role'] = list() - elif 'has as role' in block_to_update['properties'] and not isinstance(block_to_update['properties']['has as role'], list): - t = block_to_update['properties']['has as role'] - block_to_update['properties']['has as role'] = list() - block_to_update['properties']['has as role'].append(t) - - if 'has write access to' not in block_to_update['properties']: - block_to_update['properties']['has write access to'] = list() - elif 'has write access to' in block_to_update['properties'] and not isinstance(block_to_update['properties']['has write access to'], list): - t = block_to_update['properties']['has write access to'] - block_to_update['properties']['has write access to'] = list() - block_to_update['properties']['has write access to'].append(t) - - if 'belongs to' not in block_to_update['properties']: - block_to_update['properties']['belongs to'] = list() - elif 'belongs to' in block_to_update['properties'] and not isinstance(block_to_update['properties']['belongs to'], list): - t = block_to_update['properties']['belongs to'] - block_to_update['properties']['belongs to'] = list() - block_to_update['properties']['belongs to'].append(t) - else: - if 'has write access to' not in block_to_update['properties']: - block_to_update['properties']['has write access to'] = list() - elif 'has write access to' in block_to_update['properties'] and not isinstance(block_to_update['properties']['has write access to'], list): - t = block_to_update['properties']['has write access to'] - block_to_update['properties']['has write access to'] = list() - block_to_update['properties']['has write access to'].append(t) - - if 'has as role' not in block_to_update['properties']: - block_to_update['properties']['has as role'] = list() - elif 'has as role' in block_to_update['properties'] and not isinstance(block_to_update['properties']['has as role'], list): - t = block_to_update['properties']['has as role'] - block_to_update['properties']['has as role'] = list() - block_to_update['properties']['has as role'].append(t) - - if 'belongs to' not in block_to_update['properties']: - block_to_update['properties']['belongs to'] = list() - elif 'belongs to' in block_to_update['properties'] and not isinstance(block_to_update['properties']['belongs to'], list): - t = block_to_update['properties']['belongs to'] - block_to_update['properties']['belongs to'] = list() - block_to_update['properties']['belongs to'].append(t) - - if 'has as short name' not in block_to_update['properties'] or block_to_update['properties']['has as short name'] is None or '': - block_to_update['properties']['has as short name'] = ec_results['users'][user]['givenName'][0] + ec_results['users'][user]['sn'][:2] - - if 'is authorized to' not in block_to_update['properties']: - block_to_update['properties']['is authorized to'] = list() - elif 'is authorized to' in block_to_update['properties'] and not isinstance(block_to_update['properties']['is authorized to'], list): - t = block_to_update['properties']['is authorized to'] - block_to_update['properties']['is authorized to'] = list() - block_to_update['properties']['is authorized to'].append(t) - - if 'has access to application program' not in block_to_update['properties']: - block_to_update['properties']['has access to application program'] = list() - elif 'has access to application program' in block_to_update['properties'] and not isinstance(block_to_update['properties']['has access to application program'], list): - t = block_to_update['properties']['has access to application program'] - block_to_update['properties']['has access to application program'] = list() - block_to_update['properties']['has access to application program'].append(t) - - if 'has access to easiCAPs feature' not in block_to_update['properties']: - block_to_update['properties']['has access to easiCAPs feature'] = list() - elif 'has access to easiCAPs feature' in block_to_update['properties'] and not isinstance(block_to_update['properties']['has access to easiCAPs feature'], list): - t = block_to_update['properties']['has access to easiCAPs feature'] - block_to_update['properties']['has access to easiCAPs feature'] = list() - block_to_update['properties']['has access to easiCAPs feature'].append(t) - - if 'dg' in ec_results['users'][user] : - block_to_update['properties']['has as directorate general'] = ec_results['users'][user]['dg'] - - block_to_update['properties']['has as long name'] = ec_results['users'][user]['givenName'] + ' ' + ec_results['users'][user]['sn'] - - block_to_update['properties']['has as status'] = 'active' - - block_to_update['properties']['has e-mail address'] = ec_results['users'][user]['mail'] - if 'ecInternationalTelephoneNumber' in ec_results['users'][user] : - block_to_update['properties']['has telephone number'] = ec_results['users'][user]['ecInternationalTelephoneNumber'] - - if 'departmentNumber' in ec_results['users'][user] : - block_to_update['properties']['is a member of'] = ec_results['users'][user]['departmentNumber'] - - if 'c' in ec_results['users'][user] and ec_results['users'][user]['c'] == 'BE': - block_to_update['properties']['is located in'] = 'Brussels' - elif 'c' in ec_results['users'][user] and ec_results['users'][user]['c'] == 'LU': - block_to_update['properties']['is located in'] = 'Luxembourg' - - # 'com,mgt,net,pm,sd,sec,sup,tda' - # 'belongs to': 'SNet MGT' 'SNet TDA' 'SNet NET' 'SNet COM' 'SNet PM' 'SNet SEC' 'SNet SUP' - # 'has as role': 'Team Leader' 'Architect' 'Network Engineer' - - # "is authorized to" should be edited to contain "configure (easiCAPs action)", "manage job (easiCAPs action)" and "patch (easiCAPs action)" - # "has access to application program" should be edited to include "easiCAPs" - # "has access to easiCAPs feature" should be edited to contain "Port History" and "Profile Support". - - for mb in snet_results['users'][user]['membership']: - # 'com,mgt,net,pm,sd,sec,sup,tda,officials' - if mb == 'com': - if need_to_update is False and need_to_create is True: - if 'SNet COM' not in block_to_update['properties']['belongs to']: - block_to_update['properties']['belongs to'].append('SNet COM') - #Delete the security policy role if its in a dict inside the list - for i in range(len(block_to_update['properties']['has as role'])): - if isinstance(block_to_update['properties']['has as role'][i], dict): - if block_to_update['properties']['has as role'][i]['name'] == 'Security Policy': - del block_to_update['properties']['has as role'][i] - break - if 'Security Policy' in block_to_update['properties']['has as role']: - block_to_update['properties']['has as role'].remove('Security Policy') - #if 'ISMS' not in block_to_update['properties']['has as role']: - # block_to_update['properties']['has as role'].append('ISMS') - #if 'SMPM' not in block_to_update['properties']['has as role']: - # block_to_update['properties']['has as role'].append('SMPM') - elif mb == 'dev': - if need_to_update is False and need_to_create is True: - if 'SNet SUP' not in block_to_update['properties']['belongs to']: - block_to_update['properties']['belongs to'].append('SNet SUP') - if 'Developer' not in block_to_update['properties']['has as role']: - block_to_update['properties']['has as role'].append('Developer') - if 'edit object (Visual action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('edit object (Visual action)') - if 'edit relation (SID action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('edit relation (SID action)') - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - if 'SnetInventory' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('SnetInventory') - - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - elif mb == 'mgt': - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('SNet MGT') - block_to_update['properties']['has as role'].append('Team Leader') - block_to_update['properties']['has access to application program'].append('CRUD') - block_to_update['properties']['has access to application program'].append('SnetInventory') - block_to_update['properties']['has access to application program'].append('Visual') - - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - if 'SnetInventory' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('SnetInventory') - - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - elif mb == 'net': - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('SNet NET') - block_to_update['properties']['has as role'].append('Network Engineer') - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - - elif mb == 'pm': - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('SNet PM') - block_to_update['properties']['has as role'].append('Project Manager') - if 'SnetInventory' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('SnetInventory') - - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - elif mb == 'sd': - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('Snet NOC/SD') - block_to_update['properties']['has as role'].append('Service Desk Agent') - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - elif mb == 'sec': - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('Snet SEC') - block_to_update['properties']['has as role'].append('Security Engineer') - block_to_update['properties']['is authorized to'].append('edit object (Visual action)') - block_to_update['properties']['is authorized to'].append('edit relation (SID action)') - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - elif mb == 'sup': - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('SNet SUP') - block_to_update['properties']['has as role'].append('Supporting Serivces Engineer') - block_to_update['properties']['is authorized to'].append('edit object (Visual action)') - block_to_update['properties']['is authorized to'].append('edit relation (SID action)') - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - if 'SnetInventory' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('SnetInventory') - - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - elif mb == 'tda': - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('SNet TDA') - block_to_update['properties']['has as role'].append('Architect') - block_to_update['properties']['is authorized to'].append('edit object (Visual action)') - block_to_update['properties']['is authorized to'].append('edit relation (SID action)') - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - elif mb == 'officials': - ''' - if need_to_update is False and need_to_create is True: - if 'SNet SUP' not in block_to_update['properties']['belongs to']: - block_to_update['properties']['belongs to'].append('SNet SUP') - if 'Developer' not in block_to_update['properties']['has as role']: - block_to_update['properties']['has as role'].append('Developer') - if 'edit object (Visual action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('edit object (Visual action)') - if 'edit relation (SID action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('edit relation (SID action)') - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - ''' - if 'Diego' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Diego') - if 'Visual' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('Visual') - - if 'is a member of' in block_to_update['properties'] and block_to_update['properties']['is a member of'] == 'DIGIT.C.4.003': - # network team member - if 'SnetInventory' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('SnetInventory') - if 'CRUD' not in block_to_update['properties']['has access to application program']: - block_to_update['properties']['has access to application program'].append('CRUD') - - if 'edit object (Visual action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('edit object (Visual action)') - if 'patch (easiCAPs action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('patch (easiCAPs action)') - if 'configure (easiCAPs action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('configure (easiCAPs action)') - if 'manage job (easiCAPs action)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('manage job (easiCAPs action)') - if 'trunk (network function)' not in block_to_update['properties']['is authorized to']: - block_to_update['properties']['is authorized to'].append('trunk (network function)') - - block_to_update['properties']['has access to domain'] = 'All Domains' - - if 'Port History' not in block_to_update['properties']['has access to easiCAPs feature']: - block_to_update['properties']['has access to easiCAPs feature'].append('Port History') - if 'Profile Support' not in block_to_update['properties']['has access to easiCAPs feature']: - block_to_update['properties']['has access to easiCAPs feature'].append('Profile Support') - - elif mb == 'proxy': - #For proxy users, in case more fields are to be added in the future - if need_to_update is False and need_to_create is True: - block_to_update['properties']['belongs to'].append('SNet Prox') - block_to_update['properties']['has as role'].append('Proxy User') - - # Cleanup the properties - - if need_to_update is False and need_to_create is True and 'departmentNumber' in ec_results['users'][user]: - if ec_results['users'][user]['departmentNumber'] == 'DIGIT.C.4.007': - block_to_update['properties']['belongs to'].append('NIS') - block_to_update['properties']['belongs to'].append('OIS') - block_to_update['properties']['has as role'] = 'OIS' - - if 'OIS' in block_to_update['properties']['has as role']: - # authorised OIS to update the wireless access point. - block_to_update['properties']['has write access to'].append('wireless access point') - - if 'belongs to' in block_to_update['properties'] and len(block_to_update['properties']['belongs to']) == 1: - block_to_update['properties']['belongs to'] = block_to_update['properties']['belongs to'][0] - if 'has as role' in block_to_update['properties'] and len(block_to_update['properties']['has as role']) == 1: - block_to_update['properties']['has as role'] = block_to_update['properties']['has as role'][0] - if 'has write access to' in block_to_update['properties'] and len(block_to_update['properties']['has write access to']) == 1: - block_to_update['properties']['has write access to'] = block_to_update['properties']['has write access to'][0] - - if len(block_to_update['properties']['is authorized to']) == 1: - block_to_update['properties']['is authorized to'] = block_to_update['properties']['is authorized to'][0] - if len(block_to_update['properties']['has access to application program']) == 1: - block_to_update['properties']['has access to application program'] = block_to_update['properties']['has access to application program'][0] - if len(block_to_update['properties']['has write access to']) == 1: - block_to_update['properties']['has write access to'] = block_to_update['properties']['has write access to'][0] - - # has as role (OQM, Product Owner, SDM - # print("This '%s' is a PM -> also need to add a 'is a' 'approver' + 'scheduler'" % user) - if user in sid_results[1] and 'has as role' in sid_results[1][user] : - if isinstance(sid_results[1][user]['has as role'], list): - for role in sid_results[1][user]['has as role']: - if role == 'OQM' or role == 'Product Owner' or role == 'SDM' : - sid_need_approver.append(user) - sid_need_scheduler.append(user) - else : - role = sid_results[1][user]['has as role'] - if role == 'OQM' or role == 'Product Owner' or role == 'SDM' : - sid_need_approver.append(user) - sid_need_scheduler.append(user) - - # check and cleanup the data before scrat - dict_keys = list(block_to_update['properties'].keys()) - for prop in dict_keys: - # has mobile telephone number - if isinstance(block_to_update['properties'][prop], list) and len(block_to_update['properties'][prop]) > 1: - pass - elif isinstance(block_to_update['properties'][prop], list) and len(block_to_update['properties'][prop]) == 0: - # empty dictionary - del block_to_update['properties'][prop] - elif isinstance(block_to_update['properties'][prop], dict): - if block_to_update['properties'][prop]['uid'] == 0 and block_to_update['properties'][prop]['name'] is None: - # delete prop - del block_to_update['properties'][prop] - elif block_to_update['properties'][prop] is None: - del block_to_update['properties'][prop] - - ''' - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s create cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - ''' - - if not dryrun and need_to_create is True: - sid_create_user(diego, fqdn, res_rw_user, user, block_to_update, verify=verify, error_stop=error_stop) - - # New action : Add any new user into their corresponding EC LDAP group. - # Warn : Only impact currently existent group. - sid_associate_user_to_group(diego, user, ec_ldap_sid_results, scrat, logger) - - elif not dryrun and need_to_update is True: - # New workaround : Do not touch "active" scheduler until next design (it is a broken update for them). - if user not in approver_scheduler_list: - sid_update_user(diego, fqdn, res_rw_user, user, block_to_update, verify=verify, error_stop=error_stop) - - # Action : Add any new user into their corresponding EC LDAP group. - # Warn : Only impact currently existent group. - sid_associate_user_to_group(diego, user, ec_ldap_sid_results, scrat, logger) - else: - logger.debug('dryrun') - to_print = pformat(block_to_update) - for i in list(range(0, int(round(len(to_print) / 250)) + 1)): - logger.info('scrat %s cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) - - logger.info('Finished Synchronization') - sys.exit(0) - - params = {} - sid_s_results = diego.diego_run_dieget_by_name('sid_sheduler_check', params) - for user in sid_s_results[1]: - if user in devnull_del_user: - continue - if user not in sid_need_scheduler or user not in approver_scheduler_list: - logger.error('SID user ' + user + ' should not be an scheduler.') - if not dryrun: - if user in sid_results[1] : - sid_update_user_exlude_approver_scheduler_change_management(diego, fqdn, res_rw_user, user, sid_results[1][user]['uid'], 'scheduler') - #pass - else: - logger.error('dry run, user not removed from the scheduler role.') - continue - - print(sid_need_scheduler, "SCHEDULERS-LIST") - for user in sid_need_scheduler: - if user in devnull_user: - continue - need_to_create = False - need_to_update = False - if user in sid_s_results[1]: - need_to_update = True - - elif user not in sid_s_results[1]: - need_to_create = True - logger.debug('SID user ' + user + ' should be addded to scheduler.') - #create the relation if not exists - - if not dryrun : - sid_create_update_user_approver_scheduler_change_management(diego, fqdn, res_rw_user, user, sid_results[1][user]['uid'], 'scheduler', need_to_update, verify=verify, error_stop=error_stop) - #pass - else: - logger.error('dry run, user not add/update from the scheduler role in "has as act"') - continue - - params = {} - sid_a_results = diego.diego_run_dieget_by_name('sid_approver_check', params) - for user in sid_a_results[1]: - if user in devnull_del_user: - continue - if user not in sid_need_approver or user not in approver_scheduler_list: - logger.error('SID user ' + user + ' should not be an approver.') - if not dryrun : - if user in sid_results[1] : - sid_update_user_exlude_approver_scheduler_change_management(diego, fqdn, res_rw_user, user, sid_results[1][user]['uid'], 'approver', verify=verify, error_stop=error_stop) - else: - logger.error('dry run, user not removed from the approver role.') - continue - - print(sid_need_approver, "APRROVERS-LIST") - for user in sid_need_approver: - if user in devnull_user: - continue - need_to_create = False - need_to_update = False - if user in sid_a_results[1]: - need_to_update = True - - elif user not in sid_a_results[1]: - need_to_create = True - logger.debug('SID user ' + user + ' should be addded to approver.') - - #create the relation if not exists - if not dryrun: - sid_create_update_user_approver_scheduler_change_management(diego, fqdn, res_rw_user, user, sid_results[1][user]['uid'], 'approver', need_to_update, verify=verify, error_stop=error_stop) - else: - logger.error('dry run, user not add/update from the approver role in "has as act".') - continue - ''' - * scrat department - DIGIT.C.4.006 is a departement - --> has as member - ''' - - for department in departments: - params = {'name': department} - sid_d_results = diego.diego_run_dieget_by_name('sid_department_check', params) - logger.info(sid_d_results[1]) - - if 'has as member' in sid_d_results[1][department] and sid_d_results[1][department]['has as member'] is not None: - if not isinstance(sid_d_results[1][department]['has as member'], list): - # This is not a list, so this is a single value: - t = sid_d_results[1][department]['has as member'] - sid_d_results[1][department]['has as member'] = list() - sid_d_results[1][department]['has as member'].append(t) - logger.info(sid_d_results[1]) - - for user in sid_d_results[1][department]['has as member']: - if user in devnull_del_user: - logger.debug("Skipping the user in the dev_null:" + user) - continue - if user not in snet_account_index: - logger.error('SID user ' + user + ' should be deleted. Need to ask SEE ?') - - for user in snet_account_index: - if user in devnull_user: - continue - if 'departmentNumber' in ec_results['users'][user] and ec_results['users'][user]['departmentNumber'] != department: - continue - if 'has as member' in sid_d_results[1][department] and sid_d_results[1][department]['has as member'] is not None and user not in sid_d_results[1][department]['has as member']: - logger.info('SID user ' + user + ' should be addded to department ' + department + '.') - if not dryrun: - logger.info('dryrun') - continue - sid_add_user_to_department(diego, fqdn, res_rw_user, user, sid_d_results[1]['DIGIT.C.4.006']['uid'], department, verify=verify, error_stop=error_stop) - else: - logger.info('dryrun') - - -if __name__ == '__main__': - main() diff --git a/bin/synchronize_home_Users.pl b/bin/synchronize_home_Users.pl deleted file mode 100755 index 139252a..0000000 --- a/bin/synchronize_home_Users.pl +++ /dev/null @@ -1,422 +0,0 @@ -#!/usr/bin/perl - -# ------------------------------------------------------------------------------ -# $Id$ -# -# ------------------------------------------------------------------------------ - -use strict; -use warnings; -use Getopt::Long; -use Data::Dumper; -use Config::IniFiles; -use Net::LDAP; -use File::Copy; -use File::Basename; -use Sys::Hostname; -use Cwd; -#use Net::OpenSSH::Compat 'Net::SSH2'; - -# unbuffered output: -$| = 1; - -use lib ( new Config::IniFiles( -file => "/opt/etc/ini/global.ini" )->val( 'APPLICATION', 'LIBRARY' ) ); - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} - -use SNET::common; -use SNET::snmpd; -use SNET::LdapNS qw(:all); -#use SNET::SSHDeviceInterfacer::Linux; - -use vars qw($verbose $debug $help $force $cli_mode $dry_run ); -$verbose = 0; -$debug = 0; -$cli_mode = 1; - -my $PROGNAME = basename( $0 ); -$PROGNAME =~ s/\.p[lm]$//; - -my %options = ( - "help" => \$help, - "debug" => \$debug, - "verbose" => \$verbose, - "force" => \$force, - "dry-run" => \$dry_run, -); - -my $SNMP_ENTERPRISEOID = "99"; -my $SNMP_OID = "1.3.6.1.4.1.99999.$SNMP_ENTERPRISEOID"; -my $SNMP_GEN = "6"; -my $SNMP_SPE = "1"; -my $msg = ''; -my $title = "Cacti ImportUser"; - -help() if !GetOptions( %options ) or $help; -$verbose = 1 if $debug; - -# ldap_find_users_and_groups() -# -# Read users and groups from SNet LDAP. - -sub ldap_find_users_and_groups ($$$$$$$$$$) -{ - my ( - $cfg_ldap_server, $cfg_ldap_user, $cfg_ldap_passwd, $cfg_ldap_group_search, $cfg_ldap_search_scope, - $cfg_ldap_group_search_filter, $cfg_ldap_group_attribute, $cfg_ldap_groupname, $hostname, $cfg_ldap_cafile - ) = @_; - - my %users; - - # Connect to the LDAP server - metaprint( 'verbose', "Initiating connection to LDAP server <$cfg_ldap_server>:" ) if $verbose; - my $ldap = Net::LDAP->new( - $cfg_ldap_server, - async => 0, - onerror => ( - ( $debug == 0 ) ? sub { return $_[0] } : sub { - my $message = shift; - my $error = defined( $message->error_desc ) ? $message->error_desc : $message->error(); - $msg = "Ldap: Unable to process request: $error."; - metaprint( 'error', $title . ": " . $msg ); - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - return $message; - } - ), - ); - if ( !$ldap ) { - $msg = "LDAP connection to <$cfg_ldap_server> failed."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - metaprint( 'verbose', "* LDAP connection completed successfully." ) if $verbose; - - my $message; - eval { - print STDERR 'Starting tls' . "\n" if ( $debug ); - $message = $ldap->start_tls( verify => 'require', - cafile => $cfg_ldap_cafile, ); - if ( $message->is_error() ) { - $msg = "Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - }; - if ( $@ ) { - $msg = "Crash - Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - eval { - print STDERR 'binding' . "\n" if ( $debug ); - $message = $ldap->bind( - $cfg_ldap_user, - password => $cfg_ldap_passwd, - version => 3, - ); - if ( $message->is_error() ) { - $msg = "LDAP bind error occurred."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - }; - if ( $@ ) { - $msg = "Crash - LDAP bind error occurred ('" . $message->error_name . "')."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - metaprint( 'verbose', "* LDAP bind operation completed successfully." ) if $verbose; - - # Search AD for objects in a particular group using LDAP - - metaprint( 'info', "Getting the LDAP member with expiration." ) if $verbose; - my %searchargs; - $searchargs{base} = 'ou=posix,' . $cfg_ldap_group_search; - $searchargs{scope} = $cfg_ldap_search_scope; - $searchargs{filter} = $cfg_ldap_group_search_filter; - $searchargs{attrs} = $cfg_ldap_group_attribute; - - print Dumper( \%searchargs ) if $verbose; - - my $results; - eval { $results = $ldap->search( %searchargs ); }; - if ( $@ ) { - my $title = "Check Password"; - my $msg = "Crash - LDAP Users Search."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); - } elsif ( $results->count() == 0 ) { - metaprint( 'error', 'no result' ); - } else { - metaprint( 'verbose', "* Search returned " . $results->count . " object." ) if $verbose; - print Dumper( $results->as_struct() ) if $verbose; - my $ldap_hash = $results->as_struct(); - - my $attribute = $searchargs{attrs}[0]; - if ( defined( $ldap_hash->{ "cn=$cfg_ldap_groupname," . $searchargs{base} }{$attribute} ) ) { - foreach my $url ( @{ $ldap_hash->{ "cn=$cfg_ldap_groupname," . $searchargs{base} }{$attribute} } ) { - - print "$url\n" if $verbose; - push( @{ $users{$url}{'groups'} }, $cfg_ldap_groupname ); - - # fetch the user gecos - my %usersearch; - $usersearch{base} = $cfg_ldap_group_search; - $usersearch{base} =~ s/groups/people/; - $usersearch{attrs} = [ 'gecos', 'uid' ]; - $usersearch{scope} = 'sub'; - $usersearch{filter} = '(&(objectClass=posixAccount)(uid=' . $url . '))'; - print Dumper( \%usersearch ) if $verbose; - - my $userresults; - eval { $userresults = $ldap->search( %usersearch ); }; - if ( $@ ) { - my $title = "Check Password"; - my $msg = "Crash - LDAP Mail Users Search."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - if ( $userresults->is_error() ) { - metaprint( 'error', 'search failed: ' . $userresults->error_text ); - metaprint( 'error', 'search failed: ' . $userresults->code ); - metaprint( 'error', 'search failed: ' . $userresults->error ); - } elsif ( $userresults->count() == 0 ) { - metaprint( 'error', 'no result' ); - } else { - metaprint( 'info', "* Search returned " . $userresults->count . " url for '$url'." ) if $verbose; - print Dumper ( $userresults ) if $verbose; - - foreach my $uid ( $userresults->entries ) { - print "'" . $uid->get_value( 'uid' ) . "'\n" if $verbose; - if ( !defined( $uid->get_value( 'gecos' ) ) ) { - $users{ $uid->get_value( 'uid' ) } = ''; - } else { - $users{ $uid->get_value( 'uid' ) }{'gecos'} = $uid->get_value( 'gecos' ); - } - } - } - - } - } else { - metaprint( 'error', "Could not parse the hash result: {" . "cn=$cfg_ldap_groupname," . $searchargs{base} . "} { " . $attribute . " }" ); - } - } - - print "\nClosing LDAP connection.\n" if $verbose; - $ldap->unbind; - return %users; -} - -# -# Global Declarations -# -# load the INI -metaprint( "info", "Loading INI file Parameters" ); -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -my $CiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'RME' ) ); -metaprint( "error", "error value of CiniFile is undefined" ) if ( !defined( $CiniFile ) ); - -my $outpath = $CiniFile->val( 'GLOBAL', 'OUTPATH' ); -metaprint( "error", "The defined outpath is not valid, please correct-it" ) if ( !defined( $outpath ) ); - -my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); -metaprint( "error", "error value of AiniFile is undefined" ) if ( !defined( $AiniFile ) ); - -my $cfg_ldap_server = $AiniFile->val( 'LDAP_SNET_NG', 'SERVER' ); -metaprint( "error", "error value of cfg_ldap_server is undefined" ) if ( !defined( $cfg_ldap_server ) ); -my $cfg_ldap_user = $AiniFile->val( 'LDAP_SNET_NG', 'USER' ); -metaprint( "error", "error value of cfg_ldap_user is undefined" ) if ( !defined( $cfg_ldap_user ) ); -my $cfg_ldap_passwd = $AiniFile->val( 'LDAP_SNET_NG', 'PASSWORD' ); -metaprint( "error", "error value of cfg_ldap_passwd is undefined" ) if ( !defined( $cfg_ldap_passwd ) ); -my $cfg_ldap_group_search = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_SEARCH' ); -metaprint( "error", "error value of cfg_ldap_group_search is undefined" ) if ( !defined( $cfg_ldap_group_search ) ); -my $cfg_ldap_group_search_filter = $AiniFile->val( 'LDAP_SNET_NG', 'FILTER' ); -metaprint( "error", "error value of cfg_ldap_group_search_filter is undefined" ) if ( !defined( $cfg_ldap_group_search_filter ) ); -$cfg_ldap_group_search_filter = "(&(objectclass=posixGroup)(cn=REPLACE))"; -my $cfg_ldap_group_attribute = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_ATTRIBUTE' ); -metaprint( "error", "error value of cfg_ldap_group_attribute is undefined" ) if ( !defined( $cfg_ldap_group_attribute ) ); -$cfg_ldap_group_attribute = ["memberuid"]; -my $cfg_ldap_search_scope = $AiniFile->val( 'LDAP_SNET_NG', 'SEARCH_SCOPE' ); -metaprint( "error", "error value of cfg_ldap_search_scope is undefined" ) if ( !defined( $cfg_ldap_search_scope ) ); -my $cfg_ldap_cafile = $AiniFile->val( 'LDAP_SNET_NG', 'CA' ); -metaprint( "error", "error value of cfg_ldap_cafile is undefined" ) if ( !defined( $cfg_ldap_cafile ) ); - -# vSHARE credentails configuration -my $LiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'RME' ) ); -metaprint( "error", "error value of LiniFile is undefined" ) if ( !defined( $LiniFile ) ); -my $vshare_servers = $LiniFile->val( 'vshare', 'SERVERS' ); -metaprint( "error", "error value of vshare_servers is undefined" ) if ( !defined( $vshare_servers ) ); -my $vshare_user = $LiniFile->val( 'vshare', 'USER' ); -metaprint( "error", "error value of vshare_user is undefined" ) if ( !defined( $vshare_user ) ); -my $vshare_passwd = $LiniFile->val( 'vshare', 'PASSWD' ); -metaprint( "error", "error value of vshare_passwd is undefined" ) if ( !defined( $vshare_passwd ) ); - -my @filters; -push( @filters, 'com' ); -push( @filters, 'mgt' ); -push( @filters, 'net' ); -push( @filters, 'pi' ); -push( @filters, 'pm' ); -push( @filters, 'sd' ); -push( @filters, 'sec' ); -push( @filters, 'sup' ); -push( @filters, 'tda' ); -push( @filters, 'officials' ); - -my $hostname = hostname(); - -# Main Application -metaprint( "info", "Starting users synchro" ); - -my $errors = 0; - -my $already_defined_users = {}; -my $ssh; -my $out; - -metaprint( 'info', "processing vshare servers..." ); -foreach my $server ( split( /,/, $vshare_servers ) ) { - - # SSH to server. - metaprint 'info', 'Working on ' . $server . '...'; - $ssh = new SNET::SSHDeviceInterfacer::Linux( $debug, $server, $vshare_user, $vshare_passwd ); - if ( !$cli_mode ) { - $ssh->set_webmode( 1 ); - } - - if ( $ssh->openSSHConnection() ) { - metaprint 'info', "-> ok connected"; - } else { - metaprint 'error', "-> connection failed"; - $errors++; - next; - } - - my $cln = (); - $cln->{'uid'} = 3; - $cln->{'gid'} = 4; - $cln->{'name'} = 9; - - $out = $ssh->sendCMD( "/bin/ls -aildn /opt/home/*" ); - if ( $out =~ m/\s\/opt\/home\/\w+/i ) { - foreach my $line ( split( /\n/, $out ) ) { - chomp $line; - next if ( $line =~ /ls -aildn/ ); - next if ( $line =~ /\/export\/home\/snet/ ); - next if ( $line =~ /lost\+found/ ); - $line =~ s/^\s*//; - print Dumper ( $line ) if $debug; - - my $tmp = (); - @$tmp = split( /\s+/, $line ); - $tmp->[ $cln->{'name'} ] =~ s/\/*$//g; - $tmp->[ $cln->{'name'} ] =~ s/^\/.*\///; - print Dumper ( $tmp ) if $debug; - - # 3 : uid - # 4 : gid - # 9 : name - foreach my $pos ( keys %$cln ) { - $already_defined_users->{ $tmp->[ $cln->{'name'} ] }{$pos} = $tmp->[ $cln->{$pos} ]; - } - } - last; - } else { - $errors++; - next; - } - -} - -if ( $errors ) { - metaprint( 'error', "Some errors have been found, please contact SS Team!" . nl() . "Please copy/paste the output to the email!" ); - exit 1; -} - -#Print Users from Cacti -print Dumper ( $already_defined_users ) if $verbose; - -# -- Create the import file -my $cpt = 0; -my $cpt_del = 0; - -foreach my $filter ( @filters ) { - - metaprint "info", "Checking groups '$filter'."; - my $cfg_ldap_group_search_f = $cfg_ldap_group_search_filter; - $cfg_ldap_group_search_f =~ s/REPLACE/$filter/; - print "$cfg_ldap_group_search_f\n" if $verbose; - my %ldap_users = ldap_find_users_and_groups( $cfg_ldap_server, $cfg_ldap_user, $cfg_ldap_passwd, $cfg_ldap_group_search, $cfg_ldap_search_scope, - $cfg_ldap_group_search_f, $cfg_ldap_group_attribute, $filter, $hostname, $cfg_ldap_cafile ); - - print Dumper ( \%ldap_users ) if $verbose; - - foreach my $u ( keys %ldap_users ) { - if ( defined( $already_defined_users->{$u} ) && ( $already_defined_users->{$u} ) ) { - metaprint( "info", "Skipping user $u import, user is already defined, but user need to be checked." ) if $verbose; - - # TODO check uid:gid - $already_defined_users->{$u}{'found'} = 1; - next; - } - - next if ( $ldap_users{$u} =~ /^$/ ); - my $cmd = "sudo mkdir /mnt/home/$u && sudo chown $u:snmc /mnt/home/$u"; - metaprint( "info", "$u need to be created: '$cmd'." ); - if ( !$dry_run ) { - eval { $out = $ssh->sendCMD( $cmd ); }; - if ( $out =~ m/password/i ) { - $out = $ssh->sendCMD( $vshare_passwd ); - } - print $out; - } - $cpt++; - } -} - -my $local_user_no_del = (); -$local_user_no_del->{'snet'} = 1; -$local_user_no_del->{'quotas'} = 1; -$local_user_no_del->{'casuser'} = 1; -# $local_user_no_del->{'ns-alogin'} = 1; - -metaprint "info", "Checking all others vshare home directory users defined."; -foreach my $u ( keys %$already_defined_users ) { - if ( defined( $already_defined_users->{$u} ) - && ( $already_defined_users->{$u} ) - && defined( $already_defined_users->{$u}{'found'} ) - && ( $already_defined_users->{$u}{'found'} ) ) { - next; - } elsif ( defined( $local_user_no_del->{$u} ) ) { - next; - } else { - metaprint( "error", "User $u need to be deleted manually." ); - metaprint( "error", "MANUAL: sudo tar -jcf /mnt/home/_OLD/$u.tbz /mnt/home/$u ; sudo rm -rf /mnt/home/$u" ); - $cpt_del++; - } -} -eval { $out = $ssh->sendCMD( "exit" ); }; - -metaprint( "info", "$cpt user(s) created." ); -metaprint( "info", "$cpt_del user(s) need to be deleted." ); -metaprint( "info", "--- Process Done ---" ); -exit( 0 ); diff --git a/bin/synchronize_proteus_Users.pl b/bin/synchronize_proteus_Users.pl deleted file mode 100755 index f2f54b4..0000000 --- a/bin/synchronize_proteus_Users.pl +++ /dev/null @@ -1,567 +0,0 @@ -#!/usr/bin/perl - -# ------------------------------------------------------------------------------ -# $Id$ -# -# ------------------------------------------------------------------------------ - -use strict; -use warnings; -use Getopt::Long; -use Data::Dumper; -use Config::IniFiles; -use Net::LDAP; -use File::Copy; -use File::Basename; -use Sys::Hostname; -use Sys::Hostname::Long; - -use IO::Socket::SSL; - -no if $] >= 5.017011, warnings => 'experimental::smartmatch'; - -my $SERVER = 'SERVER'; -if ( $] eq '5.020002' ) { - - # jessie - $SERVER = 'SERVER'; -} else { - $SERVER = 'SERVER_PROXY'; - - # set some variables in order to disable SSL certificate check due to stunnel - $ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0; - $ENV{HTTPS_DEBUG} = 1; - IO::Socket::SSL::set_ctx_defaults( SSL_verifycn_scheme => 'www', - SSL_verify_mode => 0 ); -} - -# unbuffered output: -$| = 1; - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} - -use SNET::common; -use SNET::snmpd; -use SNET::LdapNS qw(:all); -use SNET::libsoap; -## load the Proteus API -use Proteus::API; -use Proteus::SNET; - -use vars qw($verbose $debug $help $script $cli_mode $force $dry_run ); -$verbose = 0; -$debug = 0; -$cli_mode = 1; - -my $PROGNAME = basename( $0 ); -$PROGNAME =~ s/\.p[lm]$//; -( $script ) = split( /\./, basename( $0 ) ); -my $hostname = hostname(); -my $fqdn = hostname_long(); - -my %options = ( - "help" => \$help, - "debug" => \$debug, - "verbose" => \$verbose, - "force" => \$force, - "dry-run" => \$dry_run, -); - -my $SNMP_ENTERPRISEOID = "99"; -my $SNMP_OID = "1.3.6.1.4.1.99999.$SNMP_ENTERPRISEOID"; -my $SNMP_GEN = "6"; -my $SNMP_SPE = "1"; -my $msg = ''; -my $title = "Proteus ImportUser"; - -help() if !GetOptions( %options ) or $help; -$verbose = 1 if $debug; - -# ldap_find_users_and_groups() -# -# Read users and groups from SNet LDAP. - -sub ldap_find_users_and_groups ($$$$$$$$$$) -{ - my ( - $cfg_ldap_server, $cfg_ldap_user, $cfg_ldap_passwd, $cfg_ldap_group_search, $cfg_ldap_search_scope, - $cfg_ldap_group_search_filter, $cfg_ldap_group_attribute, $cfg_ldap_groupname, $hostname, $cfg_ldap_cafile - ) = @_; - - my %users; - - # Connect to the LDAP server - metaprint( 'verbose', "Initiating connection to LDAP server <$cfg_ldap_server>:" ) if $verbose; - my $ldap = Net::LDAP->new( - $cfg_ldap_server, - async => 0, - onerror => ( - ( $debug == 0 ) ? sub { return $_[0] } : sub { - my $message = shift; - my $error = defined( $message->error_desc ) ? $message->error_desc : $message->error(); - $msg = "Ldap: Unable to process request: $error."; - metaprint( 'error', $title . ": " . $msg ); - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - return $message; - } - ), - ); - if ( !$ldap ) { - $msg = "LDAP connection to <$cfg_ldap_server> failed."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - metaprint( 'verbose', "* LDAP connection completed successfully." ) if $verbose; - - my $message; - eval { - print STDERR 'Starting tls' . "\n" if ( $debug ); - $message = $ldap->start_tls( verify => 'require', - cafile => $cfg_ldap_cafile, ); - if ( $message->is_error() ) { - $msg = "Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - }; - if ( $@ ) { - $msg = "Crash - Could not encrypt LDAP connection."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - eval { - print STDERR 'binding' . "\n" if ( $debug ); - $message = $ldap->bind( - $cfg_ldap_user, - password => $cfg_ldap_passwd, - version => 3, - ); - if ( $message->is_error() ) { - $msg = "LDAP bind error occurred."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - }; - if ( $@ ) { - $msg = "Crash - LDAP bind error occurred ('" . $message->error_name . "')."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - metaprint( 'verbose', "* LDAP bind operation completed successfully." ) if $verbose; - - # Search AD for objects in a particular group using LDAP - - metaprint( 'info', "Getting the LDAP member with expiration." ) if $verbose; - my %searchargs; - $searchargs{base} = 'ou=posix,' . $cfg_ldap_group_search; - $searchargs{scope} = $cfg_ldap_search_scope; - $searchargs{filter} = $cfg_ldap_group_search_filter; - $searchargs{attrs} = $cfg_ldap_group_attribute; - - print Dumper( \%searchargs ) if $verbose; - - my $results; - eval { $results = $ldap->search( %searchargs ); }; - if ( $@ ) { - my $title = "Check Password"; - my $msg = "Crash - LDAP Users Search."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - - if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); - } elsif ( $results->count() == 0 ) { - metaprint( 'error', 'no result' ); - } else { - metaprint( 'verbose', "* Search returned " . $results->count . " object." ) if $verbose; - print Dumper( $results->as_struct() ) if $verbose; - my $ldap_hash = $results->as_struct(); - - my $attribute = $searchargs{attrs}[0]; - if ( defined( $ldap_hash->{ "cn=$cfg_ldap_groupname," . $searchargs{base} }{$attribute} ) ) { - foreach my $url ( @{ $ldap_hash->{ "cn=$cfg_ldap_groupname," . $searchargs{base} }{$attribute} } ) { - - print "$url\n" if $verbose; - push( @{ $users{$url}{'groups'} }, $cfg_ldap_groupname ); - - # fetch the user gecos - my %usersearch; - $usersearch{base} = $cfg_ldap_group_search; - $usersearch{base} =~ s/groups/people/; - $usersearch{attrs} = [ 'gecos', 'uid', 'mail' ]; - $usersearch{scope} = 'sub'; - $usersearch{filter} = '(&(objectClass=posixAccount)(uid=' . $url . '))'; - print Dumper( \%usersearch ) if $verbose; - - my $userresults; - eval { $userresults = $ldap->search( %usersearch ); }; - if ( $@ ) { - my $title = "Check Password"; - my $msg = "Crash - LDAP Mail Users Search."; - metaprint( 'error', $title . ": " . $msg ) if $verbose; - snmp_trap_send_multi_vars( $SNMP_OID, $SNMP_GEN, $SNMP_SPE, [ $hostname, $title, $msg ] ); - exit 1; - } - if ( $userresults->is_error() ) { - metaprint( 'error', 'search failed: ' . $userresults->error_text ); - metaprint( 'error', 'search failed: ' . $userresults->code ); - metaprint( 'error', 'search failed: ' . $userresults->error ); - } elsif ( $userresults->count() == 0 ) { - metaprint( 'error', 'no result' ); - } else { - metaprint( 'info', "* Search returned " . $userresults->count . " url for '$url'." ) if $verbose; - print Dumper ( $userresults ) if $verbose; - - foreach my $uid ( $userresults->entries ) { - print "'" . $uid->get_value( 'uid' ) . "'\n" if $verbose; - if ( !defined( $uid->get_value( 'gecos' ) ) ) { - $users{ $uid->get_value( 'uid' ) } = ''; - } else { - $users{ $uid->get_value( 'uid' ) }{'gecos'} = $uid->get_value( 'gecos' ); - } - if ( !defined( $uid->get_value( 'mail' ) ) ) { - $users{ $uid->get_value( 'uid' ) } = ''; - } else { - $users{ $uid->get_value( 'uid' ) }{'mail'} = $uid->get_value( 'mail' ); - } - } - } - } - } else { - metaprint( 'error', "Could not parse the hash result: {" . "cn=$cfg_ldap_groupname," . $searchargs{base} . "} { " . $attribute . " }" ); - } - } - - print "\nClosing LDAP connection.\n" if $verbose; - $ldap->unbind; - return %users; -} - -# -# Global Declarations -# -# load the INI -metaprint( "info", "Loading INI file Parameters" ); -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -my $CiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'RME' ) ); -metaprint( "error", "error value of CiniFile is undefined" ) if ( !defined( $CiniFile ) ); - -my $outpath = $CiniFile->val( 'GLOBAL', 'OUTPATH' ); -metaprint( "error", "The defined outpath is not valid, please correct-it" ) if ( !defined( $outpath ) ); - -my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); -metaprint( "error", "error value of AiniFile is undefined" ) if ( !defined( $AiniFile ) ); - -my $cfg_ldap_server = $AiniFile->val( 'LDAP_SNET_NG', 'SERVER' ); -metaprint( "error", "error value of cfg_ldap_server is undefined" ) if ( !defined( $cfg_ldap_server ) ); -my $cfg_ldap_user = $AiniFile->val( 'LDAP_SNET_NG', 'USER' ); -metaprint( "error", "error value of cfg_ldap_user is undefined" ) if ( !defined( $cfg_ldap_user ) ); -my $cfg_ldap_passwd = $AiniFile->val( 'LDAP_SNET_NG', 'PASSWORD' ); -metaprint( "error", "error value of cfg_ldap_passwd is undefined" ) if ( !defined( $cfg_ldap_passwd ) ); -my $cfg_ldap_group_search = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_SEARCH' ); -metaprint( "error", "error value of cfg_ldap_group_search is undefined" ) if ( !defined( $cfg_ldap_group_search ) ); -my $cfg_ldap_group_search_filter = $AiniFile->val( 'LDAP_SNET_NG', 'FILTER' ); -metaprint( "error", "error value of cfg_ldap_group_search_filter is undefined" ) if ( !defined( $cfg_ldap_group_search_filter ) ); -$cfg_ldap_group_search_filter = "(&(objectclass=posixGroup)(cn=REPLACE))"; -my $cfg_ldap_group_attribute = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_ATTRIBUTE' ); -metaprint( "error", "error value of cfg_ldap_group_attribute is undefined" ) if ( !defined( $cfg_ldap_group_attribute ) ); -$cfg_ldap_group_attribute = ["memberuid"]; -my $cfg_ldap_search_scope = $AiniFile->val( 'LDAP_SNET_NG', 'SEARCH_SCOPE' ); -metaprint( "error", "error value of cfg_ldap_search_scope is undefined" ) if ( !defined( $cfg_ldap_search_scope ) ); -my $cfg_ldap_cafile = $AiniFile->val( 'LDAP_SNET_NG', 'CA' ); -metaprint( "error", "error value of cfg_ldap_cafile is undefined" ) if ( !defined( $cfg_ldap_cafile ) ); - -my $PiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'Proteus' ) ); -print "error value of PiniFile is undefined" if ( !defined( $PiniFile ) ); - -# Proteus SOAP credentials -my $proteusUser = $PiniFile->val( 'PROTEUS_SOAP', 'USER' ); -print "error value of proteusUser is undefined" if ( !defined( $proteusUser ) ); -my $proteusPass = $PiniFile->val( 'PROTEUS_SOAP', 'PASSWORD' ); -print "error value of proteusPass is undefined" if ( !defined( $proteusPass ) ); -my $proteusServer = $PiniFile->val( 'PROTEUS_SOAP', $SERVER ); -print "error value of proteusDbServer is undefined" if ( !defined( $proteusServer ) ); -my $Proteus_cfg_name = $PiniFile->val( 'GLOBAL', 'CONFIG' ); -print "error value of Proteus_cfg_name is undefined" if ( !defined( $Proteus_cfg_name ) ); - -my @filters; -push( @filters, 'com' ); -push( @filters, 'mgt' ); -push( @filters, 'net' ); -push( @filters, 'pi' ); -push( @filters, 'pm' ); -push( @filters, 'sd' ); -push( @filters, 'sec' ); -push( @filters, 'sup' ); -push( @filters, 'tda' ); -push( @filters, 'officials' ); - -my %attr; -$attr{'mgt'} = 'snmc'; -$attr{'net'} = 'snmc'; -$attr{'pi'} = 'snmc'; -$attr{'sd'} = 'snmc'; -$attr{'sec'} = 'snmc'; -$attr{'sup'} = 'snmc'; -$attr{'tda'} = 'snmc'; -# -$attr{'pm'} = 'cn=pm,ou=posix,ou=groups,ou=SNet,ou=snmc,o=DIGIT,dc=ec,dc=europa,dc=eu'; -$attr{'com'} = 'cn=com,ou=posix,ou=groups,ou=SNet,ou=snmc,o=DIGIT,dc=ec,dc=europa,dc=eu'; -$attr{'officials'} = 'cn=officials,ou=posix,ou=groups,ou=SNet,ou=snmc,o=DIGIT,dc=ec,dc=europa,dc=eu'; - -my $local_jrc = (); -$local_jrc->{'bossifa'} = 1; -$local_jrc->{'cacerja'} = 1; -$local_jrc->{'ceccman'} = 1; -$local_jrc->{'fotisva'} = 1; -$local_jrc->{'gysenpa'} = 1; -$local_jrc->{'meysjoh'} = 1; -$local_jrc->{'michojm'} = 1; -$local_jrc->{'peizean'} = 1; -$local_jrc->{'sowaraf'} = 1; -$local_jrc->{'tomasje'} = 1; -$local_jrc->{'torreja'} = 1; -$local_jrc->{'vegthan'} = 1; -$local_jrc->{'watkipr'} = 1; -$local_jrc->{'wawakfa'} = 1; - -my $autogroup = (); -$autogroup->{'officials'} = 1; -$autogroup->{'com'} = 1; -$autogroup->{'pm'} = 1; - -my $authlocal = (); -$authlocal->{'admin'} = 1; -$authlocal->{'snet'} = 1; -$authlocal->{'dave'} = 1; - -my $hostname = hostname(); - -# my $proteus_uid = (); - -=head2 initialise soap and SQL handlers - -Etablished the SOAP connection needed to connect to all the data. - -=cut - -# initiallise the SOAP connection : -my $service = soap_connect( $proteusServer, $proteusUser, $proteusPass ); - -if ( !$service ) { - metaprint( 'info', "Soap connection errors" ); - exit 1; -} - -# # get group id -# foreach my $a ( keys %attr ) { -# if ( !defined( $proteus_uid->{ $attr{$a} } ) ) { -# $proteus_uid->{$a} = soap_get_group( $service, $attr{$a} ); -# $proteus_uid->{ $attr{$a} } = $proteus_uid->{$a}; -# } -# } -# $proteus_uid->{'alogin'} = soap_get_user( $service, 'alogin' ); -# -# metaprint( 'info', "proteus_uid:" . Dumper( $proteus_uid ) ); - -# Main Application -metaprint( "info", "Starting users synchro" ); - -my $already_defined_users = (); -my $already_defined_auth = (); -my $already_defined_group = (); - -# get all existing ldap (up to 100) -my $proteus_authenticator; -eval { - @$proteus_authenticator = $service->getEntities( - SOAP::Data->type( 'long' )->name( 'parentId' )->value( 0 )->attr( { xmlns => '' } ), - SOAP::Data->type( 'string' )->name( 'type' )->value( ObjectTypes::LDAP )->attr( { xmlns => '' } ), - SOAP::Data->type( 'int' )->name( 'start' )->value( 0 )->attr( { xmlns => '' } ), - SOAP::Data->type( 'int' )->name( 'count' )->value( 100 )->attr( { xmlns => '' } ) - )->valueof( '//getEntitiesResponse/return/item' ); -}; - -if ( ( $@ ) || !defined( $proteus_authenticator ) ) { - print "get all users failed: " . Dumper( $@ ); -} else { - print Dumper ( $proteus_authenticator ) if ( $debug ); - - # list configurations - foreach my $eachConfiguration ( @$proteus_authenticator ) { - my $obj = Service->blessAPIEntity( "object" => $eachConfiguration ); - my $tmp_name = $obj->get_name(); - $already_defined_auth->{$tmp_name}{'properties'} = $obj->get_properties(); - $already_defined_auth->{$tmp_name}{'id'} = $obj->get_id(); - } -} - -print Dumper ( $already_defined_auth ); - -# get all existing group (up to 10) -my $proteus_group; -eval { - @$proteus_group = $service->getEntities( - SOAP::Data->type( 'long' )->name( 'parentId' )->value( 0 )->attr( { xmlns => '' } ), - SOAP::Data->type( 'string' )->name( 'type' )->value( ObjectTypes::UserGroup )->attr( { xmlns => '' } ), - SOAP::Data->type( 'int' )->name( 'start' )->value( 0 )->attr( { xmlns => '' } ), - SOAP::Data->type( 'int' )->name( 'count' )->value( 100 )->attr( { xmlns => '' } ) - )->valueof( '//getEntitiesResponse/return/item' ); -}; - -if ( ( $@ ) || !defined( $proteus_group ) ) { - print "get all groups failed: " . Dumper( $@ ); -} else { - print Dumper ( $proteus_group ) if ( $debug ); - - # list configurations - foreach my $eachConfiguration ( @$proteus_group ) { - my $obj = Service->blessAPIEntity( "object" => $eachConfiguration ); - my $tmp_name = $obj->get_name(); - $already_defined_group->{$tmp_name}{'properties'} = $obj->get_properties(); - $already_defined_group->{$tmp_name}{'id'} = $obj->get_id(); - } -} - -print Dumper ( $already_defined_group ); - -# get all existing user (up to 10) -my $configurations; -eval { - @$configurations = $service->getEntities( - SOAP::Data->type( 'long' )->name( 'parentId' )->value( 0 )->attr( { xmlns => '' } ), - SOAP::Data->type( 'string' )->name( 'type' )->value( ObjectTypes::User )->attr( { xmlns => '' } ), - SOAP::Data->type( 'int' )->name( 'start' )->value( 0 )->attr( { xmlns => '' } ), - SOAP::Data->type( 'int' )->name( 'count' )->value( 100 )->attr( { xmlns => '' } ) - )->valueof( '//getEntitiesResponse/return/item' ); -}; - -if ( ( $@ ) || !defined( $configurations ) ) { - print "get all users failed: " . Dumper( $@ ); -} else { - print Dumper ( $configurations ) if ( $debug ); - - # list configurations - foreach my $eachConfiguration ( @$configurations ) { - my $obj = Service->blessAPIEntity( "object" => $eachConfiguration ); - my $tmp_user = $obj->get_name(); - $already_defined_users->{$tmp_user}{'properties'} = $obj->get_properties(); - $already_defined_users->{$tmp_user}{'id'} = $obj->get_id(); - foreach my $auth ( keys %$already_defined_auth ) { - my $snet_auth = "\\\|authenticator=" . $already_defined_auth->{$auth}{'id'} . "\\\|"; - if ( $already_defined_users->{$tmp_user}{'properties'} =~ /$snet_auth/ ) { - $already_defined_users->{$tmp_user}{'realm'} = $auth; - } - } - } -} - -#Print Users from Proteus -metaprint( 'info', Dumper( $already_defined_users ) ) if $debug; -metaprint( 'info', Dumper( $already_defined_users->{'snet'} ) ) if $verbose; -# metaprint( 'info', Dumper( $already_defined_users->{'alogin'} ) ) if $verbose; - -# -- Create the import file -my $cpt = 0; -my $cpt_del = 0; - -foreach my $filter ( @filters ) { - - metaprint "info", "Checking groups '$filter'."; - my $cfg_ldap_group_search_f = $cfg_ldap_group_search_filter; - $cfg_ldap_group_search_f =~ s/REPLACE/$filter/; - print "$cfg_ldap_group_search_f\n" if $verbose; - my %ldap_users = ldap_find_users_and_groups( $cfg_ldap_server, $cfg_ldap_user, $cfg_ldap_passwd, $cfg_ldap_group_search, $cfg_ldap_search_scope, - $cfg_ldap_group_search_f, $cfg_ldap_group_attribute, $filter, $hostname, $cfg_ldap_cafile ); - - print Dumper ( \%ldap_users ) if $verbose; - - foreach my $u ( keys %ldap_users ) { - if ( defined( $already_defined_users->{$u} ) - && ( $already_defined_users->{$u} ) - && defined( $already_defined_users->{$u}{'realm'} ) - && ( $already_defined_users->{$u}{'realm'} eq 'LDAP' ) ) { - metaprint( "info", "Skipping user $u import, user is already defined." ) if $verbose; - $already_defined_users->{$u}{'found'} = 1; - next; - } elsif ( defined( $already_defined_users->{$u} ) && ( $already_defined_users->{$u} ) ) { - metaprint( "info", "Skipping user $u import, user is already defined, but user need to be checked." ); - $already_defined_users->{$u}{'found'} = 1; - next; - } - - next if ( $ldap_users{$u} =~ /^$/ ); - - # autogroup are ldap group, so user are added at the first connection. - next if ( defined( $autogroup->{$filter} ) && ( $autogroup->{$filter} ) ); - if ( defined( $attr{$filter} ) && defined( $ldap_users{$u}{'gecos'} ) ) { - metaprint( "info", "$u '" . $ldap_users{$u}{'gecos'} . "' '" . $ldap_users{$u}{'mail'} . "' need to be created in group '" . $attr{$filter} . "'" ); - if ( !$dry_run ) { - - # email=david.vernazobres@ext.ec.europa.eu|authenticator=3816318|userType=ADMIN|userAccessType=GUI| - # my $prop = 'email=' . $ldap_users{$u}{'mail'} . '|authenticator=' . $already_defined_auth->{'nldap'}{'id'} . '|userType=UserType::ADMIN|userAccessType=UserAccessType::GUI|'; - my $prop = 'email=' . $ldap_users{$u}{'mail'} . '|authenticator=' . $already_defined_auth->{'nldap'}{'id'} . '|userType=ADMIN|userAccessType=GUI|'; - soap_add_user( $service, $prop, $u ); - } - - } elsif ( !defined( $attr{$filter} ) ) { - metaprint( "error", "checking user '$u': attr" ); - - } elsif ( !defined( $ldap_users{$u}{'gecos'} ) ) { - metaprint( "error", "checking user '$u': ldap_users" ); - print Dumper ( \%ldap_users ); - } else { - metaprint( "error", "checking user '$u'" ); - } - - # set user enabled + description of the user. - $cpt++; - } -} - -soap_disconnect( $service ); - -metaprint "info", "Checking all other Proteus users defined."; -foreach my $u ( keys %$already_defined_users ) { - if ( defined( $already_defined_users->{$u} ) && ( $already_defined_users->{$u} ) && ( defined( $already_defined_users->{$u}{'realm'} ) && ( $already_defined_users->{$u}{'realm'} !~ /LDAP/i ) ) - || ( !defined( $already_defined_users->{$u}{'realm'} ) ) ) { - if ( defined( $authlocal->{$u} ) && ( $authlocal->{$u} ) ) { - metaprint( "info", "User '$u' localy authorised." ); - next; - } else { - metaprint( "error", "User $u is defined locally and is not authorised? Please check-it manually." ); - next; - } - } elsif ( defined( $already_defined_users->{$u} ) - && ( $already_defined_users->{$u} ) - && defined( $already_defined_users->{$u}{'found'} ) - && ( $already_defined_users->{$u}{'found'} ) ) { - next; - } elsif ( defined( $local_jrc->{$u} ) && ( $local_jrc->{$u} ) ) { - metaprint( "warn", "User $u belong to JRC." ); - next; - } else { - metaprint( "error", "User $u need to be checked manually." ); - $cpt_del++; - } -} - -metaprint( "info", "$cpt user(s) created." ); -metaprint( "info", "$cpt_del user(s) need to be deleted." ); -metaprint( "info", "--- Process Done ---" ); -exit( 0 ); diff --git a/bin/synchronize_redmine_projects.py b/bin/synchronize_redmine_projects.py deleted file mode 100755 index e5395c4..0000000 --- a/bin/synchronize_redmine_projects.py +++ /dev/null @@ -1,760 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import pprint -import inspect -import traceback -import shlex -import re -import requests -from subprocess import check_output, STDOUT, CalledProcessError - -pp = pprint.PrettyPrinter(indent=4) - -PROGNAME = os.path.basename(sys.argv[0]).split(".")[0] -script = os.path.basename(__file__).split(".")[0] - -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -basedir = '/opt/SNet/scm' - -wanted_membership = {} -wanted_membership['com'] = 'Reporter' -wanted_membership['mgt'] = 'Reporter' -wanted_membership['officials'] = 'Reporter' -wanted_membership['net'] = 'Developer' -wanted_membership['pi'] = 'Developer' -wanted_membership['sd'] = 'Developer' -wanted_membership['sec'] = 'Developer' -wanted_membership['sup'] = 'Developer' -wanted_membership['tda'] = 'Developer' -wanted_membership['pm'] = 'Manager' - -cmd = ("ssh vcodebox-lu find %s -path '\*/.hg' -prune -o -type d -path '\*/.hg' | grep -v '^.hg$'" % (basedir)) - -try: - output = check_output((shlex.split(cmd)), stderr=STDOUT, shell=False) -except CalledProcessError as ex: - output = ex.output -# print(output) - -folder_projects = [] -for l in output.splitlines(): - if not l.startswith(basedir): - continue - if not l.endswith('/.hg'): - continue - if l == basedir + '/.hg': - continue - if 'archive_' in l: - continue - pat = l.replace('/.hg', '').replace(basedir + '/', '') - - # print("%s %s" % (l, pat)) - folder_projects.append(pat) - - -def obj_dump(obj): - ''' - Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - print("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - except: - print("obj.%s = %s" % (attr, getattr(obj, attr))) - - for name, data in inspect.getmembers(obj): - if inspect.isclass(data): - print('name:%s' % (name)) - print(data) - - -def obj_dump_r(obj, level=0, deepth=2): - ''' - Recursive Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - msg = 2*level*' ' - msg += ("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - print(msg) - except: - msg = 2*level*' ' - msg += ("obj.%s = %s" % (attr, getattr(obj, attr))) - print(msg) - - if level >= deepth: - continue - - try: - obj_dump_r(getattr(obj, attr), level=level+1) - except: - msg = 2*level*' ' - msg += "Dump is stinking... crashed." - print(msg) - - -def redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, pj_id, pj_ident, repository_url): - - ''' - curl -v -H "Content-Type: application/json" -X POST -d '{"id": "3581", "vendor": "Mercurial", "repository": {"url": "/opt/SNet/scm/pkg/bind9-snet/bind9-bindhg-snet", "identifier":"bind9-bindhg-snet"}}' "https://redmine.snmc.cec.eu.int/sys/projects/3581/repository?key=tU0LvEthIX4cMzCI9YPI" - ''' - - redmine_url = "%s://%s/sys/projects/%s/repository?key=%s" % (REDMINE_PROTO, REDMINE_HOSTNAME, pj_id, REDMINE_WS_KEY) - playload = {} - playload['id'] = pj_id - playload['vendor'] = 'Mercurial' - playload['repository'] = {} - playload['repository']['identifier'] = pj_ident - playload['repository']['url'] = repository_url - - try: - response = requests.post(redmine_url, - json=playload, - allow_redirects=True, - verify=CA_bundle) - - except requests.exceptions.SSLError as e: - self.logger.error('%s: %s' % (redmine_url, str(e))) - return None - except Exception as e: - self.logger.error('Generic: %s' % (str(e))) - return None - - if response.status_code == 201: - print('OK') - print(response.content) - return None - else: - print('ERROR') - print(response.status_code) - print(response.content) - return None - - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') -REDMINE_WS_KEY = redmine_config_global.get('GLOBAL', 'WS_KEY') - -redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), key=REDMINE_KEY, requests={'verify': CA_bundle}, version='3.4.4') - -all_red_parent = {} -all_red_pj = {} -all_red_cross_pj = {} -red_projects = redmine.project.all(offset=0, limit=1000, include='enabled_modules,repositories,trackers') - -for u in red_projects: - # print(u) - # print('%s' % (u.id)) - # print('%s' % (u.name)) - # print('%s' % (u.identifier)) - all_red_pj[u.identifier] = {} - all_red_pj[u.identifier]['id'] = u.id - all_red_pj[u.identifier]['name'] = u.name - all_red_pj[u.identifier]['identifier'] = u.identifier - all_red_pj[u.identifier]['enabled_modules'] = u.enabled_modules - all_red_pj[u.identifier]['repositories'] = u.repositories - if hasattr(u, 'is_public'): - all_red_pj[u.identifier]['is_public'] = u.is_public - else: - all_red_pj[u.identifier]['is_public'] = False - - if 'parent' in dir(u): - # print('parent:%s' % (u.parent)) - all_red_pj[u.identifier]['parent'] = {} - all_red_pj[u.identifier]['parent']['name'] = u.parent.name - all_red_pj[u.identifier]['parent']['id'] = u.parent.id - # all_red_pj[u.identifier]['parent']['identifier'] = u.parent.identifier - all_red_parent[u.parent.name+'/'+u.name] = u.identifier - - if u.identifier == 'refconfig': - pp.pprint(all_red_pj[u.identifier]) - # obj_dump(u) - # obj_dump_r(u, level=0, deepth=1) - print(u.enabled_modules) - print(u.repositories) - print(u.is_public) - print(list(u)) - # sys.exit(0) - - if u.name != u.identifier: - all_red_cross_pj[u.name] = u.identifier - # pp.pprint(all_red_cross_pj[u.name]) - - continue - print('%s' % (u.id)) - print('%s' % (u.name)) - print('%s' % (u.identifier)) - if 'parent' in u: - print('%s' % (u.parent)) - -pp.pprint(all_red_parent) - -red_groups = redmine.group.all() -all_red_grp = {} -for g in red_groups: - all_red_grp[g.name] = {} - all_red_grp[g.name]['id'] = g.id - all_red_grp[g.id] = {} - all_red_grp[g.id]['name'] = g.name -# print(pp.pformat(all_red_grp)) - -red_roles = redmine.role.all() -all_red_rl = {} -for r in red_roles: - all_red_rl[r.name] = {} - all_red_rl[r.name]['id'] = r.id - all_red_rl[r.id] = {} - all_red_rl[r.id]['name'] = r.name -# print(pp.pformat(all_red_rl)) - -# sys.exit(1) - -limit = 3000 -cpt = 0 -for pj in sorted(folder_projects): - if cpt > limit: - break - cpt += 1 - - print("----%s" % (pj)) - if '/' in pj: - (parent, pjj) = pj.rsplit('/', 1) - if '/' in parent: - cnt = parent.count('/') - if cnt == 1: - if parent in all_red_parent: - parent = all_red_parent[parent] - else: - print("Parent '%s' with 1/ but not found (%s), creating pre-parent" % (parent, pj)) - - prepa, ppa = parent.split('/') - prepa_ident = prepa.lower().replace('.', '-') - ppa_ident = ppa.lower().replace('.', '-') - ''' Pre-parent check-up. ''' - if prepa_ident in all_red_pj: - print("Pre-Parent '%s' is found" % (prepa)) - prepa_id = all_red_pj[prepa_ident]['id'] - elif prepa in all_red_cross_pj: - print("Pre-Parent '%s' is found in the bad list" % (prepa)) - prepa_id = all_red_pj[all_red_cross_pj[prepa]]['id'] - else: - print("Pre-Parent '%s:%s' need to be created" % (prepa, prepa_ident)) - - try: - project = redmine.project.new() - project.name = prepa - project.identifier = prepa_ident - project.description = prepa - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = None - project.enabled_module_names = [] - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (parent, str(e))) - print(traceback.format_exc(5)) - sys.exit(1) - prepa_id = project.id - - all_red_pj[project.identifier] = {} - all_red_pj[project.identifier]['id'] = project.id - all_red_pj[project.identifier]['name'] = project.name - all_red_pj[project.identifier]['identifier'] = project.identifier - all_red_pj[project.identifier]['enabled_modules'] = project.enabled_modules - all_red_pj[project.identifier]['repositories'] = project.repositories - if hasattr(project, 'is_public'): - all_red_pj[project.identifier]['is_public'] = project.is_public - else: - all_red_pj[project.identifier]['is_public'] = False - - # Preparent membership - - print("membership prepa_id is %s." % (prepa_id)) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=prepa_id) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = prepa_id - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(prepa_id) - membership.delete(mb) - - ''' Parent check-up. ''' - if ppa_ident in all_red_pj: - print("Parent '%s' is found" % (ppa)) - ppa_id = all_red_pj[ppa_ident]['id'] - elif ppa in all_red_cross_pj: - print("Parent '%s' is found in the bad list" % (ppa)) - ppa_id = all_red_pj[all_red_cross_pj[ppa]]['id'] - else: - print("Parent '%s:%s' need to be created" % (ppa, ppa_ident)) - - try: - project = redmine.project.new() - project.name = ppa - project.identifier = ppa_ident - project.description = ppa - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = prepa_id - project.enabled_module_names = [] - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (ppa, str(e))) - print(traceback.format_exc(5)) - sys.exit(1) - ppa_id = project.id - - all_red_pj[project.identifier] = {} - all_red_pj[project.identifier]['id'] = project.id - all_red_pj[project.identifier]['name'] = project.name - all_red_pj[project.identifier]['identifier'] = project.identifier - all_red_pj[project.identifier]['enabled_modules'] = project.enabled_modules - if hasattr(project, 'is_public'): - all_red_pj[project.identifier]['is_public'] = project.is_public - else: - all_red_pj[project.identifier]['is_public'] = False - - all_red_pj[project.identifier]['parent'] = {} - all_red_pj[project.identifier]['parent']['name'] = project.parent.name - all_red_pj[project.identifier]['parent']['id'] = project.parent.id - all_red_parent[project.parent.name+'/'+project.name] = project.identifier - - else: - match = re.search(r'^.*/([^/]+/[^/]+)$', parent) - if match.group(1) in all_red_parent: - parent = all_red_parent[match.group(1)] - else: - print("Parent '%s' need to be decomposed for %s, skipping for now" % (parent, pj)) - continue - else: - parent = None - pjj = pj - - print("%s:%s" % (parent, pjj)) - if parent: - parent_ident = parent.lower().replace('.', '-') - pj_ident = pjj.lower().replace('.', '-') - - ''' - PARENT - ''' - - if parent and parent_ident in all_red_pj: - print("Parent '%s' is found" % (parent)) - parent_id = all_red_pj[parent_ident]['id'] - elif parent and parent in all_red_cross_pj: - print("Parent '%s' is found in the bad list" % (parent)) - parent_id = all_red_pj[all_red_cross_pj[parent]]['id'] - elif parent: - print("Parent '%s:%s' need to be created" % (parent, parent_ident)) - - try: - project = redmine.project.new() - project.name = parent - project.identifier = parent_ident - project.description = parent - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = None - project.enabled_module_names = [] - # project.enabled_modules = [] readonly attribute - # project.custom_fields = [{'id': 1, 'value': 'PE'}, {'id': 11, 'value': 'scm'}] - # list(project) - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (parent, str(e))) - print(traceback.format_exc(5)) - break - - all_red_pj[project.identifier] = {} - all_red_pj[project.identifier]['id'] = project.id - all_red_pj[project.identifier]['name'] = project.name - all_red_pj[project.identifier]['identifier'] = project.identifier - all_red_pj[project.identifier]['is_public'] = True - parent_id = project.id - - else: - parent_id = None - - if parent_id is not None: - - project = redmine.project.get(parent_id) - project.is_public = True - project.inherit_members = False - project.save() - - if 'enabled_modules' not in all_red_pj[parent_ident]: - print("No repository module activated for parent, OK") - - elif 'repository' not in all_red_pj[parent_ident]['enabled_modules']: - print("No repository for parent, OK") - - elif len(all_red_pj[parent_ident]['repositories']) == 0: - print("No repository for parent, OK") - - else: - print("repository activated for parent should not") - - print("membership parent_id is %s." % (parent_id)) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=parent_id) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = parent_id - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(parent_id) - membership.delete(mb) - - ''' - ITSELF - ''' - - if pjj in all_red_pj: - print("The project '%s' is found in all_red_pj." % (pjj)) - repository_url = os.path.join(basedir, pj) - print("hg:%s:%s" % (pj_ident, repository_url)) - pp.pprint(all_red_pj[pjj]) - - if parent and 'parent' in all_red_pj[pjj]: - if parent != all_red_pj[pjj]['parent']['name']: - print("Not the same parent %s:%s" % (parent, all_red_pj[pjj]['parent']['name'])) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.parent_id = parent_id - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.save() - - elif parent: - print("Not the same parent %s:None" % (parent)) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.parent_id = parent_id - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[pjj]['id'], pj_ident, repository_url) - - if 'repository' not in all_red_pj[pjj]['enabled_modules']: - print("Repository is not activated for repo %s:%s" % (pjj, pj_ident)) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[pjj]['id'], pj_ident, repository_url) - - elif len(all_red_pj[pjj]['repositories']) == 0: - print("Repository URL is empty for repo %s:%s (%s)" % (pjj, pj_ident, os.path.join(basedir, pj))) - project = redmine.project.get(all_red_pj[pjj]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[pjj]['id'], pj_ident, repository_url) - - elif os.path.join(basedir, pj) != all_red_pj[pjj]['repositories'][0]['url']: - print("Repository URL is bad for repo %s:%s (%s <> %s)" - % (pjj, pj_ident, os.path.join(basedir, pj), all_red_pj[pjj]['repositories'][0]['url'])) - - # if all_red_pj[pjj]['is_public']: - # reset verything to is_public false - project = redmine.project.get(all_red_pj[pjj]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': repository_url}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - - print("membership all_red_pj id %s." % (all_red_pj[pjj]['id'])) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=all_red_pj[pjj]['id']) - # print('%s' % (pp.pprint(pj_wanted_membership))) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print(list(mb)) - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - if 'inherited' in mb: - if mb.inherited == True: - print("inherited = True") - else: - print("inherited = False") - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if mb.group.name in pj_wanted_membership and pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = all_red_pj[pjj]['id'] - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(all_red_pj[pjj]['id']) - membership.delete(mb) - - elif pjj in all_red_cross_pj: - print("The project '%s' is found in all_red_cross_pj." % (pjj)) - repository_url = os.path.join(basedir, pj) - print("hg:%s:%s" % (pj_ident, repository_url)) - pp.pprint(all_red_pj[all_red_cross_pj[pjj]]) - if parent and 'parent' in all_red_pj[all_red_cross_pj[pjj]]: - if parent != all_red_pj[all_red_cross_pj[pjj]]['parent']['name']: - print("Not the same parent %s:%s" % (parent, all_red_pj[all_red_cross_pj[pjj]]['parent']['name'])) - elif parent: - print("Not the same parent %s:None" % (parent)) - elif 'parent' in all_red_pj[all_red_cross_pj[pjj]]: - print("Not the same parent None:%s" % (all_red_pj[all_red_cross_pj[pjj]]['parent']['name'])) - - if 'repository' not in all_red_pj[all_red_cross_pj[pjj]]['enabled_modules']: - print("Repository is not activated for repo %s:%s" % (pjj, pj_ident)) - project = redmine.project.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[all_red_cross_pj[pjj]]['id'], pj_ident, repository_url) - - elif len(all_red_pj[all_red_cross_pj[pjj]]['repositories']) == 0: - print("Repository URL is empty for repo %s:%s (%s)" % (pjj, pj_ident, repository_url)) - project = redmine.project.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - redmine_create_repository(REDMINE_PROTO, REDMINE_HOSTNAME, REDMINE_WS_KEY, all_red_pj[all_red_cross_pj[pjj]]['id'], pj_ident, repository_url) - - elif os.path.join(basedir, pj) != all_red_pj[all_red_cross_pj[pjj]]['repositories'][0]['url']: - print("Repository URL is bad for repo %s:%s (%s <> %s)" - % (pjj, pj_ident, os.path.join(basedir, pj), all_red_pj[all_red_cross_pj[pjj]]['repositories'][0]['url'])) - - # if all_red_pj[pjj]['is_public']: - # reset verything to is_public false - project = redmine.project.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - project.is_public = True - project.inherit_members = False - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - project.enabled_module_names = ['repository', 'issue_tracking', 'time_tracking', - 'calendar', 'gantt', 'agile', 'scrum', 'easy_gantt'] - project.tracker_ids = [1, 2] - project.save() - - print("membership all_red_cross_pj id %s." % (all_red_pj[all_red_cross_pj[pjj]]['id'])) - - pj_wanted_membership = dict(wanted_membership) - pj_membership_del = [] - real_membership = redmine.project_membership.filter(project_id=all_red_pj[all_red_cross_pj[pjj]]['id']) - - for mb in real_membership: - if hasattr(mb, 'user'): - continue - ''' - print("------------") - print("membership") - print("mb.project: %s %s" % (mb.project.id, mb.project.name)) - print("mb.group: %s %s" % (mb.group.id, mb.group.name)) - print("mb.roles") - for rl in mb.roles: - print("%s %s" % (rl.id, rl.name)) - ''' - if mb.group.name in pj_wanted_membership: - for rl in mb.roles: - if pj_wanted_membership[mb.group.name] == rl.name: - del(pj_wanted_membership[mb.group.name]) - else: - for rl in mb.roles: - pj_membership_del.append(mb.id) - - else: - pj_membership_del.append(mb.id) - - pp.pprint(pj_wanted_membership) - for gr in pj_wanted_membership: - membership = redmine.project_membership.new() - membership.project_id = all_red_pj[all_red_cross_pj[pjj]]['id'] - # http://www.redmine.org/issues/17904 group is user... - membership.user_id = all_red_grp[gr]['id'] - membership.role_ids = [all_red_rl[pj_wanted_membership[gr]]['id']] - membership.save() - - pp.pprint(pj_membership_del) - for mb in pj_membership_del: - membership = redmine.project_membership.get(all_red_pj[all_red_cross_pj[pjj]]['id']) - membership.delete(mb) - - # break - - else: - print("The project '%s' need to be created." % (pj)) - print("hg:%s:%s" % (pj_ident, os.path.join(basedir, pj))) - - if parent and parent in all_red_pj: - print("Parent '%s' is found" % (parent)) - elif parent and parent in all_red_cross_pj: - print("Parent '%s' is found in the bad list" % (parent)) - - try: - print('id:%s' % (pj_ident)) - project = redmine.project.new() - project.name = pjj - project.identifier = pj_ident - project.description = pjj - project.homepage = None - project.is_public = True - project.inherit_members = False - project.parent_id = parent_id - # project.enabled_modules = ['repository'] Readonly attribute - # project.custom_fields = [{'id': 1, 'value': 'PE'}, {'id': 11, 'value': 'scm'}] - project.custom_fields = [{'id': 11, 'value': os.path.join(basedir, pj)}] - # list(project) - project.save() - except Exception as e: - print('The creation of the ressources project "%s" did not suceed: %s' % (pjj, str(e))) - print(traceback.format_exc(5)) - break - - # try: - # project = redmine.project.get(pjj) - # except ResourceNotFoundError as e: - # print('The ressources is not found') - -sys.exit(0) diff --git a/bin/synchronize_redmine_users.py b/bin/synchronize_redmine_users.py deleted file mode 100755 index e7e9d6c..0000000 --- a/bin/synchronize_redmine_users.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import absolute_import, print_function - -import os -import sys - -import configparser as ConfigParser -import pprint -import inspect - -pp = pprint.PrettyPrinter(indent=4) - -PROGNAME = os.path.basename(sys.argv[0]).split(".")[0] -script = os.path.basename(__file__).split(".")[0] - -global_iniFile = '/opt/etc/ini/global.ini' -config_global = ConfigParser.RawConfigParser() -config_global.optionxform(str()) -config_global.optionxform = str -config_global.read(global_iniFile) -sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) - -from redminelib import Redmine - -if 'http_proxy' in os.environ: - del os.environ['http_proxy'] -if 'https_proxy' in os.environ: - del os.environ['https_proxy'] - - -CA_bundle = '/usr/local/share/ca-certificates/snetroot/SNetRootCA_device_bundle.pem' -CA_bundle = '/etc/ssl/certs/ca-certificates.crt' - -def obj_dump(obj): - ''' - Object dumper - ''' - for attr in dir(obj): - if '_' in attr: - continue - try: - print("obj.%s = %s" % (attr, str(getattr(obj, attr)))) - except: - print("obj.%s = %s" % (attr, getattr(obj, attr))) - - for name, data in inspect.getmembers(obj): - if inspect.isclass(data): - print('name:%s' % (name)) - print(data) - -redmine_config_global = ConfigParser.RawConfigParser() -redmine_config_global.read(config_global.get('INI', 'Redmine')) - -# Parse config -REDMINE_HOSTNAME = redmine_config_global.get('GLOBAL', 'HOST') -REDMINE_PROTO = redmine_config_global.get('GLOBAL', 'PROTO') -REDMINE_KEY = redmine_config_global.get('CREDENTIAL', 'APIkey') - -redmine = Redmine('%s://%s' % (REDMINE_PROTO, REDMINE_HOSTNAME), key=REDMINE_KEY, requests={'verify': CA_bundle}) - -users = redmine.user.all(offset=0, limit=100) -for u in users: - # print(u) - # print '%s' % (u.id) - # print '%s' % (u.login) - # print '%s' % (u.firstname) - # print '%s' % (u.lastname) - # print '%s' % (u.mail) - # print '%s' % (u.auth_source_id) - # print '%s' % (u.mail_notification) - - print('%s %s %s <%s> (%s)' % (u.login, u.firstname, u.lastname, u.mail, u.id)) - obj_dump(u) - # obj_dump(u.contacts) - # obj_dump(u.deals) - obj_dump(u.groups) - obj_dump(u.memberships) - break diff --git a/bin/synchronize_users.pl b/bin/synchronize_users.pl deleted file mode 100755 index 4685de8..0000000 --- a/bin/synchronize_users.pl +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/perl -T - -# -use strict; -use warnings FATAL => 'all'; -use diagnostics; - -use Data::Dumper; -use Config::IniFiles; -use File::Basename; - -use Net::LDAP; - -use lib ( - new Config::IniFiles( - -file => "/opt/etc/ini/global.ini" - )->val( 'APPLICATION', 'LIBRARY' ) -); - -use SNET::LdapNS qw(:all); - -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); -my $ldap_iniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); - -my $ldap_server = { - 'uri' => $ldap_iniFile->val( 'LDAP_SNET', 'SERVER' ), - 'base' => $ldap_iniFile->val( 'LDAP_SNET', 'BASE' ), - 'user' => $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'USER' ), - 'password' => $ldap_iniFile->val( 'LDAP_CREDENTIALS', 'PASSWORD' ), -}; - -my $ldap_server_ng = { - 'uri' => $ldap_iniFile->val( 'LDAP_NG', 'SERVER' ), - 'base' => $ldap_iniFile->val( 'LDAP_NG', 'BASE' ), - 'user' => $ldap_iniFile->val( 'LDAP_NG_CREDENTIALS', 'USER' ), - 'password' => $ldap_iniFile->val( 'LDAP_NG_CREDENTIALS', 'PASSWORD' ), -}; - -sub synchronize($$) -{ - - my ( $cfrom, $cto ) = @_; - - die 'missing parameters' unless ( ( defined( $cfrom ) && defined( $cto ) ) - && ( ref( $cfrom ) eq 'HASH' ) - && ( ref( $cto ) eq 'HASH' ) ); - - my $from = $cfrom->{'userInfos'}; - my $to = $cto->{'userInfos'}; - - die 'missing userInfos' unless ( defined( $from ) - && defined( $to ) ); - - while ( my ( $k, $v ) = each %{$from} ) { - - my $uid = $cfrom->{'connection'}->clean_dn( $k ); - my $dn = 'uid=' . $uid . ',ou=People,' . $cto->{'base'}; - - if ( !defined( $to->{$dn} ) ) { - print STDERR "$0: [warning] user `$dn' not found\n"; - next; - } - - my $entry = Net::LDAP::Entry->new( $dn ); - $entry->changetype( 'modify' ); - my $changes = 0; - - foreach my $attr ( 'userpassword', 'uidnumber' ) { - - next unless ( defined( $v->{$attr} ) - && defined( $to->{$dn}->{$attr} ) ); - - my $from_attr = ${ $v->{$attr} }[0]; - my $to_attr = ${ $to->{$dn}->{$attr} }[0]; - - if ( $from_attr ne $to_attr ) { - $changes++; - $entry->replace( $attr => $from_attr ); - } - - } - - if ( $changes > 0 ) { - my $result = $entry->update( $cto->{'connection'}->{'connection'} ); - if ( $result->is_error() ) { - print STDERR "$0: [error] unable to synchronize $uid:" . ( defined( $result->error_desc ) ? $result->error_desc : $result->error() ) . "\n"; - } else { - print STDERR "$0: [success] $uid synchronized\n"; - } - } - - } - -} - -eval { - - foreach my $server ( $ldap_server, $ldap_server_ng ) { - my $uri = $server->{'uri'}; - die "invalid uri `$uri'" unless ( $uri =~ m/^(?:ldap:\/\/)?([^:]+)(?::389)?$/i ); - $server->{'server'} = $1; - } - - SNET::LdapNS::ldapns_add_dn_exception( $ldap_server->{'user'} ); - SNET::LdapNS::ldapns_bind( $ldap_server->{'server'}, $ldap_server->{'user'}, $ldap_server->{'password'}, $ldap_server->{'uri'}, 'LDAPISS', 0, 0, 0 ); - $ldap_server->{'connection'} = SNET::LdapNS::get_connection( $ldap_server->{'uri'} ); - $ldap_server->{'userInfos'} = $ldap_server->{'connection'}->search( - base => 'ou=People,' . $ldap_server->{'base'}, - scope => 'sub', - filter => '(objectClass=posixAccount)', - attrs => [ 'uid', 'uidNumber', 'userPassword' ] - ); - SNET::LdapNS::ldapns_del_dn_exception( $ldap_server->{'user'} ); - - SNET::LdapNS::ldapns_bind( $ldap_server_ng->{'server'}, $ldap_server_ng->{'user'}, $ldap_server_ng->{'password'}, $ldap_server_ng->{'uri'}, 'LDAPISS', 1, 0, 0 ); - $ldap_server_ng->{'connection'} = SNET::LdapNS::get_connection( $ldap_server_ng->{'uri'} ); - $ldap_server_ng->{'userInfos'} = $ldap_server_ng->{'connection'}->search( - base => 'ou=People,' . $ldap_server_ng->{'base'}, - scope => 'sub', - filter => '(objectClass=posixAccount)', - attrs => [ 'uid', 'uidNumber', 'userPassword' ] - ); - - synchronize( $ldap_server, $ldap_server_ng ); - -}; -if ( $@ ) { - print STDERR $@; - exit 1; -} - -exit 0; - diff --git a/cgi-bin/check_users_in_AD_group.pl b/cgi-bin/check_users_in_AD_group.pl deleted file mode 100755 index 515d8a6..0000000 --- a/cgi-bin/check_users_in_AD_group.pl +++ /dev/null @@ -1,262 +0,0 @@ -#!/usr/bin/perl -# Check if user is member of an AD's group (up to 3 group of group deep) -# 1. check if user is a direct member of the group -# 2. check recursively in each user's group to find if a member's group is included in the target group -# -use strict; -use warnings; - -# -use Data::Dumper; -use CGI qw/:standard start_ol/; -use Config::IniFiles; -use File::Basename; - -use Net::LDAP; - -# unbuffered output: -$| = 1; - -sub is_memberOf ($$$); -sub get_memberOf ($$); -sub get_dn ($$$); -sub found ($$); -sub search_rec ($$$$$$); - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} -use SNET::access; -use SNET::common; -use SNET::html; -use SNET::ActiveDirectory; - -use vars qw($verbose $debug $help $env $script $cli_mode); -$debug = 0; -$verbose = 0; -( $script ) = split( /\./, basename( $0 ) ); - -my $title = "AD Group Checker"; -my $function = "AD_Group_Checker"; -my $href = ""; -my $header = ""; -my $html_msg = ""; - -my $AuthGroup = $ENV{"HTTP_AUTHGROUP"}; -my $AuthUser = $ENV{"HTTP_AUTHUSER"}; -$env = $ENV{"ENV"}; -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -if ( !defined( $env ) || ( $env =~ /^$/ ) ) { - $env = "test"; -} - -if ( !defined( $ENV{'DOCUMENT_ROOT'} ) - && !defined( $ENV{'REQUEST_URI'} ) - && !defined( $ENV{'HTTP_REFERER'} ) - && !defined( $ENV{'HTTP_CLIENT_IP'} ) - && !defined( $ENV{'SERVER_NAME'} ) - && !defined( $ENV{'HTTP_HOST'} ) - && ( $env eq "test" ) ) { - $cli_mode = 1; -} else { - $cli_mode = 0; - if ( ( ( !defined( $AuthGroup ) ) || ( $AuthGroup =~ /^$/ ) ) && ( $AuthUser =~ /^NET1\\(.*)$/ ) ) { - $AuthUser = $1; - my $html_msg_temp = ''; - ( $AuthGroup, $html_msg_temp ) = Access_LDAP_Get_User_Group( $global_iniFile, $AuthUser ); - $html_msg .= $html_msg_temp; - undef $html_msg_temp; - $html_msg .= "AuthGroup:$AuthGroup" . br if $verbose; - } elsif ( $AuthGroup =~ /^cudgroup==/ ) { - $AuthGroup =~ s/cudgroup==//g; - } - if ( Access_Check_Script_Authorisation( $global_iniFile, $AuthGroup, $script ) != 1 ) { - $html_msg .= "AuthGroup:$AuthGroup" . br; - $html_msg .= "AuthUser:$AuthUser" . br; - Access_barf 401, "Not Authorized User", "Not Authorized User", $html_msg; - exit 1; - } -} - -print header( -type => "text/html", - -charset => 'UTF-8', ); - -dg_header_html( $title, 1, 0, $href, $header ); -print $html_msg; - -print "Loading INI file Parameters" . br . "\n" if $verbose; -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'AD' ) ); -my $adserver = $AiniFile->val( 'AD_NET1', 'SERVER' ); -print "error value of adserver is undefined" if ( !defined( $adserver ) ); -my $aduser = $AiniFile->val( 'AD_NET1', 'USER' ); -print "error value of aduser is undefined" if ( !defined( $aduser ) ); -my $adpasswd = $AiniFile->val( 'AD_NET1', 'PASSWORD' ); -print "error value of adpasswd is undefined" if ( !defined( $adpasswd ) ); - -my $searchbase = 'DC=net1,DC=cec,DC=eu,DC=int'; - -############ Get user name, group - -my $action = ''; -$action = param( 'action' ) if ( ( defined( param( 'action' ) ) ) && ( param( 'action' ) !~ /^$/ ) && ( param( 'action' ) =~ /^\w+$/ ) ); -my $groupname = ''; -$groupname = param( 'groupname' ) if ( ( defined( param( 'groupname' ) ) ) && ( param( 'groupname' ) !~ /^$/ ) && ( param( 'groupname' ) =~ /^[\w\.-]+$/ ) ); -my $uid = ''; -$uid = param( 'uid' ) if ( ( defined( param( 'uid' ) ) ) && ( param( 'uid' ) !~ /^$/ ) && ( param( 'uid' ) =~ /^\w+$/ ) ); - -if ( ( $action eq 'Search' ) && ( $uid =~ /^\w+$/ ) && ( $groupname =~ /^[\w\.-]+$/ ) ) { - - my $ad_net1 = AD_connect( $adserver, $aduser, $adpasswd ); - - # TODO check for bind errors - #print "bind: ldap_error_text($mesg->code) \n"; - #print Dumper($mesg); - -##################################### MAIN ########################################### -## -## Get DN for user and goup - my $user_dn = get_dn( $ad_net1, $searchbase, $uid ); - if ( $user_dn eq "Not found" ) { - print "uid $uid not found in AD !" . br; - exit 1; - } - print "User DN: $user_dn" . br; - - my $grp_dn = get_dn( $ad_net1, $searchbase, $groupname ); - if ( $grp_dn eq "Not found" ) { - print "group $groupname not found in AD !" . br; - exit 1; - } - print "Group DN: $grp_dn" . br; - my $grp_cn = "CN=" . substr( $grp_dn, 3 ); - print "Group CN: $grp_cn" . br; - -## -## Simple match (user is part of group) - print br. "Searching using Fast path." . br; - my $fp = is_memberOf( $ad_net1, $user_dn, $grp_dn ); - if ( 1 == $fp ) { - found( $uid, $groupname ); - } else { - -## -## Recursive check - print "Not found using Fast path." . br; - print "Searching using Slow path." . br; - $fp = search_rec( $ad_net1, $user_dn, $grp_dn, $fp, 1, $user_dn ); - if ( 0 == $fp ) { - printf "User '$uid' NOT found in '$groupname'." . br; - } - } -} else { - - print "Check if user is member of an AD's group (up to 3 group of group deep)" . br; - print start_ol(); - print li( [ "Check if user is a direct member of the group.", "Check recursively in each user's group to find if a member's group is included in the target group." ] ); - print end_ol(); - print "Most of the groups are in the form of <DG>-IAP-Users" . br; - - print start_form( -enctype => &CGI::URL_ENCODED ); - print "<em>Username:</em>" . br; - print textfield( -name => 'uid', -value => $uid ) . br; - print "<em>Groupname:</em>" . br; - print textfield( -name => 'groupname', -value => $groupname ) . br . br . br; - print submit( -name => 'action', -value => 'Search' ); - print endform; -} -print '</div>'; -dg_footer_html(); - -################ Some functions ############################### - -sub is_memberOf ($$$) -{ - my ( $ad, $user, $grp ) = @_; - my $attrs = ['memberOf']; - my $filter = "memberOf=$grp"; - my $results = $ad->search( base => $user, filter => $filter, attrs => $attrs, scope => 'base' ); - my $count = $results->count; - if ( $count == 1 ) { - return 1; - } elsif ( $count == 0 ) { - return 0; - } else { - print "Should not happen\n"; - print Dumper( $results ); - return -1; - } -} - -sub get_memberOf ($$) -{ - my ( $ad, $grp ) = @_; - my @memberOf = (); - my $attrs = ['memberOf']; - my $filter = "objectclass=*"; - my $results = $ad->search( base => $grp, filter => $filter, attrs => $attrs, scope => 'base' ); - my $count = $results->count; - if ( $count == 1 ) { - my $entry = $results->entry( 0 ); - - #print Dumper($entry); - @memberOf = $entry->get_value( 'memberOf' ); - } - return @memberOf; -} - -sub get_dn ($$$) -{ - my ( $ad, $searchbase, $user ) = @_; - my $attrs = ['cn']; - my $filter = "sAMAccountName=$user"; - my $results = $ad->search( base => $searchbase, filter => $filter, attrs => $attrs ); - my $count = $results->count; - if ( $count == 1 ) { - my $entry = $results->entry( 0 ); - print "dn-> " . $entry->dn . "\n" if ( $main::debug ); - return $entry->dn; - } else { - return "Not found"; - } -} - -sub found ($$) -{ - my ( $uid, $groupname ) = @_; - printf br. "User '$uid' found in '$groupname'" . br; -} - -sub search_rec ($$$$$$) -{ - my ( $ad, $user_dn, $grp_dn, $fp, $level, $base ) = @_; - if ( 0 == $fp ) { - my @memberOf = get_memberOf( $ad, $base ); - foreach my $grp ( @memberOf ) { - next if ( $grp =~ /Distribution|Resource/ ); - - #print "."; - $grp =~ /^CN=(.+?),OU=/; - print "$level: search in $1 \n" if ( $main::debug ); - $fp = is_memberOf( $ad, $grp, $grp_dn ); - if ( 1 == $fp ) { - found( $uid, $groupname ); - last; - } elsif ( 0 == $fp && $level < 3 ) { - $level = $level + 1; - $grp =~ /^CN=(.+?),OU=/; - print "\tgoing to $1\n" if ( $main::debug ); - $fp = search_rec( $ad, $user_dn, $grp_dn, $fp, $level, $grp ); - $level = $level - 1; - } - last if ( 1 == $fp ); - } - } - return $fp; -} - -exit 0; - diff --git a/cgi-bin/get_groups_content_from_AD.pl b/cgi-bin/get_groups_content_from_AD.pl deleted file mode 100755 index 18984a6..0000000 --- a/cgi-bin/get_groups_content_from_AD.pl +++ /dev/null @@ -1,356 +0,0 @@ -#!/usr/bin/perl -# Check if user is member of an AD's group (up to 3 group of group deep) -# 1. check if user is a direct member of the group -# 2. check recursively in each user's group to find if a member's group is included in the target group -# -use strict; -use warnings; - -# -use Data::Dumper; -use CGI qw/:standard start_ol/; -use Config::IniFiles; -use File::Basename; - -use Net::LDAP; - -# unbuffered output: -$| = 1; - -sub is_memberOf ($$$); -sub get_memberOf ($$$$$); -sub get_ldap_memberOf ($$$$$); -sub get_dn ($$$$$;$); -sub search_rec ($$$$); - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} -use SNET::access; -use SNET::common; -use SNET::html; -use SNET::ActiveDirectory; - -use vars qw($verbose $debug $help $env $script $cli_mode); -$debug = 0; -$verbose = 0; -( $script ) = split( /\./, basename( $0 ) ); - -my $title = "Group Dump"; -my $function = $title; -$function =~ s/\s/_/g; -my $href = ""; -my $header = h1( a( { href => "/snet/cgi-bin/auth/$script.pl" }, $title ) ); -my $html_msg = ""; - -$env = $ENV{"ENV"}; -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -if ( !defined( $env ) || ( $env =~ /^$/ ) ) { - $env = "test"; -} - -( $html_msg ) = Access_snet_script_head( $script, $global_iniFile, $ENV, $env ); - -print header( -type => "text/html", -charset => 'UTF-8', ); - -dg_header_html( $title, 1, 0, $href, $header ); -print $html_msg; - -print "Loading INI file Parameters" . br . "\n" if $verbose; -my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); -metaprint( "error", "error value of AiniFile is undefined" ) if ( !defined( $AiniFile ) ); - -my $credential = (); - -$credential->{'NET1'}{'server'} = $AiniFile->val( 'AD_NET1', 'SERVER' ); -metaprint( "error", "error value of adserver is undefined" ) if ( !defined( $credential->{'NET1'}{'server'} ) ); -$credential->{'NET1'}{'user'} = $AiniFile->val( 'AD_NET1', 'USER' ); -metaprint( "error", "error value of aduser is undefined" ) if ( !defined( $credential->{'NET1'}{'user'} ) ); -$credential->{'NET1'}{'passwd'} = $AiniFile->val( 'AD_NET1', 'PASSWORD' ); -metaprint( "error", "error value of adpasswd is undefined" ) if ( !defined( $credential->{'NET1'}{'passwd'} ) ); -$credential->{'NET1'}{'base'} = 'DC=net1,DC=cec,DC=eu,DC=int'; -$credential->{'NET1'}{'attrs'} = ['cn']; -$credential->{'NET1'}{'filter'} = "sAMAccountName="; - -#### - -$credential->{'EC_LDAP'}{'server'} = $AiniFile->val( 'LDAP_EC', 'SERVER' ); -metaprint( "error", "error value of ec_ldapserver is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'server'} ) ); -$credential->{'EC_LDAP'}{'user'} = $AiniFile->val( 'LDAP_EC', 'USER' ); -metaprint( "error", "error value of ec_ldapuser is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'user'} ) ); -$credential->{'EC_LDAP'}{'passwd'} = $AiniFile->val( 'LDAP_EC', 'PASSWORD' ); -metaprint( "error", "error value of ec_ldappasswd is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'passwd'} ) ); -$credential->{'EC_LDAP'}{'base'} = $AiniFile->val( 'LDAP_EC', 'BASE' ); -metaprint( "error", "error value of ec_basedn is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'base'} ) ); -$credential->{'EC_LDAP'}{'attrs'} = ['cn']; -$credential->{'EC_LDAP'}{'attrs_gon'} = ['cudgroup']; -$credential->{'EC_LDAP'}{'filter'} = "(&(objectClass=cudperson)(cudgroup="; -$credential->{'EC_LDAP'}{'filter_post'} = "))"; - -$credential->{'EC_LDAP_Proxy'}{'server'} = $AiniFile->val( 'LDAP_EC', 'SERVER' ); -metaprint( "error", "error value of ec_ldapserver is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'server'} ) ); -$credential->{'EC_LDAP_Proxy'}{'user'} = $AiniFile->val( 'LDAP_EC', 'USER' ); -metaprint( "error", "error value of ec_ldapuser is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'user'} ) ); -$credential->{'EC_LDAP_Proxy'}{'passwd'} = $AiniFile->val( 'LDAP_EC', 'PASSWORD' ); -metaprint( "error", "error value of ec_ldappasswd is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'passwd'} ) ); -$credential->{'EC_LDAP_Proxy'}{'base'} = $AiniFile->val( 'LDAP_EC', 'BASE' ); -metaprint( "error", "error value of ec_basedn is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'base'} ) ); -$credential->{'EC_LDAP_Proxy'}{'attrs'} = ['cn']; -$credential->{'EC_LDAP_Proxy'}{'attrs_gon'} = ['cudgroup']; -$credential->{'EC_LDAP_Proxy'}{'filter'} = "(&(objectClass=cudperson)(cudgroup="; -$credential->{'EC_LDAP_Proxy'}{'filter_post'} = "))"; - -$credential->{'EC_LDAP_RP'}{'server'} = $AiniFile->val( 'LDAP_EC', 'SERVER' ); -metaprint( "error", "error value of ec_ldapserver is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'server'} ) ); -$credential->{'EC_LDAP_RP'}{'user'} = $AiniFile->val( 'LDAP_EC', 'USER' ); -metaprint( "error", "error value of ec_ldapuser is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'user'} ) ); -$credential->{'EC_LDAP_RP'}{'passwd'} = $AiniFile->val( 'LDAP_EC', 'PASSWORD' ); -metaprint( "error", "error value of ec_ldappasswd is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'passwd'} ) ); -$credential->{'EC_LDAP_RP'}{'base'} = $AiniFile->val( 'LDAP_EC', 'BASE' ); -metaprint( "error", "error value of ec_basedn is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'base'} ) ); -$credential->{'EC_LDAP_RP'}{'attrs'} = ['cn']; -$credential->{'EC_LDAP_RP'}{'attrs_gon'} = ['cudgroup']; -$credential->{'EC_LDAP_RP'}{'filter'} = "(&(objectClass=cudperson)(cudgroup="; -$credential->{'EC_LDAP_RP'}{'filter_post'} = "))"; - -#### - -$credential->{'SNMC_LDAP'}{'server'} = $AiniFile->val( 'LDAP_SNET_NG', 'SERVER' ); -metaprint( "error", "error value of cfg_ldap_server is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'server'} ) ); -$credential->{'SNMC_LDAP'}{'user'} = $AiniFile->val( 'LDAP_SNET_NG', 'USER' ); -metaprint( "error", "error value of cfg_ldap_user is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'user'} ) ); -$credential->{'SNMC_LDAP'}{'passwd'} = $AiniFile->val( 'LDAP_SNET_NG', 'PASSWORD' ); -metaprint( "error", "error value of cfg_ldap_passwd is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'passwd'} ) ); -$credential->{'SNMC_LDAP'}{'base'} = $AiniFile->val( 'LDAP_SNET_NG', 'BASE' ); -metaprint( "error", "error value of cfg_ldap_search_scope is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'base'} ) ); -$credential->{'SNMC_LDAP'}{'cafile'} = $AiniFile->val( 'LDAP_SNET_NG', 'CA' ); -metaprint( "error", "error value of cfg_ldap_cafile is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'cafile'} ) ); -$credential->{'SNMC_LDAP'}{'attrs'} = [ 'cn', 'memberOf' ]; -$credential->{'SNMC_LDAP'}{'attrs_gon'} = ['memberOf']; -$credential->{'SNMC_LDAP'}{'filter'} = "uid="; - -#my $cfg_ldap_group_search = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_SEARCH' ); -#metaprint( "error", "error value of cfg_ldap_group_search is undefined" ) if ( !defined( $cfg_ldap_group_search ) ); -#my $cfg_ldap_group_search_filter = $AiniFile->val( 'LDAP_SNET_NG', 'FILTER' ); -#metaprint( "error", "error value of cfg_ldap_group_search_filter is undefined" ) if ( !defined( $cfg_ldap_group_search_filter ) ); -#$cfg_ldap_group_search_filter = "(&(objectclass=posixGroup)(cn=REPLACE))"; -#my $cfg_ldap_group_attribute = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_ATTRIBUTE' ); -#metaprint( "error", "error value of cfg_ldap_group_attribute is undefined" ) if ( !defined( $cfg_ldap_group_attribute ) ); -#$cfg_ldap_group_attribute = ["memberuid"]; -#my $cfg_ldap_search_scope = $AiniFile->val( 'LDAP_SNET_NG', 'SEARCH_SCOPE' ); -#metaprint( "error", "error value of cfg_ldap_search_scope is undefined" ) if ( !defined( $cfg_ldap_search_scope ) ); - -############ Get user name, group - -my $action = ''; -$action = param( 'action' ) if ( ( defined( param( 'action' ) ) ) && ( param( 'action' ) !~ /^$/ ) && ( param( 'action' ) =~ /^\w+$/ ) ); -my $uid = ''; -$uid = param( 'uid' ) if ( ( defined( param( 'uid' ) ) ) && ( param( 'uid' ) !~ /^$/ ) && ( param( 'uid' ) =~ /^\w+$/ ) ); -my $type = 'NET1'; -$type = param( 'type' ) if ( ( defined( param( 'type' ) ) ) && ( param( 'type' ) !~ /^$/ ) && ( param( 'type' ) =~ /^((EC|SNMC)_LDAP(_Proxy|RP)?|NET1)$/ ) ); -my $format = ''; -$format = param( 'format' ) if ( ( defined( param( 'format' ) ) ) && ( param( 'format' ) !~ /^$/ ) && ( param( 'format' ) =~ /^\w+$/ ) ); - -$verbose = 1 if ( ( defined( param( 'verbose' ) ) ) && ( param( 'verbose' ) !~ /^$/ ) && ( param( 'verbose' ) =~ /^[\d\w]+$/ ) && ( param( 'verbose' ) eq 'godmode1' ) ); -$debug = 1 if ( ( defined( param( 'debug' ) ) ) && ( param( 'debug' ) !~ /^$/ ) && ( param( 'debug' ) =~ /^[\d\w]+$/ ) && ( param( 'debug' ) eq 'godmode1' ) ); - -if ( ( $action eq 'Search' ) && ( $uid =~ /^\w+$/ ) && ( $type =~ /^((EC|SNMC)_LDAP(_Proxy|RP)?|NET1)$/ ) ) { - - print '<div class="preview">'; - my ( $status, $connection ) = - AD_connect( $credential->{$type}{'server'}, $credential->{$type}{'user'}, $credential->{$type}{'passwd'}, ( $credential->{$type}{'cafile'} ? $credential->{$type}{'cafile'} : '' ) ); - if ( !$status ) { - print "ERROR: $connection." . nl(); - exit 1; - } - my $searchbase = $credential->{$type}{'base'}; - - # TODO check for bind errors - #print "bind: ldap_error_text($mesg->code) \n"; - #print Dumper($mesg); - -##################################### MAIN ########################################### - print "Searching for group '$uid' in $type !" . nl(); - -## -## Get DN for user and goup - my $user_dn = undef; - if ( defined( $credential->{$type}{'filter_post'} ) && $credential->{$type}{'filter_post'} ) { - $user_dn = get_dn( $connection, $searchbase, $uid, $credential->{$type}{'attrs'}, $credential->{$type}{'filter'}, $credential->{$type}{'filter_post'} ); - } else { - $user_dn = get_dn( $connection, $searchbase, $uid, $credential->{$type}{'attrs'}, $credential->{$type}{'filter'} ); - } - if ( $user_dn eq "Not found" ) { - print "uid $uid not found in $type ($searchbase) with query (" . $credential->{$type}{'filter'} . ")!" . nl(); - exit 1; - } - print "User DN: $user_dn" . nl(); - -## -## Recursive check - print "Searching all group recursivly." . nl(); - if ( defined( $credential->{$type}{'attrs_gon'} ) ) { - print "Searching for groupOfName membership." . nl(); - my @ldap_group = get_ldap_memberOf( $connection, $searchbase, $uid, $credential->{$type}{'attrs_gon'}, $credential->{$type}{'filter'} ); - foreach ( @ldap_group ) { - print "level 0 groupname: '$_'" . nl(); - } - } - if ( $type eq 'SNMC_LDAP' ) { - print "Searching for PosixGroup membership." . nl(); - my $attrs = ['cn']; - my $filter = "(&(objectclass=posixGroup)(memberuid=$uid))"; - my $base = 'sub'; - - my @ldap_group = get_memberOf( $connection, $searchbase, $attrs, $filter, $base ); - foreach ( @ldap_group ) { - print "level 0 groupname: '$_'" . nl(); - } - } - if ( $type eq 'NET1' ) { - my $known = (); - search_rec( $connection, $user_dn, 1, $known ); - } - print '</div>'; -} else { - - print "Display the group membership" . nl(); - print start_ol(); - print "Please fill the groupname in lower case." . nl(); - print "Please choose the authorisation to perform the audit." . nl(); - print end_ol(); - - print start_form( -enctype => &CGI::URL_ENCODED ); - print "<em>Groupname:</em>" . nl(); - print textfield( -name => 'uid', -value => $uid ) . nl(); - print popup_menu( 'type', [ 'EC_LDAP', 'SNMC_LDAP', 'NET1', 'EC_LDAP_Proxy', 'EC_LDAP_RP' ], 'NET1' ); - print submit( -name => 'action', -value => 'Search' ); - print end_form(); -} -print '</div>'; -dg_footer_html(); - -################ Some functions ############################### - -sub is_memberOf ($$$) -{ - my ( $ad, $user, $grp ) = @_; - my $attrs = ['memberOf']; - my $filter = "memberOf=$grp"; - my $results = $ad->search( base => $user, filter => $filter, attrs => $attrs, scope => 'base' ); - my $count = $results->count; - if ( $count == 1 ) { - return 1; - } elsif ( $count == 0 ) { - return 0; - } else { - print "Should not happen\n"; - print Dumper( $results ); - return -1; - } -} - -sub get_memberOf ($$$$$) -{ - my ( $ad, $grp, $attrs, $filter, $base ) = @_; - my @memberOf = (); - my $results = $ad->search( base => $grp, filter => $filter, attrs => $attrs, scope => $base ); - my $count = $results->count; - - # print html_rendering ( Dumper( $results->as_struct() ) ); # if $verbose; - if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); - } elsif ( $count == 0 ) { - metaprint( 'error', 'Not found' ); - } elsif ( $count >= 1 ) { - foreach my $entry ( $results->entries ) { - - # print html_rendering( Dumper( $entry ) ); - foreach my $key ( @$attrs ) { - my @tmp = $entry->get_value( lc( $key ) ); - foreach my $v ( @tmp ) { - push( @memberOf, $v ); - } - } - } - } - return @memberOf; -} - -sub get_ldap_memberOf ($$$$$) -{ - my ( $ad, $searchbase, $user, $attrs, $filter ) = @_; - $filter = $filter . $user; - my @memberOf = (); - my $results = $ad->search( base => $searchbase, filter => $filter, attrs => $attrs, scope => 'sub' ); - my $count = $results->count; - - # print html_rendering ( Dumper( $results->as_struct() ) ) if $verbose; - if ( $count >= 1 ) { - foreach my $entry ( $results->entries ) { - - # print html_rendering( Dumper( $entry ) ); - foreach my $key ( @$attrs ) { - my @tmp = $entry->get_value( lc( $key ) ); - foreach my $v ( @tmp ) { - push( @memberOf, $v ); - } - } - } - } - return @memberOf; -} - -sub get_dn ($$$$$;$) -{ - my ( $ad, $searchbase, $user, $attrs, $filter, $filter_post ) = @_; - $filter = $filter . $user; - if ( defined( $filter_post ) ) { - $filter = $filter . $filter_post; - } - metaprint( 'error', $filter); - my $results = $ad->search( base => $searchbase, filter => $filter, attrs => $attrs, scope => 'sub' ); - my $count = $results->count; - print html_rendering ( Dumper( $results->as_struct() ) ) if $verbose; - if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); - } elsif ( $count == 0 ) { - metaprint( 'error', 'Not found' ); - } elsif ( $count == 1 ) { - my $entry = $results->entry( 0 ); - print "dn-> " . $entry->dn . "\n" if ( $main::debug ); - return $entry->dn; - } else { - return "Not found"; - } -} - -sub search_rec ($$$$) -{ - my ( $ad, $user_dn, $level, $known ) = @_; - my $attrs = ['memberOf']; - my $filter = "objectclass=*"; - my $base = 'base'; - my @memberOf = get_memberOf( $ad, $user_dn, $attrs, $filter, $base ); - foreach my $grp ( @memberOf ) { - print "'$grp'<br>"; - next if ( $grp =~ /Distribution|Resource/ ); - - print "level $level groupname: '$grp'" . nl(); - if ( ( !defined( $known->{$grp} ) ) && ( $grp =~ /^CN=(.+?),OU=/ ) ) { - $known->{$grp} = $1; - $level++; - search_rec( $ad, $grp, $level, $known ); - $level--; - } - } -} - -exit 0; - diff --git a/cgi-bin/get_users_in_AD_group.pl b/cgi-bin/get_users_in_AD_group.pl deleted file mode 100755 index 8ea5553..0000000 --- a/cgi-bin/get_users_in_AD_group.pl +++ /dev/null @@ -1,344 +0,0 @@ -#!/usr/bin/perl -# Check if user is member of an AD's group (up to 3 group of group deep) -# 1. check if user is a direct member of the group -# 2. check recursively in each user's group to find if a member's group is included in the target group -# -use strict; -use warnings; - -# -use Data::Dumper; -use CGI qw/:standard start_ol/; -use Config::IniFiles; -use File::Basename; - -use Net::LDAP; - -# unbuffered output: -$| = 1; - -sub is_memberOf ($$$); -sub get_memberOf ($$$$$); -sub get_ldap_memberOf ($$$$$); -sub get_dn ($$$$$); -sub search_rec ($$$$); - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} -use SNET::access; -use SNET::common; -use SNET::html; -use SNET::ActiveDirectory; - -use vars qw($verbose $debug $help $env $script $cli_mode); -$debug = 0; -$verbose = 0; -( $script ) = split( /\./, basename( $0 ) ); - -my $title = "User Dump"; -my $function = $title; -$function =~ s/\s/_/g; -my $href = ""; -my $header = h1( a( { href => "/snet/cgi-bin/auth/$script.pl" }, $title ) ); -my $html_msg = ""; - -$env = $ENV{"ENV"}; -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -if ( !defined( $env ) || ( $env =~ /^$/ ) ) { - $env = "test"; -} - -( $html_msg ) = Access_snet_script_head( $script, $global_iniFile, $ENV, $env ); - -print header( -type => "text/html", -charset => 'UTF-8', ); - -dg_header_html( $title, 1, 0, $href, $header ); -print $html_msg; - -print "Loading INI file Parameters" . br . "\n" if $verbose; -my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'LDAP' ) ); -metaprint( "error", "error value of AiniFile is undefined" ) if ( !defined( $AiniFile ) ); - -my $credential = (); - -$credential->{'NET1'}{'server'} = $AiniFile->val( 'AD_NET1', 'SERVER' ); -metaprint( "error", "error value of adserver is undefined" ) if ( !defined( $credential->{'NET1'}{'server'} ) ); -$credential->{'NET1'}{'user'} = $AiniFile->val( 'AD_NET1', 'USER' ); -metaprint( "error", "error value of aduser is undefined" ) if ( !defined( $credential->{'NET1'}{'user'} ) ); -$credential->{'NET1'}{'passwd'} = $AiniFile->val( 'AD_NET1', 'PASSWORD' ); -metaprint( "error", "error value of adpasswd is undefined" ) if ( !defined( $credential->{'NET1'}{'passwd'} ) ); -$credential->{'NET1'}{'base'} = 'DC=net1,DC=cec,DC=eu,DC=int'; -$credential->{'NET1'}{'attrs'} = ['cn']; -$credential->{'NET1'}{'filter'} = "sAMAccountName="; - -#### - -$credential->{'EC_LDAP'}{'server'} = $AiniFile->val( 'LDAP_EC', 'SERVER' ); -metaprint( "error", "error value of ec_ldapserver is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'server'} ) ); -$credential->{'EC_LDAP'}{'user'} = $AiniFile->val( 'LDAP_EC', 'USER' ); -metaprint( "error", "error value of ec_ldapuser is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'user'} ) ); -$credential->{'EC_LDAP'}{'passwd'} = $AiniFile->val( 'LDAP_EC', 'PASSWORD' ); -metaprint( "error", "error value of ec_ldappasswd is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'passwd'} ) ); -$credential->{'EC_LDAP'}{'base'} = $AiniFile->val( 'LDAP_EC', 'BASE' ); -metaprint( "error", "error value of ec_basedn is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'base'} ) ); -$credential->{'EC_LDAP'}{'attrs'} = ['cn']; -$credential->{'EC_LDAP'}{'attrs_gon'} = ['cudgroup']; -$credential->{'EC_LDAP'}{'filter'} = "uid="; - -$credential->{'EC_LDAP_Proxy'}{'server'} = $AiniFile->val( 'LDAP_EC', 'SERVER' ); -metaprint( "error", "error value of ec_ldapserver is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'server'} ) ); -$credential->{'EC_LDAP_Proxy'}{'user'} = $AiniFile->val( 'LDAP_EC', 'USER' ); -metaprint( "error", "error value of ec_ldapuser is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'user'} ) ); -$credential->{'EC_LDAP_Proxy'}{'passwd'} = $AiniFile->val( 'LDAP_EC', 'PASSWORD' ); -metaprint( "error", "error value of ec_ldappasswd is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'passwd'} ) ); -$credential->{'EC_LDAP_Proxy'}{'base'} = $AiniFile->val( 'LDAP_EC', 'BASE' ); -metaprint( "error", "error value of ec_basedn is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'base'} ) ); -$credential->{'EC_LDAP_Proxy'}{'attrs'} = ['cn']; -$credential->{'EC_LDAP_Proxy'}{'attrs_gon'} = ['cudgroup']; -$credential->{'EC_LDAP_Proxy'}{'filter'} = "uid="; - -$credential->{'EC_LDAP_RP'}{'server'} = $AiniFile->val( 'LDAP_EC', 'SERVER' ); -metaprint( "error", "error value of ec_ldapserver is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'server'} ) ); -$credential->{'EC_LDAP_RP'}{'user'} = $AiniFile->val( 'LDAP_EC', 'USER' ); -metaprint( "error", "error value of ec_ldapuser is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'user'} ) ); -$credential->{'EC_LDAP_RP'}{'passwd'} = $AiniFile->val( 'LDAP_EC', 'PASSWORD' ); -metaprint( "error", "error value of ec_ldappasswd is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'passwd'} ) ); -$credential->{'EC_LDAP_RP'}{'base'} = $AiniFile->val( 'LDAP_EC', 'BASE' ); -metaprint( "error", "error value of ec_basedn is undefined" ) if ( !defined( $credential->{'EC_LDAP'}{'base'} ) ); -$credential->{'EC_LDAP_RP'}{'attrs'} = ['cn']; -$credential->{'EC_LDAP_RP'}{'attrs_gon'} = ['cudgroup']; -$credential->{'EC_LDAP_RP'}{'filter'} = "uid="; - -#### - -$credential->{'SNMC_LDAP'}{'server'} = $AiniFile->val( 'LDAP_SNET_NG', 'SERVER' ); -metaprint( "error", "error value of cfg_ldap_server is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'server'} ) ); -$credential->{'SNMC_LDAP'}{'user'} = $AiniFile->val( 'LDAP_SNET_NG', 'USER' ); -metaprint( "error", "error value of cfg_ldap_user is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'user'} ) ); -$credential->{'SNMC_LDAP'}{'passwd'} = $AiniFile->val( 'LDAP_SNET_NG', 'PASSWORD' ); -metaprint( "error", "error value of cfg_ldap_passwd is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'passwd'} ) ); -$credential->{'SNMC_LDAP'}{'base'} = $AiniFile->val( 'LDAP_SNET_NG', 'BASE' ); -metaprint( "error", "error value of cfg_ldap_search_scope is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'base'} ) ); -$credential->{'SNMC_LDAP'}{'cafile'} = $AiniFile->val( 'LDAP_SNET_NG', 'CA' ); -metaprint( "error", "error value of cfg_ldap_cafile is undefined" ) if ( !defined( $credential->{'SNMC_LDAP'}{'cafile'} ) ); -$credential->{'SNMC_LDAP'}{'attrs'} = [ 'cn', 'memberOf' ]; -$credential->{'SNMC_LDAP'}{'attrs_gon'} = ['memberOf']; -$credential->{'SNMC_LDAP'}{'filter'} = "uid="; - -#my $cfg_ldap_group_search = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_SEARCH' ); -#metaprint( "error", "error value of cfg_ldap_group_search is undefined" ) if ( !defined( $cfg_ldap_group_search ) ); -#my $cfg_ldap_group_search_filter = $AiniFile->val( 'LDAP_SNET_NG', 'FILTER' ); -#metaprint( "error", "error value of cfg_ldap_group_search_filter is undefined" ) if ( !defined( $cfg_ldap_group_search_filter ) ); -#$cfg_ldap_group_search_filter = "(&(objectclass=posixGroup)(cn=REPLACE))"; -#my $cfg_ldap_group_attribute = $AiniFile->val( 'LDAP_SNET_NG', 'GRP_ATTRIBUTE' ); -#metaprint( "error", "error value of cfg_ldap_group_attribute is undefined" ) if ( !defined( $cfg_ldap_group_attribute ) ); -#$cfg_ldap_group_attribute = ["memberuid"]; -#my $cfg_ldap_search_scope = $AiniFile->val( 'LDAP_SNET_NG', 'SEARCH_SCOPE' ); -#metaprint( "error", "error value of cfg_ldap_search_scope is undefined" ) if ( !defined( $cfg_ldap_search_scope ) ); - -############ Get user name, group - -my $action = ''; -$action = param( 'action' ) if ( ( defined( param( 'action' ) ) ) && ( param( 'action' ) !~ /^$/ ) && ( param( 'action' ) =~ /^\w+$/ ) ); -my $uid = ''; -$uid = param( 'uid' ) if ( ( defined( param( 'uid' ) ) ) && ( param( 'uid' ) !~ /^$/ ) && ( param( 'uid' ) =~ /^\w+$/ ) ); -my $type = 'NET1'; -$type = param( 'type' ) if ( ( defined( param( 'type' ) ) ) && ( param( 'type' ) !~ /^$/ ) && ( param( 'type' ) =~ /^((EC|SNMC)_LDAP(_Proxy|RP)?|NET1)$/ ) ); -my $format = ''; -$format = param( 'format' ) if ( ( defined( param( 'format' ) ) ) && ( param( 'format' ) !~ /^$/ ) && ( param( 'format' ) =~ /^\w+$/ ) ); - -$verbose = 1 if ( ( defined( param( 'verbose' ) ) ) && ( param( 'verbose' ) !~ /^$/ ) && ( param( 'verbose' ) =~ /^[\d\w]+$/ ) && ( param( 'verbose' ) eq 'godmode1' ) ); -$debug = 1 if ( ( defined( param( 'debug' ) ) ) && ( param( 'debug' ) !~ /^$/ ) && ( param( 'debug' ) =~ /^[\d\w]+$/ ) && ( param( 'debug' ) eq 'godmode1' ) ); - -if ( ( $action eq 'Search' ) && ( $uid =~ /^\w+$/ ) && ( $type =~ /^((EC|SNMC)_LDAP(_Proxy|RP)?|NET1)$/ ) ) { - - print '<div class="preview">'; - my ( $status, $connection ) = - AD_connect( $credential->{$type}{'server'}, $credential->{$type}{'user'}, $credential->{$type}{'passwd'}, ( $credential->{$type}{'cafile'} ? $credential->{$type}{'cafile'} : '' ) ); - if ( !$status ) { - print "ERROR: $connection." . nl(); - exit 1; - } - my $searchbase = $credential->{$type}{'base'}; - - # TODO check for bind errors - #print "bind: ldap_error_text($mesg->code) \n"; - #print Dumper($mesg); - -##################################### MAIN ########################################### - print "Searching for uid '$uid' in $type !" . nl(); - -## -## Get DN for user and goup - my $user_dn = get_dn( $connection, $searchbase, $uid, $credential->{$type}{'attrs'}, $credential->{$type}{'filter'} ); - if ( $user_dn eq "Not found" ) { - print "uid $uid not found in $type ($searchbase)!" . nl(); - exit 1; - } - print "User DN: $user_dn" . nl(); - -## -## Recursive check - print "Searching all group recursivly." . nl(); - if ( defined( $credential->{$type}{'attrs_gon'} ) ) { - print "Searching for groupOfName membership." . nl(); - my @ldap_group = get_ldap_memberOf( $connection, $searchbase, $uid, $credential->{$type}{'attrs_gon'}, $credential->{$type}{'filter'} ); - foreach ( @ldap_group ) { - print "level 0 groupname: '$_'" . nl(); - } - } - if ( $type eq 'SNMC_LDAP' ) { - print "Searching for PosixGroup membership." . nl(); - my $attrs = ['cn']; - my $filter = "(&(objectclass=posixGroup)(memberuid=$uid))"; - my $base = 'sub'; - - my @ldap_group = get_memberOf( $connection, $searchbase, $attrs, $filter, $base ); - foreach ( @ldap_group ) { - print "level 0 groupname: '$_'" . nl(); - } - } - if ( $type eq 'NET1' ) { - my $known = (); - search_rec( $connection, $user_dn, 1, $known ); - } - print '</div>'; -} else { - - print "Display the user membership" . nl(); - print start_ol(); - print "Please fill the username in lower case." . nl(); - print "Please choose the authorisation to perform the audit." . nl(); - print end_ol(); - - print start_form( -enctype => &CGI::URL_ENCODED ); - print "<em>Username:</em>" . nl(); - print textfield( -name => 'uid', -value => $uid ) . nl(); - print popup_menu( 'type', [ 'EC_LDAP', 'SNMC_LDAP', 'NET1', 'EC_LDAP_Proxy', 'EC_LDAP_RP' ], 'NET1' ); - print submit( -name => 'action', -value => 'Search' ); - print end_form(); -} -print '</div>'; -dg_footer_html(); - -################ Some functions ############################### - -sub is_memberOf ($$$) -{ - my ( $ad, $user, $grp ) = @_; - my $attrs = ['memberOf']; - my $filter = "memberOf=$grp"; - my $results = $ad->search( base => $user, filter => $filter, attrs => $attrs, scope => 'base' ); - my $count = $results->count; - if ( $count == 1 ) { - return 1; - } elsif ( $count == 0 ) { - return 0; - } else { - print "Should not happen\n"; - print Dumper( $results ); - return -1; - } -} - -sub get_memberOf ($$$$$) -{ - my ( $ad, $grp, $attrs, $filter, $base ) = @_; - my @memberOf = (); - my $results = $ad->search( base => $grp, filter => $filter, attrs => $attrs, scope => $base ); - my $count = $results->count; - - # print html_rendering ( Dumper( $results->as_struct() ) ); # if $verbose; - if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); - } elsif ( $count == 0 ) { - metaprint( 'error', 'Not found' ); - } elsif ( $count >= 1 ) { - foreach my $entry ( $results->entries ) { - - # print html_rendering( Dumper( $entry ) ); - foreach my $key ( @$attrs ) { - my @tmp = $entry->get_value( lc( $key ) ); - foreach my $v ( @tmp ) { - push( @memberOf, $v ); - } - } - } - } - return @memberOf; -} - -sub get_ldap_memberOf ($$$$$) -{ - my ( $ad, $searchbase, $user, $attrs, $filter ) = @_; - $filter = $filter . $user; - my @memberOf = (); - my $results = $ad->search( base => $searchbase, filter => $filter, attrs => $attrs, scope => 'sub' ); - my $count = $results->count; - - # print html_rendering ( Dumper( $results->as_struct() ) ) if $verbose; - if ( $count >= 1 ) { - foreach my $entry ( $results->entries ) { - - # print html_rendering( Dumper( $entry ) ); - foreach my $key ( @$attrs ) { - my @tmp = $entry->get_value( lc( $key ) ); - foreach my $v ( @tmp ) { - push( @memberOf, $v ); - } - } - } - } - return @memberOf; -} - -sub get_dn ($$$$$) -{ - my ( $ad, $searchbase, $user, $attrs, $filter ) = @_; - $filter = $filter . $user; - my $results = $ad->search( base => $searchbase, filter => $filter, attrs => $attrs, scope => 'sub' ); - my $count = $results->count; - print html_rendering ( Dumper( $results->as_struct() ) ) if $verbose; - if ( $results->is_error() ) { - metaprint( 'error', 'search failed: ' . $results->error_text ); - metaprint( 'error', 'search failed: ' . $results->code ); - metaprint( 'error', 'search failed: ' . $results->error ); - } elsif ( $count == 0 ) { - metaprint( 'error', 'Not found' ); - } elsif ( $count == 1 ) { - my $entry = $results->entry( 0 ); - print "dn-> " . $entry->dn . "\n" if ( $main::debug ); - return $entry->dn; - } else { - return "Not found"; - } -} - -sub search_rec ($$$$) -{ - my ( $ad, $user_dn, $level, $known ) = @_; - my $attrs = ['memberOf']; - my $filter = "objectclass=*"; - my $base = 'base'; - my @memberOf = get_memberOf( $ad, $user_dn, $attrs, $filter, $base ); - foreach my $grp ( @memberOf ) { - print "'$grp'<br>"; - next if ( $grp =~ /Distribution|Resource/ ); - - print "level $level groupname: '$grp'" . nl(); - if ( ( !defined( $known->{$grp} ) ) && ( $grp =~ /^CN=(.+?),OU=/ ) ) { - $known->{$grp} = $1; - $level++; - search_rec( $ad, $grp, $level, $known ); - $level--; - } - } -} - -exit 0; - diff --git a/cgi-bin/ldap_NS.pl b/cgi-bin/ldap_NS.pl deleted file mode 100755 index 3a69971..0000000 --- a/cgi-bin/ldap_NS.pl +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/perl -use strict; -use warnings; -exec '/usr/bin/perl', '-T', '/opt/auth/bin/ldap_NS.pl'; - diff --git a/cgi-bin/ldap_NS_adduser.pl b/cgi-bin/ldap_NS_adduser.pl deleted file mode 100755 index df49fc3..0000000 --- a/cgi-bin/ldap_NS_adduser.pl +++ /dev/null @@ -1,515 +0,0 @@ -#!/usr/bin/perl - -# -use strict; -use warnings; - -# -use Data::Dumper; -use CGI qw/:standard start_ol/; -use Config::IniFiles; -use File::Basename; - -use Net::LDAP; -use Data::Dumper; - -# unbuffered output: -$| = 1; - -BEGIN { - my $iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - push( @INC, $iniFile->val( 'APPLICATION', 'LIBRARY' ) ); -} -use SNET::access; -use SNET::common; -use SNET::html; -use SNET::ActiveDirectory; - -use vars qw($verbose $debug $help $env $script $cli_mode $action $IM $username $belongs_iss3 $belongs_network $belongs_security $ldap_admin $ldap_passwd); -$debug = 0; -$verbose = 0; -( $script ) = split( /\./, basename( $0 ) ); - -my $title = "LDAP Add User"; -my $function = $title; -$function =~ s/\s/_/g; -my $href = ""; -my $header = ""; -my $html_msg = ""; - -my $global_iniFile = new Config::IniFiles( -file => "/opt/etc/ini/global.ini" ); - -$env = "test"; # "prod"; -( $html_msg ) = Access_snet_script_head( $script, $global_iniFile, $ENV, $env ); - -# Get current user -my $run_user = ''; -if ( defined( $ENV{"HTTP_AUTHUSER"} ) ) { - $run_user = $ENV{"HTTP_AUTHUSER"}; -} -if ( $cli_mode && ( $run_user eq '' ) ) { - $run_user = $ENV{"USERNAME"}; -} -$run_user =~ s/uid=//; -$run_user =~ s/,.*$//g; - -=head1 print_prompt - HTML Form - - Display the HTML Form parameters. - - Arguments: - - Login name: - - Text field to write the new login name to be created. The username should already exist in Net1. - - IM: - - Text field to write the SMT IM associated with the request. - - Options: - - iss3,network,security: select only one where the user belong to. - - verbose: active the verbose output. - - debug: active the debug output. - -=cut - -sub print_prompt ($$$$) -{ - my ( $ldap_admin, $ldap_passwd, $username, $IM ) = @_; - - print start_form( -enctype => &CGI::MULTIPART ); - - print "<em>Administrator dn: </em>"; - print textfield( - -name => 'ldap_admin', - -default => ( - $ldap_admin - ? $ldap_admin - : 'cn=administrator,ou=admin,dc=snmc,dc=cec,dc=eu,dc=int' - ), - -size => 50, - -maxlength => 80 - ); - print nl(); - - print nl(); - print "<em>Administrator password: </em>"; - print password_field( - -name => 'ldap_passwd', - -default => ( $ldap_passwd ? $ldap_passwd : '' ), - -size => 50, - -maxlength => 100 - ); - print nl(); - - print nl(); - print "<em>Login name (same as net1): </em>"; - print textfield( - -name => 'username', - -default => ( $username ? $username : '' ), - -size => 50, - -maxlength => 80 - ); - print nl(); - - print nl(); - print "<em>IM (Full SMT ticket number): </em>"; - print textfield( - -name => 'IM', - -default => ( $IM ? $IM : '' ), - -override => 1, - -size => 50, - -maxlength => 100 - ); - print nl(); - - print nl(); - print "<em>Options: </em>" . nl(); - print checkbox_group( - -name => 'belongs', - -values => [ 'iss3', 'network', 'security', 'verbose', 'debug' ], - -linebreak => 'true' - ); - print nl(); - - print "<p>", submit( 'action', 'Submit' ), reset; - print end_form(); - -} - -=head1 do_work - HTML Parameters - - display the parameters passed to the web interface. - - Arguments: None - -=cut - -sub do_work () -{ - my ( @values, $key ); - - return if ( !param ); - print "<h2>Here are the current settings used for the $title processor</h2>"; - - foreach $key ( param ) { - next if ( $key =~ /passw/i ); - print "<strong>$key</strong> -> "; - @values = param( $key ); - print join( ", ", @values ) . nl(); - } - print nl() . nl(); -} - -$action = ''; - -$IM = param( 'IM' ) if ( defined( param( 'IM' ) ) && ( param( 'IM' ) !~ /^$/ ) && ( param( 'IM' ) =~ /^IM\d+$/ ) ); -$action = param( 'action' ) if ( defined( param( 'action' ) ) && ( param( 'action' ) !~ /^$/ ) && ( param( 'action' ) =~ /^\w+$/ ) ); -$username = param( 'username' ) if ( defined( param( 'username' ) ) && ( param( 'username' ) !~ /^$/ ) && ( param( 'username' ) =~ /^[\w-]+$/ ) ); -$ldap_admin = param( 'ldap_admin' ) if ( defined( param( 'ldap_admin' ) ) && ( param( 'ldap_admin' ) !~ /^$/ ) && ( param( 'ldap_admin' ) =~ /^[\w,-]+$/ ) ); -$ldap_passwd = param( 'ldap_passwd' ) if ( defined( param( 'ldap_passwd' ) ) && ( param( 'ldap_passwd' ) !~ /^$/ ) ); - -$belongs_iss3 = 0; -$belongs_network = 0; -$belongs_security = 0; -my $pcount = 0; - -if ( ( defined( param( 'belongs' ) ) && ( param( 'belongs' ) !~ /^$/ ) ) ) { - my @values = param( 'belongs' ); - my $belongs = join( ", ", @values ); - $belongs =~ s/\n//; - $belongs =~ s/\r//; - $belongs =~ s/\s+//; - if ( $belongs =~ /iss3/ ) { - $belongs_iss3 = 1; - $pcount++; - } - if ( $belongs =~ /network/ ) { - $belongs_network = 1; - $pcount++; - } - if ( $belongs =~ /security/ ) { - $belongs_security = 1; - $pcount++; - } - - $verbose = 1 if ( $belongs =~ /verbose/ ); - $debug = 1 if ( $belongs =~ /debug/ ); -} - -print header( -charset => 'UTF-8', ); - -dg_header_html( $title, 1, 0, $href, $header ); -print $html_msg . nl(); - -# TODO add only one belongs_* stuff -#$belongs_iss3 = 0; -#$belongs_network = 0; -#$belongs_security = 0; - -if ( defined( $username ) - && ( $username !~ /^$/ ) - && ( $username =~ /^[\w-]+$/ ) - && defined( $IM ) - && ( $IM !~ /^$/ ) - && ( $IM =~ /^IM\d{10}$/ ) - && ( defined( $action ) ) - && ( $action eq "Submit" ) - && ( $pcount == 1 ) ) { - - do_work(); - - my $AiniFile = new Config::IniFiles( -file => $global_iniFile->val( 'INI', 'AD' ) ); - my $adserver = $AiniFile->val( 'AD_NET1', 'SERVER' ); - print "error value of adserver is undefined" if ( !defined( $adserver ) ); - my $aduser = $AiniFile->val( 'AD_NET1', 'USER' ); - print "error value of aduser is undefined" if ( !defined( $aduser ) ); - my $adpasswd = $AiniFile->val( 'AD_NET1', 'PASSWORD' ); - print "error value of adpasswd is undefined" if ( !defined( $adpasswd ) ); - - my $homeserver = "home.snmc.cec.eu.int"; - - #my $ldap_server = 'vldap02.dev.snmc.cec.eu.int'; - my $ldap_server = 'ldap.snmc.cec.eu.int'; - - #my $ldap_admin = 'cn=administrator,ou=admin,dc=snmc,dc=cec,dc=eu,dc=int'; - my $ldap_min_uid = 2000; - my $ldap_max_uid = 10000; - - my $attrs = [ 'displayName', 'mail' ]; - - my ( $mail, $name ) = ( '', '' ); - print "Searching Net1 for userlogin : '$username'" . nl(); - - my $ad = Net::LDAP->new( $adserver ) - or die "Could not connect to AD: $adserver!"; - - $ad->bind( $aduser, password => $adpasswd ); - - my $searchbase = 'OU=Users_ITIC,OU=DIGIT,OU=DGs,DC=net1,DC=cec,DC=eu,DC=int'; - my $filter = "sAMAccountName=$username"; - - my $results = $ad->search( base => $searchbase, filter => $filter, attrs => $attrs ); - if ( ( $results->code ) && ( $results->code != 32 ) ) { - print "Code:" . $results->code . " '" . $results->error . "'" . nl(); - $ad->unbind; - exit 1; - } - my $count = $results->count; - - if ( $count != 1 ) { - print "More than 1 entries fetched from the AD Net1. Do not know what to do. One and only one entry should be found." . nl(); - $ad->unbind; - exit; - } else { - print "'$count' record fetched from Net1." . nl(); - } - - my $entry = $results->entry( 0 ); - - $mail = $entry->get_value( 'mail' ); - $name = $entry->get_value( 'displayName' ); - $name =~ s/\s\(.*$//; - $mail = lc( $mail ); - - $ad->unbind; - undef $results; - - print "Pursuing the addition of user '$username' with parameters:" . nl(); - print " - Realname: '$name'" . nl(); - print " - Email: '$mail'" . nl(); - print br; - - # Check if username already exist - my $ldap = Net::LDAP->new( $ldap_server ) or die "$@"; - $ldap->bind; - $results = $ldap->search( base => "ou=people,o=snet,dc=snmc,dc=cec,dc=eu,dc=int", filter => "(uid=$username)", attrs => [ "cn", "uidNumber" ] ); - $results->code && die $results->error; - - $count = $results->count; - - if ( $count != 0 ) { - print "Account already exist ('$count') in SNet LDAP. stopping process." . nl(); - $entry = $results->entry( 0 ); - print "cn: " . $entry->get_value( 'cn' ) . " uid " . $entry->get_value( 'uidNumber' ) . nl(); - $ldap->unbind; - exit; - } else { - print "Did not found any existing entry in the LDAP SNet directory." . nl(); - } - - undef $results; - - $results = $ldap->search( base => "ou=people,o=dead,dc=snmc,dc=cec,dc=eu,dc=int", filter => "(uid=$username)", attrs => [ "cn", "uidNumber" ] ); - - # TODO: branch does not yet exist... - if ( ( $results->code ) && ( $results->code != 32 ) ) { - print "Code:" . $results->code . " '" . $results->error . "'" . nl(); - $ldap->unbind; - exit 1; - } - $count = $results->count; - - if ( $count != 0 ) { - print "Account already exist in SNet LDAP for the old members! stopping process." . nl(); - $ldap->unbind; - exit; - } else { - print "Did not found any existing entry in the LDAP SNet old members directory." . nl(); - } - - undef $results; - - # fetching all the uid, to find the next available uid - - # first tree... the living one... - $results = $ldap->search( base => "ou=people,o=snet,dc=snmc,dc=cec,dc=eu,dc=int", filter => "(uid=*)", attrs => [ "cn", "uidNumber" ] ); - if ( ( $results->code ) && ( $results->code != 32 ) ) { - print "Code:" . $results->code . " '" . $results->error . "'" . nl(); - $ldap->unbind; - exit 1; - } - - my %blah; - foreach my $entry ( $results->entries ) { - - # $entry->dump; - my $uid = $entry->get_value( 'cn' ); - my $uidnumber = $entry->get_value( 'uidNumber' ); - - if ( defined( $blah{$uidnumber} ) ) { - $blah{$uidnumber} = $blah{$uidnumber} + 1; - } else { - if ( ( $uidnumber >= $ldap_min_uid ) && ( $uidnumber < 10000 ) ) { - $blah{$uidnumber} = 1; - } - } - } - - undef $results; - - # searching the dead one... - $results = $ldap->search( base => "ou=people,o=dead,dc=snmc,dc=cec,dc=eu,dc=int", filter => "(uid=*)", attrs => [ "cn", "uidNumber" ] ); - if ( ( $results->code ) && ( $results->code != 32 ) ) { - print "Code:" . $results->code . " '" . $results->error . "'" . nl(); - $ldap->unbind; - exit 1; - } - - foreach my $entry ( $results->entries ) { - - # $entry->dump; - my $uid = $entry->get_value( 'cn' ); - my $uidnumber = $entry->get_value( 'uidNumber' ); - - if ( defined( $blah{$uidnumber} ) ) { - $blah{$uidnumber} = $blah{$uidnumber} + 1; - } else { - if ( ( $uidnumber >= $ldap_min_uid ) && ( $uidnumber < $ldap_max_uid ) ) { - $blah{$uidnumber} = 1; - } - } - } - - $ldap->unbind; - undef $results; - - foreach my $key ( sort { $a <=> $b } ( keys( %blah ) ) ) { - if ( $blah{$key} > 1 ) { - print "WARNING : uid number $key is used several time!" . nl(); - } - } - - my $next_free_uidnumber; - for ( $next_free_uidnumber = $ldap_min_uid ; $next_free_uidnumber <= $ldap_max_uid ; $next_free_uidnumber++ ) { - if ( !defined( $blah{$next_free_uidnumber} ) ) { - last; - } - } - - if ( $next_free_uidnumber < $ldap_max_uid ) { - print "next free uid number : $next_free_uidnumber" . nl(); - } else { - print "No more uid number available!" . nl(); - exit 1; - } - - my $uidn = $next_free_uidnumber; - my $gidn = 3500; # gid is snmc... - - my $description = (); - my $folder = ''; - if ( $belongs_network ) { - push( @$description, 'RPRO' ); - push( @$description, 'PSRO' ); - push( @$description, 'CWRW' ); - $folder = 'network'; - } elsif ( $belongs_security ) { - push( @$description, 'RPRW' ); - push( @$description, 'PSRW' ); - push( @$description, 'CWRO' ); - $folder = 'security'; - } elsif ( $belongs_iss3 ) { - push( @$description, 'RPRW' ); - push( @$description, 'PSRW' ); - push( @$description, 'CWRA' ); - $folder = 'iss3'; - } - - my $uid_dn = "uid=${username},ou=${folder},ou=people,o=snet,dc=snmc,dc=cec,dc=eu,dc=int"; - - print "Creating user '$username' using the following parameters:" . nl(); - print " - Realname: '$name'" . nl(); - print " - Email: '$mail'" . nl(); - print " - UID number: '$uidn'" . nl(); - print " - GID number: '$gidn'" . nl(); - print " - description: " . Dumper( $description ) . nl(); - print " - uid_dn: '$uid_dn'" . nl(); - print " - AUDIT: '$IM;$run_user;A;" . time . "'" . nl(); - print br; - - # Need to SSH to home.snmc.cec.eu.int - # if ( ! -d "/opt/home/$username" ) { - # print "Creation directory"; - # system "mkdir /opt/home/$username"; - # system "chown $next_free_uidnumber:3500 /opt/home/$username"; - # } - - my $word = 'P@ssword01'; - - # password is sha1 automatically on server side. - # - # srand(time ^ $$); - # my @saltchars=('a'..'z','A'..'Z',0..9,'.','/'); - # my $salt=$saltchars[int(rand($#saltchars+1))]; - # $salt.=$saltchars[int(rand($#saltchars+1))]; - # my $pass = crypt($word,$salt); - my $pass = $word; - - print "Adding to the SNet LDAP server '$ldap_server'" . nl(); - - $ldap = Net::LDAP->new( $ldap_server ) or die "$@"; - $ldap->bind( $ldap_admin, password => $ldap_passwd ); - - $results = $ldap->add( - $uid_dn, - attr => [ - 'cn' => $username, - 'sn' => $username, - 'uid' => $username, - 'uidNumber' => $uidn, - 'gidNumber' => $gidn, - 'description' => $description, - 'mail' => $mail, - 'gecos' => $name, - 'homeDirectory' => "/home/$username", - 'loginShell' => '/bin/ksh', - 'userPassword' => '{CLEARTXT}' . $pass, - - #'shadowLastChange' => '11640', - #'shadowFlag' => '0', - 'auditInformation' => "$IM;$run_user;A;" . time, - 'objectClass' => [ 'inetOrgPerson', 'organizationalPerson', 'person', 'posixAccount', 'simpleSecurityObject', 'SNetPerson', 'top' ], - ] - ); - if ( ( $results->code ) && ( $results->code != 32 ) ) { - print "Code:" . $results->code . " '" . $results->error . "'" . nl(); - $ldap->unbind; - exit 1; - } - - $results->code && warn "failed to add entry: ", $results->error; - - undef $results; - - # $result = $ldap->modify( "cn=snmc,ou=group,dc=snmc,dc=cec,dc=eu,dc=int", add => { memberUid => $username } ); - # $result->code && warn "failed to modify group snmc: ", $result->error ; - # $result = $ldap->modify( "cn=NS,ou=group,dc=snmc,dc=cec,dc=eu,dc=int", add => { memberUid => $username } ); - # $result->code && warn "failed to modify group: ", $result->error ; - - print "User '$username' created." . nl(); - -} else { - - if ( ( defined( $action ) ) && ( $action eq "Submit" ) ) { - - if ( $pcount > 1 ) { - print "ERROR: only 1 group is valid" . nl(); - } elsif ( $pcount < 1 ) { - - print "ERROR: at least 1 group is needed" . nl(); - } - if ( defined( $username ) && ( $username !~ /^$/ ) && ( $username !~ /^[\w-]+$/ ) ) { - print "ERROR: username contains some unsupported characters." . nl(); - } - if ( defined( $IM ) && ( $IM !~ /^$/ ) && ( $IM !~ /^IM\d{10}$/ ) ) { - print "ERROR: IM is not a valid IM number." . nl(); - } - if ( defined( $ldap_admin ) && ( $ldap_admin !~ /^$/ ) && ( $ldap_admin !~ /^[\w,-]+$/ ) ) { - print "ERROR: admin dn contains some unsupported characters." . nl(); - } - } - print_prompt( $ldap_admin, $ldap_passwd, $username, $IM ); -} -print '</div>'; -print "<hr> <address>Snet NS Team</address><br> <a href=\"\">Home Page</a>"; -print end_html; - -exit 1; - diff --git a/htdocs/css/ldapns.css b/htdocs/css/ldapns.css deleted file mode 100644 index 37a5cdd..0000000 --- a/htdocs/css/ldapns.css +++ /dev/null @@ -1,468 +0,0 @@ - -.ldapns_header, -.ldapns_footer, -.ldapns_body { - position:relative; - clear:both; - float:left; - width:100%; - margin:0; - padding:0; - overflow:hidden; -} - -.ldapns_body { - font-family: verdana, sans-serif; - font-style: normal; - font-variant: normal; - font-weight: normal; - font-size: medium; - text-align: left; - white-space: nowrap; - text-transform: none; - text-decoration: none; - text-indent: 0ex; -} - -/* - * 80% of the main container is located outside - * of the window, to the left - */ -.ldapns_columns { - float:left; - width:100%; - position:relative; - right:80%; -} - -/* - * the left pannel is located 81% from the - * right border of the main pannel, - * that is, in the 20% of the visible - * main pannel - */ -.ldapns_left_pannel { - width:18%; - left:81%; - text-transform: capitalize; -} - -/* - * same with the right pannel - */ -.ldapns_right_pannel { - width:78%; - left:82%; -} - -.ldapns_left_pannel, -.ldapns_right_pannel { - float:left; - position:relative; - overflow:hidden; -} - -.ldapns_left_pannel { - padding:2em 0 2em 0; - line-height:3em; -} - -.ldapns_left_pannel { - font-family: tahoma, verdana, sans-serif; -} - -.ldapns_left_pannel a { - display: block; - text-decoration:none; -} -.ldapns_left_pannel a, .ldapns_left_pannel .ldapns_current { - width:100%; -} - -.ldapns_left_pannel a:hover { - text-decoration:none; - font-weight:bold; - background-color:#369; -} - -.ldapns_left_pannel ul { - margin: 0; - padding: 1em; - text-align:left; - text-decoration:none; - list-style:none; - width:100%; -} - -.ldapns_left_pannel li { - text-indent: 1em; - border-bottom: #fff solid; - border-top: #fff solid; - border-width: 1px; - background:#ebf4fb; -} - -.ldapns_tab { - position: relative; - clear: both; - float: left; - width: 100%; - height: 3em; - text-transform: capitalize; -} - -.ldapns_tab ul { - margin: 0 1em; - padding: 0; - position: absolute; - bottom: -1px; -} - -.ldapns_tab ul li { - list-style: none; - display: inline; -} - -.ldapns_tab ul a,.ldapns_tab ul span { - display: block; - float: left; - padding: 4px 1em; - margin: 1px 2px 0 0; - text-decoration:none; - font-weight: normal; -} - -.ldapns_tab ul span { - border: 1px solid #b7ddf2; - border-bottom: none; - background:#ebf4fb; - padding-bottom: 6px; - margin-top: 0; - color: #333; -} - -.ldapns_tab ul a { - background:#ebf4f5; - border: 1px solid #bbe1f6; - border-bottom: none; - color: #666; -} - -.ldapns_tab ul a:hover { - margin-top: 0; - border-color: #b7ddf2; - background:#ebf4fb; - border-bottom: 1px solid #ebf4f5; -} - -.ldapns_right_pannel { - padding: 2px 4px 2px 2px; - /*border: 1px solid #b7dd02;*/ -} - -.ldapns_right_content { - float: left; - clear: both; - width: 100%; - background:#ebf4fb; - border: 1px solid #b7ddf2; - padding-top: 2em; - padding-bottom: 1em; -} - -.ldapns_right_content hr { - height:1px; - color:#aacfe4; - background-color:#aacfe4; -} - -.ldapns_current { - font-weight:bold; -} - -.ldapns_blank p { - line-height:3em; -} - -.ldapns_message { - position:relative; - float:left; - clear:both; - font-size:smaller; -} - -.ldapns_message, -.ldapns_error { - position:relative; - float:left; - clear:both; - white-space: normal; - width: auto; - font-size:smaller; - margin-left: 1em; -} - -.ldapns_message { - color:green; -} - -.ldapns_error { - color:red; -} - -.ldapns_addgroup, -.ldapns_adduser, -.ldapns_blank, -.ldapns_delgroup, -.ldapns_deluser, -.ldapns_modgroup, -.ldapns_passwd, -.ldapns_reset, -.ldapns_selectgroup, -.ldapns_selectgroupclass, -.ldapns_selectuser, -.ldapns_selectpolicy, -.ldapns_modpolicy, -.ldapns_groupinfos, -.ldapns_policyinfos, -.ldapns_userinfos { - position: relative; - float:left; - clear:both; - width: 99%; - overflow:hidden; - /*border: 1px solid #b70d02;*/ - margin: 2px; -} - -.ldapns_groupinfos table, -.ldapns_policyinfos table, -.ldapns_userinfos table { - border-collapse: collapse; - width: 100%; - line-height:1.5em; - border: 2px solid #b7ddf2; - padding: 2em; -} - -.ldapns_groupinfos thead, -.ldapns_policyinfos thead, -.ldapns_userinfos thead { - background-color: #b7dff2; - font-weight: bold; - text-align:center; -} - -.ldapns_groupinfos tr th, -.ldapns_policyinfos tr th, -.ldapns_userinfos tr th { - width:25%; -} - -.ldapns_groupinfos tr td, -.ldapns_policyinfos tr td, -.ldapns_userinfos tr td { - width:75%; -} - -#ldapns_modpolicy_form td { - vertical-align: top; -} - -.ldapns_field { - position: relative; - float:left; - clear:both; - overflow:hidden; - margin: 0.5em 1em; - width: 90%; - /*border: 2px solid #b70db2;*/ -} - -.ldapns_field label { - display: block; - float: left; - clear: left; - text-align: right; - width: 15em; - line-height:2em; -} - -.ldapns_field .ldapns_fb_input { - display: block; - float: left; - margin: 0.2em 1em 0.2em 1em; - padding:0.3em 0.3em; -} - -.ldapns_field select { - margin: 0.2em 1em 0.2em 1em; - padding: 0.2em 0.2em 0.2em 0.2em; -} - -.ldapns_field select[multiple] { - padding: 0.2em 1em 0.2em 0.2em; -} - -/* -select[multiple] { - size: 15; - height: 100%; -} -*/ - -.ldapns_field .ldapns_fb_checkbox { - position: relative; - float: left; - width: auto; - clear: left; - margin: 0.5em 1em 0.5em 1em; - /*border: 2px solid #b70db2;*/ -} - -.ldapns_field .ldapns_fb_option { - float: left; - clear: none; - text-align: left; -} - -.ldapns_field .ldapns_submit { - position: relative; - clear: right; - display: inline; -} - -.ldapns_submit { - position: relative; - float:left; - text-align:center; - margin: 2em 2em 0 2em; - /*margin: 0 1em 0 1em;*/ - /*border: 2px solid #b70d32;*/ -} - -.ldapns_list { - position: relative; - float: left; - clear: right; - overflow: hidden; -} - -.ldapns_list .ldapns_fb_select, -.ldapns_list .ldapns_fb_checkbox, -.ldapns_list .ldapns_fb_radio { - position: relative; - float: left; - clear: left; - width: auto; -} - -.ldapns_list .ldapns_fb_checkbox, -.ldapns_list .ldapns_fb_radio { - margin: 0.5em 1em 0.5em 1em; -} - -.ldapns_list .ldapns_fb_option { - display: block; - position: relative; - text-align: left; - clear: right; - float: left; - font-size: smaller; - font-weight: normal; - width: auto; - /*border: 2px solid #b70db2;*/ -} - -.ldapns_field_description { - position: relative; - float: left; -} - -.ldapns_field_description input { - float: left; - clear: both; -} - -.ldapns_field_description #_grow_description { - clear: both; - margin: 0.2em 1em 0.2em 1em; -} - -.ldapns_login { - display: block; - margin: auto auto; - overflow:hidden; - width: 30em; - background: #ebf4fb; - border:solid 2px #b7ddf2; -} - -.ldapns_login label { - width: 11em; -} - -.ldapns_login .ldapns_field { - margin: auto auto; - float: left; - clear: both; - /*border:solid 2px #b7ddf2;*/ -} - -.ldapns_field .ldapns_fb_password, -.ldapns_login .ldapns_fb_password { - display: block; - float: left; - margin: 0.2em 1em 0.2em 1em; - padding:0.3em 0.3em; -} - -.ldapns_login .ldapns_submit { - clear: both; - text-align: center; - float: none; - margin: 1em; - /*border:solid 2px #b7ddf2;*/ -} - -.ldapns_login .ldapns_fb_button { - margin-top: 2em; - margin-bottom: 0em; -} - -.ldapns_comment { - clear: both; - width: auto; - float: left; - white-space: normal; - text-align: left; - /*border: 2px solid #b70db2;*/ -} - -.ldapns_comment label { - line-height:1em; -} - -.ldapns_fb_form { - padding:1em; - position:relative; - float:left; - width:90%; - overflow:hidden; -} - -.ldapns_fb_form label{ - font-weight:bold; - text-align:right; -} - -.ldapns_fb_comment { - color:#666666; - font-size:smaller; - font-weight:normal; - text-align:right; - display:block; - position:relative; - clear:left; -} - diff --git a/htdocs/css/zboub.css b/htdocs/css/zboub.css deleted file mode 100644 index 72dd641..0000000 --- a/htdocs/css/zboub.css +++ /dev/null @@ -1,64 +0,0 @@ -#main { - border: 1px solid #666; - clear: both; - background: #FFF3B3; - padding-top: 2em; -} - -#contents { - padding: 1.5em; - background: #FFFDF3; - min-height: 300px; -} - -#header { - position: relative; - width: 100%; - height: 9em; - width: 45em; /* a width is required for Opera, older Mozilla browsers, and Konqueror browsers */ -} - -#header ul#primary { - margin: 0; - padding: 0; - position: absolute; - bottom: -1px; - width: 45em; /* a width is required for Opera, older Mozilla browsers, and Konqueror browsers */ -} - -#header ul#primary li { - display: inline; - list-style: none; -} - -#header ul#primary a,#header ul#primary span,#header ul#primary a.current { - display: block; - float: left; - padding: 4px 0; - margin: 1px 2px 0 0; - color: #333; -} - -#header ul#primary span,#header ul#primary a.current,#header ul#primary a.current:hover { - border: 1px solid #666; - border-bottom: none; - background: #FFF3B3; - padding-bottom: 6px; - margin-top: 0; -} - -#header ul#primary a { - background: #FFFAE1; - border: 1px solid #AAA; - border-bottom: none; -} - -#header ul#primary a:hover { - margin-top: 0; - border-color: #666; - background: #FFF7CD; - padding-bottom: 15px; -} - - - diff --git a/library/leankit/__init__.py b/library/leankit/__init__.py deleted file mode 100755 index f1b9c0c..0000000 --- a/library/leankit/__init__.py +++ /dev/null @@ -1,196 +0,0 @@ -from logging import getLogger - -from library.leankit.models.Card import Card -from library.leankit.models.ListResponse import BoardListResponse -#from library.leankit.connector.Card import api -from .connector import api - -# from .connector import api - -__author__ = "DVE" -__email__ = "david.vernazobres@ext.ec.europa.eu" -__license__ = "MIT" -__version__ = "1.0.0" - - -def get_users(limit=200): - log.debug('Getting users') - return api._get('/io/user?limit=' + str(200)) - - -def get_user(user_info): - log.debug('Getting user') - return api._get('/io/user?search=' + user_info) - - -def create_user(duser): - log.debug('Creating users') - return api._post('/io/user', duser) - - -def get_invitations(limit=200): - log.debug('Getting intation user pending') - return api._get('/io/invitation?limit=' + str(limit)) - - -def get_boards(limit=100): - log.debug('Getting boards') - return api._get('/io/board?limit=' + str(limit)) - - -def get_board_by_name(board_name: str, limit=100) -> dict: - search_results = search_board(board_name) - for result in search_results.boards: - if result["title"] == board_name: - return result - return None - - -def get_board(board_name: str, limit=100): - return get_board_by_name(board_name, limit) - -#necessary check the import -def search_board(board_name, limit=100) -> BoardListResponse: - log.debug('Getting board') - results = api._get('/io/board', url_params={'limit': str(limit), 'search': board_name}) - # print(results) - list_result = BoardListResponse.decode(results) - return list_result - - -def get_board_detail(board_id): - log.debug('Getting board') - return api._get('/io/board/' + str(board_id)) - - -def get_cards(board_id=None, limit=100, offset=0): - log.debug('Getting cards') - params={} - if board_id is not None: - params['board'] = str(board_id) - if limit is not None: - params['limit'] = str(limit) - if offset is not None: - params['offset'] = str(offset) - - return api._get('/io/card/', params) - - -def get_card(card_id): - log.debug('Getting card') - return api._get('/io/card/' + str(card_id)) - -#necessary check the import -def create_card(card: Card, returnFullRecord=False): - """ - see https://success.planview.com/Planview_LeanKit/LeanKit_API/01_v2/card/create - - :param card: Card-class instance - :param returnFullRecord: Returns the full card record - :return: full card object - """ - log.debug('Assigning card') - return api._post(f'/io/card/?returnFullRecord={str(bool(returnFullRecord)).lower}', dict(card)) - - -def card_assign(assign_card): - log.debug('Assigning card') - return api._post('/io/card/assign', assign_card) - - -def get_cardtype_from_board(board_id): - log.debug('Getting card') - return api._get('/io/board/' + str(board_id) + '/cardType') - - -def update_card(card_id, dcard): - log.debug('Updating card') - return api._patch('/io/card/' + str(card_id), dcard) - -def add_comment(card_id, dcard): - log.debug('add comment to card') - return api._post('/io/card/' + str(card_id) + '/comment', dcard) - - - -# HELPER METHODS - -# get boards ids -def get_boards_ids(boards: dict = None) -> object: - """ - Helper method to enumerate boardname and id only as a list of tuples - - Parameters - ---------- - boards : dict - use data from leankit.get_boards() - - Returns - ------- - eg. [('31512086836591', '[SEC]'), ('31512089953496', 'Compliance'), ('31512089554405', 'Coordination [NET]'),...] - """ - if not boards: - boards = get_boards() - - return [(board['id'], board['title']) for board in boards['boards']] - - -def get_cards_by_board(board_id): - request_params = { - 'board': board_id, # sets the board ID to be queried - filled in later by the program - 'limit': '100000', # sets the limit on the number of cards that can be queried at a time - } - - leankitData = api._get(f'/io/card', url_params=request_params) - - return leankitData - -def get_parent_cards(card_id, board_id): - """ - https://success.planview.com/Planview_LeanKit/LeanKit_API/01_v2/connections/parents - - Method to list the parent cards of a specific card - :param card_id: the id of the card to list its parents - :param board_id: the id of the board to which the card belongs to - - :return: list of card objects - """ - request_params = { - 'board': board_id, - 'limit': '100000' - } - - leankitData = api._get(f'/io/card/{card_id}/connection/parents', url_params = request_params) - - return leankitData - -def add_parent(card_id, parent_id): - """ - https://success.planview.com/Planview_LeanKit/LeanKit_API/01_v2/connections/create - - Method to add a parent connection to a card - :param card_id: the id of card to add the parent connection - :param parent_id: the id of the parent to be added as a connection - :return 201 Created - """ - request_params = { - "cardIds":[card_id], - "connections":{ - "parents":[parent_id] - } - } - return api._post(f'/io/card/connections', request_params) - -''' -def get_newer_if_exists(board_id, version, timezone='UTC'): - """ Downloads a board if a newer version number exists """ - url = '/Board/{}/BoardVersion/{}/GetNewerIfExists' - log.debug('Getting board {} version >{}'.format(board_id, version)) - board = api._get(url.format(board_id, version)) - if board: - return Board(board, timezone) - else: - return None -''' - -log = getLogger(__name__) diff --git a/library/leankit/connector.py b/library/leankit/connector.py deleted file mode 100755 index a9bbf4b..0000000 --- a/library/leankit/connector.py +++ /dev/null @@ -1,135 +0,0 @@ -import logging -import requests -from requests import Response, Request -from pprint import pformat -from json import dumps as json_dumps -from datetime import datetime -import pandas as pd -import time -from . import env_user - - -class Leankit(object): - # see https://success.planview.com/Planview_LeanKit/LeanKit_API/01_v2/01-overview/rate-limiting - RESPONSE_ERROR_TOO_MANY_REQUESTS = 429 - - def __init__(self): - self.session = requests.Session() - - self.proxies = {'http': env_user.http_proxy, 'https': env_user.http_proxy} - - self.base = 'https://{}.leankit.com'.format(env_user.domain) - self.session_token = env_user.bearer - self.headers = {'Content-Type': 'application/json', 'Authorization': 'bearer ' + self.session_token} - - def _get(self, url, url_params={}, **json_kwargs): - log.debug('GET {}'.format(url)) - try: - request = self.session.get(self.base + url, params=url_params, verify=True, headers=self.headers, proxies=self.proxies) - except Exception as error: - raise ConnectionError("Unable to make request: {}".format(error)) - if request.ok: - try: - response = request.json(**json_kwargs) - return response - ''' - else: - msg = "Error {ReplyCode}: {ReplyText}".format(**response) - raise ConnectionError(msg) - ''' - - except ValueError: - raise IOError("Invalid response") - else: - msg = 'Server responded with code {0.status_code}'.format(request) - if request.status_code == 429: - if "Retry-After" in request.headers: - retry_after = request.headers['Retry-After']#Fri, 10 Jun 2022 08:32:14 GMT - time_diff = pd.to_datetime(retry_after.rsplit(" ",1)[0]) - datetime.utcnow() - time.sleep(time_diff.total_seconds()) - return self._get(url, url_params) - msg += ' ' + str(request.text) - raise ConnectionError(msg) - - def _post(self, url, params): - log.debug('POST {}'.format(url)) - print('POST {}'.format(url)) - print(params) - try: - request = self.session.post(self.base + url, json=params, verify=True, headers=self.headers, proxies=self.proxies) - except Exception as error: - raise ConnectionError("Unable to make request: {}".format(error)) - if request.ok: - try: - response = request.json() - return response - ''' - else: - msg = "Error {ReplyCode}: {ReplyText}".format(**response) - raise ConnectionError(msg) - ''' - - except ValueError: - raise IOError("Invalid response") - else: - print(request.status_code) - print(request.content) - print('Playload:%s' % (json_dumps(params, sort_keys=True, indent=4))) - try: - print('HEADERS:' % (pformat(request.headers))) - except: - pass - try: - print('TEXT:' % (pformat(request.text))) - except: - pass - - msg = 'Server responded with code {0.status_code}'.format(request) - raise ConnectionError(msg) - - def _patch(self, url, params): - log.debug('PATCH {}'.format(url)) - print('PATCH {}'.format(url)) - print(params) - try: - request = self.session.patch(self.base + url, json=params, verify=True, headers=self.headers, proxies=self.proxies) - except Exception as error: - raise ConnectionError("Unable to make request: {}".format(error)) - if request.ok: - try: - response = request.json() - return response - ''' - else: - msg = "Error {ReplyCode}: {ReplyText}".format(**response) - raise ConnectionError(msg) - ''' - - except ValueError: - raise IOError("Invalid response") - else: - print(request.status_code) - print(request.content) - print('Playload:%s' % (json_dumps(params, sort_keys=True, indent=4))) - try: - print('HEADERS:' % (pformat(request.headers))) - except: - pass - try: - print('TEXT:' % (pformat(request.text))) - except: - pass - - msg = 'Server responded with code {0.status_code}'.format(request) - raise ConnectionError(msg) - - def check_api_limits(self, response: Response): - # see https://success.planview.com/Planview_LeanKit/LeanKit_API/01_v2/01-overview/rate-limiting - x_ratelimit_limit = response.headers["X-RateLimit-Limit"] - x_ratelimit_remaining = response.headers["X-RateLimit-Remaining"] - x_ratelimit_reset = response.headers["X-RateLimit-Reset"] - retry_after = response.headers["Retry-After"] - - -log = logging.getLogger(__name__) -api = Leankit() diff --git a/library/leankit/env_user.py b/library/leankit/env_user.py deleted file mode 100755 index 67131ac..0000000 --- a/library/leankit/env_user.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -# User Input -http_proxy = 'http://x50l002:x52503@vip-proxy-l4s.snmc.cec.eu.int:8012' - -domain = 'globalntt' -bearer = '081defc59e8ddf15a9083dde53942dd906484c40e683a7403f54777998127b759e7cfdff713adee1bba1e23feed7d3712ad70d3e136fb8a6f76737154b7eec09' - -# End User Input diff --git a/library/leankit/models/ApiObjBase.py b/library/leankit/models/ApiObjBase.py deleted file mode 100755 index e6a2a14..0000000 --- a/library/leankit/models/ApiObjBase.py +++ /dev/null @@ -1,18 +0,0 @@ -from __future__ import annotations #ApiObjBase - - -class ApiObjBase(object): - _data: dict - - def __init__(self, data: dict = {}): - """ constructor """ - self._data = data - - def __iter__(self): - """ add support for json serialization by implementing the __iter__ method""" - for key in self._data: - yield key, self._data[key] - - @staticmethod - def decode(obj: dict): - raise NotImplementedError diff --git a/library/leankit/models/Board.py b/library/leankit/models/Board.py deleted file mode 100755 index 8ef3bf8..0000000 --- a/library/leankit/models/Board.py +++ /dev/null @@ -1,83 +0,0 @@ -from library.leankit.models.User import User -from library.leankit.models.ClassOfService import ClassOfService -from library.leankit.models.CardType import CardType -from library.leankit.models.Lane import Lane, LaneType, LaneClassType -from library.leankit.models.Priority import Priority -from library.leankit.models.BoardLevel import BoardLevel - - -class BoardCustomFieldChoiceConfiguration: - choices: list - - def __iter__(self): - yield 'choices', self.choises - - -class BoardCustomField(object): - id: str # eg. '31512088420962' - index: int # eg. '0' - type: str # eg. 'choice' - label: str # eg. 'PM' - helpText: str # eg. '' - choiceConfiguration: BoardCustomFieldChoiceConfiguration # eg. '{'choices': ['CEUPPENS Olivier (DIGIT-EXT)', 'CHEVALIER Julie (DIGIT-EXT)', 'VANHOUT Chris (DIGIT-EXT)', 'DEDONIS Vytis (DIGIT-EXT)']}' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'index', self.index - yield 'type', self.type - yield 'label', self.label - yield 'helpText', self.helpText - yield 'choiceConfiguration', self.choiceConfiguration - - - - - -class Board(object): - ''' - id string The board id - title string The board title - description string The board description - boardRoleId integer The board role id - isWelcome boolean Indicates if the board is a welcome board - boardRole string The string representation of the board role - ''' - - id: str # eg. '31512088061881' - title: str # eg. 'testing' - description: str # eg. 'Board for Project Managers during the interim period until Planview is ready' - boardRoleId: str # eg. 'boardUser' - isWelcome: bool # eg. 'False' - boardRole: str # eg. 'boardUser' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'title', self.title - yield 'description', self.description - yield 'boardRoleId', self.boardRoleId - yield 'isWelcome', self.isWelcome - yield 'boardRole', self.boardRole - - def __getitem__(self, key): - return getattr(self, key) - - def get_lane_by_name(self, lane_name: str): - return next(lane for lane in self.lanes if lane.name == lane_name) - - @staticmethod - def decode(obj: dict): - newBoard = Board() - - print(obj) - # {'id': '31512097494387', 'title': 'DEV HLP', 'description': '', 'boardRoleId': 2, 'isWelcome': False, 'boardRole': 'boardUser', 'level': {'id': '31512085971730', 'depth': 3, 'maxDepth': 3, 'label': 'Team', 'color': '#ff841f'}} - - newBoard.id = str(obj["id"]) - newBoard.title = str(obj["title"]) - newBoard.description = str(obj["description"]) - newBoard.boardRoleId = str(obj["boardRoleId"]) - newBoard.isWelcome = bool(obj["isWelcome"]) - newBoard.boardRole = str(obj["boardRole"]) - - return newBoard diff --git a/library/leankit/models/BoardLevel.py b/library/leankit/models/BoardLevel.py deleted file mode 100755 index 1099d47..0000000 --- a/library/leankit/models/BoardLevel.py +++ /dev/null @@ -1,24 +0,0 @@ -class BoardLevel(object): - id: str # eg. '31512085971730' - depth: int # eg. '3' - maxDepth: int # eg. '3' - label: str # eg. 'Team' - color: str # eg. '#ff841f' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'depth', self.depth - yield 'maxDepth', self.maxDepth - yield 'label', self.label - yield 'color', self.color - - @staticmethod - def decode(obj: dict): - boardLevel = BoardLevel() - boardLevel.id = str(obj["id"]) - boardLevel.depth = int(obj["depth"]) - boardLevel.maxDepth = int(obj["maxDepth"]) - boardLevel.label = str(obj["label"]) - boardLevel.color = str(obj["color"]) - return boardLevel diff --git a/library/leankit/models/Board_bad.py b/library/leankit/models/Board_bad.py deleted file mode 100755 index 8b93843..0000000 --- a/library/leankit/models/Board_bad.py +++ /dev/null @@ -1,203 +0,0 @@ -from library.leankit.models.User import User -from library.leankit.models.ClassOfService import ClassOfService -from library.leankit.models.CardType import CardType -from library.leankit.models.Lane import Lane, LaneType, LaneClassType -from library.leankit.models.Priority import Priority -from library.leankit.models.BoardLevel import BoardLevel - - -class BoardCustomFieldChoiceConfiguration: - choices: list - - def __iter__(self): - yield 'choices', self.choises - - -class BoardCustomField(object): - id: str # eg. '31512088420962' - index: int # eg. '0' - type: str # eg. 'choice' - label: str # eg. 'PM' - helpText: str # eg. '' - choiceConfiguration: BoardCustomFieldChoiceConfiguration # eg. '{'choices': ['CEUPPENS Olivier (DIGIT-EXT)', 'CHEVALIER Julie (DIGIT-EXT)', 'VANHOUT Chris (DIGIT-EXT)', 'DEDONIS Vytis (DIGIT-EXT)']}' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'index', self.index - yield 'type', self.type - yield 'label', self.label - yield 'helpText', self.helpText - yield 'choiceConfiguration', self.choiceConfiguration - - - - - -class Board(object): - users: list # eg. '[{'id': '31512085836488', 'username': 'Olivier.CEUPPENS@ext.ec.europa.eu', 'firstName': 'Olivier', 'lastName': 'CEUPPENS', 'fullName': 'Olivier CEUPPENS', 'emailAddress': 'Olivier.CEUPPENS@ext.ec.europa.eu', 'gravatarLink': None, 'avatar': None, 'lastAccess': '2021-11-09T08:57:39.286Z', 'dateFormat': 'dd/MM/yyyy', 'organizationId': '31512084678944', 'boardId': '31512088061881', 'wip': 0, 'roleTypeId': 5, 'settings': {}, 'boardRoles': []}]' - classesOfService: list # eg. '[{'id': '31512088061890', 'name': 'Date Dependent', 'iconPath': '/customicons/24/212121/lk_icons_final_01-13.png', 'policy': ''}, {'id': '31512088061891', 'name': 'Expedite', 'iconPath': '/customicons/24/e35027/lk_icons_final_01-03.png', 'policy': ''}, {'id': '31512088061892', 'name': 'Regulatory', 'iconPath': '/customicons/24/49bbd6/lk_icons_final_05-11.png', 'policy': ''}, {'id': '31512088061893', 'name': 'Standard', 'iconPath': '/customicons/24/212121/blank_icon.png', 'policy': ''}, {'id': '31512088468643', 'name': 'PM Project Task', 'iconPath': '/customicons/24/e35027/lk_icons_final_18-12.png', 'policy': ''}]' - tags: list # eg. '[['firewall', 'proxy']]' - customFields: list # eg. '[{'id': '31512088420962', 'index': 0, 'type': 'choice', 'label': 'PM', 'helpText': '', 'choiceConfiguration': {'choices': ['CEUPPENS Olivier (DIGIT-EXT)', 'CHEVALIER Julie (DIGIT-EXT)', 'VANHOUT Chris (DIGIT-EXT)', 'DEDONIS Vytis (DIGIT-EXT)']}}, {'id': '31512088421162', 'index': 1, 'type': 'choice', 'label': 'Project Domain', 'helpText': '', 'choiceConfiguration': {'choices': ['Security', 'Network', 'Network Deployments', 'Development', 'Supporting Services', 'Compliance']}}]' - id: str # eg. '31512088061881' - title: str # eg. 'testing' - description: str # eg. 'Board for Project Managers during the interim period until Planview is ready' - creationDate: str # eg. '2021-08-30T15:24:39.296Z' - classOfServiceEnabled: bool # eg. 'True' - customIconFieldLabel: str # eg. 'Class of Service' - organizationId: str # eg. '31512084678944' - version: int # eg. '1176' - cardColorField: int # eg. '1' - isCardIdEnabled: bool # eg. 'True' - isHeaderEnabled: bool # eg. 'True' - isHyperlinkEnabled: bool # eg. 'False' - isPrefixEnabled: bool # eg. 'False' - prefix: None # eg. 'None' - format: None # eg. 'None' - isPrefixIncludedInHyperlink: bool # eg. 'False' - baseWipOnCardSize: bool # eg. 'False' - excludeCompletedAndArchiveViolations: bool # eg. 'False' - isDuplicateCardIdAllowed: bool # eg. 'True' - isAutoIncrementCardIdEnabled: bool # eg. 'False' - currentExternalCardId: str # eg. '0' - isWelcome: bool # eg. 'False' - isShared: bool # eg. 'True' - isArchived: bool # eg. 'False' - sharedBoardRole: str # eg. '2' - customBoardMoniker: None # eg. 'None' - isPermalinkEnabled: bool # eg. 'False' - isExternalUrlEnabled: bool # eg. 'False' - allowUsersToDeleteCards: bool # eg. 'True' - allowPlanviewIntegration: bool # eg. 'True' - subscriptionId: None # eg. 'None' - boardRole: str # eg. 'boardUser' - effectiveBoardRole: str # eg. 'boardUser' - cardTypes: list # eg. '[{'id': '31512088061883', 'name': 'Other Work', 'colorHex': '#FFFFFF', 'isCardType': True, 'isTaskType': False}, {'id': '31512088061884', 'name': 'Defect', 'colorHex': '#F1C7C5', 'isCardType': True, 'isTaskType': False}, {'id': '31512088061885', 'name': 'Documentation', 'colorHex': '#D0CCE0', 'isCardType': True, 'isTaskType': False}, {'id': '31512088061886', 'name': 'Improvement', 'colorHex': '#BFDFC2', 'isCardType': True, 'isTaskType': False}, {'id': '31512088061887', 'name': 'New Feature', 'colorHex': '#B8CFDF', 'isCardType': True, 'isTaskType': False}, {'id': '31512088061888', 'name': 'Risk / Issue', 'colorHex': '#FAD7B2', 'isCardType': True, 'isTaskType': False}, {'id': '31512088061889', 'name': 'Subtask', 'colorHex': '#FFF8DF', 'isCardType': False, 'isTaskType': True}, {'id': '31512088223250', 'name': 'PM Project Task', 'colorHex': '#02FE1F', 'isCardType': True, 'isTaskType': True}, {'id': '31512088468400', 'name': 'PM Project Subtask', 'colorHex': '#FFF1BF', 'isCardType': False, 'isTaskType': True}, {'id': '31512088679692', 'name': 'Project', 'colorHex': '#FFFFFF', 'isCardType': True, 'isTaskType': True}, {'id': '31512088679694', 'name': 'Change', 'colorHex': '#FFFFFF', 'isCardType': True, 'isTaskType': True}, {'id': '31512089937452', 'name': 'NTX Global Project', 'colorHex': '#FFFFFF', 'isCardType': True, 'isTaskType': False}, {'id': '31512089940077', 'name': 'Project Task', 'colorHex': '#FFFFFF', 'isCardType': True, 'isTaskType': True}]' - laneClassTypes: list # eg. '[{'id': 0, 'name': 'active'}, {'id': 1, 'name': 'backlog'}, {'id': 2, 'name': 'archive'}]' - lanes: list # eg. '[{'id': '31512088061894', 'name': 'Not Started - Future Work', 'description': None, 'cardStatus': 'notStarted', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 0, 'parentLaneId': None, 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 3, 'wipLimit': 0, 'cardCount': 6, 'cardSize': 6, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'backlog', 'laneType': 'ready', 'isCollapsed': False}, {'id': '31512088061899', 'name': 'New Requests', 'description': None, 'cardStatus': 'notStarted', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 0, 'parentLaneId': '31512088061894', 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': False, 'isDefaultDropLane': True, 'columns': 1, 'wipLimit': 0, 'cardCount': 6, 'cardSize': 6, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'backlog', 'laneType': 'ready', 'isCollapsed': False}, {'id': '31512088066548', 'name': 'Finished As Planned', 'description': None, 'cardStatus': 'finished', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 0, 'parentLaneId': '31512088061895', 'activityId': None, 'orientation': 'horizontal', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 3, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'archive', 'laneType': 'untyped', 'isCollapsed': False}, {'id': '31512088061896', 'name': 'Doing Now', 'description': None, 'cardStatus': 'started', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 1, 'parentLaneId': None, 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 2, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'active', 'laneType': 'inProcess', 'isCollapsed': False}, {'id': '31512088066547', 'name': 'Started but not Finished', 'description': None, 'cardStatus': 'finished', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 1, 'parentLaneId': '31512088061895', 'activityId': None, 'orientation': 'horizontal', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 3, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'archive', 'laneType': 'untyped', 'isCollapsed': False}, {'id': '31512088061898', 'name': 'Approved', 'description': None, 'cardStatus': 'notStarted', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 2, 'parentLaneId': '31512088061894', 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 1, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'backlog', 'laneType': 'ready', 'isCollapsed': False}, {'id': '31512088066546', 'name': 'Discarded Requests / Ideas', 'description': None, 'cardStatus': 'finished', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 2, 'parentLaneId': '31512088061895', 'activityId': None, 'orientation': 'horizontal', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 3, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'archive', 'laneType': 'untyped', 'isCollapsed': False}, {'id': '31512088066549', 'name': 'Under Review', 'description': None, 'cardStatus': 'started', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 2, 'parentLaneId': None, 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 2, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'active', 'laneType': 'inProcess', 'isCollapsed': False}, {'id': '31512088061897', 'name': 'Recently Finished', 'description': None, 'cardStatus': 'finished', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 3, 'parentLaneId': None, 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': True, 'isDefaultDropLane': False, 'columns': 2, 'wipLimit': 0, 'cardCount': 1, 'cardSize': 1, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'active', 'laneType': 'completed', 'isCollapsed': False}, {'id': '31512088066550', 'name': 'Ready to Start', 'description': None, 'cardStatus': 'notStarted', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 3, 'parentLaneId': '31512088061894', 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 1, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'backlog', 'laneType': 'ready', 'isCollapsed': False}, {'id': '31512088061895', 'name': 'Finished - Ready to Archive', 'description': None, 'cardStatus': 'finished', 'active': True, 'cardLimit': 0, 'creationDate': '2021-08-30T15:24:39.263Z', 'index': 4, 'parentLaneId': None, 'activityId': None, 'orientation': 'vertical', 'isConnectionDoneLane': False, 'isDefaultDropLane': False, 'columns': 3, 'wipLimit': 0, 'cardCount': 0, 'cardSize': 0, 'archiveCardCount': 0, 'sortBy': None, 'subscriptionId': None, 'laneClassType': 'archive', 'laneType': 'completed', 'isCollapsed': True}]' - laneTypes: list # eg. '[{'id': 1, 'name': 'ready'}, {'id': 2, 'name': 'inProcess'}, {'id': 3, 'name': 'completed'}, {'id': 99, 'name': 'untyped'}]' - userSettings: dict # eg. '{}' - level: BoardLevel # eg. '{'id': '31512085971730', 'depth': 3, 'maxDepth': 3, 'label': 'Team', 'color': '#ff841f'}' - priorities: list # eg. '[{'id': 3, 'name': 'critical'}, {'id': 2, 'name': 'high'}, {'id': 1, 'name': 'normal'}, {'id': 0, 'name': 'low'}]' - layoutChecksum: str # eg. '4634ab4f64013c1b83ad63f3571c20ba' - defaultCardTypeId: str # eg. '31512088061883' - defaultTaskTypeId: str # eg. '31512088061889' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'users', self.users - yield 'classesOfService', self.classesOfService - yield 'tags', self.tags - yield 'customFields', self.customFields - yield 'id', self.id - yield 'title', self.title - yield 'description', self.description - yield 'creationDate', self.creationDate - yield 'classOfServiceEnabled', self.classOfServiceEnabled - yield 'customIconFieldLabel', self.customIconFieldLabel - yield 'organizationId', self.organizationId - yield 'version', self.version - yield 'cardColorField', self.cardColorField - yield 'isCardIdEnabled', self.isCardIdEnabled - yield 'isHeaderEnabled', self.isHeaderEnabled - yield 'isHyperlinkEnabled', self.isHyperlinkEnabled - yield 'isPrefixEnabled', self.isPrefixEnabled - yield 'prefix', self.prefix - yield 'format', self.format - yield 'isPrefixIncludedInHyperlink', self.isPrefixIncludedInHyperlink - yield 'baseWipOnCardSize', self.baseWipOnCardSize - yield 'excludeCompletedAndArchiveViolations', self.excludeCompletedAndArchiveViolations - yield 'isDuplicateCardIdAllowed', self.isDuplicateCardIdAllowed - yield 'isAutoIncrementCardIdEnabled', self.isAutoIncrementCardIdEnabled - yield 'currentExternalCardId', self.currentExternalCardId - yield 'isWelcome', self.isWelcome - yield 'isShared', self.isShared - yield 'isArchived', self.isArchived - yield 'sharedBoardRole', self.sharedBoardRole - yield 'customBoardMoniker', self.customBoardMoniker - yield 'isPermalinkEnabled', self.isPermalinkEnabled - yield 'isExternalUrlEnabled', self.isExternalUrlEnabled - yield 'allowUsersToDeleteCards', self.allowUsersToDeleteCards - yield 'allowPlanviewIntegration', self.allowPlanviewIntegration - yield 'subscriptionId', self.subscriptionId - yield 'boardRole', self.boardRole - yield 'effectiveBoardRole', self.effectiveBoardRole - yield 'cardTypes', self.cardTypes - yield 'laneClassTypes', self.laneClassTypes - yield 'lanes', self.lanes - yield 'laneTypes', self.laneTypes - yield 'userSettings', self.userSettings - yield 'level', self.level - yield 'priorities', self.priorities - yield 'layoutChecksum', self.layoutChecksum - yield 'defaultCardTypeId', self.defaultCardTypeId - yield 'defaultTaskTypeId', self.defaultTaskTypeId - - def get_lane_by_name(self, lane_name: str): - return next(lane for lane in self.lanes if lane.name == lane_name) - - @staticmethod - def decode(obj: dict): - newBoard = Board() - - print(obj) - # {'id': '31512097494387', 'title': 'DEV HLP', 'description': '', 'boardRoleId': 2, 'isWelcome': False, 'boardRole': 'boardUser', 'level': {'id': '31512085971730', 'depth': 3, 'maxDepth': 3, 'label': 'Team', 'color': '#ff841f'}} - - if 'users' in obj: - newBoard.users = list(map(lambda user: User.decode(user), obj['users'])) - if 'classesOfService' in obj: - newBoard.classesOfService = list(map(lambda classOfService: ClassOfService.decode(classOfService), obj['classesOfService'])) - if 'tags' in obj: - newBoard.tags = obj["tags"] # a list of strings - if 'customFields' in obj: - newBoard.customFields = list(map(lambda customField: BoardCustomField.decode(customField), obj['customFields'])) - if 'id' in obj: - newBoard.id = str(obj["id"]) - if 'title' in obj: - newBoard.title = str(obj["title"]) - if 'description' in obj: - newBoard.description = str(obj["description"]) - - newBoard.creationDate = str(obj["creationDate"]) - newBoard.classOfServiceEnabled = bool(obj["classOfServiceEnabled"]) - newBoard.customIconFieldLabel = str(obj["customIconFieldLabel"]) - newBoard.organizationId = str(obj["organizationId"]) - newBoard.version = int(obj["version"]) - newBoard.cardColorField = int(obj["cardColorField"]) - newBoard.isCardIdEnabled = bool(obj["isCardIdEnabled"]) - newBoard.isHeaderEnabled = bool(obj["isHeaderEnabled"]) - newBoard.isHyperlinkEnabled = bool(obj["isHyperlinkEnabled"]) - newBoard.isPrefixEnabled = bool(obj["isPrefixEnabled"]) - newBoard.prefix = obj["prefix"] - newBoard.format = obj["format"] - newBoard.isPrefixIncludedInHyperlink = bool(obj["isPrefixIncludedInHyperlink"]) - newBoard.baseWipOnCardSize = bool(obj["baseWipOnCardSize"]) - newBoard.excludeCompletedAndArchiveViolations = bool(obj["excludeCompletedAndArchiveViolations"]) - newBoard.isDuplicateCardIdAllowed = bool(obj["isDuplicateCardIdAllowed"]) - newBoard.isAutoIncrementCardIdEnabled = bool(obj["isAutoIncrementCardIdEnabled"]) - newBoard.currentExternalCardId = str(obj["currentExternalCardId"]) - newBoard.isWelcome = bool(obj["isWelcome"]) - newBoard.isShared = bool(obj["isShared"]) - newBoard.isArchived = bool(obj["isArchived"]) - newBoard.sharedBoardRole = str(obj["sharedBoardRole"]) - newBoard.customBoardMoniker = obj["customBoardMoniker"] - newBoard.isPermalinkEnabled = bool(obj["isPermalinkEnabled"]) - newBoard.isExternalUrlEnabled = bool(obj["isExternalUrlEnabled"]) - newBoard.allowUsersToDeleteCards = bool(obj["allowUsersToDeleteCards"]) - newBoard.allowPlanviewIntegration = bool(obj["allowPlanviewIntegration"]) - newBoard.subscriptionId = str(obj["subscriptionId"]) - newBoard.boardRole = str(obj["boardRole"]) - newBoard.effectiveBoardRole = str(obj["effectiveBoardRole"]) - newBoard.cardTypes = list(map(lambda cardType: CardType.decode(cardType), obj['cardTypes'])) - # todo, continue conversion from here - newBoard.laneClassTypes = list[laneClassTypes_class](obj["laneClassTypes"]) - newBoard.lanes = list[lanes_class](obj["lanes"]) - newBoard.laneTypes = list[laneTypes_class](obj["laneTypes"]) - newBoard.userSettings = dict(obj["userSettings"]) - newBoard.level = dict(obj["level"]) - newBoard.priorities = list[priorities_class](obj["priorities"]) - newBoard.layoutChecksum = str(obj["layoutChecksum"]) - newBoard.defaultCardTypeId = str(obj["defaultCardTypeId"]) - newBoard.defaultTaskTypeId = str(obj["defaultTaskTypeId"]) - - return newBoard diff --git a/library/leankit/models/Card.py b/library/leankit/models/Card.py deleted file mode 100755 index 1cef581..0000000 --- a/library/leankit/models/Card.py +++ /dev/null @@ -1,137 +0,0 @@ -from multipledispatch import dispatch -# from library.leankit.models.User import User - - -class CardConnection(): - parents: list - children: list - - def __iter__(self): - yield 'parents', self.parents - yield 'children', self.children - - -class CardExternalLink(): - label: str - url: str - - def __iter__(self): - yield 'label', self.label - yield 'url', self.url - - -class CardCustomField(object): - fieldId: str - value: str - - def __iter__(self): - yield 'fieldId', self.fieldId - yield 'value', self.value - - -class Card(object): - boardId: str - title: str - typeId: str - assignedUserIds: list - description: str - size: int - laneId: str - connections: dict - mirrorSourceCardId: str - copiedFromCardId: str - blockReason: str - priority: str - customIconId: str - customId: str - externalLink: list - index: int - plannedStart: str - plannedFinish: str - tags: list - wipOverrideComment: str - customFields: list - - @dispatch() - def __init__(self): - """parameterless constructor for json deserialization support""" - pass - - @dispatch(str, str) - def __init__(self, boardId: str, title: str): - self.boardId = boardId - self.title = title - - def __iter__(self): - for attr_name in dir(self): - if not attr_name.startswith("__"): - print(attr_name) - yield attr_name, getattr(self, attr_name) - - # @dispatch(User) - # def assign_user(self, user: User): - # self.assign_user(user.id) - - @dispatch(str) - def assign_user(self, userid: str): - if userid not in self.assignedUserIds: - self.assignedUserIds.append(userid) - - # @dispatch(User) - # def unassign_user(self, user: User): - # self.unassign_user(user.id) - - @dispatch(str) - def unassign_user(self, userid: str): - if userid in self.assignedUserIds: - self.assignedUserIds.remove(userid) - -# def card_decoder(obj): -# if 'boardId' in obj and 'title' in obj: -# new_card = Card(obj['boardId'], obj['title']) -# if 'typeId' in obj: -# new_card['typeId'] = obj['typeId'] -# -# if 'assignedUserIds' in obj: -# new_card['assignedUserIds'] = obj['assignedUserIds'] -# -# # TODO set others, or generate using inspection/reflection -# return new_card -# return obj - -# cardObj = json.loads('{"__type__": "Card", "rollNumber":1, "name": "Ault kelly", "marks": 78}', object_hook=studentDecoder) -# { -# "boardId": "944576308", -# "title": "The title of the card", -# "typeId": "944576314", -# "assignedUserIds": [ "478440842" ], -# "description": "The card description", -# "size": 1, -# "laneId": "944576326", -# "connections": { -# "parents": ["945202295"], -# "children": ["945250930"] -# }, -# "mirrorSourceCardId": "945202295", -# "copiedFromCardId": "945261794", -# "blockReason": "The block reason", -# "priority": "normal", -# "customIconId": "944576317", -# "customId": "Card header text", -# "externalLink": { -# "label": "The link label", -# "url": "https://www.leankit.com" -# }, -# "index": 1, -# "plannedStart": "2020-01-20", -# "plannedFinish": "2020-02-01", -# "tags": [ -# "tagOne", -# "tagTwo" -# ], -# "wipOverrideComment": "The override reason", -# "customFields": [ { -# "fieldId": "945250752", -# "value": "This is the field value" -# } ] -# } diff --git a/library/leankit/models/CardType.py b/library/leankit/models/CardType.py deleted file mode 100755 index 3c36fcf..0000000 --- a/library/leankit/models/CardType.py +++ /dev/null @@ -1,14 +0,0 @@ -class CardType(object): - id: str # eg. '31512088061883' - name: str # eg. 'Other Work' - colorHex: str # eg. '#FFFFFF' - isCardType: bool # eg. 'True' - isTaskType: bool # eg. 'False' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'name', self.name - yield 'colorHex', self.colorHex - yield 'isCardType', self.isCardType - yield 'isTaskType', self.isTaskType diff --git a/library/leankit/models/ClassOfService.py b/library/leankit/models/ClassOfService.py deleted file mode 100755 index d8cf3d8..0000000 --- a/library/leankit/models/ClassOfService.py +++ /dev/null @@ -1,12 +0,0 @@ -class ClassOfService(object): - id: str # eg. '31512088061890' - name: str # eg. 'Date Dependent' - iconPath: str # eg. '/customicons/24/212121/lk_icons_final_01-13.png' - policy: str # eg. '' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'name', self.name - yield 'iconPath', self.iconPath - yield 'policy', self.policy diff --git a/library/leankit/models/Lane.py b/library/leankit/models/Lane.py deleted file mode 100755 index 92b9749..0000000 --- a/library/leankit/models/Lane.py +++ /dev/null @@ -1,73 +0,0 @@ -class LaneClassType(object): - id: int # eg. '0' - name: str # eg. 'active' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'name', self.name - - -class LaneType(object): - id: int # eg. '1' - name: str # eg. 'ready' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'name', self.name - - -class Lane(object): - id: str # eg. '31512088061894' - name: str # eg. 'Not Started - Future Work' - description: None # eg. 'None' - cardStatus: str # eg. 'notStarted' - active: bool # eg. 'True' - cardLimit: int # eg. '0' - creationDate: str # eg. '2021-08-30T15:24:39.263Z' - index: int # eg. '0' - parentLaneId: None # eg. 'None' - activityId: None # eg. 'None' - orientation: str # eg. 'vertical' - isConnectionDoneLane: bool # eg. 'False' - isDefaultDropLane: bool # eg. 'False' - columns: int # eg. '3' - wipLimit: int # eg. '0' - cardCount: int # eg. '6' - cardSize: int # eg. '6' - archiveCardCount: int # eg. '0' - sortBy: None # eg. 'None' - subscriptionId: None # eg. 'None' - laneClassType: str # eg. 'backlog' - laneType: str # eg. 'ready' - isCollapsed: bool # eg. 'False' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'name', self.name - yield 'description', self.description - yield 'cardStatus', self.cardStatus - yield 'active', self.active - yield 'cardLimit', self.cardLimit - yield 'creationDate', self.creationDate - yield 'index', self.index - yield 'parentLaneId', self.parentLaneId - yield 'activityId', self.activityId - yield 'orientation', self.orientation - yield 'isConnectionDoneLane', self.isConnectionDoneLane - yield 'isDefaultDropLane', self.isDefaultDropLane - yield 'columns', self.columns - yield 'wipLimit', self.wipLimit - yield 'cardCount', self.cardCount - yield 'cardSize', self.cardSize - yield 'archiveCardCount', self.archiveCardCount - yield 'sortBy', self.sortBy - yield 'subscriptionId', self.subscriptionId - yield 'laneClassType', self.laneClassType - yield 'laneType', self.laneType - yield 'isCollapsed', self.isCollapsed - - - diff --git a/library/leankit/models/ListResponse.py b/library/leankit/models/ListResponse.py deleted file mode 100755 index 2c67caa..0000000 --- a/library/leankit/models/ListResponse.py +++ /dev/null @@ -1,93 +0,0 @@ -from library.leankit.models.BoardLevel import BoardLevel -from library.leankit.models.Card import Card -from library.leankit.models.Board import Board - - -class PageMeta: - totalRecords: int - offset: int - limit: int - startRow: int - endRow: int - - def __getitem__(self, key): - return getattr(self, key) - - @staticmethod - def decode(obj: dict): - newPageMeta = PageMeta() - newPageMeta.totalRecords = int(obj["totalRecords"]) - newPageMeta.offset = int(obj["offset"]) - newPageMeta.limit = int(obj["limit"]) - newPageMeta.startRow = int(obj["startRow"]) - newPageMeta.endRow = int(obj["endRow"]) - return newPageMeta - - -class BoardRef: - id: str # eg. '31512088856393' - title: str # eg. 'DEV' - description: str # eg. '' - boardRoleId: int # eg. 2 - isWelcome: bool # eg. False - boardRole: str # eg. 'boardUser' - level: BoardLevel # eg. '{'id': '31512085971730', 'depth': 3, 'maxDepth': 3, 'label': 'Team', 'color': '#ff841f'}' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'title', self.title - yield 'description', self.description - yield 'boardRoleId', self.boardRoleId - yield 'isWelcome', self.isWelcome - yield 'boardRole', self.boardRole - yield 'level', self.level - - def __getitem__(self, key): - return getattr(self, key) - - @staticmethod - def decode(obj: dict): - newBoardRef = BoardRef() - newBoardRef.id = str(obj["id"]) - newBoardRef.title = str(obj["title"]) - newBoardRef.description = str(obj["description"]) - newBoardRef.boardRoleId = int(obj["boardRoleId"]) - newBoardRef.isWelcome = bool(obj["isWelcome"]) - newBoardRef.boardRole = str(obj["boardRole"]) - newBoardRef.level = BoardLevel.decode(obj["level"]) - return newBoardRef - - -class BoardListResponse: - pageMeta: PageMeta - boards: list - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'pageMeta', self.pageMeta - yield 'boards', self.boards - - def __getitem__(self, key): - return getattr(self, key) - - @staticmethod - def decode(obj: dict): - newListResponse = BoardListResponse() - newListResponse.pageMeta = PageMeta.decode(obj['pageMeta']) - print(newListResponse.pageMeta) - newListResponse.boards = list(map(lambda board: Board.decode(board), obj['boards'])) - return newListResponse - - -class CardListResponse: - pageMeta: PageMeta - cards: list - - def __getitem__(self, key): - return getattr(self, key) - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'pageMeta', self.pageMeta - yield 'cards', self.cards diff --git a/library/leankit/models/Priority.py b/library/leankit/models/Priority.py deleted file mode 100755 index d66bccd..0000000 --- a/library/leankit/models/Priority.py +++ /dev/null @@ -1,9 +0,0 @@ -class Priority(object): - id: int # eg. '3' - name: str # eg. 'critical' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'name', self.name - diff --git a/library/leankit/models/User.py b/library/leankit/models/User.py deleted file mode 100755 index 98ce865..0000000 --- a/library/leankit/models/User.py +++ /dev/null @@ -1,36 +0,0 @@ -class User(object): - id: str # eg. '31512085836488' - username: str # eg. 'Olivier.CEUPPENS@ext.ec.europa.eu' - firstName: str # eg. 'Olivier' - lastName: str # eg. 'CEUPPENS' - fullName: str # eg. 'Olivier CEUPPENS' - emailAddress: str # eg. 'Olivier.CEUPPENS@ext.ec.europa.eu' - gravatarLink: None # eg. 'None' - avatar: None # eg. 'None' - lastAccess: str # eg. '2021-11-09T08:57:39.286Z' - dateFormat: str # eg. 'dd/MM/yyyy' - organizationId: str # eg. '31512084678944' - boardId: str # eg. '31512088061881' - wip: int # eg. '0' - roleTypeId: int # eg. '5' - settings: dict # eg. '{}' - boardRoles: list # eg. '[]' - - # support for json serialization by implementing the __iter__ method - def __iter__(self): - yield 'id', self.id - yield 'username', self.username - yield 'firstName', self.firstName - yield 'lastName', self.lastName - yield 'fullName', self.fullName - yield 'emailAddress', self.emailAddress - yield 'gravatarLink', self.gravatarLink - yield 'avatar', self.avatar - yield 'lastAccess', self.lastAccess - yield 'dateFormat', self.dateFormat - yield 'organizationId', self.organizationId - yield 'boardId', self.boardId - yield 'wip', self.wip - yield 'roleTypeId', self.roleTypeId - yield 'settings', self.settings - yield 'boardRoles', self.boardRoles diff --git a/library/leankit/models/__init__.py b/library/leankit/models/__init__.py deleted file mode 100755 index e69de29..0000000 diff --git a/library/servicenow/__init__.py b/library/servicenow/__init__.py deleted file mode 100755 index f72cd1d..0000000 --- a/library/servicenow/__init__.py +++ /dev/null @@ -1,57 +0,0 @@ -from logging import getLogger -from .connector import api -#from library.servicenow.models.Incident import Incident - -__author__ = "MTF" -__email__ = "marcelo.teixeira@ext.ec.europa.eu" -__license__ = "MIT" -__version__ = "1.0.0" - -#Retrieve User GET /sys_user /api/emdig/itsm/sys_user v1 -def get_user(user_info): - log.debug('Getting user') - return api._get('/sys_user?user_name=' + user_info) - -#Create Incident POST /incident /api/emdig/itsm/incident -def create_incident(incident_info): - log.debug('Create Incident') - print(incident_info) - return api._post('/incident', incident_info) - -#Retrieve Incident(s) GET /incident /api/emdig/itsm/incident -#encoded_query=numberSTARTSWITHINC0010034 -#encoded_query=short_descriptionSTARTSWITHem -#encoded_query=assigned_toSTARTSWITHem -#encoded_query=assigned_toSTARTSWITHAndre -#?number=INC0010002 -def get_incident(incident_number): - log.debug('Retrieve Incident(s)') - return api._get('/incident?number=' + incident_number) - -#Update Incident PUT /incident /api/emdig/itsm/incident -def update_incident(data): - log.debug('Update Incident') - return api._put('/incident', data) - -#Create Incident Task POST /incident_task /api/emdig/itsm/incident_task -def create_incident_task(data): - log.debug('Create Incident') - return api._post('/incident_task' , data) - -#Retrieve Incident Task GET /incident_task /api/emdig/itsm/incident_task -def get_incident_task(user_info): - log.debug('Retrieve Incident') - return api._get('/incident_task' + user_info) - -#Update Incident Task PUT /incident_task /api/emdig/itsm/incident_task -def update_incident_task(user_info): - log.debug('Update Incident') - return api._put('/incident_task' + user_info) - -#Set Incident to Restricted PUT /incident_restricted /api/emdig/itsm/incident_restricted -def incident_restricted(user_info): - log.debug('Set Incident') - return api._put('/incident_restricted' + user_info) - - -log = getLogger(__name__) diff --git a/library/servicenow/connector.py b/library/servicenow/connector.py deleted file mode 100755 index b66da60..0000000 --- a/library/servicenow/connector.py +++ /dev/null @@ -1,159 +0,0 @@ -import logging -import requests -from requests import Response, Request -from pprint import pformat -from json import dumps as json_dumps -from datetime import datetime -import time -from . import env_user - - -class ServiceNow(object): - - def __init__(self): - self.session = requests.Session() - self.proxies = {'http': env_user.http_proxy, 'https': env_user.http_proxy} - self.base = env_user.base_url - self.headers = {'Content-Type': 'application/json', 'Authorization': env_user.authorization} - - - def _get(self, url, url_params={}, **json_kwargs): - print('GET {}'.format(url)) - log.debug('GET {}'.format(url)) - try: - request = self.session.get(self.base + url, params=url_params, verify=True, headers=self.headers, proxies=self.proxies) - except Exception as error: - raise ConnectionError("Unable to make request: {}".format(error)) - if request.ok: - try: - response = request.json(**json_kwargs) - return response - ''' - else: - msg = "Error {ReplyCode}: {ReplyText}".format(**response) - raise ConnectionError(msg) - ''' - - except ValueError: - raise IOError("Invalid response") - else: - msg = 'Server responded with code {0.status_code}'.format(request) - if request.status_code == 429: - if "Retry-After" in request.headers: - retry_after = request.headers['Retry-After'] - time_diff = pd.to_datetime(retry_after.rsplit(" ",1)[0]) - datetime.utcnow() - time.sleep(time_diff.total_seconds()) - return self._get(url, url_params) - msg += ' ' + str(request.text) - raise ConnectionError(msg) - - def _post(self, url, params): - log.debug('POST {}'.format(url)) - print('POST {}'.format(url)) - print(params) - try: - request = self.session.post(self.base + url, json=params, verify=True, headers=self.headers, proxies=self.proxies) - except Exception as error: - raise ConnectionError("Unable to make request: {}".format(error)) - if request.ok: - try: - response = request.json() - return response - ''' - else: - msg = "Error {ReplyCode}: {ReplyText}".format(**response) - raise ConnectionError(msg) - ''' - - except ValueError: - raise IOError("Invalid response") - else: - print(request.status_code) - print(request.content) - print('Playload:%s' % (json_dumps(params, sort_keys=True, indent=4))) - try: - print('HEADERS:' % (pformat(request.headers))) - except: - pass - try: - print('TEXT:' % (pformat(request.text))) - except: - pass - - msg = 'Server responded with code {0.status_code}'.format(request) - raise ConnectionError(msg) - - def _patch(self, url, params): - log.debug('PATCH {}'.format(url)) - print('PATCH {}'.format(url)) - print(params) - try: - request = self.session.patch(self.base + url, json=params, verify=True, headers=self.headers, proxies=self.proxies) - except Exception as error: - raise ConnectionError("Unable to make request: {}".format(error)) - if request.ok: - try: - response = request.json() - return response - ''' - else: - msg = "Error {ReplyCode}: {ReplyText}".format(**response) - raise ConnectionError(msg) - ''' - - except ValueError: - raise IOError("Invalid response") - else: - print(request.status_code) - print(request.content) - print('Playload:%s' % (json_dumps(params, sort_keys=True, indent=4))) - try: - print('HEADERS:' % (pformat(request.headers))) - except: - pass - try: - print('TEXT:' % (pformat(request.text))) - except: - pass - - msg = 'Server responded with code {0.status_code}'.format(request) - raise ConnectionError(msg) - - def _put(self, url, params): - log.debug('PUT {}'.format(url)) - print('PUT {}'.format(url)) - print(params) - try: - request = self.session.put(self.base + url, json=params, verify=True, headers=self.headers, proxies=self.proxies) - except Exception as error: - raise ConnectionError("Unable to make request: {}".format(error)) - if request.ok: - try: - response = request.json() - return response - ''' - else: - msg = "Error {ReplyCode}: {ReplyText}".format(**response) - raise ConnectionError(msg) - ''' - - except ValueError: - raise IOError("Invalid response") - else: - print(request.status_code) - print(request.content) - print('Playload:%s' % (json_dumps(params, sort_keys=True, indent=4))) - try: - print('HEADERS:' % (pformat(request.headers))) - except: - pass - try: - print('TEXT:' % (pformat(request.text))) - except: - pass - - msg = 'Server responded with code {0.status_code}'.format(request) - raise ConnectionError(msg) - -log = logging.getLogger(__name__) -api = ServiceNow() diff --git a/library/servicenow/env_user.py b/library/servicenow/env_user.py deleted file mode 100755 index ebe4f1d..0000000 --- a/library/servicenow/env_user.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env /opt/gvenv/venv_csui/bin/python3 -# -*- coding: utf-8 -*- -import requests -import base64 -import socket -from library.vault.client import clientV - -#approle: csui-change-mgmt-dev -#role_id a3b2fdf3-8e8a-55d9-2688-13409145c7b2 -#secret_id fc9674f1-5187-51e8-f8c8-29273b5f6951 -#read access to: apps-kv/dev/SNOW/* - -#approle: csui-change-mgmt-acc -#role_id 0743cc2f-ee65-3bf8-fe3d-27550db27d00 -#secret_id 225cc7f7-1e02-aca8-d84b-45da9a605012 -#read access to: apps-kv/acc/SNOW/* - -#approle: csui-change-mgmt-prod -#role_id 041f50d0-ece2-f9d7-8155-cbe2377081a8 -#secret_id d83c9e67-98d0-9d51-afa0-0a4c680aa0ad -#read access to: apps-kv/prod/SNOW/* - -HOSTNAME = socket.getfqdn() -IS_DEV = ('.dev.' in HOSTNAME) -IS_ACC = ('.acc.' in HOSTNAME) -IS_PRODUCTION = (not IS_DEV and not IS_ACC) - -# User Input -http_proxy = 'http://x50l002:x52503@vip-proxy-l4s.snmc.cec.eu.int:8012' - - -#TODO -> necessary check via ini files the enviorment - create a specofic ini file for that -username = 'DIGIT-WS-SNET-SMART' - -namespace_used = "EC/DIGIT_C4_SNET_ADMIN-ACC" -base_url = "https://digituat.service-now.com/api/emdig/v1/itsm" -vault_url = "https://sam-hcavault.cec.eu.int" - -#In namespace dev/acc : -#approle: csui-change-mgmt-dev -#role_id a3b2fdf3-8e8a-55d9-2688-13409145c7b2 -#secret_id fc9674f1-5187-51e8-f8c8-29273b5f6951 -#read access to: apps-kv/dev/SNOW/* -#approle: csui-change-mgmt-acc -#role_id 0743cc2f-ee65-3bf8-fe3d-27550db27d00 -#secret_id 225cc7f7-1e02-aca8-d84b-45da9a605012 -#read access to: apps-kv/acc/SNOW/* -#approle: csui-change-mgmt-prod -#role_id 041f50d0-ece2-f9d7-8155-cbe2377081a8 -#secret_id d83c9e67-98d0-9d51-afa0-0a4c680aa0ad -#read access to: apps-kv/prod/SNOW/* - -#In namespace production : -#approle: csui-change-mgmt-dev -#role_id cdbb378a-54fe-b0f1-4fcf-d0fa2d60417e -#secret_id a43be6c0-ddbe-fe4a-3fb5-8091cb893121 -#approle: csui-change-mgmt-acc -#role_id 3ae94e71-b1c8-49e5-49dd-6786b6221868 -#secret_id 19c45327-c8c2-ff49-3fef-addb533c90ea -#approle: csui-change-mgmt-prod -#role_id 331d3f1d-2361-e30b-9ac0-3a48a0f1e473 -#secret_id b741c6c9-5536-6a8e-32a2-159be4a4297c -#IS_DEV = False -#IS_ACC = False -#enviorment -if IS_DEV: - print('IS DEV') - engine = "dev" - role_id_read = 'a3b2fdf3-8e8a-55d9-2688-13409145c7b2' - secret_approle_read = 'fc9674f1-5187-51e8-f8c8-29273b5f6951' -elif IS_ACC : - print('IS ACC') - engine = "acc" - role_id_read = '0743cc2f-ee65-3bf8-fe3d-27550db27d00' - secret_approle_read = '225cc7f7-1e02-aca8-d84b-45da9a605012' -else : - print('IS PROD') - namespace_used = "EC/DIGIT_C4_SNET_ADMIN-PROD" - base_url = "https://digit.service-now.com/api/emdig/v1/itsm" - vault_url = "https://sam-hcpvault.cec.eu.int" - engine = 'prod' - role_id_read = '331d3f1d-2361-e30b-9ac0-3a48a0f1e473' - secret_approle_read = 'b741c6c9-5536-6a8e-32a2-159be4a4297c' - - -password = clientV.getPasswordByAppRole(engine+"/SNOW/csui", vault_url, namespace_used, role_id_read, secret_approle_read, "apps-kv", engine) - -credentials = f"{username}:{password}" -encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8") -authorization = f"Basic {encoded_credentials}" -# End User Input diff --git a/library/vault/examples/alternative.py b/library/vault/examples/alternative.py deleted file mode 100755 index dbff150..0000000 --- a/library/vault/examples/alternative.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/home/blondsi/learning/hashicorp-vault/python_hello_world/venv/bin/python -import requests - -VAULT_DIEGO_URL = "https://sam-hcavault.cec.eu.int/v1/kv/data/dev-DIEGO" - -headers = { - "X-Vault-Namespace": "EC/DIGIT_C4_SNET_DEV_ACC-ENV", - "X-Vault-Token": "hvs.CAESIKnpu_C6vTlQmblBTIwzNkWYnKIzIwO40yMAKNnHaq1aGikKImh2cy5WVGxaS1R3bUFKajF0Sm03MTNHR1lEVkUuYTQ5SVAQ277IAg", - "accept": "*/*" -} - -r = requests.get(VAULT_DIEGO_URL, headers=headers, verify=False) -json = r.json() -data = json["data"]["data"] -print(f"Data: {data}") diff --git a/library/vault/examples/configure_jwt.py b/library/vault/examples/configure_jwt.py deleted file mode 100755 index deffb35..0000000 --- a/library/vault/examples/configure_jwt.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/home/blondsi/learning/hashicorp-vault/python_hello_world/venv/bin/python -import hvac - -client = hvac.Client( - url='https://sam-hcavault.cec.eu.int', - token='hvs.CAESIKnpu_C6vTlQmblBTIwzNkWYnKIzIwO40yMAKNnHaq1aGikKImh2cy5WVGxaS1R3bUFKajF0Sm03MTNHR1lEVkUuYTQ5SVAQ277IAg', - namespace="EC/DIGIT_C4_SNET_DEV_ACC-ENV", - verify=False -) -print(f"Auth ok? {client.is_authenticated()}") - -r = client.auth.jwt.configure( - jwks_url="https://code.europa.eu/-/jwks", - bound_issuer="code.europa.eu" -) - -print(r) diff --git a/library/vault/examples/main.py b/library/vault/examples/main.py deleted file mode 100755 index 38a31a4..0000000 --- a/library/vault/examples/main.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/home/blondsi/learning/hashicorp-vault/python_hello_world/venv/bin/python -import hvac - -client = hvac.Client( - url='https://sam-hcavault.cec.eu.int', - token='hvs.CAESIKnpu_C6vTlQmblBTIwzNkWYnKIzIwO40yMAKNnHaq1aGikKImh2cy5WVGxaS1R3bUFKajF0Sm03MTNHR1lEVkUuYTQ5SVAQ277IAg', - namespace="EC/DIGIT_C4_SNET_DEV_ACC-ENV", - verify=False -) -print(f"Auth ok? {client.is_authenticated()}") - -secret = 'kv/dev-DIEGO' -mount_point, secret_path = secret.split('/', 1) -read_response = client.secrets.kv.v2.read_secret_version( - mount_point=mount_point, - path=secret_path, - version=1 -) -print('Value under path "dev-DIEGO": {val}'.format( - val=read_response['data']['data'], -)) diff --git a/library/vault/examples/requirement.txt b/library/vault/examples/requirement.txt deleted file mode 100644 index 6bc13b2..0000000 --- a/library/vault/examples/requirement.txt +++ /dev/null @@ -1,8 +0,0 @@ -certifi==2022.12.7 -charset-normalizer==3.0.1 -hvac==1.0.2 -idna==3.4 -pkg-resources==0.0.0 -pyhcl==0.4.4 -requests==2.28.2 -urllib3==1.26.14 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..55dbbb8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +requests==2.26.0 +pprint==0.1 +json==2.0.9 +datetime==4.3 +logging==0.5.1.2 +hvac==0.12.0 \ No newline at end of file diff --git a/templates/addgroup.tmpl b/templates/addgroup.tmpl deleted file mode 100644 index 0d2bcba..0000000 --- a/templates/addgroup.tmpl +++ /dev/null @@ -1,64 +0,0 @@ - -<div id="ldapns_addgroup" class="ldapns_addgroup"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_disabled_field"> - - <div class="ldapns_field"> - <label for="IM"> - <tmpl_var label-IM> - </label> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <label for="objectClass"> - <tmpl_var label-objectClass> - </label> - <tmpl_var field-objectClass> - </div> - - <div class="ldapns_field"> - <label for="group"> - <tmpl_var label-group> - <tmpl_var comment-group> - </label> - <tmpl_var field-group> - </div> - - </div> <!-- class="ldapns_disabled_field" --> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <tmpl_if name="posix"> - <label for="gidNumber"> - <tmpl_var label-gidNumber> - <tmpl_var comment-gidNumber> - </label> - <tmpl_var field-gidNumber> - <tmpl_else> - <label for="member"> - <tmpl_var label-member> - <tmpl_var comment-member> - </label> - <tmpl_var field-member> - </tmpl_if> - </div> - </div> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="Back" /> - <input class="ldapns_fb_button" id="_submit_2" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="Add" /> - </div> - - <!-- <tmpl_var form-submit> --> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_addgroup" class="ldapns_addgroup" --> - diff --git a/templates/addpolicy.tmpl b/templates/addpolicy.tmpl deleted file mode 100644 index 08e4099..0000000 --- a/templates/addpolicy.tmpl +++ /dev/null @@ -1,58 +0,0 @@ - -<div id="ldapns_addpolicy" class="ldapns_addpolicy"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="IM"> - <tmpl_var label-IM> - <tmpl_var comment-IM> - </label> - </div> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="docid"> - <tmpl_var label-docid> - <tmpl_var comment-docid> - </label> - </div> - <tmpl_var field-docid> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="description"> - <tmpl_var label-description> - <tmpl_var comment-description> - </label> - </div> - <tmpl_var field-description> - </div> - - <tmpl_loop name="attrs"> - <div class="ldapns_field"> - <div class="ldapns_comment"> - <tmpl_var label-labelfor> - <tmpl_var name="attr"> - <tmpl_var name="value"> - </label> - </div> - <tmpl_var - </tmpl_loop> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_addpolicy" class="ldapns_addpolicy" --> - diff --git a/templates/adduser.tmpl b/templates/adduser.tmpl deleted file mode 100644 index 8721c62..0000000 --- a/templates/adduser.tmpl +++ /dev/null @@ -1,113 +0,0 @@ - -<div id="ldapns_adduser" class="ldapns_adduser"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="IM"> - <tmpl_var label-IM> - <tmpl_var comment-IM> - </label> - </div> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="uid"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = 'Refresh';" type="submit" value="Uid" /> - <tmpl_var comment-uid> - </label> - </div> - <tmpl_var field-uid> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="uidNumber"> - <tmpl_var label-uidNumber> - <tmpl_var comment-uidNumber> - </label> - </div> - <tmpl_var field-uidNumber> - </div> - - <div class="ldapns_field"> - <label for="mail"> - <tmpl_var label-mail> - </label> - <tmpl_var field-mail> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="gecos"> - <tmpl_var label-gecos> - <tmpl_var comment-gecos> - </label> - </div> - <tmpl_var field-gecos> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="firstname"> - <tmpl_var label-firstname> - <tmpl_var comment-firstname> - </label> - </div> - <tmpl_var field-firstname> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="group"> - <input class="ldapns_fb_button" id="_submit_2" name="_submit" onclick="this.form._submitted_value.value = 'Refresh';" type="submit" value="Group" /> - <tmpl_var comment-group> - </label> - </div> - <tmpl_var field-group> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="description"> - <tmpl_var label-description> - <tmpl_var comment-description> - </label> - </div> - <div class="ldapns_field_description"> - <tmpl_var field-description> - </div> - </div> - - <tmpl_if name='mod_synchro'> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="synchronize"> - <tmpl_var label-synchronize> - <tmpl_var comment-synchronize> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-synchronize> - </div> - </div> - - </tmpl_if> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit_3" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="Add" /> - <tmpl_var form-reset> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_adduser" class="ldapns_adduser" --> - diff --git a/templates/adduserprofile.tmpl b/templates/adduserprofile.tmpl deleted file mode 100644 index c8cd44f..0000000 --- a/templates/adduserprofile.tmpl +++ /dev/null @@ -1,117 +0,0 @@ - -<div id="ldapns_adduserprofile" class="ldapns_adduserprofile"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="IM"> - <tmpl_var label-IM> - <tmpl_var comment-IM> - </label> - </div> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="uid"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = 'Refresh';" type="submit" value="Uid" /> - <tmpl_var comment-uid> - </label> - </div> - <tmpl_var field-uid> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="uidNumber"> - <tmpl_var label-uidNumber> - <tmpl_var comment-uidNumber> - </label> - </div> - <tmpl_var field-uidNumber> - </div> - - <div class="ldapns_field"> - <label for="mail"> - <tmpl_var label-mail> - </label> - <tmpl_var field-mail> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="gecos"> - <tmpl_var label-gecos> - <tmpl_var comment-gecos> - </label> - </div> - <tmpl_var field-gecos> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="firstname"> - <tmpl_var label-firstname> - <tmpl_var comment-firstname> - </label> - </div> - <tmpl_var field-firstname> - </div> - - <div class="ldapns_field"> - <label for="profile"> - <tmpl_var label-profile> - </label> - <div class="ldapns_list"> - <tmpl_var field-profile> - </div> - </div> - - <div class="ldapns_field"> - <label for="state"> - <tmpl_var label-state> - </label> - <div class="ldapns_list"> - <tmpl_var field-state> - </div> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="bcp"> - <tmpl_var label-bcp> - <tmpl_var comment-bcp> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-bcp> - </div> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="description"> - <tmpl_var label-description> - <tmpl_var comment-description> - </label> - </div> - <div class="ldapns_field_description"> - <tmpl_var field-description> - </div> - </div> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit_3" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="Add" /> - <tmpl_var form-reset> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_adduserprofile" class="ldapns_adduserprofile" --> - diff --git a/templates/blank.tmpl b/templates/blank.tmpl deleted file mode 100644 index 4ae3df0..0000000 --- a/templates/blank.tmpl +++ /dev/null @@ -1,11 +0,0 @@ - -<div id="ldapns_blank" class="ldapns_blank"> - - <tmpl_if name='br'> - <p> - <br> - </p> - </tmpl_if> - -</div> <!-- id="ldapns_blank" class="ldapns_blank" --> - diff --git a/templates/delgroup.tmpl b/templates/delgroup.tmpl deleted file mode 100644 index 7f7d632..0000000 --- a/templates/delgroup.tmpl +++ /dev/null @@ -1,41 +0,0 @@ - -<div id="ldapns_delgroup" class="ldapns_delgroup"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_field"> - <label for="IM"> - <tmpl_var label-IM> - </label> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <label for="objectClass"> - <tmpl_var label-objectClass> - </label> - <tmpl_var field-objectClass> - </div> - - <div class="ldapns_field"> - <label for="group"> - <tmpl_var label-group> - </label> - <div class="ldapns_list"> - <tmpl_var field-group> - </div> - </div> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit1'>" /> - <input class="ldapns_fb_button" id="_submit_2" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit2'>" /> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_delgroup" class="ldapns_delgroup" --> - diff --git a/templates/deluser.tmpl b/templates/deluser.tmpl deleted file mode 100644 index 8a54554..0000000 --- a/templates/deluser.tmpl +++ /dev/null @@ -1,60 +0,0 @@ - -<div id="ldapns_deluser" class="ldapns_deluser"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_field"> - <tmpl_unless name='submit2'> - <div class="ldapns_comment"> - </tmpl_unless> - <label for="IM"> - <tmpl_var label-IM> - <tmpl_var comment-IM> - </label> - <tmpl_unless name='submit2'> - </div> - </tmpl_unless> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <label for="uid"> - <tmpl_var label-uid> - </label> - <div class="ldapns_list"> - <tmpl_var field-uid> - </div> - </div> - - <tmpl_if name='mod_synchro'> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="synchronize"> - <tmpl_var label-synchronize> - <tmpl_var comment-synchronize> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-synchronize> - </div> - </div> - - </tmpl_if> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit1'>" /> - - <tmpl_if name='submit2'> - <input class="ldapns_fb_button" id="_submit_2" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit2_value'>" /> - </tmpl_if> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_deluser" class="ldapns_deluser" --> - diff --git a/templates/fields_policy.tmpl b/templates/fields_policy.tmpl deleted file mode 100644 index 83f32e7..0000000 --- a/templates/fields_policy.tmpl +++ /dev/null @@ -1,348 +0,0 @@ - -<table> - <tr> - <td> - - <tmpl_if name='if_pwdAllowUserChange'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdAllowUserChange"> - <tmpl_var label-pwdAllowUserChange> - <tmpl_var comment-pwdAllowUserChange> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdAllowUserChange> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdSafeModify'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdSafeModify"> - <tmpl_var label-pwdSafeModify> - <tmpl_var comment-pwdSafeModify> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdSafeModify> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdMustChange'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdMustChange"> - <tmpl_var label-pwdMustChange> - <tmpl_var comment-pwdMustChange> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdMustChange> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdInHistory'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdInHistory"> - <tmpl_var label-pwdInHistory> - <tmpl_var comment-pwdInHistory> - </label> - </div> - <tmpl_var field-pwdInHistory> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdMinAge'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdMinAge"> - <tmpl_var label-pwdMinAge> - <tmpl_var comment-pwdMinAge> - </label> - </div> - <tmpl_var field-pwdMinAge> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdMaxAge'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdMaxAge"> - <tmpl_var label-pwdMaxAge> - <tmpl_var comment-pwdMaxAge> - </label> - </div> - <tmpl_var field-pwdMaxAge> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdExpireWarning'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdExpireWarning"> - <tmpl_var label-pwdExpireWarning> - <tmpl_var comment-pwdExpireWarning> - </label> - </div> - <tmpl_var field-pwdExpireWarning> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdGraceAuthNLimit'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdGraceAuthNLimit"> - <tmpl_var label-pwdGraceAuthNLimit> - <tmpl_var comment-pwdGraceAuthNLimit> - </label> - </div> - <tmpl_var field-pwdGraceAuthNLimit> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdLockout'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdLockout"> - <tmpl_var label-pwdLockout> - <tmpl_var comment-pwdLockout> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdLockout> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdMaxFailure'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdMaxFailure"> - <tmpl_var label-pwdMaxFailure> - <tmpl_var comment-pwdMaxFailure> - </label> - </div> - <tmpl_var field-pwdMaxFailure> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdLockoutDuration'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdLockoutDuration"> - <tmpl_var label-pwdLockoutDuration> - <tmpl_var comment-pwdLockoutDuration> - </label> - </div> - <tmpl_var field-pwdLockoutDuration> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdFailureCountInterval'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdFailureCountInterval"> - <tmpl_var label-pwdFailureCountInterval> - <tmpl_var comment-pwdFailureCountInterval> - </label> - </div> - <tmpl_var field-pwdFailureCountInterval> - </div> - - </tmpl_if> - - </td> - - <tmpl_if name='if_pwdCheckQuality'> - - <td> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdCheckQuality"> - <tmpl_var label-pwdCheckQuality> - <tmpl_var comment-pwdCheckQuality> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdCheckQuality> - </div> - </div> - - <tmpl_if name='if_pwdConstraintQuality'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintQuality"> - <tmpl_var label-pwdConstraintQuality> - <tmpl_var comment-pwdConstraintQuality> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintQuality> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdMinLength'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdMinLength"> - <tmpl_var label-pwdMinLength> - <tmpl_var comment-pwdMinLength> - </label> - </div> - <tmpl_var field-pwdMinLength> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdConstraintAlnum'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintAlnum"> - <tmpl_var label-pwdConstraintAlnum> - <tmpl_var comment-pwdConstraintAlnum> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintAlnum> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdConstraintAlpha'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintAlpha"> - <tmpl_var label-pwdConstraintAlpha> - <tmpl_var comment-pwdConstraintAlpha> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintAlpha> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdConstraintDigit'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintDigit"> - <tmpl_var label-pwdConstraintDigit> - <tmpl_var comment-pwdConstraintDigit> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintDigit> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdConstraintLower'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintLower"> - <tmpl_var label-pwdConstraintLower> - <tmpl_var comment-pwdConstraintLower> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintLower> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdConstraintPunct'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintPunct"> - <tmpl_var label-pwdConstraintPunct> - <tmpl_var comment-pwdConstraintPunct> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintPunct> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdConstraintSpace'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintSpace"> - <tmpl_var label-pwdConstraintSpace> - <tmpl_var comment-pwdConstraintSpace> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintSpace> - </div> - </div> - - </tmpl_if> - - <tmpl_if name='if_pwdConstraintUpper'> - - <div class="ldapns_field"> - <div class=ldapns_comment> - <label for="pwdConstraintUpper"> - <tmpl_var label-pwdConstraintUpper> - <tmpl_var comment-pwdConstraintUpper> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-pwdConstraintUpper> - </div> - </div> - - </tmpl_if> - - </td> - - </tmpl_if> - - </tr> -</table> - diff --git a/templates/groupinfos.tmpl b/templates/groupinfos.tmpl deleted file mode 100644 index b760d42..0000000 --- a/templates/groupinfos.tmpl +++ /dev/null @@ -1,21 +0,0 @@ - -<div class="ldapns_groupinfos"> - -<table> - <thead> - <tr> - <td colspan="2"><tmpl_var name='groupdn'></td> - </tr> - </thead> - <tbody> - <tmpl_loop name="attrs"> - <tr> - <th><tmpl_var name="attr"></th> - <td><tmpl_var name="value"></td> - </tr> - </tmpl_loop> - </tbody> -</table> - -</div> <!-- class="ldapns_groupinfos" --> - diff --git a/templates/ldapns_footer.tmpl b/templates/ldapns_footer.tmpl deleted file mode 100644 index 57a3cce..0000000 --- a/templates/ldapns_footer.tmpl +++ /dev/null @@ -1,57 +0,0 @@ - <tmpl_unless name='login'> - - <tmpl_if name='error'> - <div id="ldapns_footer_msg"> - <hr> - <tmpl_else> - <tmpl_if name='message'> - <div id="ldapns_footer_msg"> - <hr> - </tmpl_if> - </tmpl_if> - - <tmpl_if name='error'> - <div id="ldapns_error" class="ldapns_error"> - <p class="ldapns_error"> - <tmpl_var name='error_msg'> - </p> - </div> <!-- id="ldapns_error" class="ldapns_error" --> - </tmpl_if> - - <tmpl_if name='message'> - <div id="ldapns_message" class="ldapns_message"> - <p class="ldapns_message"> - <tmpl_var name='message_msg'> - </p> - </div> <!-- id="ldapns_message" class="ldapns_message" --> - </tmpl_if> - - <tmpl_if name='error'> - </div> <!-- id="ldapns_footer_msg" --> - <tmpl_else> - <tmpl_if name='message'> - </div> <!-- id="ldapns_footer_msg" --> - </tmpl_if> - </tmpl_if> - - </div> <!-- id="ldapns_right_content" class="ldapns_right_content" --> - - </div> <!-- id="ldapns_right_pannel" class="ldapns_right_pannel" --> - - </div> <!-- id="ldapns_columns" class="ldapns_columns" --> - - </tmpl_unless> - - </div> <!-- id="ldapns_body" class="ldapns_body" --> - - <div id="ldapns_footer" class="ldapns_footer"> - <hr> - <address>Snet NS Team</address> - <br> - <tmpl_unless name='login'> - <a href="?tab=home&action=blank">Home Page</a> - </tmpl_unless> - </div> <!-- id="ldapns_footer" class="ldapns_footer" --> - -</div> <!-- class="Body" --> - diff --git a/templates/ldapns_header.tmpl b/templates/ldapns_header.tmpl deleted file mode 100644 index ca03933..0000000 --- a/templates/ldapns_header.tmpl +++ /dev/null @@ -1,25 +0,0 @@ - -<div id="ldapns_header" class="ldapns_header"> - <hr> -</div> - -<div id="ldapns_body" class="ldapns_body"> - - <tmpl_unless name='login'> - - <div id="ldapns_columns" class="ldapns_columns"> - - <!-- left_pannel.tmpl --> - <tmpl_include name='left_pannel.tmpl'> - <!-- /left_pannel.tmpl --> - - <div id="ldapns_right_pannel" class="ldapns_right_pannel"> - - <!-- tab.tmpl --> - <tmpl_include name='tab.tmpl'> - <!-- /tab.tmpl --> - - <div id="ldapns_right_content" class="ldapns_right_content"> - - </tmpl_unless> - diff --git a/templates/left_groups.tmpl b/templates/left_groups.tmpl deleted file mode 100644 index 8a4cb8f..0000000 --- a/templates/left_groups.tmpl +++ /dev/null @@ -1,50 +0,0 @@ - -<tmpl_if name='groupinfos'> - - <li><span class="ldapns_current">display groups</span></li> - <li><a href="?action=addgroup">add groups</a></li> - <li><a href="?action=delgroup">del groups</a></li> - <li><a href="?action=modgroup">modify groups</a></li> - -<tmpl_else> - - <tmpl_if name='delgroup'> - - <li><a href="?action=groupinfos">display groups</a></li> - <li><a href="?action=addgroup">add groups</a></li> - <li><span class="ldapns_current">del groups</span></li> - <li><a href="?action=modgroup">modify groups</a></li> - - <tmpl_else> - - <tmpl_if name='modgroup'> - - <li><a href="?action=groupinfos">display groups</a></li> - <li><a href="?action=addgroup">add groups</a></li> - <li><a href="?action=delgroup">del groups</a></li> - <li><span class="ldapns_current">modify groups</span></li> - - <tmpl_else> - - <tmpl_if name='addgroup'> - - <li><a href="?action=groupinfos">display groups</a></li> - <li><span class="ldapns_current">add groups</span></li> - <li><a href="?action=delgroup">del groups</a></li> - <li><a href="?action=modgroup">modify groups</a></li> - - <tmpl_else> - - <li><a href="?action=groupinfos">display groups</a></li> - <li><a href="?action=addgroup">add groups</a></li> - <li><a href="?action=delgroup">del groups</a></li> - <li><a href="?action=modgroup">modify groups</a></li> - - </tmpl_if> - - </tmpl_if> - - </tmpl_if> - -</tmpl_if> - diff --git a/templates/left_home.tmpl b/templates/left_home.tmpl deleted file mode 100644 index 3711a8a..0000000 --- a/templates/left_home.tmpl +++ /dev/null @@ -1,30 +0,0 @@ - -<tmpl_if name='userMustChange'> - - <li><span class="ldapns_current">change password</span></li> - -<tmpl_else> - - <tmpl_if name='passwd'> - - <li><a href="?action=info">user details</a></li> - <li><span class="ldapns_current">change password</span></li> - - <tmpl_else> - - <tmpl_if name='info'> - - <li><span class="ldapns_current">user details</span></li> - <li><a href="?action=passwd">change password</a></li> - - <tmpl_else> - - <li><a href="?action=info">user details</a></li> - <li><a href="?action=passwd">change password</a></li> - - </tmpl_if> - - </tmpl_if> - -</tmpl_if> - diff --git a/templates/left_pannel.tmpl b/templates/left_pannel.tmpl deleted file mode 100644 index 9fe9098..0000000 --- a/templates/left_pannel.tmpl +++ /dev/null @@ -1,35 +0,0 @@ - -<div class="ldapns_left_pannel"> - - <ul> - - <tmpl_if name='tab_users'> - <!-- left_users.tmpl --> - <tmpl_include name='left_users.tmpl'> - <!-- /left_users.tmpl --> - <tmpl_else> - - <tmpl_if name='tab_groups'> - <!-- left_groups.tmpl --> - <tmpl_include name='left_groups.tmpl'> - <!-- /left_groups.tmpl --> - <tmpl_else> - <tmpl_if name='tab_policy'> - <!-- left_policy.tmpl --> - <tmpl_include name='left_policy.tmpl'> - <!-- /left_policy.tmpl --> - <tmpl_else> - <!-- left_home.tmpl --> - <tmpl_include name='left_home.tmpl'> - <!-- /left_home.tmpl --> - </tmpl_if> - </tmpl_if> - - </tmpl_if> - - <li><a href="/snet/cgi-bin/auth/ldap_NS.pl?logout=1">logout</a></li> - - </ul> - -</div> <!-- div class="ldapns_left_pannel" --> - diff --git a/templates/left_policy.tmpl b/templates/left_policy.tmpl deleted file mode 100644 index 6a63801..0000000 --- a/templates/left_policy.tmpl +++ /dev/null @@ -1,50 +0,0 @@ - -<tmpl_if name='policyinfos'> - - <li><span class="ldapns_current">display policies</span></li> - <li><a href="?action=addpolicy">add policies</a></li> - <li><a href="?action=delpolicy">del policies</a></li> - <li><a href="?action=modpolicy">modify policies</a></li> - -<tmpl_else> - - <tmpl_if name='delpolicy'> - - <li><a href="?action=policyinfos">display policies</a></li> - <li><a href="?action=addpolicy">add policies</a></li> - <li><span class="ldapns_current">del policies</span></li> - <li><a href="?action=modpolicy">modify policies</a></li> - - <tmpl_else> - - <tmpl_if name='modpolicy'> - - <li><a href="?action=policyinfos">display policies</a></li> - <li><a href="?action=addpolicy">add policies</a></li> - <li><a href="?action=delpolicy">del policies</a></li> - <li><span class="ldapns_current">modify policies</span></li> - - <tmpl_else> - - <tmpl_if name='addpolicy'> - - <li><a href="?action=policyinfos">display policies</a></li> - <li><span class="ldapns_current">add policies</span></li> - <li><a href="?action=delpolicy">del policies</a></li> - <li><a href="?action=modpolicy">modify policies</a></li> - - <tmpl_else> - - <li><a href="?action=policyinfos">display policies</a></li> - <li><a href="?action=addpolicy">add policies</a></li> - <li><a href="?action=delpolicy">del policies</a></li> - <li><a href="?action=modpolicy">modify policies</a></li> - - </tmpl_if> - - </tmpl_if> - - </tmpl_if> - -</tmpl_if> - diff --git a/templates/left_users.tmpl b/templates/left_users.tmpl deleted file mode 100644 index 6c24eff..0000000 --- a/templates/left_users.tmpl +++ /dev/null @@ -1,86 +0,0 @@ - -<tmpl_if name='userinfos'> - - <li><span class="ldapns_current">display user</span></li> - <li><a href="?action=adduser">add users</a></li> - <li><a href="?action=adduserprofile">add users profile</a></li> - <li><a href="?action=deluser">del users</a></li> - <li><a href="?action=moduser">modify users</a></li> - <li><a href="?action=reset">reset passwords</a></li> - -<tmpl_else> - - <tmpl_if name='deluser'> - - <li><a href="?action=userinfos">display user</a></li> - <li><a href="?action=adduser">add users</a></li> - <li><a href="?action=adduserprofile">add users profile</a></li> - <li><span class="ldapns_current">del users</span></li> - <li><a href="?action=moduser">modify users</a></li> - <li><a href="?action=reset">reset passwords</a></li> - - <tmpl_else> - - <tmpl_if name='reset'> - - <li><a href="?action=userinfos">display user</a></li> - <li><a href="?action=adduser">add users</a></li> - <li><a href="?action=adduserprofile">add users profile</a></li> - <li><a href="?action=deluser">del users</a></li> - <li><a href="?action=moduser">modify users</a></li> - <li><span class="ldapns_current">reset passwords</span></li> - - <tmpl_else> - - <tmpl_if name='adduser'> - - <li><a href="?action=userinfos">display user</a></li> - <li><span class="ldapns_current">add users</span></li> - <li><a href="?action=adduserprofile">add users profile</a></li> - <li><a href="?action=deluser">del users</a></li> - <li><a href="?action=moduser">modify users</a></li> - <li><a href="?action=reset">reset passwords</a></li> - - <tmpl_else> - - <tmpl_if name='moduser'> - - <li><a href="?action=userinfos">display user</a></li> - <li><a href="?action=adduser">add users</a></li> - <li><a href="?action=adduserprofile">add users profile</a></li> - <li><a href="?action=deluser">del users</a></li> - <li><span class="ldapns_current">modify users</span></li> - <li><a href="?action=reset">reset passwords</a></li> - - <tmpl_else> - - <tmpl_if name='adduserprofile'> - - <li><a href="?action=userinfos">display user</a></li> - <li><a href="?action=adduser">add users</a></li> - <li><span class="ldapns_current">add users profile</span></li> - <li><a href="?action=deluser">del users</a></li> - <li><a href="?action=moduser">modify users</a></li> - <li><a href="?action=reset">reset passwords</a></li> - - <tmpl_else> - - <li><a href="?action=userinfos">display user</a></li> - <li><a href="?action=adduser">add users</a></li> - <li><a href="?action=adduserprofile">add users profile</a></li> - <li><a href="?action=deluser">del users</a></li> - <li><a href="?action=moduser">modify users</a></li> - <li><a href="?action=reset">reset passwords</a></li> - - </tmpl_if> - - </tmpl_if> - - </tmpl_if> - - </tmpl_if> - - </tmpl_if> - -</tmpl_if> - diff --git a/templates/login.tmpl b/templates/login.tmpl deleted file mode 100644 index a0fd9d8..0000000 --- a/templates/login.tmpl +++ /dev/null @@ -1,51 +0,0 @@ - -<div id="ldapns_login" class="ldapns_login"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="uid"> - <tmpl_var label-uid> - <tmpl_var comment-uid> - </label> - </div> - <tmpl_var field-uid> - </div> - - <div class="ldapns_field"> - <label for="password"> - <tmpl_var label-password> - </label> - <tmpl_var field-password> - </div> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_if name='error'> - <hr> - <tmpl_else> - <tmpl_if name='message'> - <hr> - </tmpl_if> - </tmpl_if> - - <tmpl_if name='error'> - <div id="ldapns_error" class="ldapns_error"> - <p class="ldapns_error"> <tmpl_var name='error_msg'> </p> - </div> <!-- id="ldapns_error" class="ldapns_error" --> - </tmpl_if> - <tmpl_if name='message'> - <div id="ldapns_message" class="ldapns_message"> - <p class="ldapns_message"> <tmpl_var name='message_msg'> </p> - </div> <!-- id="ldapns_message" class="ldapns_message" --> - </tmpl_if> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_login" class="ldapns_login" --> - diff --git a/templates/modgroup.tmpl b/templates/modgroup.tmpl deleted file mode 100644 index 9543d93..0000000 --- a/templates/modgroup.tmpl +++ /dev/null @@ -1,72 +0,0 @@ - -<div id="ldapns_modgroup" class="ldapns_modgroup"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_disabled_field"> - - <div class="ldapns_field"> - <label for="IM"> - <tmpl_var label-IM> - </label> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <label for="objectClass"> - <tmpl_var label-objectClass> - </label> - <tmpl_var field-objectClass> - </div> - - <div class="ldapns_field"> - <label for="group"> - <tmpl_var label-group> - </label> - <tmpl_var field-group> - </div> - - </div> <!-- class="ldapns_disabled_field" --> - - <tmpl_unless name="disable_deluser"> - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="deluser"> - <tmpl_var label-deluser> - <tmpl_var comment-deluser> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-deluser> - </div> - </div> - </tmpl_unless> - - <tmpl_unless name="disable_adduser"> - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="adduser"> - <tmpl_var label-adduser> - <tmpl_var comment-adduser> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-adduser> - </div> - </div> - </tmpl_unless> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit1'>" /> - <input class="ldapns_fb_button" id="_submit_2" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit2'>" /> - <tmpl_var form-reset> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_modgroup" class="ldapns_modgroup" --> - diff --git a/templates/modpolicy.tmpl b/templates/modpolicy.tmpl deleted file mode 100644 index 3255f43..0000000 --- a/templates/modpolicy.tmpl +++ /dev/null @@ -1,46 +0,0 @@ - -<div id="ldapns_modpolicy" class="ldapns_modpolicy"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_disabled_field"> - - <div class="ldapns_field"> - <label for="IM"> - <tmpl_var label-IM> - </label> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <label for="policy"> - <tmpl_var label-policy> - </label> - <tmpl_var field-policy> - </div> - - <div class="ldapns_field"> - <label for="description"> - <tmpl_var label-description> - </label> - <tmpl_var field-description> - </div> - - </div> <!-- class="ldapns_disabled_field" --> - - <tmpl_include name='fields_policy.tmpl'> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit1'>" /> - <input class="ldapns_fb_button" id="_submit_2" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit2'>" /> - <tmpl_var form-reset> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_modpolicy" class="ldapns_modpolicy" --> - diff --git a/templates/passwd.tmpl b/templates/passwd.tmpl deleted file mode 100644 index 26d74f0..0000000 --- a/templates/passwd.tmpl +++ /dev/null @@ -1,50 +0,0 @@ - -<div id="ldapns_passwd" class="ldapns_passwd"> - - <tmpl_var form-start> - - <div class="ldapns_field"> - <label for="old"> - <tmpl_var label-old> - </label> - <tmpl_var field-old> - </div> - - <div class="ldapns_field"> - <label for="new"> - <tmpl_var label-new> - </label> - <tmpl_var field-new> - </div> - - <div class="ldapns_field"> - <label for="repeat"> - <tmpl_var label-repeat> - </label> - <tmpl_var field-repeat> - </div> - - <tmpl_if name='mod_synchro'> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="synchronize"> - <tmpl_var label-synchronize> - <tmpl_var comment-synchronize> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-synchronize> - </div> - </div> - - </tmpl_if> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_passwd" class="ldapns_passwd" --> - diff --git a/templates/policyinfos.tmpl b/templates/policyinfos.tmpl deleted file mode 100644 index 5ceba93..0000000 --- a/templates/policyinfos.tmpl +++ /dev/null @@ -1,29 +0,0 @@ - -<div class="ldapns_policyinfos"> - -<table> - <thead> - <tr> - <td colspan="2">dn: <tmpl_var name='policydn'></td> - </tr> - </thead> - <tbody> - <tmpl_loop name="attrs"> - <tr> - <th><tmpl_var name="attr"></th> - <td><tmpl_var name="value"></td> - </tr> - </tmpl_loop> - <tbody> -<tmpl_if name='reset'> - </tfoot> - <tr> - <th>pwdreset</th> - <td><span class="ldapns_error">TRUE</span></td> - </tr> - </tfoot> -</tmpl_if> -</table> - -</div> <!-- class="ldapns_policyinfos" --> - diff --git a/templates/reset.tmpl b/templates/reset.tmpl deleted file mode 100644 index bb413ad..0000000 --- a/templates/reset.tmpl +++ /dev/null @@ -1,46 +0,0 @@ - -<div id="ldapns_reset" class="ldapns_reset"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <tmpl_var field-_submitted_value> - - <div class="ldapns_field"> - <label for="uid"> - <tmpl_var label-uid> - </label> - <div class="ldapns_list"> - <tmpl_var field-uid> - </div> - </div> - - <tmpl_if name='mod_synchro'> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="synchronize"> - <tmpl_var label-synchronize> - <tmpl_var comment-synchronize> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-synchronize> - </div> - </div> - - </tmpl_if> - - <div class="ldapns_submit"> - <input class="ldapns_fb_button" id="_submit" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit1'>" /> - - <tmpl_if name='submit2'> - <input class="ldapns_fb_button" id="_submit_2" name="_submit" onclick="this.form._submitted_value.value = this.value;" type="submit" value="<tmpl_var name='submit2_value'>" /> - </tmpl_if> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_reset" class="ldapns_reset" --> - diff --git a/templates/selectgroup.tmpl b/templates/selectgroup.tmpl deleted file mode 100644 index e0d3781..0000000 --- a/templates/selectgroup.tmpl +++ /dev/null @@ -1,36 +0,0 @@ - -<div id="ldapns_selectgroup" class="ldapns_selectgroup"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <div class="ldapns_field"> - <label for="group"> - <tmpl_var label-group> - </label> - <tmpl_var field-group> - </div> - - <tmpl_if name="audit"> - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="audit"> - <tmpl_var label-audit> - <tmpl_var comment-audit> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-audit> - </div> - </div> - </tmpl_if> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_selectgroup" class="ldapns_selectgroup" --> - diff --git a/templates/selectgroupclass.tmpl b/templates/selectgroupclass.tmpl deleted file mode 100644 index 664d6e9..0000000 --- a/templates/selectgroupclass.tmpl +++ /dev/null @@ -1,34 +0,0 @@ - -<div id="ldapns_selectgroupclass" class="ldapns_selectgroupclass"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="IM"> - <tmpl_var label-IM> - <tmpl_var comment-IM> - </label> - </div> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <label for="objectClass"> - <tmpl_var label-objectClass> - </label> - <div class="ldapns_list"> - <tmpl_var field-objectClass> - </div> - </div> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_selectgroupclass" class="ldapns_selectgroupclass" --> - diff --git a/templates/selectpolicy.tmpl b/templates/selectpolicy.tmpl deleted file mode 100644 index abedb31..0000000 --- a/templates/selectpolicy.tmpl +++ /dev/null @@ -1,34 +0,0 @@ - -<div id="ldapns_selectpolicy" class="ldapns_selectpolicy"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="IM"> - <tmpl_var label-IM> - <tmpl_var comment-IM> - </label> - </div> - <tmpl_var field-IM> - </div> - - <div class="ldapns_field"> - <label for="policy"> - <tmpl_var label-policy> - </label> - <div class="ldapns_list"> - <tmpl_var field-policy> - </div> - </div> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_selectpolicy" class="ldapns_selectpolicy" --> - diff --git a/templates/selectppolicy.tmpl b/templates/selectppolicy.tmpl deleted file mode 100644 index 4c4e573..0000000 --- a/templates/selectppolicy.tmpl +++ /dev/null @@ -1,34 +0,0 @@ - -<div id="ldapns_selectppolicy" class="ldapns_selectppolicy"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <div class="ldapns_field"> - <label for="policy"> - <tmpl_var label-policy> - </label> - <tmpl_var field-policy> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="audit"> - <tmpl_var label-audit> - <tmpl_var comment-audit> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-audit> - </div> - </div> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_selectppolicy" class="ldapns_selectppolicy" --> - diff --git a/templates/selectuser.tmpl b/templates/selectuser.tmpl deleted file mode 100644 index 6a605c9..0000000 --- a/templates/selectuser.tmpl +++ /dev/null @@ -1,34 +0,0 @@ - -<div id="ldapns_selectuser" class="ldapns_selectuser"> - - <tmpl_var js-head> - - <tmpl_var form-start> - - <div class="ldapns_field"> - <label for="uid"> - <tmpl_var label-uid> - </label> - <tmpl_var field-uid> - </div> - - <div class="ldapns_field"> - <div class="ldapns_comment"> - <label for="audit"> - <tmpl_var label-audit> - <tmpl_var comment-audit> - </label> - </div> - <div class="ldapns_list"> - <tmpl_var field-audit> - </div> - </div> - - <div class="ldapns_submit"> - <tmpl_var form-submit> - </div> - - <tmpl_var form-end> - -</div> <!-- id="ldapns_selectuser" class="ldapns_selectuser" --> - diff --git a/templates/tab.tmpl b/templates/tab.tmpl deleted file mode 100644 index 2116b2f..0000000 --- a/templates/tab.tmpl +++ /dev/null @@ -1,59 +0,0 @@ - -<div class="ldapns_tab" id="ldapns_tab"> - - <ul> - - <tmpl_unless name='isAdmin'> - - <li><span class="ldapns_current">Home</span></li> - - <tmpl_else> - - <tmpl_if name='tab_users'> - - <li><a href="?tab=home">Home</a></li> - <li><span class="ldapns_current">Users</span></li> - <li><a href="?tab=groups">Groups</a></li> - <li><a href="?tab=ppolicies">Password policies</a></li> - - <tmpl_else> - - <tmpl_if name='tab_groups'> - - <li><a href="?tab=home">Home</a></li> - <li><a href="?tab=users">Users</a></li> - <li><span class="ldapns_current">Groups</span></li> - <li><a href="?tab=ppolicies">Password policies</a></li> - - <tmpl_else> - - <tmpl_if name='tab_policy'> - - <li><a href="?tab=home">Home</a></li> - <li><a href="?tab=users">Users</a></li> - <li><a href="?tab=groups">Groups</a></li> - <li><span class="ldapns_current">Passwords policies</span></li> - - <tmpl_else> - - <tmpl_if name='tab_home'> - - <li><span class="ldapns_current">Home</span></li> - <li><a href="?tab=users">Users</a></li> - <li><a href="?tab=groups">Groups</a></li> - <li><a href="?tab=ppolicies">Password policies</a></li> - - </tmpl_if> - - </tmpl_if> - - </tmpl_if> - - </tmpl_if> - - </tmpl_unless> - - </ul> - -</div> <!-- class="ldapns_tab" id="ldapns_tab" --> - diff --git a/templates/userinfos.tmpl b/templates/userinfos.tmpl deleted file mode 100644 index 6d3465c..0000000 --- a/templates/userinfos.tmpl +++ /dev/null @@ -1,29 +0,0 @@ - -<div class="ldapns_userinfos"> - -<table> - <thead> - <tr> - <td colspan="2">dn: <tmpl_var name='userdn'></td> - </tr> - </thead> - <tbody> - <tmpl_loop name="attrs"> - <tr> - <th><tmpl_var name="attr"></th> - <td><tmpl_var name="value"></td> - </tr> - </tmpl_loop> - <tbody> -<tmpl_if name='reset'> - </tfoot> - <tr> - <th>pwdreset</th> - <td><span class="ldapns_error">TRUE</span></td> - </tr> - </tfoot> -</tmpl_if> -</table> - -</div> <!-- class="ldapns_userinfos" --> - diff --git a/library/vault/client.py b/vault/client.py similarity index 61% rename from library/vault/client.py rename to vault/client.py index 6c20e1c..3ef21e1 100755 --- a/library/vault/client.py +++ b/vault/client.py @@ -1,4 +1,3 @@ -#!/opt/gvenv/venv_csui/bin/python3 import logging import requests from requests import Response, Request @@ -8,12 +7,11 @@ from datetime import datetime import time import sys import hvac -from library.servicenow import env_user -#https://intragate.ec.europa.eu/snet/wiki/index.php/System/accessing_and_managing_hashicorp_vault + #https://developer.hashicorp.com/vault/docs/auth/approle #https://hvac.readthedocs.io/en/stable/usage/auth_methods/approle.html #https://hvac.readthedocs.io/en/stable/usage/secrets_engines/kv_v2.html#read-secret-metadata -#curl -H "X-Vault-Namespace: EC/DIGIT_C4_SNET_ADMIN-ACC" -X POST --tlsv1.2 --data '{"password": "password"}' https://sam-hcavault.cec.eu.int/v1/auth/userpass/login/fandrem + class Vault(object): def __init__(self): @@ -21,18 +19,34 @@ class Vault(object): def getPasswordByAppRole(self, key, vault_url, namespace_used, role_id, secret_id, mount_point, engine): # Create a client instance - #verify="/etc/ssl/certs/" client = hvac.Client(url=vault_url, namespace=namespace_used, verify=False) response = client.auth.approle.login(role_id=role_id, secret_id=secret_id) # Extract the client token from the response client.token = response['auth']['client_token'] #TODO : Acc using version 1 in the past now all is uniform - #secret = client.secrets.kv.v1.read_secret(path=key,mount_point=mount_point) secret = client.secrets.kv.v2.read_secret_version(path=key ,mount_point=mount_point) secret_data = False if secret is not None and 'data' in secret and secret['data'] is not None: secret_data =secret['data']['data']['data']['password'] - #print(secret_data) + else: + print(secret, "secret") + print("Failed to retrieve the secret.") + client.logout() + return secret_data + + + def getKeysData(self, key, vault_url, namespace_used, role_id, secret_id, mount_point, engine): + # Create a client instance + client = hvac.Client(url=vault_url, namespace=namespace_used, verify=False) + response = client.auth.approle.login(role_id=role_id, secret_id=secret_id) + # Extract the client token from the response + client.token = response['auth']['client_token'] + #TODO : Acc using version 1 in the past now all is uniform + secret = client.secrets.kv.v2.read_secret_version(path=key ,mount_point=mount_point) + secret_data = False + if secret is not None and 'data' in secret and secret['data'] is not None: + secret_data =secret['data']['data'] + else: print(secret, "secret") print("Failed to retrieve the secret.") -- GitLab