class ServerListenCommand(Command): def __init__(self, port, sharedSecret): self.host = "0.0.0.0" self.port = port self.kex = KeyExchanger() self.auth = Authenticator(sharedSecret) def execute(self): self.sock = socket.socket() logger.info("Server socket created") try: self.sock.bind((self.host, self.port)) logger.info("Server listening on port: {}".format(self.port)) except socket.error as msg: logger.error("Server socket bind failed") self.sock.close() return logger.info("Server socket bind complete") t = Thread(target=self.listenThread) t.start() def listenThread(self): logger.info("Listening for connection on separate thread") self.sock.listen(NUM_CLIENTS) try: while True: conn, addr = self.sock.accept() logger.info("Connected with {} : {}".format(addr[0], addr[1])) self.handleClient(conn) except: logger.info("Connection to client closed unexpectedly") traceback.print_exc() self.sock.close() def handleClient(self, conn): try: conn = ConnectionWrapper(conn) self.kex.exchangeKey(KeyExchanger.SERVER, conn) self.auth.authenticate(conn) t = Thread(target=packetListener, args=(conn, )) t.start() while True: try: msg = Q.get(timeout=0.2) if not msg: break if msg.mtype == Message.SEND: conn.send(msg.bytes) Q.task_done() except Empty: pass except AuthError as err: logger.error(str(err)) finally: logger.info("Connection to client closed") conn.close()
def __init__(self): logging.info("GoogleDriveUploader constructor: IN") if GoogleDriveUploader.__instance__ != None: raise Exception("GoogleDriveUploader is a Singleton! Please use 'instance()' to get an object.") else: super(GoogleDriveUploader, self).__init__() GoogleDriveUploader.__instance__ = self self.auth = Authenticator("client_secrets.json", "drive_saved_creds.pickle", "drive") self.drive_service = self.auth.getDriveService()
class AuthenticatorTest(unittest.TestCase): def setUp(self): self.authenticator = Authenticator() self.authenticator.add_user("joe", "joepassword") @unittest.skip("this is useless") def test_add_user(self): self.authenticator.add_user("joe", "joepassword") self.assertTrue("joe" in self.authenticator.users.keys()) def test_login(self): self.assertTrue(self.authenticator.login("joe", "joepassword"))
class AuthorizorTest(unittest.TestCase): """docstring for AuthorizorTest""" def setUp(self): self.authenticator = Authenticator() self.authenticator.add_user("joe", "joepassword") self.authenticator.login("joe", "joepassword") self.authorizor = Authorizor(self.authenticator) self.authorizor.add_permission("paint") @unittest.skip("this is useless") def test_add_permission(self): self.authorizor.add_permission("paint") self.assertTrue("paint" in self.authorizor.permissions.keys()) def test_check_permission(self): self.authorizor.permit_user("paint", "joe") self.authorizor.check_permission("paint", "joe")
def setup_app(): from flask_marshmallow import Marshmallow from flask_cors import CORS from auth import Authenticator cors = CORS(_app, resources={r"/*": {"origins": "*"}}) basic_auth = Authenticator( _app, db, enforce_paths=(re.compile(r'.*/api/.*'), ))
def prepare(self): self.authenticated_hosts = {} self.auth = Authenticator( self.conf['admin_key_length'], self.conf['admin_salt_length'], self.conf['admin_key_iters'], self.conf['admin_key_hash'] )
class ClientConnectCommand(Command): def __init__(self, host, port, sharedSecret): self.host = host self.port = port self.kex = KeyExchanger() self.auth = Authenticator(sharedSecret) def execute(self): self.sock = socket.socket() logger.info("Client socket created") t = Thread(target=self.connectThread) t.start() def connectThread(self): conn = None try: self.sock.connect((self.host, self.port)) logger.info("Client connected") conn = ConnectionWrapper(self.sock) # use connection from now on to talk self.kex.exchangeKey(KeyExchanger.CLIENT, conn) self.auth.authenticate(conn) t = Thread(target=packetListener, args=(conn, )) t.start() while True: try: msg = Q.get(timeout=0.2) if not msg: break if msg.mtype == Message.SEND: conn.send(msg.bytes) Q.task_done() except Empty: pass except AuthError as err: logger.error(str(err)) finally: logger.info("Connection to server closed") if conn: conn.close()
def __init__(self, API_obj, serveraddress, serverroot, docMap, enableUpload, guiOpts, pathManager=None, examples=None, externalExamples=None): def_dsetname = docMap.keys()[0] self.pT= template.template( \ titlePrefix= guiOpts['titlePrefix'][def_dsetname], homeText= guiOpts['homeText'][def_dsetname], headerImage= guiOpts['headerImage'][def_dsetname], topLink= guiOpts['topLink'][def_dsetname], bottomText= guiOpts['bottomText'][def_dsetname], haveLogout= False, enableUpload= enableUpload[def_dsetname], ballads= def_dsetname.startswith('ballads') ) if pathManager == None: self.pathManager_obj = pathManager_open(docMap) else: self.pathManager_obj = pathManager self.auth_obj = Authenticator(self.pT, userpass=None, allNeedLogin=False) self.login = self.auth_obj.login self.logout = self.auth_obj.logout self.API_obj = API_obj self.upload_obj = upload.upload(self.pT, API_obj) self.docMap = docMap self.page0_obj = page0.page0(self.pT, self.docMap, self.pathManager_obj, examples=examples, externalExamples=externalExamples, browse=True) self.dynamicImage_obj = dynamic_image.dynamicImage(docMap) self.searchPage_obj = search_page.searchPage(self.pT, docMap, self.pathManager_obj) self.doSearch_obj = do_search.doSearch(self.pT, API_obj, docMap, self.pathManager_obj, upload_obj=self.upload_obj, examples=examples, guiOpts=guiOpts) self.details_obj = details.details( self.pT, API_obj, docMap, self.pathManager_obj, doRegistration=guiOpts['registration'][def_dsetname]) if True: self.registerImages_obj = register_images.registerImages( self.pT, API_obj) if False: self.sendComments_obj = send_comments.sendComments(self.pT) self.index = self.page0_obj.index self.page0 = self.index self.getImage = self.dynamicImage_obj.index self.search = self.searchPage_obj.index self.dosearch = self.doSearch_obj.index self.details = self.details_obj.index self.drawMatches = self.details_obj.drawMatches self.upload = self.upload_obj.upload self.uploadNext = self.upload_obj.uploadNext self.uploadSave = self.upload_obj.uploadSave self.uploadProcess = self.upload_obj.uploadProcess self.drop_obj = drop.drop() self.drop = self.drop_obj.index self.webAPI_obj = web_api.webAPI(serveraddress, serverroot, self.upload_obj, self.API_obj, self.docMap, self.pathManager_obj) self.webAPI = self.webAPI_obj.uploadAPI if True: self.register = self.registerImages_obj.index self.tmpImage = self.registerImages_obj.tmpImage self.getImageFull = self.searchPage_obj.getImageFull if False: self.sendComments = self.sendComments_obj.index # axes/ballads API stuff self.api_version = self.webAPI_obj.api_version self.api_engine_reachable = self.webAPI_obj.api_engine_reachable self.api_exec_query = self.webAPI_obj.api_exec_query
class GoogleDriveUploader(BackgroundProcessor): __instance__ = None @staticmethod def instance(): if GoogleDriveUploader.__instance__ == None: GoogleDriveUploader() return GoogleDriveUploader.__instance__ def __init__(self): logging.info("GoogleDriveUploader constructor: IN") if GoogleDriveUploader.__instance__ != None: raise Exception("GoogleDriveUploader is a Singleton! Please use 'instance()' to get an object.") else: super(GoogleDriveUploader, self).__init__() GoogleDriveUploader.__instance__ = self self.auth = Authenticator("client_secrets.json", "drive_saved_creds.pickle", "drive") self.drive_service = self.auth.getDriveService() def preWorkFunction(self, data_array): logging.info("GoogleDriveUploader.preWorkFunction()") return True ################################################################################################################################## # name - workFunction() # The guts of this class is in this method. Essentially uploads files in the incoming files_array to google drive. # - From configuration, gets the name of folder to upload files to # - Searches for the folder in GoogleDrive # - Once found, uploads files to the folder ################################################################################################################################## def workFunction(self, files_array): logging.info("GoogleDriveUploader.workFunction()...") # Get name of folder to upload from configuration and... folder=Configurator.instance().getGoogleDriveUploadFolder() if folder == None: raise Exception("GoogleDriveUploader.workFunction(): Invalid Google Drive folder") # ...try to find the folder on google drive. upload_folder_id = self.findFolder(folder) if upload_folder_id == None: raise Exception("Invalid folder: [%s]. Please create this folder on the drive." % (folder)) # Iterate and upload. Simple. for filepath in files_array: logging.info("GoogleDriveUploader.workFunction(): Uploading to folder: [%s], thefile: [%s]..." % (folder, filepath)) self.upload(filepath, upload_folder_id) logging.info("GoogleDriveUploader.workFunction(): DONE with [%s]" % (filepath)) ################################################################################################################################## ################################################################################################################################## # upload() # Uploads an incoming file to the folder specified # The incoming folder_id represents the folder into which the file must be uploaded ################################################################################################################################## def upload(self, thefile, folder_id): file_metadata = { 'name': thefile, 'parents': [folder_id] } media = MediaFileUpload(thefile, mimetype='image/jpeg') thefile = self.drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() ################################################################################################################################## # name - findFolder() # Iterate through the list of drive folders and find the one that represents the incoming folder name # return: Folder ID ################################################################################################################################## def findFolder(self, folder_name): page_token = None # Execute a query to look only for mimetype= 'folder'... while True: results = self.drive_service.files().list(q="mimeType='application/vnd.google-apps.folder'", # Look only for folders spaces='drive', fields='nextPageToken, files(id, name)', pageToken=page_token).execute() #...and get the list of folders folder_list = results.get('files', []) for folder in folder_list: # Search for YOUR folder and... if folder.get('name') == folder_name: id = folder.get('id') print ("ID for Folder:[%s] is [%s]" %(folder_name, id)) return id #...return its ID page_token = results.get('nextPageToken', None) if page_token is None: break
class Plugin(plugin.Plugin): def prepare(self): self.authenticated_hosts = {} self.auth = Authenticator( self.conf['admin_key_length'], self.conf['admin_salt_length'], self.conf['admin_key_iters'], self.conf['admin_key_hash'] ) def register_commands(self): self.commands = [ ('auth <pass>', self.authenticate), ('mkpasswd <pass>', self.make_passkey), ('sit', self.sit), ('say <target> <<message>>', self.say), ('act <target> <<message>>', self.act), ('ctcp <target> <ctcp> <<content>>', self.ctcp), ('ctcp <target> <ctcp>', self.solo_ctcp), ('join <channel>', self.join), ('part <channel> <<reason>>', self.part_with_reason), ('part <channel>', self.part), ] def authenticate(self, message, args): """ Authenticate with <pyfoot>. """ try: pword_conf = self.conf['admin_admins'][message.nick] except KeyError: self.irc.act(message.source, self.conf['admin_denies']) return pword_msg = b' '.join(message.content_raw.split(b' ')[1:]) print('\a !! auth attempt by ' + message.nick) if self.auth.check_passkey(pword_conf, pword_msg): self.authenticated_hosts[message.host] = message.nick self.irc.privmsg(message.source, self.conf['admin_greeting']) else: self.irc.act(message.source, self.conf['admin_denies']) def make_passkey(self, message, args): """ Make a passkey for use with <pyfoot>. """ pword_msg = b' '.join(message.content_raw.split(b' ')[1:]) new_passkey = self.auth.make_passkey(pword_msg) self.irc.privmsg(message.source, new_passkey) def can_trust(self, message): if (message.host in self.authenticated_hosts and self.authenticated_hosts[message.host] == message.nick): return True else: self.irc.act(message.source, self.conf['admin_denies']) return False def act(self, message, args): """ Make <pyfoot> do something. """ if self.can_trust(message): self.irc.act(args['target'], args['message']) def say(self, message, args): """ Make <pyfoot> say something. """ if self.can_trust(message): self.irc.privmsg(args['target'], args['message']) def ctcp(self, message, args): """ Send a CTCP message. Content optional. """ if self.can_trust(message): self.irc.ctcp(args['target'], args['ctcp'], args['content']) def solo_ctcp(self, message, args): if self.can_trust(message): self.irc.ctcp(args['target'], args['ctcp']) def join(self, message, args): """ Make <pyfoot> join a channel. """ if self.can_trust(message): self.irc.join(args['channel']) self.irc.privmsg(message.source, 'joined ' + args['channel']) def part_with_reason(self, message, args): """ Make <pyfoot> leave a channel. Reason optional. """ if self.can_trust(message): self.irc.part(args['channel'], args['reason']) self.irc.privmsg(message.source, 'left ' + args['channel']) def part(self, message, args): if self.can_trust(message): self.irc.part(args['channel']) self.irc.privmsg(message.source, 'left ' + args['channel']) def sit(self, message, args): """ Test authentication state. """ if self.can_trust(message): self.irc.act(message.source, 'sits')
app.config["SECRET_KEY"] = "Highly secret key" admins = {"admin": "password"} auth = False questions = Questions() surveys = Surveys() reader = CSVReader() writer = CSVWriter() sview = SurveyView() smodel = SurveyModel() scntrl = SurveyController(smodel, sview) author = Authenticator(User('', 'invalid')) def check_auth(): global auth return auth def check_password(user_name, password): global auth global admins if user_name in admins: if password == admins[user_name]: auth = True return auth
from flask import Flask from flask_sqlalchemy import SQLAlchemy from auth import Authenticator from datetime import datetime from util import convert NEW_BALANCE = 1000 POINTS_PER_CARD = 10000 db = SQLAlchemy() auth = Authenticator() def init_app(app): app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False) db.init_app(app) auth.set_app(app) # [START model] class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(255), nullable=False, unique=True) password = db.Column(db.String(255), nullable=False) admin = db.Column(db.Boolean, nullable=False) giftable = db.relationship('Giftable', lazy=False, uselist=False) redeemable = db.relationship('Redeemable', lazy=False, uselist=False) def __repr__(self):
def __init__(self, host, port, sharedSecret): self.host = host self.port = port self.kex = KeyExchanger() self.auth = Authenticator(sharedSecret)
def setUp(self): self.authenticator = Authenticator() self.authenticator.add_user("joe", "joepassword") self.authenticator.login("joe", "joepassword") self.authorizor = Authorizor(self.authenticator) self.authorizor.add_permission("paint")
def setUp(self): self.authenticator = Authenticator() self.authenticator.add_user("joe", "joepassword")