Advertisement
joyeusenoelle

Classes for Legendsz

Jun 4th, 2015
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.31 KB | None | 0 0
  1. # Get as many imports on the same line as possible without going over 80 char
  2. # I'm not sure if it's better practice but it looks nicer to me than a
  3. # vertical pile of import statements :)
  4. import time, praw, os, smtplib, email, datetime, html, configparser
  5. #import  premailer,
  6. #import mysql.connector
  7. from passlib.hash import pbkdf2_sha256, sha256_crypt
  8. from email import encoders
  9. from email.header import Header
  10. from email.mime.text import MIMEText
  11. from email.mime.multipart import MIMEMultipart
  12.  
  13.  
  14.  
  15. # This class can be pulled out into its own file, something like
  16. # "configuration.py". Then you can access it using
  17. # from configuration import Configuration
  18. # and use it just like you were including it directly.
  19. class Configuration:
  20.     """ Retrieves config information from a text file and stores it in
  21.        a dict. Currently defaults to config.ini if no text file is
  22.        specified. """
  23.  
  24.     # DEFAULTS
  25.     DFILE = "config.ini"
  26.     DSECTION = "mysql"
  27.     # METHODS
  28.     # Create a new Configuration
  29.     def __init__(self, configfile=None, section=None):
  30.         self.configfile = configfile if configfile != None else Configuration.DFILE
  31.         sect = section if section != None else Configuration.DSECTION
  32.         config = configparser.ConfigParser()
  33.         config.read(self.configfile)
  34.         self.usr = config.get(sect,'user')
  35.         self.passwd = config.get(sect,'password')
  36.         self.hst = config.get(sect,'host')
  37.         self.db = config.get(sect,'database')
  38.    
  39.     @property
  40.     def user(self):
  41.         return self.usr
  42.    
  43.     @property
  44.     def password(self):
  45.         return self.passwd
  46.  
  47.     @property
  48.     def host(self):
  49.         return self.hst
  50.    
  51.     @property
  52.     def database(self):
  53.         return self.db
  54.  
  55.     # Useful for passing to MySQL
  56.     @property
  57.     def full(self):
  58.         return {"user"     : self.user,
  59.                 "password" : self.password,
  60.                 "host"     : self.host,
  61.                 "database" : self.database}
  62.  
  63. # This class can be pulled out into its own file, something like
  64. # "passwords.py". Then you can access it using
  65. # from passwords import Password
  66. # and use it just like you were including it directly.
  67. class Password:
  68.     """Handles password salting and hashing.
  69.    Use hashpw() to create a hashed password.
  70.    Use checkpw() to see if a user's submitted password matches the
  71.    password on file.
  72.    """
  73.     # DEFAULTS
  74.     DROUNDS = 200000
  75.     DSALTSIZE = 16
  76.     DCHANCES = 5
  77.  
  78.     def __init__(self, rounds=None, saltsize=None, chances=None):
  79.         self.rounds = rounds if rounds != None else Password.DROUNDS
  80.         self.saltsize = saltsize if saltsize != None else Password.DSALTSIZE
  81.         self.chances = chances if chances != None else Password.DCHANCES
  82.         self.storedpws = []
  83.    
  84.     def hashpw(self, password):
  85.         hashedpw = sha256_crypt.encrypt(password, rounds=self.rounds, salt_size = self.saltsize)
  86.         self.storedpws.append(hashedpw)
  87.         return hashedpw
  88.  
  89.     def checkpw(self, hpw):
  90.         verified, i = False, 0
  91.         # give them a certain number of chances to get it right (default: 5)
  92.         while verified != True and i < self.chances:
  93.             i += 1
  94.             ipw = input("Password: ")
  95.             if type(hpw) == list:
  96.                 for pw in hpw:
  97.                     if sha256_crypt.verify(ipw, pw):
  98.                         verified = True
  99.                         break
  100.             else:
  101.                 if sha256_crypt.verify(ipw,hpw):
  102.                     verified = True
  103.         return verified
  104.    
  105.     def checkpwlocal(self):
  106.         return self.checkpw(self.storedpws)
  107.  
  108.     def checkpwremote(self, username=None, connection=None):
  109.         if username == None or type(username) != str:
  110.             raise ValueError("You must submit a username as a string.")
  111.         if connection == None or type(connection) != Connection:
  112.             raise ValueError("You must submit a connection as a Connection object.")
  113.         output = connection.selectone("programPassword","prawuse",
  114.                  ["programLoginName = '{}'".format(username), "LIMIT 1"])
  115. #        hashedpw = output[0].encode("utf-8")
  116.         return self.checkpw(output[0].encode("utf-8"))
  117.  
  118.  
  119. # This class can be pulled out into its own file, something like
  120. # "connection.py". Then you can access it using
  121. # from connection import Connection
  122. # and use it just like you were including it directly.
  123. #class Connection:
  124.     """Creates a connection to the MySQL server.
  125.    We can select results to be iterated over later, we can select
  126.    a single row, or we can select all the rows.
  127.    Insert and Update methods can be built later.
  128.    """
  129. """    #DEFAULTS
  130.  
  131.    # Initialize with a dict of values: user, password, host, database
  132.    def __init__(self, config):
  133.        self.conn = mysql.connector.connect(**config)
  134.        self.cursor = self.conn.cursor()
  135.  
  136.    # Returns all results as a result object
  137.    def select(self, columns, table, conditions=None):
  138.        qstr = "SELECT {0} FROM {1}".format(columns, table)
  139.        if conditions != None:
  140.            qstr += " WHERE"
  141.            for condition in conditions:
  142.                qstr += " {}".format(condition)
  143.        return self.cursor.execute(qstr)
  144.  
  145.    # Returns ONLY THE FIRST RESULT as a tuple of objects
  146.    def selectone(self, columns, table, conditions=None):
  147.        results = self.select(columns, table, conditions)
  148.        wanted = results.fetchone()
  149.        while results != None: #we have to get all the data out of this
  150.            results.fetchone() #request before we can send another on
  151.        return wanted          #the same connection
  152.  
  153.    # Returns all results as a list of tuples of objects
  154.    def selectall(self, columns, table, conditions=None):
  155.        results = self.fetch(columns, table, conditions)
  156.        return results.fetchall()
  157.  
  158.    #we don't need any update methods yet so I won't write them yet"""
  159.  
  160. def main():
  161.     #Let's do some setup
  162.     config = Configuration('config.ini')
  163.     print(config.full)
  164.     #conn = Connection(config.full)
  165.     pw = Password()
  166.     hashedpw = pw.hashpw(input("What's the password? ").strip())
  167.     print("Now let's check it.")
  168.     if pw.checkpwlocal() == True:
  169.         print("You got it!")
  170.     else:
  171.         print("Nope. :(")
  172.    
  173. if __name__ == "__main__":
  174.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement