Skip to content

Commit 7e3cb9c

Browse files
committed
tests unitaires
1 parent 27c98bc commit 7e3cb9c

22 files changed

+433
-35
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,5 @@ cython_debug/
163163
/src/.ssh
164164
src/etc/config.conf
165165
/tests
166+
unittest/files_ad_utils/id_ed25519
167+
unittest/files_ad_utils/config.conf

src/bin/activation.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
template = "disable.template"
1919
if args.active == "1":
2020
template="enable.template"
21-
ad.ad_exec_script(entity, template)
21+
r=ad.ad_exec_script(entity, template)
22+
exit(r)
2223
else:
2324
print(u.returncode(0, "not concerned"))

src/bin/changepwd.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
config=u.read_config('../etc/config.conf')
1616
ad.set_config(config)
1717
if u.is_backend_concerned(entity):
18-
ad.ad_exec_script(entity,'changepassword.template',entity['payload']['uid']+ ' "'+ entity['payload']['oldPassword'] + '" "'+ entity['payload']['newPassword'] +'"')
18+
r=ad.change_password(entity)
19+
exit(r)
1920
else:
2021
print(u.returncode(0,"not concerned"))

src/bin/ping.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,10 @@
77
config=u.read_config('../etc/config.conf')
88
ad.set_config(config)
99
## test connection
10-
ad.test_conn()
10+
exitCode=ad.test_conn()
11+
if exitCode == 0:
12+
print(u.returncode(0, "I m alive"))
13+
exit(0)
14+
else:
15+
print(u.returncode(1, "Can't connect"))
16+
exit(1)

src/bin/resetpwd.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
entity=u.readjsoninput()
1515
config=u.read_config('../etc/config.conf')
1616
ad.set_config(config)
17-
ad.__DEBUG__=1
1817
if u.is_backend_concerned(entity):
19-
ad.ad_exec_script(entity,'resetpassword.template',"-user " + entity['payload']['uid']+ " -newp " + entity['payload']['newPassword'])
18+
r=ad.reset_password(entity)
19+
exit(r)
2020
else:
2121
print(u.returncode(0,"not concerned"))

src/lib/ad_utils.py

Lines changed: 70 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,24 @@
66
from jinja2 import FileSystemLoader,BaseLoader
77
import backend_utils as u
88
import jinja2
9-
9+
__PRIVATE_KEY__ = '../.ssh/id_ed25519'
10+
__TEMPLATES_PS1__ = "../ps1_templates/"
1011
__DEBUG__=0
12+
def set_private_key(keyfile):
13+
global __PRIVATE_KEY__
14+
__PRIVATE_KEY__=keyfile
15+
16+
def set_template_ps1_dir(dir):
17+
global __TEMPLATES_PS1__
18+
__TEMPLATES_PS1__=dir
1119
def set_config(config):
1220
u.__CONFIG__ = config
13-
21+
def set_debug():
22+
global __DEBUG__
23+
__DEBUG__=1
1424
def open_ssh_conn():
1525
"""Opening a ssh client connection with parameter in ../etc/config.conf"""
16-
pkey = paramiko.Ed25519Key.from_private_key_file('../.ssh/id_ed25519')
26+
pkey = paramiko.Ed25519Key.from_private_key_file(__PRIVATE_KEY__)
1727
client = paramiko.SSHClient()
1828
policy = paramiko.AutoAddPolicy()
1929
client.set_missing_host_key_policy(policy)
@@ -51,11 +61,17 @@ def compose_dn(entity):
5161
data['rdnValue']=rdnValue
5262
if branchAttr != '':
5363
branchValue=u.find_key(entity,branchAttr)
54-
key_branch='branchFor' + branchValue
55-
if branchValue != '':
64+
if type(branchValue) is list:
65+
key_branch = 'branchFor' + branchValue[0]
66+
else:
67+
key_branch='branchFor' + branchValue
68+
if key_branch != '':
5669
branch=u.config(key_branch,'')
5770
data['branch']=branch
58-
template_string = 'cn={{ rdnValue}},{{ branch }},{{ config.base }}'
71+
if branch == "":
72+
template_string = 'cn={{ rdnValue}},{{ config.base }}'
73+
else:
74+
template_string = 'cn={{ rdnValue}},{{ branch }},{{ config.base }}'
5975
else:
6076
template_string = 'cn={{ rdnValue}},{{ config.base }}'
6177
else:
@@ -71,7 +87,7 @@ def dn_superior(dn):
7187

