Advertisement
Guest User

Untitled

a guest
Jun 13th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. import re
  2.  
  3. class Terminal:
  4.     """This class emulates a simple Terminal promt with a basic login and CLI"""
  5.     def __init__(self):
  6.         """self.user will contain the username of the currently logged in user, otherwise None
  7.        self.users is a dictionary that should contain all users as keys with their
  8.                   corresponding passwords as values
  9.        self.run should be set to False to terminate the main loop"""
  10.         self.user = None
  11.         self.users = {}
  12.         self.run = False
  13.  
  14.     def check_login(self):
  15.         """This function checks if the currently logged in user, which is stored in
  16.        the user string, exists in the users dictionary and return True, otherwise it
  17.        will start a login attempt and return its value"""
  18.         if self.user in self.users.keys():
  19.             return True
  20.         else:
  21.             return self.do_login()
  22.            
  23.     def do_login(self):
  24.         """This function will prompt the user for a name and password.
  25.        If the given name exists as a key in the users dictionary it will check if
  26.        the password matches the value of that key and set that user to be currently
  27.        logged in.
  28.  
  29.        This function returns True for a successful login attempt, otherwise False."""
  30.         username = raw_input('Username: ')
  31.         password = raw_input('Password: ')
  32.         if username in self.users.keys():
  33.             if password == self.users[username]:
  34.                 print 'login ok!'
  35.                 print 'Welcome %s!' % (username)
  36.                 self.user = username
  37.                 return True
  38.         print 'login failed!'
  39.         return False
  40.  
  41.     def commandline(self):
  42.         """This is a function to prompt for commands, check them and execute them.
  43.        Sould not be called anywhere but the main loop"""
  44.         cmd = raw_input('INPUT# ')
  45.         if cmd == 'logout':
  46.             print 'Bye!'
  47.             self.user = None
  48.         if cmd == 'quit':
  49.             self.run = False
  50.  
  51.     def main(self):
  52.         """This is the main loop. When this is called,
  53.        control of the application is given to the Terminal class."""
  54.         self.run = True
  55.         while self.run:
  56.             if self.check_login(): self.commandline()
  57.  
  58. term = Terminal()
  59. term.users = { 'ndakota':'transltr', 'elite':'awesum' }
  60. term.main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement