-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuserGUI.py
595 lines (498 loc) · 22.4 KB
/
userGUI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
#!/usr/bin/python
# Author: Gabriele Bozzola (sbozzolo)
# Email: [email protected]
#~ This module is used to draw the interface
import npyscreen as nps
import checkpwd as cp
import lcmldap as ldap
from os import system as system
from re import search as search
from re import sub
import pwd, smtplib, time, os, sys
#~ This dictionary is intended to contain every string of Umanager,
#~ so it is easier to modify text and maintain the code compact
words = {
'MainFormName' : "Welcome to Umanager",
'ExitText' : "Quit",
'MenuButtonText' : "Menu",
'MainFormText1' : "This script allows you to perform "
+"actions on LCM users database. ",
'MainFormText2' : "To open the menu press 'm' or select MENU",
'MainMenu' : "Main Menu",
'NewUser' : "New User",
'ChangePassword' : "Change Password",
'DeleteUser' : "Delete User",
'AboutUmanager' : "About Umanager",
'ConfirmExit' : "Do you reallly want to quit?",
'QuitUmanager' : "Quit Umanager",
'Ldap' : "Ldap password",
'Name' : "First name",
'Surname' : "Last name",
'Username' : "Username",
'BadgeNum' : "Badge number",
'Email' : "Email",
'Password' : "Enter Password",
'PasswordRepet' : "Retype Password",
'AppTitle' : "LCM Umanager",
'About' : "About",
'AboutApp' : "Umanager version 1.0.0",
'ReturnToMain' : "BackToMenu",
'LdapPassword' : "Enter LDAP password!",
'NullPassword' : "Enter a valid password!",
'WrongPassword' : "Passwords do not match!",
'BadPassword0' : "Short password! Try again!",
'BadPassword1' : "Password can not contain spaces or tabs! Try again!",
'BadPassword2' : "Password based on user credentials!",
'BadPassword3' : "Password should contain at least three chars type!",
'Add' : "Done",
'Warning' : "Warning!",
'ConfirmUserExit': "Do you really want to quit? All changes will be lost!",
'ConfirmDel' : "Do you want to delete user? ",
'AreYouSure' : "Do you really want to delete this user?",
'ItCannotBeUndo' : "This action can not be undone!",
'RenewUser' : "Renew User",
'ExpDate1' : "User account ",
'ExpDate2' : " will expire on the day ",
'ExpDate3' : " Renew until ",
'InsertUsername' : "Insert a valid username!",
'InsertName' : "Insert user's first name!",
'InsertSurname' : "Insert user's last name!",
'InsertBadgeNo' : "Insert user's badge number!",
'InsertEmail' : "Insert user's email for redirection!",
'BadChar' : "Invalid character! ",
'DBConnFail' : "Failed connection with LDAP! Retype LDAP password!",
'User' : "The user ",
'UserNotExist' : " does not exist!",
'UserExist' : " already exists! ",
'RenewUser1' : "Do you want to renew ",
'RenewUser2' : "'s account until the day: ",
'SendMailToUser' : "Do you want to send an email to the user?",
'MailSent' : "Successfully sent mail!",
'MailNotSent' : "Unable to sent mail!",
'NewUserCreated' : "User successfully created!",
'UserDeleted' : "User successfully deleted!",
'PasswordEdited' : "User's password successfully changed!",
'UserRenewed' : "User's account successfully renewed!"
}
def get_term_size() :
# Stty returns cols and rows. Read the only line (e.g. '50 150') and properly
# convert it to a list of integer.
return tuple(map(int , os.popen('stty size').read().strip().split() ) )
def get_mid_point(col, lin) :
ty, tx = get_term_size()
return map(int, [(tx-col)/2, (ty-lin)/2 ])
class MainForm ( nps.ActionFormWithMenus ):
"""Class that draws the main screen of Umanager"""
#~ Define a shortcut to open menu
MENU_KEY = "m"
OK_BUTTON_TEXT = words['ExitText']
CANCEL_BUTTON_TEXT = words['MenuButtonText']
#~ Create form elements and menus
def create(self):
"""Add to the form the widgets"""
#~ Text on main screen
self.add(nps.TitleFixedText, name = words['MainFormName'], editable = False)
self.add(nps.FixedText, value = words['MainFormText1'], editable = False)
self.add(nps.FixedText, value = words['MainFormText2'], editable = False)
#~ Main Menu and Edit User menu
self.menu = self.new_menu(name = words['MainMenu'], shortcut = "m")
self.menu.addItem(words['NewUser'], self.new_user, "n")
self.menu.addItem(words['ChangePassword'], self.edit_user, "c")
self.menu.addItem(words['RenewUser'], self.renew_user, "r")
self.menu.addItem(words['DeleteUser'], self.delete_user, "d")
self.menu.addItem(words['AboutUmanager'], self.about, "a")
self.menu.addItem(words['QuitUmanager'], self.exit_application, "q")
def on_cancel(self):
"""Displays the main menu when the button cancel is pressed"""
self.popup_menu(self.menu)
def on_ok(self):
"""Ask a confirmation for exiting"""
exiting = nps.notify_yes_no(words['ConfirmExit'], words['ExitText'], editw = 2)
if (exiting):
self.exit_application()
else:
pass #~ Do nothing
def about(self):
"""Displys info about the Umanager script"""
nps.notify_confirm(words['AboutApp'], words['About'], editw=1)
def exit_application(self):
"""Closes the GUI"""
self.editing = False
self.parentApp.setNextForm(None)
self.parentApp.switchFormNow()
def renew_user(self):
"""Launch RENEW form"""
self.parentApp.setNextForm('RENEWUSER')
self.parentApp.switchFormNow()
def new_user(self):
"""Launch NEWUSER form"""
self.parentApp.setNextForm('NEWUSER')
self.parentApp.switchFormNow()
def edit_user(self):
"""Launch EDITUSERPWDFORM form"""
self.parentApp.setNextForm('EDITUSERPWDFORM')
self.parentApp.switchFormNow()
def delete_user(self):
"""Launch DELUSER form"""
self.parentApp.setNextForm('DELUSER')
self.parentApp.switchFormNow()
class NewUserForm (nps.ActionFormV2):
"""Class that handles the creation of a user"""
OK_BUTTON_TEXT = words['Add']
CANCEL_BUTTON_TEXT = words['ReturnToMain']
def create(self):
"""Add to the form the widgets"""
self.ldap = self.add(nps.TitlePassword, name = words['Ldap'], begin_entry_at = 20)
self.nname = self.add(nps.TitleText, name = words['Name'], begin_entry_at = 20)
self.surname = self.add(nps.TitleText, name = words['Surname'], begin_entry_at = 20)
self.username = self.add(nps.TitleText, name = words['Username'], begin_entry_at = 20)
self.userpass = self.add(nps.TitlePassword, name = words['Password'], begin_entry_at = 20)
self.passrepe = self.add(nps.TitlePassword, name = words['PasswordRepet'], begin_entry_at = 20)
self.badgenum = self.add(nps.TitleText, name = words['BadgeNum'], begin_entry_at = 20)
self.email = self.add(nps.TitleText, name = words['Email'], begin_entry_at = 20)
def on_cancel(self):
"""Return to the main screen when the button cancel is pressed"""
exiting = nps.notify_yes_no(words['ConfirmUserExit'], words['ExitText'], editw = 2)
if (exiting):
self.return_to_main_screen()
else:
pass #~ Do nothing
def on_ok(self):
"""Checks and create the user"""
# First of all, check password
# In my experience this is the most difficult step --andreatsh
if (self.userpass.value=="" or self.passrepe.value==""):
nps.notify_confirm(words['NullPassword'], words['Warning'])
self.userpass.value = None
self.passrepe.value = None
return
if (self.userpass.value != self.passrepe.value):
nps.notify_confirm(words['WrongPassword'], words['Warning'])
self.userpass.value = None
self.passrepe.value = None
return
tp = cp.ispwdweak(self.userpass.value, \
sub('\s','',self.nname.value), \
sub('\s','',self.surname.value), \
self.username.value)
if (tp[0]):
if (tp[1]==0):
nps.notify_confirm(words['BadPassword0'], words['Warning'])
elif (tp[1]==1):
nps.notify_confirm(words['BadPassword1'], words['Warning'])
elif (tp[1]==2):
nps.notify_confirm(words['BadPassword2'], words['Warning'])
elif (tp[1]==3):
nps.notify_confirm(words['BadPassword3'], words['Warning'])
self.userpass.value = None
self.passrepe.value = None
return
# Check empty fields
if (self.ldap.value == ""):
nps.notify_confirm(words['LdapPassword'], words['Warning'])
return
if (self.nname.value == ""):
nps.notify_confim(words['InsertName'], words['Warning'])
return
if (self.surname.value == "InsertSurname"):
nps.notify_confim(words['Warning'], words['Warning'])
return
if (self.username.value == ""):
nps.notify_confim(words['InsertUsername'], words['InsertUsername'])
return
if (self.badgenum.value == ""):
nps.notify_confim(words['InsertBadgeNo'], words['Warning'])
return
if (self.email.value == ""):
nps.notify_confirm(words['InsertEmail'], words['Warning'])
return
# Check if fields contains bad chars
if (search(r'[^A-Za-z0-9_\s]', self.nname.value) or
search(r'[^A-Za-z0-9_\s]', self.surname.value) or
search(r'[^a-z0-9_]', self.username.value) or
search(r'[^A-Za-z0-9_]', self.badgenum.value)):
nps.notify_confirm(words['BadChar'], words['Warning'], editw = 1)
return
# Check if the chosen username already exists
if(ldap.userexists(self.username.value)):
errormsg = words['User']+self.username.value+words['UserExist']
nps.notify_confirm(errormsg, words['Warning'], editw = 1)
return
# else no user with chosen username exists: do nothing
try:
db = ldap.lcmldap("ldaps://xx8.xx1.mi.infn.it/",
"cn=Manager","dc=xx8,dc=xx1", self.ldap.value)
except:
nps.notify_confirm(words['DBConnFail'], words['Warning'])
self.ldap.value = None
return
# Add user on main server
templist = []
for i in pwd.getpwall():
if (i.pw_uid<64000): templist.append(i.pw_uid)
useruidNo=str( max(templist)+1 )
expDate=str( (int(time.time())+3*86400*365) / 86400 )
addusercmd='useradd -u '+useruidNo+ \
' -c "'+self.nname.value+',,,,'+self.badgenum.value+'"'+ \
' -d /home/'+self.username.value+ \
' -g users -m -s /bin/bash'+ \
' -e '+expDate+' '+self.username.value
try:
system(addusercmd)
except:
nps.notify_confirm(words['Warning'], words['Warneng'])
return
# Add user to LDAP database
db.adduser(self.nname.value,self.surname.value,self.username.value,
self.userpass.value,expDate,useruidNo,self.badgenum.value)
# Configure user's mail
mforwardfile="/home/"+self.username.value+"/.forward"
ofs = open(mforwardfile,"w")
ofs.write(self.username.value)
ofs.write("\n")
ofs.write(self.email.value)
ofs.close()
# Limit user's disk quota
quotacmd="edquota -p lcm-quota -f /home "+self.username.value
system(quotacmd)
nps.notify_confirm(words['NewUserCreated'], words['Warning'])
self.return_to_main_screen()
def return_to_main_screen(self):
"""Clear values and return to the main screen"""
self.ldap.value = None
self.nname.value = None
self.surname.value = None
self.username.value = None
self.userpass.value = None
self.passrepe.value = None
self.badgenum.value = None
self.email.value = None
self.editing = False
self.parentApp.setNextForm("MAIN")
self.parentApp.switchFormNow()
class EditUserPwdForm (nps.ActionFormV2):
"""Class that asks the username which has to be edited"""
CANCEL_BUTTON_TEXT = words['ReturnToMain']
def create(self):
self.show_atx, self.show_aty = get_mid_point(self.columns, self.lines)
self.ldap = self.add(nps.TitlePassword, name = words['Ldap'], begin_entry_at = 20)
self.username = self.add(nps.TitleText, name = words['Username'], begin_entry_at = 20)
self.userpass = self.add(nps.TitlePassword, name = words['Password'], begin_entry_at = 20)
self.passrepe = self.add(nps.TitlePassword, name = words['PasswordRepet'], begin_entry_at = 20)
def on_cancel(self):
"""Discard edits and return to the main screen"""
self.return_to_main_screen()
def on_ok(self):
# Check fields validity
if (self.ldap.value == ""):
nps.notify_confirm(words['LdapPassword'], words['Warning'])
return
if (self.username.value == ""):
nps.notify_confim(words['InsertUsername'], words['Warning'])
return
# Check if fields contains bad chars
if(search(r'[^A-Za-z0-9_]', self.username.value)):
nps.notify_confirm(words['BadChar'], words['Warning'])
return
# Try to connect to LDAP database
try:
db = ldap.lcmldap("ldaps://xx8.xx1.mi.infn.it/",
"cn=Manager","dc=xx8,dc=xx1", self.ldap.value)
except:
nps.notify_confirm(words['DBConnFail'], words['Warning'])
self.ldap.value = None
return
# Check if this user exists
if(ldap.userexists(self.username.value)):
pass
else:
errormsg = words['User']+self.username.value+words['UserNotExist']
nps.notify_confirm(errormsg, words['Warning'], editw = 1)
return
nname, surname = db.getusercredbyuid(self.username.value)
# Check password
if (self.userpass.value=="" or self.passrepe.value==""):
nps.notify_confirm(words['NullPassword'], words['Warning'])
self.userpass.value = None
self.passrepe.value = None
return
if (self.userpass.value != self.passrepe.value):
nps.notify_confirm(words['WrongPassword'], words['Warning'])
self.userpass.value = None
self.passrepe.value = None
return
tp = cp.ispwdweak(self.userpass.value, \
sub('\s','',nname), \
sub('\s','',surname), \
self.username.value)
if (tp[0]):
if (tp[1]==0):
nps.notify_confirm(words['BadPassword0'], words['Warning'])
elif (tp[1]==1):
nps.notify_confirm(words['BadPassword1'], words['Warning'])
elif (tp[1]==2):
nps.notify_confirm(words['BadPassword2'], words['Warning'])
elif (tp[1]==3):
nps.notify_confirm(words['BadPassword3'], words['Warning'])
self.userpass.value = None
self.passrepe.value = None
return
db.changepwd(self.username.value,self.userpass.value)
nps.notify_confirm(words['PasswordEdited'], words['Warning'])
self.return_to_main_screen()
def return_to_main_screen(self):
"""Return to the main screen"""
self.ldap.value = None
self.username.value = None
self.userpass.value = None
self.passrepe.value = None
self.editing = False
self.parentApp.setNextForm("MAIN")
self.parentApp.switchFormNow()
class DelUserForm (nps.ActionFormV2):
"""Class that deletes an user"""
CANCEL_BUTTON_TEXT = words['ReturnToMain']
def create(self):
self.show_atx, self.show_aty = get_mid_point(self.columns, self.lines)
self.ldap = self.add(nps.TitlePassword, name = words['Ldap'], begin_entry_at = 20)
self.uname = self.add(nps.TitleText, name = words['Username'], begin_entry_at = 20)
def on_cancel(self):
"""Discard edits and return to the main screen"""
self.return_to_main_screen()
def on_ok(self):
# Check fields validity
if (self.ldap.value == ""):
nps.notify_confirm(words['LdapPassword'], words['Warning'])
return
if (self.uname.value == ""):
nps.notify_confim(words['InsertUsername'], words['Warning'])
return
# Check if this user exists
if(ldap.userexists(self.uname.value)):
pass
else:
errormsg = words['User']+self.uname.value+words['UserNotExist']
nps.notify_confirm(errormsg, words['Warning'], editw = 1)
return
# Try to connect to LDAP database
try:
db = ldap.lcmldap("ldaps://xx8.xx1.mi.infn.it/",
"cn=Manager","dc=xx8,dc=xx1", self.ldap.value)
except:
nps.notify_confirm(words['DBConnFail'], words['Warning'])
self.ldap.value = None
return
# Ask to confirm you really want to delete this user
dele = nps.notify_yes_no(words['ConfirmDel']+self.uname.value+"?",
words['DeleteUser'], editw = 2)
if (dele):
dele2 = nps.notify_yes_no(words['AreYouSure']+self.uname.value+"?\n"+
words['ItCannotBeUndo'], words['DeleteUser'], editw = 2)
if (dele2):
pass
else:
return
else:
return
delusercmd="userdel -r "+self.uname.value
system(delusercmd)
db.deluser(self.uname.value)
nps.notify_confirm(words['UserDeleted'], words['Warning'])
self.return_to_main_screen()
def return_to_main_screen(self):
"""Return to the main screen"""
self.ldap.value = None
self.uname.value = None
self.editing = False
self.parentApp.setNextForm("MAIN")
self.parentApp.switchFormNow()
class RenewForm (nps.ActionFormV2):
"""Class that rennews an user"""
CANCEL_BUTTON_TEXT = words['ReturnToMain']
def create(self):
self.show_atx, self.show_aty = get_mid_point(self.columns, self.lines)
self.ldap = self.add(nps.TitlePassword, name = words['Ldap'], begin_entry_at = 20)
self.uname = self.add(nps.TitleText, name = words['Username'], begin_entry_at = 20)
def on_cancel(self):
"""Discard edits and return to the main screen"""
self.return_to_main_screen()
def on_ok(self):
# Check fields validity
if (self.ldap.value == ""):
nps.notify_confirm(words['LdapPassword'], words['Warning'])
return
if (self.uname.value == ""):
nps.notify_confirm(words['InsertUsername'], words['Warning'])
return
if (search(r'[^A-Za-z0-9_]', self.uname.value)):
nps.notify_confirm(words['BadChar'], words['Warning'])
return
# Check if this user exists
if(ldap.userexists(self.uname.value)):
pass
else:
errormsg = words['User']+self.uname.value+words['UserNotExist']
nps.notify_confirm(errormsg, words['Warning'], editw = 1)
return
# Try to connect to LDAP database
try:
db = ldap.lcmldap("ldaps://xx8.xx1.mi.infn.it/",
"cn=Manager","dc=xx8,dc=xx1", self.ldap.value)
except:
nps.notify_confirm(words['DBConnFail'], words['Warning'])
self.ldap.value = None
return
newday = time.gmtime(time.time()+3*86400*365)
newdaystr = time.strftime("%d/%m/%Y", newday)
# Convert in the right format for chage command
newshadow = time.strftime("%m/%d/%Y", newday)
text = words['RenewUser1'] + self.uname.value + words['RenewUser2']
text = text + newdaystr + "?"
ren = nps.notify_yes_no(text, words['RenewUser'], editw = 2)
if (not ren):
self.return_to_main_screen()
return
cmd = "chage " + self.uname.value + " -E " + newshadow
expDate=str( (int(time.time())+3*86400*365) / 86400 )
db.changeshadowexpire(self.uname.value, expDate)
system(cmd)
# Ask to send mail to user
sm = nps.notify_yes_no(words['SendMailToUser'], editw = 2)
if (sm):
sender = '[email protected]'
usermail = self.uname.value + "@lcm.mi.infn.it"
receivers = [ usermail, '[email protected]' ]
message = """From: <[email protected]>
To: """ + usermail + """
Subject: Rinnovo account LCM
Reply-to: <[email protected]>
Ciao,
abbiamo rinnovato il tuo account.
Nuova data di scadenza: """ + newdaystr + """
A presto,
LCM Staff
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
nps.notify_confirm(words['MailSent'], words['Warning'])
except smtplib.SMTPException:
nps.notify_confirm(words['MailNotSent'], words['Warning'])
nps.notify_confirm(words['UserRenewed'], words['Warning'])
self.return_to_main_screen()
def return_to_main_screen(self):
"""Return to the main screen"""
self.ldap.value = None
self.uname.value = None
self.parentApp.setNextForm("MAIN")
self.editing = False
self.parentApp.switchFormNow()
class GUI (nps.NPSAppManaged):
"""Defines the whole application GUI"""
def onStart(self):
"""Adds the forms"""
self.addForm('MAIN', MainForm, name = words['AppTitle'])
self.addForm('NEWUSER', NewUserForm, name = words['NewUser'])
self.addForm('EDITUSERPWDFORM', EditUserPwdForm, name = words['ChangePassword'], lines = 10, columns = 70)
self.addForm('DELUSER', DelUserForm, name = words['DeleteUser'], lines = 10, columns = 70)
self.addForm('RENEWUSER', RenewForm, name = words['RenewUser'], lines = 10, columns = 70)