7288

7389
def test_conn():
74-
environment = jinja2.Environment(loader=FileSystemLoader("../ps1_templates/"))
90+
environment = jinja2.Environment(loader=FileSystemLoader(__TEMPLATES_PS1__))
7591
template = environment.get_template('ping.template')
7692
content=template.render({})
7793
scriptName='ping.ps1'
@@ -85,12 +101,8 @@ def test_conn():
85101
exitCode = chan.recv_exit_status()
86102
content = chan.recv(4096).decode('utf-8')
87103
del client
88-
if exitCode == 0:
89-
print(u.returncode(0, content.rstrip("\n")))
90-
exit(0)
91-
else:
92-
print(u.returncode(1, content.rstrip("\n")))
93-
exit(1)
104+
return exitCode
105+
94106

95107
def gen_script_from_template(entity,template):
96108
dataStatus = 0
@@ -108,7 +120,7 @@ def gen_script_from_template(entity,template):
108120
'dataStatus' : dataStatus
109121
}
110122

111-
environment = jinja2.Environment(loader=FileSystemLoader("../ps1_templates/"))
123+
environment = jinja2.Environment(loader=FileSystemLoader(__TEMPLATES_PS1__))
112124
template = environment.get_template(template)
113125
content=template.render(data)
114126
return content
@@ -145,10 +157,52 @@ def ad_exec_script(entity,template,params=""):
145157
del client
146158
if exitCode == 0:
147159
print(u.returncode(0,content.rstrip("\n")))
148-
exit(0)
160+
return(0)
149161
else:
150162
print(u.returncode(1,content.rstrip("\n")))
151-
exit(1)
163+
return(1)
152164
else:
153165
print(u.returncode(0, "Backend in debug mode"))
166+
return(0)
154167

168+
def ad_exec_script_content(entity,template,params=""):
169+
if u.config('debug',0) == "1":
170+
__DEBUG__ = 1
171+
else:
172+
__DEBUG__ = 0
173+
content=gen_script_from_template(entity,template)
174+
client = open_ssh_conn()
175+
sshfile = client.open_sftp()
176+
pid=os.getpid()
177+
if __DEBUG__ == 0 :
178+
scriptName='sesame_script.' + str(pid) + '.ps1'
179+
else:
180+
scriptName = os.path.splitext(os.path.basename(sys.argv[0]))[0] + ".ps1"
181+
with sshfile.open(scriptName, mode="w") as message:
182+
message.write(content)
183+
##execution du script
184+
chan = client.get_transport().open_session()
185+
if params == '':
186+
cmd=scriptName
187+
else:
188+
cmd=scriptName + " " + params
189+
if __DEBUG__ == 0 :
190+
chan.exec_command('powershell -ExecutionPolicy Bypass -NonInteractive -File ' + cmd)
191+
exitCode = chan.recv_exit_status()
192+
content = chan.recv(4096).decode()
193+
error = chan.recv_stderr(4096).decode()
194+
chan = client.get_transport().open_session()
195+
##supression du script
196+
chan.exec_command('del ' + scriptName)
197+
del client
198+
return(content.rstrip("\n"))
199+
else:
200+
return("")
201+
def reset_password(entity):
202+
x= ad_exec_script(entity, 'resetpassword.template',"-user " + entity['payload']['uid'] + " -newp " + '"' + entity['payload']['newPassword'] + '"')
203+
return x
204+
def change_password(entity):
205+
r=ad_exec_script(entity, 'changepassword.template',
206+
"-user " + entity['payload']['uid'] + ' -oldp "' + entity['payload']['oldPassword'] + '" -newp "' +
207+
entity['payload']['newPassword'] + '"')
208+
return(r)

src/lib/backend_utils.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ def readjsoninput():
2626
input = stdin.read()
2727
return json.loads(input)
2828

29+
def readjsonfile(file):
30+
fic=open(file,"r")
31+
content=fic.read()
32+
fic.close()
33+
return json.loads(content)
2934

3035
def returncode(code,message):
3136
'''
@@ -44,24 +49,29 @@ def is_backend_concerned(entity):
4449
else:
4550
# il n y a pas de branchAttr dans le fichier de config on traitre tout
4651
return True
47-
listBackend=config('backendFor')
48-
c=type(peopleType)
52+
x=config('backendFor')
53+
if config('backendFor','') == '':
54+
return True
55+
listBackend=config('backendFor').split(',')
4956
if type(peopleType) is list:
5057
for v in peopleType:
51-
peopleType=v
52-
if (listBackend.find(peopleType) == -1):
53-
return False
58+
if v in listBackend :
59+
return True
5460
else:
55-
if (listBackend.find(peopleType) == -1):
56-
return False
61+
if peopleType in listBackend:
62+
return True
5763

58-
return True
64+
return False
5965

6066
def find_key(element, key):
6167
'''
6268
Check if *keys (nested) exists in `element` (dict).
6369
'''
64-
return _finditem(element,key)
70+
r=_finditem(element,key)
71+
if r is None:
72+
return ""
73+
else:
74+
return r
6575

6676
def _finditem(obj, key):
6777
if key in obj: return obj[key]
@@ -70,7 +80,7 @@ def _finditem(obj, key):
7080
item = _finditem(v, key)
7181
if item is not None:
7282
return item
73-
return ""
83+
7484
def make_entry_array(entity):
7585
data = {}
7686
if "identity" in entity['payload']:

src/ps1_templates/changepassword.template

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ Function Test-ADAuthentication {
1414
{% if dataStatus == -2 %}
1515
Set-ADUser -Identity $user -Enabled $True
1616
{% endif %}
17-
$userFound=get-aduser -Filter "SamAccountName -eq $user -and Enabled -eq '$True' -and PasswordExpired -eq '$False'"
17+
$userFound=get-aduser -Filter "SamAccountName -eq '$user' -and Enabled -eq '$True' -and PasswordExpired -eq '$False'"
1818
if ( ! $userFound ){
1919
Write-Host 'user not active or not found or password expired'
2020
exit 1
2121
}
22-
if (Test-ADAuthentication -username "$user" -password "$oldp"){
22+
if (Test-ADAuthentication -username $user -password $oldp){
2323
Write-Host "password ok"
2424
try{
2525
Set-ADUser -Identity $user -CannotChangePassword $false

src/ps1_templates/resetpassword.template

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@ param (
22
[string]$user,
33
[string]$newp
44
)
5+
{% if dataStatus == -3 %}
6+
Write-Host "User Disabled"
7+
exit 1
8+
{% endif %}
59
try{
6-
Set-ADUser -Identity $user -CannotChangePassword $false -Enabled $true
10+
Unlock-ADAccount -Identity $user
711
Set-ADAccountPassword -Identity $user -NewPassword (ConvertTo-SecureString -AsPlainText $newp -Force) -Reset
812
Set-ADAccountPassword -Identity $user -NewPassword (ConvertTo-SecureString -AsPlainText $newp -Force) -Reset
9-
Set-ADUser -Identity $user -CannotChangePassword $true
13+
Set-ADUser -Identity $user -CannotChangePassword $true -Enabled $true
1014
}catch{
1115
Write-Host $_
1216
exit 1

src/ps1_templates/upsertidentity.template

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,17 @@ try{
1010
exit 1
1111
}
1212
}
13+
# Name changed ?
14+
$name=$tab['Name']
15+
if ($name -ne "{{ e.cn}}"){
16+
try{
17+
Set-ADUser -Identity "{{ e.uid }}" -PassThru | Rename-ADObject -NewName "{{ e.cn}}"
18+
}catch{
19+
Write-Host $_
20+
exit 1
21+
}
22+
}
23+
1324
$UserExists = $true
1425
}
1526
catch{
@@ -39,6 +50,8 @@ if ($UserExists -eq $false){
3950
}
4051
}else{
4152
try{
53+
## cas ou le DN à changé nous relisons l entree
54+
$tab=Get-ADUser -Filter 'employeeNumber -eq "{{ e.employeeNumber }}" -and employeeType -eq "{{ e.employeeType }}"' -Properties "DistinguishedName"
4255
$dn=$tab["DistinguishedName"]
4356
$UserPrincipalName = "{{ e.uid }}" + '@' + "{{ domain }}"
4457
set-adUser -Identity "$dn" -SamAccountName "{{ e.uid }}" -DisplayName "{{e.displayName}}" -GivenName "{{ e.givenName }}" -EmailAddress "{{ e.mail }}" -UserPrincipalName "$UserPrincipalName"

0 commit comments

Comments
 (0)