class LayoutData: def __init__(self): self.authentication = Authentication(); self.authentication.session_init(); def getPortal(self): return Services.getPortalManager().get(portalId) def getPortals(self): return Services.getPortalManager().portals def getPortalName(self): return self.getPortal().getDescription() def escapeText(self, text): return StringEscapeUtils.escapeXml(text) def md5Hash(self, data): return md5.new(data).hexdigest() def capitalise(self, text): return text[0].upper() + text[1:] def getTemplate(self, templateName): portalName = portalId if not Services.pageService.resourceExists(portalId, templateName, False): portalName = Services.portalManager.DEFAULT_PORTAL_NAME return "%s/%s" % (portalName, templateName)
def authenticate_user(self): global AUTHENTICATED # we should check to see if we are already authenticated before blindly doing it again if (AUTHENTICATED == False ): obj = Authentication(self._vipr_info['hostname'], int(self._vipr_info['port'])) cookiedir = '/tmp/vipr_cookie_dir' cookiefile = 'cookie-' + self._vipr_info['username'] + '-' + str(os.getpid()) obj.authenticate_user(self._vipr_info['username'], self._vipr_info['password'], cookiedir, cookiefile) AUTHENTICATED = True
def __init__(self, username=None, api_key=None, timeout=10, **kwargs): """ Accepts keyword arguments for Rackspace Cloud username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. @type username: str @param username: a Rackspace Cloud username @type api_key: str @param api_key: a Rackspace Cloud API key """ self.connection_args = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.us_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate()
def __init__(self): # init Query super(Client, self).__init__() self.token = None self.server_info = None self.headers = {} self.config = Config().get_data() self.authentication = None data = 'data' in self.config.keys() and self.config['data'] or None if data: self.hostname = 'hostname' in data.keys() and \ data['hostname'] or '' self.sf_apikey = 'apikey' in data.keys() and \ data['apikey'] or '' self.username = '******' in data.keys() and \ data['username'] or '' self.password = '******' in data.keys() and \ data['password'] or '' self.impersonation_username = \ 'impersonation_username' in data.keys() and \ data['impersonation_username'] or '' self.token_life_time = 'token_life_time' in data.keys() and \ data['token_life_time'] or 0 self.handler = Handler(self.config) self.authentication = Authentication( hostname=self.hostname, sf_apikey=self.sf_apikey, username=self.username, password=self.password, impersonation_username=self.impersonation_username)
class RequestAccessControlTests(unittest.TestCase): def setUp(self): self.auth = Authentication(EphemeralAuthenticationBackend()) def test_sequential_api_calls_call_backend(self): self.assertTrue(RequestAccessControl(self.auth).enforce_sequential_api_calls(lambda role: True)) self.assertTrue(RequestAccessControl(self.auth).enforce_sequential_api_calls(lambda role: True)) def test_second_parallel_api_call_is_processed_sequentially(self): access_controller = RequestAccessControl(self.auth) first_api_call = threading.Thread(target=lambda: access_controller.enforce_sequential_api_calls(lambda role: time.sleep(1))) first_api_call.start() second_response = access_controller.enforce_sequential_api_calls(lambda role: True) self.assertTrue(second_response) first_api_call.join() self.assertTrue(RequestAccessControl(self.auth).enforce_sequential_api_calls(lambda role: True)) def test_user_with_valid_role_hits_endpoint(self): self.assertTrue(RequestAccessControl(self.auth).enforce_sequential_api_calls(lambda role: True, "user")) def capture_role(self, role): self.captured_role = role def test_capturing_user_role_on_added_user(self): self.assertEqual(('', 200), self.auth.add_user("testRoleUser", {"password": base64.b64encode("password".encode()), "role": "support"}, "admin")) RequestAccessControl(self.auth).enforce_sequential_api_calls(lambda role: self.capture_role(role), "testRoleUser") self.assertEqual("support", self.captured_role)
def get_vendor(self, card_num): validity = Authentication().verify_card( card_num ) #call verify card method fron Authentication class and assign it to variable #check for validity if validity == 'Valid': first_digit = str(card_num)[0] #assign first digits of card number industry = '' #declare which type of industry card belongs to if first_digit == '1' or first_digit == '2': #if first digit of card is 1 or 2 industry = 'Airline' #it is in airline industry elif first_digit == '3': #if digit is 3 industry = 'Travel & Entertainment' issuer = 'American Express' #amex card elif first_digit == '4' or first_digit == '5' or first_digit == '6': #if digits are 4 or 5 or 6 industry = 'Banking' # it is banking industry if first_digit == '4': #if digit is 4 issuer = 'Visa' #card is VISA elif first_digit == '5': #if digit is 5 issuer = 'MasterCard' #it is Mastercard else: issuer = 'Discover' #any other digit is Discover return '\tIndustry: {0} \n\tIssuer: {1}'.format(industry, issuer) else: self.vendor = "Invalid card has no Vendor" #otherwise card has no vendor return self.vendor
def display_login(self): cls() print(""" ================================= | 1. Login As a Buyer | | 2. Login As a Vendor | | 3. Go back | ================================= \n\n """) i = Validation.get_int_input(input(), 3) if i == 3: self.display_store() print("Enter Username Or Email") username = input() print("Enter Password") password = input() acc_type = "buyer" if i == 1 else "seller" while not Authentication.authenticate_user(username, password, acc_type): print("Invalid Credentials") inp = input("Enter 0 to go back or 1 to try again ") if inp == "0": self.display_login() return print("Enter Username or Contact info (email/phone)") username = input() print("Enter Password") password = input() self.logged_in_menu() return
def __init__(self): self.db = Database() self.command = commands.Commands() self.encrypt = Encrypt() self.auth = Authentication() self.commands = { "help": self.command.help, "new": self.command.new, "show": self.command.show, "save": self.command.save, "search": self.command.search, "delete": self.command.delete, "update": self.command.update_master_password, "security": self.command.security }
def register_product(self): idd = random.randint(0, 1000000000) details = [] details.append(idd) cls() print("==========================================") print("Enter Product Name: ", end="") details.append(input()) print() print("Enter Product Description : ", end="") details.append(input()) print() print("Enter Product Price : ", end="") details.append(input()) print() details.append(Authentication.get_authenticated_user()) details.append(-1) details.append(0) print("Enter Product Stock : ", end="") details.append(input()) print() print("Enter Product Category : ", end="") details.append(input()) print() Product.add_product(*details)
def __init__(self, username=None, api_key=None, **kwargs): """ Accepts keyword arguments for Mosso username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. @type username: str @param username: a Mosso username @type api_key: str @param api_key: a Mosso API key """ self.cdn_enabled = False self.cdn_args = None self.connection_args = None self.cdn_connection = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) socket.setdefaulttimeout = int(kwargs.get('timeout', 5)) self.auth = kwargs.has_key('auth') and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.default_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate()
def register(profile_cipher, profile_dict): profile_type = Authentication.decrypt_profile_type(profile_type) """This code block will update info from external service (Facebook, Linkedin, etc) using token or refresh token""" if profile_type == "Facebook" and type(profile_dict) is str: #WILL NEED TO GET TOKEN SOMEHOW/use refresh token #make facebook api call and put data in dict FacebookProfile(profile_dict).put() #return status_code if profile_type == "Linkedin" and type(profile_dict) is str: #WILL NEED TO GET TOKEN SOMEHOW/use refresh token #make linkedin api call and put data in dict LinkedinProfile(profile_dict).put() #return status_code """This code block will update info from the dictionary sent up by user. Fields that they changed should now remain static""" if profile_type == "Facebook" and type(profile_dict) is dict: #figure out how to not allow fields the user changed to be modifed from external service FacebookProfile(profile_dict).put() #return status_code if profile_type == "Linkedin" and type(profile_dict) is dict: #figure out how to not allow fields the user changed to be modifed from external service LinkedinProfile(profile_dict).put() #return status_code """This code block will always update with user's curr app info since they do not use any external services""" if profile_type == "BCFrd": BlueConnectFriend(profile_dict).put() #return status_code if profile_type == "BCPro": BlueConnectProfessional(profile_dict).put() #return status_code else: raise TypeError("Invalid Profile Type")
def setup_clients(self): """ A method to seting up authentication and necessary clients for the tool - Called by Constructor """ auth = Authentication() self.novaclient = NovaClient(auth) self.keystoneclient = KeystoneClient(auth)
def menu_click_lock(self, widget, ssid, bssid, wificard): if bssid in open(wpa_supplican).read(): connectToSsid(ssid, wificard) else: Authentication(ssid, bssid, wificard) self.updateinfo() self.ifruning = False
class LayoutData: def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.config = JsonConfig() def getPortal(self): return Services.getPortalManager().get(portalId) def getPortals(self): return Services.getPortalManager().portals def getPortalName(self): return self.getPortal().getDescription() def escapeXml(self, text): return StringEscapeUtils.escapeXml(text) def escapeHtml(self, text): return StringEscapeUtils.escapeHtml(text) def unescapeHtml(self, text): return StringEscapeUtils.unescapeHtml(text) def md5Hash(self, data): return md5.new(data).hexdigest() def capitalise(self, text): return text[0].upper() + text[1:] def getTemplate(self, templateName): portalName = portalId if not Services.pageService.resourceExists(portalId, templateName, False): portalName = Services.portalManager.DEFAULT_PORTAL_NAME return "%s/%s" % (portalName, templateName) def isConfigured(self): return self.config.isConfigured() def isNotConfigured(self): return not self.config.isConfigured() def isOutdated(self): return self.config.isOutdated() def needRestart(self): return "true" == sessionState.get("need-restart", "false")
def __init__(self, username=None, api_key=None, timeout=5, **kwargs): """ Accepts keyword arguments for Mosso username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. Setting the argument servicenet to True will make use of Rackspace servicenet network. @type username: str @param username: a Mosso username @type api_key: str @param api_key: a Mosso API key @type servicenet: bool @param servicenet: Use Rackspace servicenet to access Cloud Files. @type cdn_log_retention: bool @param cdn_log_retention: set logs retention for this cdn enabled container. """ self.cdn_enabled = False self.cdn_args = None self.connection_args = None self.cdn_connection = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.servicenet = kwargs.get('servicenet', False) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout # if the environement variable RACKSPACE_SERVICENET is set (to # anything) it will automatically set servicenet=True if not 'servicenet' in kwargs \ and 'RACKSPACE_SERVICENET' in os.environ: self.servicenet = True self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.us_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate()
def __init__(self, username=None, api_key=None, timeout=15, **kwargs): """ Accepts keyword arguments for Mosso username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. Setting the argument servicenet to True will make use of Rackspace servicenet network. @type username: str @param username: a Mosso username @type api_key: str @param api_key: a Mosso API key @type servicenet: bool @param servicenet: Use Rackspace servicenet to access Cloud Files. @type cdn_log_retention: bool @param cdn_log_retention: set logs retention for this cdn enabled container. """ self.cdn_enabled = False self.cdn_args = None self.connection_args = None self.cdn_connection = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.servicenet = kwargs.get('servicenet', False) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout # if the environement variable RACKSPACE_SERVICENET is set (to # anything) it will automatically set servicenet=True if not 'servicenet' in kwargs \ and 'RACKSPACE_SERVICENET' in os.environ: self.servicenet = True self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.us_authurl) if username and api_key and authurl and authurl.startswith('hubic|'): self.auth = HubicAuthentication(username, api_key, authurl, useragent=self.user_agent, timeout=self.timeout) elif username and api_key and authurl: self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent, timeout=self.timeout) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate()
class SearchTreeData: def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.__search() def __search(self): query = formData.get("query") searchQuery = sessionState.get("searchQuery") if query is None or query == "": query = "*:*" if searchQuery and query == "*:*": query = searchQuery elif searchQuery: query += " AND " + searchQuery facetField = formData.get("facet.field") req = SearchRequest(query) req.setParam("facet", "true") req.setParam("fl", "id") req.setParam("rows", "0") req.setParam("facet.limit", "-1") req.setParam("facet.field", facetField) fq = sessionState.get("fq") if fq is not None: req.setParam("fq", fq) req.addParam("fq", 'item_type:"object"') # Make sure 'fq' has already been set in the session security_roles = self.authentication.get_roles_list(); security_query = 'security_filter:("' + '" OR "'.join(security_roles) + '")' req.addParam("fq", security_query) out = ByteArrayOutputStream() indexer = Services.getIndexer() indexer.search(req, out) result = JsonConfigHelper(ByteArrayInputStream(out.toByteArray())) self.__facetList = FacetList(facetField, result) def getFacetList(self): return self.__facetList def getFacet(self, value): return self.__facetList.get(value)
def menu_click_lock(self, widget, ssid, bssid): if ssid in open(wpa_supplican).read(): connectToSsid(ssid) else: Authentication(ssid, bssid) if not self.thr.is_alive(): self.thr.start() else: self.nmMenu = self.nm_menu()
def main(): encryption_main() if checking_hashfile(): arc4_decoder(HASH_KEY) root = Tk() from authentication import Authentication my_gui = Authentication(root) root.mainloop()
def post(self): params = self.get_params(["username", "password"]) log_token = aut.valid_login(*params) if log_token: username, _ = params self.set_cookies({"username":username, "log_token":log_token}) self.redirect("/") else: self.redirect("/login")
def post(self): params = self.get_params(["username", "email", "password"]) user = User.save(*params) if user: log_token = aut.create_and_save_log_token(user) self.set_cookies({'username':user.username, 'log_token':log_token}) self.redirect("/") else: self.redirect("/signup")
def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.writer = response.getPrintWriter("text/html; charset=UTF-8") if self.authentication.is_logged_in() and self.authentication.is_admin(): self.process() else: self.throw_error("Only administrative users can access this feature")
def __init__(self, username=None, api_key=None, timeout=5, **kwargs): """ Accepts keyword arguments for chouti username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. @type username: str @param username: a chouti username, pattern is account:admin @type api_key: str @param api_key: a chouti password container. """ self.connection_args = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.servicenet = kwargs.get('servicenet', False) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout self.username = username self.api_key = api_key self._share_user_uri = kwargs.get('_share_user_uri', None) self._share_request = kwargs.get('_share_request', False) if kwargs.get('share_request', False): # 产生一个专为共享请求的请求连接方法 self.make_request = self.make_share_requst self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.chouti_authurl) if username and api_key and authurl: # 此处的auth为Authentication类的实例 self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate()
def main(): codeUser, wordObjects = Authentication().login() correctAnswer = True while correctAnswer: userInput = input( 'Would you like to do the wordtrainer (WT) or crossword puzzle (CW): ' ) if userInput.lower() == 'wt': WordTrainer().keepAsking(codeUser, wordObjects) elif userInput.lower() == 'cw': correctAnswer = Crossword(wordObjects)
class Application(tornado.web.Application): def __init__(self): settings = dict( autoreload=False, compiled_template_cache=False, static_hash_cache=False, serve_traceback=True, gzip=True, template_path=os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates')), static_path=os.path.abspath(os.path.join(os.path.dirname(__file__), 'static')), login_url='/login' ) handlers = [ url(r'/', Domains, name="Domains", kwargs={'title': 'Domains'}), url('/mailboxes', Mailboxes, name="Mailboxes", kwargs={'title': 'Mailboxes'}), url('/login', Login, name="Login", kwargs={'title': "Login"}), url('/logout', Logout, name="Logout"), url('/set_language', SetLanguage, name="SetLanguage"), url('/aliases', Aliases, name="Aliases", kwargs={'title': 'Aliases'}), url('/profile', Profile, name="Profile", kwargs={'title': 'Profile'}) ] self.logger = logging.getLogger("application") logging.basicConfig(level=logging.DEBUG) self.app_settings = Settings self.database = Database(self.app_settings.Database.DatabaseName, {'user': self.app_settings.Database.Username, 'passwd': self.app_settings.Database.Password, 'host': self.app_settings.Database.Address, 'port': self.app_settings.Database.Port}) self.authentication = Authentication(self) tornado.locale.load_translations(os.path.join(os.path.dirname(__file__), Settings.Language.TranslationFolder)) tornado.locale.set_default_locale(Settings.Language.DefaultLanguage) if not self.database.is_populated(): self.database.initialise() self.authentication.create_user("admin", "admin") tornado.web.Application.__init__(self, handlers, **settings)
class DeleteData: def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.writer = response.getPrintWriter("text/html; charset=UTF-8") if self.authentication.is_logged_in() and self.authentication.is_admin(): self.process() else: self.throw_error("Only administrative users can access this feature") def process(self): record = formData.get("record") try: Services.storage.removeObject(record) Services.indexer.remove(record) self.writer.println(record) self.writer.close() except Exception, e: self.throw_error("Error deleting object: " + e.getMessage())
class LayoutData: def __init__(self): self.authentication = Authentication(); self.authentication.session_init(); self.config = JsonConfig() def getPortal(self): return Services.getPortalManager().get(portalId) def getPortals(self): return Services.getPortalManager().portals def getPortalName(self): return self.getPortal().getDescription() def escapeXml(self, text): return StringEscapeUtils.escapeXml(text) def escapeHtml(self, text): return StringEscapeUtils.escapeHtml(text) def unescapeHtml(self, text): return StringEscapeUtils.unescapeHtml(text) def md5Hash(self, data): return md5.new(data).hexdigest() def capitalise(self, text): return text[0].upper() + text[1:] def getTemplate(self, templateName): return Services.pageService.resourceExists(portalId, templateName) def getQueueStats(self): return Services.getHouseKeepingManager().getQueueStats() def getSsoProviders(self): return security.ssoBuildLogonInterface()
def __init__(self): self.authentication = Authentication() self.authentication.session_init() if self.authentication.is_logged_in(): if self.authentication.is_admin(): responseMsg = self.authentication.get_name() + ":admin" else: responseMsg = self.authentication.get_name() + ":notadmin" else: responseMsg = self.authentication.get_error() response.setStatus(500) writer = response.getPrintWriter("text/html") writer.println(responseMsg) writer.close()
class Follow: @app.route("/follow", methods=['POST']) def followUser(): try: req_json = request.get_json() except Exception, e: print e profile_api = req_json['profile_api'] profile_user = req_json['profile_user'] endpoint = "https://api.twitter.com/1.1/friendships/create.json?screen_name=" + profile_user + "&follow=true" api_handler = Authentication().twitter(profile_api) res, data = api_handler.request(endpoint, "POST") return data
def post(self): args = parser.parse_args() credentials = Authentication.get_credentials(args['Authorization']) user_exists = check_if_user_exists(credentials['username']) if user_exists: return '', 409 hash = pbkdf2_sha256.encrypt(credentials['password'], rounds=100, salt_size=16) register_new_user(credentials['username'], hash) return '', 200
def list_buys(self): cnt = 1 my_purchs = Product.list_purchases() if len(my_purchs) == 0: print("No purchase records found") for x in my_purchs: current_product = Product.get_product(x[1]) if x[2] == Authentication.get_authenticated_user(): print("Purchase " + str(cnt) + ":") print("====================================") print("Purchase ID : " + x[0]) print("Product Name : " + current_product.product_name) print("Prodcut Price : " + current_product.price) print("====================================\n") cnt += 1 input("Enter any key to continue...") self.logged_in_menu()
def __init__(self, username=None, api_key=None, token=None, tenant_id=None, timeout=10, **kwargs): """ Accepts keyword arguments for Rackspace Cloud username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. @type username: str @param username: a Rackspace Cloud username @type api_key: str @param api_key: a Rackspace Cloud API key """ self.connection_args = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout self.auth = 'auth' in kwargs and kwargs['auth'] or None #Temporary hack - if we already have a token and tenant_id, skip auth process and jump straight to connecting if token and tenant_id: #TODO: Make sure token is valid for tenant_id, otherwise, throw back a 401 self.token = token url = "https://dns.api.rackspacecloud.com/v1.0/%s" % tenant_id self.connection_args = parse_url(url) if version_info[0] <= 2 and version_info[1] < 6: self.conn_class = self.connection_args[3] and THTTPSConnection or \ THTTPConnection else: self.conn_class = self.connection_args[3] and HTTPSConnection or \ HTTPConnection self.http_connect() else: if not self.auth: authurl = kwargs.get('authurl', consts.us_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate()
def __init__(self, username=None, api_key=None, **kwargs): """ Accepts keyword arguments for Mosso username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. Setting the argument servicenet to True will make use of Rackspace servicenet network. @type username: str @param username: a Mosso username @type api_key: str @param api_key: a Mosso API key @ivar servicenet: Use Rackspace servicenet to access Cloud Files. @type cdn_log_retention: bool """ self.cdn_enabled = False self.cdn_args = None self.connection_args = None self.cdn_connection = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.servicenet = kwargs.get('servicenet', False) # if the environement variable RACKSPACE_SERVICENET is set (to anything) # it will automatically set servicenet=True if not 'servicenet' in kwargs \ and 'RACKSPACE_SERVICENET' in os.environ: self.servicenet = True socket.setdefaulttimeout = int(kwargs.get('timeout', 5)) self.auth = kwargs.has_key('auth') and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.default_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate()
def get_vendor(self, card_num): validity = Authentication().verify_card(card_num) if validity == 'Valid': first_digit = str(card_num)[0] industry = '' if first_digit == '1' or first_digit == '2': industry = 'Airline' elif first_digit == '3': industry = 'Travel & Entertainment' issuer = 'American Express' elif first_digit == '4' or first_digit == '5' or first_digit == '6': industry = 'Banking' if first_digit == '4': issuer = 'Visa' elif first_digit == '5': issuer = 'MasterCard' else: issuer = 'Discover' return '\tIndustry: {0} \n\tIssuer: {1}'.format(industry, issuer) else: return "Invalid card has no Vendor"
def viewsales(self): cnt = 1 my_sales = Database.get_seller_sales( Authentication.get_authenticated_user()) if len(my_sales) == 0: print("No sales record found") for x in my_sales: current_purchase = Database.get_purchase_info(x) current_product = Product.get_product(current_purchase[1]) buyer_info = Database.get_user_details(current_purchase[2], "buyer", False) print("Sale " + str(cnt) + ":") print("====================================") print("Purchase ID : " + current_purchase[0]) print("Product Name : " + current_product.product_name) print("Prodcut Price : " + current_product.price) print("Buyer Name: {0} {1}".format(buyer_info[0], buyer_info[1])) print("Buyer Username: {0}".format(buyer_info[2])) print("Buyer Address: {0}".format(buyer_info[5])) print("====================================\n") cnt += 1 input("Enter any key to continue...") self.logged_in_menu()
from server import server from authentication import Authentication from models.user import User server.blueprint(Authentication.resource(url_prefix='/v1')) server.blueprint(User.resource(url_prefix='/v1', pubsub=True))
class Connection(object): """ Manages the connection to the storage system and serves as a factory for Container instances. @undocumented: cdn_connect @undocumented: http_connect @undocumented: cdn_request @undocumented: make_request @undocumented: _check_container_name """ def __init__(self, username=None, api_key=None, **kwargs): """ Accepts keyword arguments for Mosso username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. @type username: str @param username: a Mosso username @type api_key: str @param api_key: a Mosso API key """ self.cdn_enabled = False self.cdn_args = None self.connection_args = None self.cdn_connection = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) socket.setdefaulttimeout = int(kwargs.get('timeout', 5)) self.auth = kwargs.has_key('auth') and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.default_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate() def _authenticate(self): """ Authenticate and setup this instance with the values returned. """ (url, self.cdn_url, self.token) = self.auth.authenticate() self.connection_args = parse_url(url) self.conn_class = self.connection_args[3] and HTTPSConnection or \ HTTPConnection self.http_connect() if self.cdn_url: self.cdn_connect() def cdn_connect(self): """ Setup the http connection instance for the CDN service. """ (host, port, cdn_uri, is_ssl) = parse_url(self.cdn_url) conn_class = is_ssl and HTTPSConnection or HTTPConnection self.cdn_connection = conn_class(host, port) self.cdn_enabled = True def http_connect(self): """ Setup the http connection instance. """ (host, port, self.uri, is_ssl) = self.connection_args self.connection = self.conn_class(host, port=port) self.connection.set_debuglevel(self.debuglevel) def cdn_request(self, method, path=[], data='', hdrs=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, performs an http request against the CDN service. """ if not self.cdn_enabled: raise CDNNotEnabled() path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join([quote(i) for i in path])) headers = {'Content-Length': len(data), 'User-Agent': consts.user_agent, 'X-Auth-Token': self.token} if isinstance(hdrs, dict): headers.update(hdrs) # Send the request self.cdn_connection.request(method, path, data, headers) def retry_request(): '''Re-connect and re-try a failed request once''' self.cdn_connect() self.cdn_connection.request(method, path, data, headers) return self.cdn_connection.getresponse() try: response = self.cdn_connection.getresponse() except HTTPException: response = retry_request() if response.status == 401: self._authenticate() response = retry_request() return response def make_request(self, method, path=[], data='', hdrs=None, parms=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, and an optional dictionary of query parameters, performs an http request. """ path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join([quote(i) for i in path])) if isinstance(parms, dict) and parms: query_args = \ ['%s=%s' % (quote(x),quote(str(y))) for (x,y) in parms.items()] path = '%s?%s' % (path, '&'.join(query_args)) headers = {'Content-Length': len(data), 'User-Agent': consts.user_agent, 'X-Auth-Token': self.token} isinstance(hdrs, dict) and headers.update(hdrs) def retry_request(): '''Re-connect and re-try a failed request once''' self.http_connect() self.connection.request(method, path, data, headers) return self.connection.getresponse() try: self.connection.request(method, path, data, headers) response = self.connection.getresponse() except HTTPException: response = retry_request() if response.status == 401: self._authenticate() response = retry_request() return response def get_info(self): """ Return tuple for number of containers and total bytes in the account >>> connection.get_info() (5, 2309749) @rtype: tuple @return: a tuple containing the number of containers and total bytes used by the account """ response = self.make_request('HEAD') count = size = None for hdr in response.getheaders(): if hdr[0].lower() == 'x-account-container-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-account-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return (count, size) def _check_container_name(self, container_name): if not container_name or \ '/' in container_name or \ len(container_name) > consts.container_name_limit: raise InvalidContainerName(container_name) def create_container(self, container_name): """ Given a container name, returns a L{Container} item, creating a new Container if one does not already exist. >>> connection.create_container('new_container') <cloudfiles.container.Container object at 0xb77d628c> @param container_name: name of the container to create @type container_name: str @rtype: L{Container} @return: an object representing the newly created container """ self._check_container_name(container_name) response = self.make_request('PUT', [container_name]) buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return Container(self, container_name) def delete_container(self, container_name): """ Given a container name, delete it. >>> connection.delete_container('old_container') @param container_name: name of the container to delete @type container_name: str """ if isinstance(container_name, Container): container_name = container_name.name self._check_container_name(container_name) response = self.make_request('DELETE', [container_name]) buff = response.read() if (response.status == 409): raise ContainerNotEmpty(container_name) elif (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) if self.cdn_enabled: response = self.cdn_request('POST', [container_name], hdrs={'X-CDN-Enabled': 'False'}) def get_all_containers(self, limit=None, marker=None, **parms): """ Returns a Container item result set. >>> connection.get_all_containers() ContainerResults: 4 containers >>> print ', '.join([container.name for container in connection.get_all_containers()]) new_container, old_container, pictures, music @rtype: L{ContainerResults} @return: an iterable set of objects representing all containers on the account @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker return ContainerResults(self, self.list_containers_info(**parms)) def get_container(self, container_name): """ Return a single Container item for the given Container. >>> connection.get_container('old_container') <cloudfiles.container.Container object at 0xb77d628c> >>> container = connection.get_container('old_container') >>> container.size_used 23074 @param container_name: name of the container to create @type container_name: str @rtype: L{Container} @return: an object representing the container """ self._check_container_name(container_name) response = self.make_request('HEAD', [container_name]) count = size = None for hdr in response.getheaders(): if hdr[0].lower() == 'x-container-object-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-container-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 buff = response.read() if response.status == 404: raise NoSuchContainer(container_name) if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return Container(self, container_name, count, size) def list_public_containers(self): """ Returns a list of containers that have been published to the CDN. >>> connection.list_public_containers() ['container1', 'container2', 'container3'] @rtype: list(str) @return: a list of all CDN-enabled container names as strings """ response = self.cdn_request('GET', ['']) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return response.read().splitlines() def list_containers_info(self, limit=None, marker=None, **parms): """ Returns a list of Containers, including object count and size. >>> connection.list_containers_info() [{u'count': 510, u'bytes': 2081717, u'name': u'new_container'}, {u'count': 12, u'bytes': 23074, u'name': u'old_container'}, {u'count': 0, u'bytes': 0, u'name': u'container1'}, {u'count': 0, u'bytes': 0, u'name': u'container2'}, {u'count': 0, u'bytes': 0, u'name': u'container3'}, {u'count': 3, u'bytes': 2306, u'name': u'test'}] @rtype: list({"name":"...", "count":..., "bytes":...}) @return: a list of all container info as dictionaries with the keys "name", "count", and "bytes" @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker parms['format'] = 'json' response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return json_loads(response.read()) def list_containers(self, limit=None, marker=None, **parms): """ Returns a list of Containers. >>> connection.list_containers() ['new_container', 'old_container', 'container1', 'container2', 'container3', 'test'] @rtype: list(str) @return: a list of all containers names as strings @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return response.read().splitlines() def __getitem__(self, key): """ Container objects can be grabbed from a connection using index syntax. >>> container = conn['old_container'] >>> container.size_used 23074 @rtype: L{Container} @return: an object representing the container """ return self.get_container(key)
def authentication() -> Authentication: return Authentication(data_folder="test/fixtures", password_salt="a test salt", failed_login_delay_base=0)
def test_password_is_not_stored_plain(authentication: Authentication) -> None: user = authentication.user_data(username=EXISTING_USERNAME) assert user["password"] != CORRECT_PASSWORD assert user["password"] == authentication._hash_password(CORRECT_PASSWORD)
class Connection(object): """ Manages the connection to the storage system and serves as a factory for Container instances. @undocumented: cdn_connect @undocumented: http_connect @undocumented: cdn_request @undocumented: make_request @undocumented: _check_container_name """ def __init__(self, username=None, api_key=None, timeout=15, **kwargs): """ Accepts keyword arguments for Mosso username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. Setting the argument servicenet to True will make use of Rackspace servicenet network. @type username: str @param username: a Mosso username @type api_key: str @param api_key: a Mosso API key @type servicenet: bool @param servicenet: Use Rackspace servicenet to access Cloud Files. @type cdn_log_retention: bool @param cdn_log_retention: set logs retention for this cdn enabled container. """ self.cdn_enabled = False self.cdn_args = None self.connection_args = None self.cdn_connection = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.servicenet = kwargs.get('servicenet', False) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout # if the environement variable RACKSPACE_SERVICENET is set (to # anything) it will automatically set servicenet=True if not 'servicenet' in kwargs \ and 'RACKSPACE_SERVICENET' in os.environ: self.servicenet = True self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.us_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent, timeout=self.timeout) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate() def _authenticate(self): """ Authenticate and setup this instance with the values returned. """ (url, self.cdn_url, self.token) = self.auth.authenticate() url = self._set_storage_url(url) self.connection_args = parse_url(url) if version_info[0] <= 2 and version_info[1] < 6: self.conn_class = self.connection_args[3] and THTTPSConnection or \ THTTPConnection else: self.conn_class = self.connection_args[3] and HTTPSConnection or \ HTTPConnection self.http_connect() if self.cdn_url: self.cdn_connect() def _set_storage_url(self, url): if self.servicenet: return "https://snet-%s" % url.replace("https://", "") return url def cdn_connect(self): """ Setup the http connection instance for the CDN service. """ (host, port, cdn_uri, is_ssl) = parse_url(self.cdn_url) self.cdn_connection = self.conn_class(host, port, timeout=self.timeout) self.cdn_enabled = True def http_connect(self): """ Setup the http connection instance. """ (host, port, self.uri, is_ssl) = self.connection_args self.connection = self.conn_class(host, port=port, \ timeout=self.timeout) self.connection.set_debuglevel(self.debuglevel) def cdn_request(self, method, path=[], data='', hdrs=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, performs an http request against the CDN service. """ if not self.cdn_enabled: raise CDNNotEnabled() path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join([unicode_quote(i) for i in path])) headers = {'Content-Length': str(len(data)), 'User-Agent': self.user_agent, 'X-Auth-Token': self.token} if isinstance(hdrs, dict): headers.update(hdrs) def retry_request(): '''Re-connect and re-try a failed request once''' self.cdn_connect() self.cdn_connection.request(method, path, data, headers) return self.cdn_connection.getresponse() try: self.cdn_connection.request(method, path, data, headers) response = self.cdn_connection.getresponse() except (socket.error, IOError, HTTPException): response = retry_request() if response.status == 401: self._authenticate() headers['X-Auth-Token'] = self.token response = retry_request() return response def make_request(self, method, path=[], data='', hdrs=None, parms=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, and an optional dictionary of query parameters, performs an http request. """ path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join([unicode_quote(i) for i in path])) if isinstance(parms, dict) and parms: path = '%s?%s' % (path, urlencode(parms)) headers = {'Content-Length': str(len(data)), 'User-Agent': self.user_agent, 'X-Auth-Token': self.token} isinstance(hdrs, dict) and headers.update(hdrs) def retry_request(): '''Re-connect and re-try a failed request once''' self.http_connect() self.connection.request(method, path, data, headers) return self.connection.getresponse() try: self.connection.request(method, path, data, headers) response = self.connection.getresponse() except (socket.error, IOError, HTTPException): response = retry_request() if response.status == 401: self._authenticate() headers['X-Auth-Token'] = self.token response = retry_request() return response def get_info(self): """ Return tuple for number of containers, total bytes in the account and account metadata >>> connection.get_info() (5, 2309749) @rtype: tuple @return: a tuple containing the number of containers, total bytes used by the account and a dictionary containing account metadata """ response = self.make_request('HEAD') count = size = None metadata = {} for hdr in response.getheaders(): if hdr[0].lower() == 'x-account-container-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-account-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 if hdr[0].lower().startswith('x-account-meta-'): metadata[hdr[0].lower()[15:]] = hdr[1] buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return (count, size, metadata) def update_account_metadata(self, metadata): """ Update account metadata >>> metadata = {'x-account-meta-foo' : 'bar'} >>> connection.update_account_metadata(metadata) @param metadata: Dictionary of metadata @type metdada: dict """ response = self.make_request('POST', hdrs=metadata) response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) def _check_container_name(self, container_name): if not container_name or \ '/' in container_name or \ len(container_name) > consts.container_name_limit: raise InvalidContainerName(container_name) def create_container(self, container_name, error_on_existing=False): """ Given a container name, returns a L{Container} item, creating a new Container if one does not already exist. >>> connection.create_container('new_container') <cloudfiles.container.Container object at 0xb77d628c> @param container_name: name of the container to create @type container_name: str @param error_on_existing: raise ContainerExists if container already exists @type error_on_existing: bool @rtype: L{Container} @return: an object representing the newly created container """ self._check_container_name(container_name) response = self.make_request('PUT', [container_name]) buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) if error_on_existing and (response.status == 202): raise ContainerExists(container_name) return Container(self, container_name) def delete_container(self, container_name): """ Given a container name, delete it. >>> connection.delete_container('old_container') @param container_name: name of the container to delete @type container_name: str """ if isinstance(container_name, Container): container_name = container_name.name self._check_container_name(container_name) response = self.make_request('DELETE', [container_name]) response.read() if (response.status == 409): raise ContainerNotEmpty(container_name) elif (response.status == 404): raise NoSuchContainer elif (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) if self.cdn_enabled: response = self.cdn_request('POST', [container_name], hdrs={'X-CDN-Enabled': 'False'}) def get_all_containers(self, limit=None, marker=None, **parms): """ Returns a Container item result set. >>> connection.get_all_containers() ContainerResults: 4 containers >>> print ', '.join([container.name for container in connection.get_all_containers()]) new_container, old_container, pictures, music @rtype: L{ContainerResults} @return: an iterable set of objects representing all containers on the account @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker return ContainerResults(self, self.list_containers_info(**parms)) def get_container(self, container_name): """ Return a single Container item for the given Container. >>> connection.get_container('old_container') <cloudfiles.container.Container object at 0xb77d628c> >>> container = connection.get_container('old_container') >>> container.size_used 23074 @param container_name: name of the container to create @type container_name: str @rtype: L{Container} @return: an object representing the container """ self._check_container_name(container_name) response = self.make_request('HEAD', [container_name]) count = size = None metadata = {} for hdr in response.getheaders(): if hdr[0].lower() == 'x-container-object-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-container-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 if hdr[0].lower().startswith('x-container-meta-'): metadata[hdr[0].lower()[17:]] = hdr[1] buff = response.read() if response.status == 404: raise NoSuchContainer(container_name) if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return Container(self, container_name, count, size, metadata) def list_public_containers(self): """ Returns a list of containers that have been published to the CDN. >>> connection.list_public_containers() ['container1', 'container2', 'container3'] @rtype: list(str) @return: a list of all CDN-enabled container names as strings """ response = self.cdn_request('GET', ['']) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return response.read().splitlines() def list_containers_info(self, limit=None, marker=None, **parms): """ Returns a list of Containers, including object count and size. >>> connection.list_containers_info() [{u'count': 510, u'bytes': 2081717, u'name': u'new_container'}, {u'count': 12, u'bytes': 23074, u'name': u'old_container'}, {u'count': 0, u'bytes': 0, u'name': u'container1'}, {u'count': 0, u'bytes': 0, u'name': u'container2'}, {u'count': 0, u'bytes': 0, u'name': u'container3'}, {u'count': 3, u'bytes': 2306, u'name': u'test'}] @rtype: list({"name":"...", "count":..., "bytes":...}) @return: a list of all container info as dictionaries with the keys "name", "count", and "bytes" @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker parms['format'] = 'json' response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return json_loads(response.read()) def list_containers(self, limit=None, marker=None, **parms): """ Returns a list of Containers. >>> connection.list_containers() ['new_container', 'old_container', 'container1', 'container2', 'container3', 'test'] @rtype: list(str) @return: a list of all containers names as strings @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return response.read().splitlines() def __getitem__(self, key): """ Container objects can be grabbed from a connection using index syntax. >>> container = conn['old_container'] >>> container.size_used 23074 @rtype: L{Container} @return: an object representing the container """ return self.get_container(key)
def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.config = JsonConfig()
from flask import Flask, render_template, request, jsonify, redirect, abort, Response, make_response import re from typing import Optional # noqa: F401 import config import json from gregorian_calendar import GregorianCalendar from calendar_data import CalendarData from authentication import Authentication from app_utils import (previous_month_link, next_month_link, new_session_id, add_session, authenticated, get_session_username, authorized) app = Flask(__name__) authentication = Authentication(data_folder=config.USERS_DATA_FOLDER, password_salt=config.PASSWORD_SALT) @app.route("/", methods=["GET"]) @authenticated def index() -> Response: username = get_session_username(session_id=str(request.cookies.get("sid"))) user_data = authentication.user_data(username=username) return redirect("/{}/".format(user_data["default_calendar"])) @app.route("/login", methods=["GET"]) def login() -> Response: return render_template("login.html")
class Connection(object): """ Manages the connection to the storage system and serves as a factory for Container instances. @undocumented: cdn_connect @undocumented: http_connect @undocumented: cdn_request @undocumented: make_request @undocumented: _check_container_name """ def __init__(self, username=None, api_key=None, timeout=5, **kwargs): """ Accepts keyword arguments for Mosso username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. Setting the argument servicenet to True will make use of Rackspace servicenet network. @type username: str @param username: a Mosso username @type api_key: str @param api_key: a Mosso API key @type servicenet: bool @param servicenet: Use Rackspace servicenet to access Cloud Files. @type cdn_log_retention: bool @param cdn_log_retention: set logs retention for this cdn enabled container. """ self.cdn_enabled = False self.cdn_args = None self.connection_args = None self.cdn_connection = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.servicenet = kwargs.get('servicenet', False) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout # if the environement variable RACKSPACE_SERVICENET is set (to # anything) it will automatically set servicenet=True if not 'servicenet' in kwargs \ and 'RACKSPACE_SERVICENET' in os.environ: self.servicenet = True self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.us_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate() def _authenticate(self): """ Authenticate and setup this instance with the values returned. """ (url, self.cdn_url, self.token) = self.auth.authenticate() url = self._set_storage_url(url) self.connection_args = parse_url(url) if version_info[0] <= 2 and version_info[1] < 6: self.conn_class = self.connection_args[3] and THTTPSConnection or \ THTTPConnection else: self.conn_class = self.connection_args[3] and HTTPSConnection or \ HTTPConnection self.http_connect() if self.cdn_url: self.cdn_connect() def _set_storage_url(self, url): if self.servicenet: return "https://snet-%s" % url.replace("https://", "") return url def cdn_connect(self): """ Setup the http connection instance for the CDN service. """ (host, port, cdn_uri, is_ssl) = parse_url(self.cdn_url) self.cdn_connection = self.conn_class(host, port, timeout=self.timeout) self.cdn_enabled = True def http_connect(self): """ Setup the http connection instance. """ (host, port, self.uri, is_ssl) = self.connection_args self.connection = self.conn_class(host, port=port, \ timeout=self.timeout) self.connection.set_debuglevel(self.debuglevel) def cdn_request(self, method, path=[], data='', hdrs=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, performs an http request against the CDN service. """ if not self.cdn_enabled: raise CDNNotEnabled() path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join([unicode_quote(i) for i in path])) headers = { 'Content-Length': str(len(data)), 'User-Agent': self.user_agent, 'X-Auth-Token': self.token } if isinstance(hdrs, dict): headers.update(hdrs) def retry_request(): '''Re-connect and re-try a failed request once''' self.cdn_connect() self.cdn_connection.request(method, path, data, headers) return self.cdn_connection.getresponse() try: self.cdn_connection.request(method, path, data, headers) response = self.cdn_connection.getresponse() except (socket.error, IOError, HTTPException): response = retry_request() if response.status == 401: self._authenticate() headers['X-Auth-Token'] = self.token response = retry_request() return response def make_request(self, method, path=[], data='', hdrs=None, parms=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, and an optional dictionary of query parameters, performs an http request. """ path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join([unicode_quote(i) for i in path])) if isinstance(parms, dict) and parms: query_args = \ ['%s=%s' % (quote(x), quote(str(y))) for (x, y) in parms.items()] path = '%s?%s' % (path, '&'.join(query_args)) headers = { 'Content-Length': str(len(data)), 'User-Agent': self.user_agent, 'X-Auth-Token': self.token } isinstance(hdrs, dict) and headers.update(hdrs) def retry_request(): '''Re-connect and re-try a failed request once''' self.http_connect() self.connection.request(method, path, data, headers) return self.connection.getresponse() try: self.connection.request(method, path, data, headers) response = self.connection.getresponse() except (socket.error, IOError, HTTPException): response = retry_request() if response.status == 401: self._authenticate() headers['X-Auth-Token'] = self.token response = retry_request() return response def get_info(self): """ Return tuple for number of containers and total bytes in the account >>> connection.get_info() (5, 2309749) @rtype: tuple @return: a tuple containing the number of containers and total bytes used by the account """ response = self.make_request('HEAD') count = size = None for hdr in response.getheaders(): if hdr[0].lower() == 'x-account-container-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-account-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return (count, size) def _check_container_name(self, container_name): if not container_name or \ '/' in container_name or \ len(container_name) > consts.container_name_limit: raise InvalidContainerName(container_name) def create_container(self, container_name, error_on_existing=False): """ Given a container name, returns a L{Container} item, creating a new Container if one does not already exist. >>> connection.create_container('new_container') <cloudfiles.container.Container object at 0xb77d628c> @param container_name: name of the container to create @type container_name: str @param error_on_existing: raise ContainerExists if container already exists @type error_on_existing: bool @rtype: L{Container} @return: an object representing the newly created container """ self._check_container_name(container_name) response = self.make_request('PUT', [container_name]) buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) if error_on_existing and (response.status == 202): raise ContainerExists(container_name) return Container(self, container_name) def delete_container(self, container_name): """ Given a container name, delete it. >>> connection.delete_container('old_container') @param container_name: name of the container to delete @type container_name: str """ if isinstance(container_name, Container): container_name = container_name.name self._check_container_name(container_name) response = self.make_request('DELETE', [container_name]) if (response.status == 409): raise ContainerNotEmpty(container_name) elif (response.status == 404): raise NoSuchContainer elif (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) if self.cdn_enabled: response = self.cdn_request('POST', [container_name], hdrs={'X-CDN-Enabled': 'False'}) def get_all_containers(self, limit=None, marker=None, **parms): """ Returns a Container item result set. >>> connection.get_all_containers() ContainerResults: 4 containers >>> print ', '.join([container.name for container in connection.get_all_containers()]) new_container, old_container, pictures, music @rtype: L{ContainerResults} @return: an iterable set of objects representing all containers on the account @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker return ContainerResults(self, self.list_containers_info(**parms)) def get_container(self, container_name): """ Return a single Container item for the given Container. >>> connection.get_container('old_container') <cloudfiles.container.Container object at 0xb77d628c> >>> container = connection.get_container('old_container') >>> container.size_used 23074 @param container_name: name of the container to create @type container_name: str @rtype: L{Container} @return: an object representing the container """ self._check_container_name(container_name) response = self.make_request('HEAD', [container_name]) count = size = None for hdr in response.getheaders(): if hdr[0].lower() == 'x-container-object-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-container-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 buff = response.read() if response.status == 404: raise NoSuchContainer(container_name) if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return Container(self, container_name, count, size) def list_public_containers(self): """ Returns a list of containers that have been published to the CDN. >>> connection.list_public_containers() ['container1', 'container2', 'container3'] @rtype: list(str) @return: a list of all CDN-enabled container names as strings """ response = self.cdn_request('GET', ['']) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return response.read().splitlines() def list_containers_info(self, limit=None, marker=None, **parms): """ Returns a list of Containers, including object count and size. >>> connection.list_containers_info() [{u'count': 510, u'bytes': 2081717, u'name': u'new_container'}, {u'count': 12, u'bytes': 23074, u'name': u'old_container'}, {u'count': 0, u'bytes': 0, u'name': u'container1'}, {u'count': 0, u'bytes': 0, u'name': u'container2'}, {u'count': 0, u'bytes': 0, u'name': u'container3'}, {u'count': 3, u'bytes': 2306, u'name': u'test'}] @rtype: list({"name":"...", "count":..., "bytes":...}) @return: a list of all container info as dictionaries with the keys "name", "count", and "bytes" @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker parms['format'] = 'json' response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return json_loads(response.read()) def list_containers(self, limit=None, marker=None, **parms): """ Returns a list of Containers. >>> connection.list_containers() ['new_container', 'old_container', 'container1', 'container2', 'container3', 'test'] @rtype: list(str) @return: a list of all containers names as strings @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return response.read().splitlines() def __getitem__(self, key): """ Container objects can be grabbed from a connection using index syntax. >>> container = conn['old_container'] >>> container.size_used 23074 @rtype: L{Container} @return: an object representing the container """ return self.get_container(key)
class LoginData: def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.writer = response.getPrintWriter("text/html; charset=UTF-8") if self.authentication.is_logged_in() and self.authentication.is_admin(): self.process() else: self.throw_error("Only administrative users can access this feature") def add_user(self): username = formData.get("field") rolename = formData.get("hidden") source = formData.get("source") self.authentication.set_role_plugin(source) self.authentication.set_role(username, rolename) err = self.authentication.get_error() if err is None: self.writer.println(username) self.writer.close() else: self.throw_error(err) def change_password(self): username = formData.get("username") password = formData.get("password") password_confirm = formData.get("password_confirm") if password != password_confirm: self.throw_error("The confirm password field does not match the password.") else: source = formData.get("source") self.authentication.set_auth_plugin(source) self.authentication.change_password(username, password) err = self.authentication.get_error() if err is None: self.writer.println(username) self.writer.close() else: self.throw_error(err) def confirm_message(self): msgId = formData.get("message") hk = Services.getHouseKeepingManager() if msgId is None: self.throw_error("No message ID provided") try: if msgId == "ALL": list = hk.getUserMessages(); for entry in list: if not entry.block: hk.confirmMessage(str(entry.id)); else: hk.confirmMessage(msgId); except: error = sys.exc_info()[1] self.throw_error(error.getMessage()) self.writer.println("ok") self.writer.close() def create_role(self): rolename = formData.get("field") source = formData.get("source") self.authentication.set_role_plugin(source) self.authentication.create_role(rolename) err = self.authentication.get_error() if err is None: self.writer.println(rolename) self.writer.close() else: self.throw_error(err) def create_user(self): username = formData.get("username") password = formData.get("password") password_confirm = formData.get("password_confirm") if password != password_confirm: self.throw_error("The confirm password field does not match the password.") else: source = formData.get("source") self.authentication.set_auth_plugin(source) self.authentication.create_user(username, password) err = self.authentication.get_error() if err is None: self.writer.println(username) self.writer.close() else: self.throw_error(err) def delete_role(self): rolename = formData.get("rolename") source = formData.get("source") self.authentication.set_role_plugin(source) self.authentication.delete_role(rolename) err = self.authentication.get_error() if err is None: self.writer.println(rolename) self.writer.close() else: self.throw_error(err) def delete_user(self): username = formData.get("username") source = formData.get("source") self.authentication.set_auth_plugin(source) self.authentication.delete_user(username) err = self.authentication.get_error() if err is None: self.writer.println(username) self.writer.close() else: self.throw_error(err) def get_current_access(self): record = formData.get("record") roles_list = self.authentication.get_access_roles_list(record) err = self.authentication.get_error() if err is None: # We need a JSON string for javascript plugin_strings = [] for plugin in roles_list.keys(): roles = roles_list[plugin] if len(roles) > 0: plugin_strings.append("'" + plugin + "' : ['" + "','".join(roles) + "']") else: plugin_strings.append("'" + plugin + "' : []") responseMessage = "{" + ",".join(plugin_strings) + "}" self.writer.println(responseMessage) self.writer.close() else: self.throw_error(err) def grant_access(self): record = formData.get("record") role = formData.get("role") source = formData.get("source") self.authentication.set_access_plugin(source) self.authentication.grant_access(record, role) err = self.authentication.get_error() if err is None: self.writer.println(role) self.writer.close() self.reindex_record(record) else: self.throw_error(err) def list_users(self): rolename = formData.get("rolename") source = formData.get("source") self.authentication.set_auth_plugin(source) user_list = self.authentication.list_users(rolename) err = self.authentication.get_error() if err is None: # We need a JSON string for javascript responseMessage = "{['" + "','".join(user_list) + "']}" self.writer.println(responseMessage) self.writer.close() else: self.throw_error(err) def process(self): action = formData.get("verb") switch = { "add-user" : self.add_user, "confirm-message" : self.confirm_message, "create-role" : self.create_role, "create-user" : self.create_user, "delete-role" : self.delete_role, "delete-user" : self.delete_user, "change-password" : self.change_password, "get-current-access" : self.get_current_access, "grant-access" : self.grant_access, "list-users" : self.list_users, "remove-user" : self.remove_user, "revoke-access" : self.revoke_access } switch.get(action, self.unknown_action)() def reindex_record(self, recordId): portalManager = Services.getPortalManager() portalManager.reharvest(recordId) def remove_user(self): username = formData.get("username") rolename = formData.get("rolename") source = formData.get("source") self.authentication.set_role_plugin(source) self.authentication.remove_role(username, rolename) err = self.authentication.get_error() if err is None: self.writer.println(username) self.writer.close() else: self.throw_error(err) def revoke_access(self): record = formData.get("record") role = formData.get("role") source = formData.get("source") self.authentication.set_access_plugin(source) self.authentication.revoke_access(record, role) err = self.authentication.get_error() if err is None: self.writer.println(role) self.writer.close() self.reindex_record(record) else: self.throw_error(err) def throw_error(self, message): response.setStatus(500) self.writer.println("Error: " + message) self.writer.close() def unknown_action(self): self.throw_error("Unknown action requested - '" + formData.get("verb") + "'")
def test_authentication_change_password(self): auth = Authentication(FakePersist()) auth.add_user('foobar', 'baz', 'student') auth.login('foobar', 'baz') self.assertDictEqual(auth.change_password('foobar', 'qux'), {})
def test_authentication_login_unknown_user_fail(self): auth = Authentication(FakePersist()) self.assertDictEqual(auth.login('foobar', 'baz'), { 'success': False, 'message': 'User does not exist.' })
def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.__search()
class Connection(object): """ Manages the connection to the storage system and serves as a factory for Container instances. create container ---> PUT delete container ---> DELETE rename container ---> POST 没实现 set ACL ---> POST 没实现 get container ---> GET get info ---> HEAD list containers ---> GET 解析json数据 _authenticate ---> 认证 http_connect ---> 生成conn连接 make_request ---> 向服务端发送http请求 """ def __init__(self, username=None, api_key=None, timeout=5, **kwargs): """ Accepts keyword arguments for chouti username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. @type username: str @param username: a chouti username, pattern is account:admin @type api_key: str @param api_key: a chouti password container. """ self.connection_args = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.servicenet = kwargs.get('servicenet', False) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout self.username = username self.api_key = api_key self._share_user_uri = kwargs.get('_share_user_uri', None) self._share_request = kwargs.get('_share_request', False) if kwargs.get('share_request', False): # 产生一个专为共享请求的请求连接方法 self.make_request = self.make_share_requst self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.chouti_authurl) if username and api_key and authurl: # 此处的auth为Authentication类的实例 self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate() def _authenticate(self): """ Authenticate and setup this instance with the values returned. 私有方法,开始认证 """ (url, self.token) = self.auth.authenticate() self.connection_args = parse_url(url) if version_info[0] <= 2 and version_info[1] < 6: self.conn_class = self.connection_args[3] and THTTPSConnection or \ THTTPConnection else: self.conn_class = self.connection_args[3] and HTTPSConnection or \ HTTPConnection self.http_connect() def authorization(self, url=None): """ 授权功能 @type url: str @param url: 用户接收到的共享文件的链接. url需要解析,解析出container与object 先认证授权,成功后返回连接对象,此对象所使用的make_request均为share_request """ path = [] self._share_user_uri, cont = url.rsplit('/', 1) # 临时开关,临时使用share_request self._share_request = True path.append(cont) resp = self.make_request('HEAD', path) if resp.status == 204: self._share_request = False return Connection(self.username, self.api_key, _share_request=True, _share_user_uri = self._share_user_uri) else: self._share_request = False return None def http_connect(self): """ Setup the http connection instance. """ (host, port, self.uri, is_ssl) = self.connection_args # roamin9 set the authorization conn's right uri if self._share_request: self.uri = self._share_user_uri self.connection = self.conn_class(host, port=port, \ timeout=self.timeout) self.connection.set_debuglevel(self.debuglevel) def make_request(self, method, path=[], data='', hdrs=None, parms=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, and an optional dictionary of query parameters, performs an http request. @type method: str @param method: http method @type path: list @param path: the url's path, include [container_name], [obj_name] @type hdrs: dict @param hdrs: http headers @type parms: dict @param parms: query args """ if self._share_request and self._share_user_uri: path = '/%s/%s' % \ (self._share_user_uri.rstrip('/'), '/'.join([unicode_quote(i) for i in path])) else: path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join([unicode_quote(i) for i in path])) if isinstance(parms, dict) and parms: # 查询参数中的变量是固定的,为limits等字符,都为英文字符 # 但查询参数中的值有可能是unicode值, # 因此,对于对于查询参数中的值需要进行unicode处理,使用unicode_quote() # 这应该算一个bug,可以提交给作者 query_args = \ ['%s=%s' % (unicode_quote(x), unicode_quote(y)) for (x, y) in parms.items()] path = '%s?%s' % (path, '&'.join(query_args)) headers = { # 设置了Content-Length,这样上传或下载文件时需要优化一下 'Content-Length': str(len(data)), 'User-Agent': self.user_agent, 'X-Auth-Token': self.token } isinstance(hdrs, dict) and headers.update(hdrs) def retry_request(): '''Re-connect and re-try a failed request once''' self.http_connect() self.connection.request(method, path, data, headers) return self.connection.getresponse() try: self.connection.request(method, path, data, headers) response = self.connection.getresponse() except (socket.error, IOError, HTTPException): response = retry_request() if response.status == 401: self._authenticate() headers['X-Auth-Token'] = self.token response = retry_request() return response def get_info(self): """ Return tuple for number of containers and total bytes in the account >>> connection.get_info() (5, 2309749) @rtype: tuple @return: a tuple containing the number of containers and total bytes used by the account """ response = self.make_request('HEAD') count = size = None for hdr in response.getheaders(): if hdr[0].lower() == 'x-account-container-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-account-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return (count, size) def _check_container_name(self, container_name): # container名称中不能包含'/' if not container_name or \ '/' in container_name or \ len(container_name) > consts.container_name_limit: raise InvalidContainerName(container_name) def create_container(self, container_name): """ Given a container name, returns a L{Container} item, creating a new Container if one does not already exist. >>> connection.create_container('new_container') <cloudfiles.container.Container object at 0xb77d628c> @param container_name: name of the container to create @type container_name: str @rtype: L{Container} @return: an object representing the newly created container """ self._check_container_name(container_name) response = self.make_request('PUT', [container_name]) buff = response.read() if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return Container(self, container_name) def delete_container(self, container_name): """ Given a container name, delete it. >>> connection.delete_container('old_container') @param container_name: name of the container to delete @type container_name: str """ # Container类的实例 if isinstance(container_name, Container): container_name = container_name.name self._check_container_name(container_name) response = self.make_request('DELETE', [container_name]) if (response.status == 409): raise ContainerNotEmpty(container_name) elif (response.status == 404): raise NoSuchContainer elif (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) # 一旦删除了一个container,需要标记CDN的状态为关闭 #if self.cdn_enabled: # response = self.cdn_request('POST', [container_name], # hdrs={'X-CDN-Enabled': 'False'}) def get_all_containers(self, limit=None, marker=None, **parms): """ Returns a Container item result set. >>> connection.get_all_containers() ContainerResults: 4 containers >>> print ', '.join([container.name for container in connection.get_all_containers()]) new_container, old_container, pictures, music @rtype: L{ContainerResults} @return: an iterable set of objects representing all containers on the account @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker return ContainerResults(self, self.list_containers_info(**parms)) def get_container(self, container_name): """ Return a single Container item for the given Container. >>> connection.get_container('old_container') <cloudfiles.container.Container object at 0xb77d628c> >>> container = connection.get_container('old_container') >>> container.size_used 23074 @param container_name: name of the container to create @type container_name: str @rtype: L{Container} @return: an object representing the container """ self._check_container_name(container_name) response = self.make_request('HEAD', [container_name]) count = size = None for hdr in response.getheaders(): if hdr[0].lower() == 'x-container-object-count': try: count = int(hdr[1]) except ValueError: count = 0 if hdr[0].lower() == 'x-container-bytes-used': try: size = int(hdr[1]) except ValueError: size = 0 buff = response.read() if response.status == 404: raise NoSuchContainer(container_name) if (response.status < 200) or (response.status > 299): raise ResponseError(response.status, response.reason) return Container(self, container_name, count, size) #def list_public_containers(self): # """ # Returns a list of containers that have been published to the CDN. # >>> connection.list_public_containers() # ['container1', 'container2', 'container3'] # @rtype: list(str) # @return: a list of all CDN-enabled container names as strings # """ # response = self.cdn_request('GET', ['']) # if (response.status < 200) or (response.status > 299): # buff = response.read() # raise ResponseError(response.status, response.reason) # return response.read().splitlines() def list_containers_info(self, limit=None, marker=None, **parms): """ Returns a list of Containers, including object count and size. >>> connection.list_containers_info() [{u'count': 510, u'bytes': 2081717, u'name': u'new_container'}, {u'count': 12, u'bytes': 23074, u'name': u'old_container'}, {u'count': 0, u'bytes': 0, u'name': u'container1'}, {u'count': 0, u'bytes': 0, u'name': u'container2'}, {u'count': 0, u'bytes': 0, u'name': u'container3'}, {u'count': 3, u'bytes': 2306, u'name': u'test'}] @rtype: list({"name":"...", "count":..., "bytes":...}) @return: a list of all container info as dictionaries with the keys "name", "count", and "bytes" @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker parms['format'] = 'json' response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return json_loads(response.read()) def list_containers(self, limit=None, marker=None, **parms): """ Returns a list of Containers. >>> connection.list_containers() ['new_container', 'old_container', 'container1', 'container2', 'container3', 'test'] @rtype: list(str) @return: a list of all containers names as strings @param limit: number of results to return, up to 10,000 @type limit: int @param marker: return only results whose name is greater than "marker" @type marker: str """ if limit: parms['limit'] = limit if marker: parms['marker'] = marker response = self.make_request('GET', [''], parms=parms) if (response.status < 200) or (response.status > 299): buff = response.read() raise ResponseError(response.status, response.reason) return response.read().splitlines() def __getitem__(self, key): """ Container objects can be grabbed from a connection using index syntax. >>> container = conn['old_container'] >>> container.size_used 23074 @rtype: L{Container} @return: an object representing the container """ return self.get_container(key)
class Client(Query): def __init__(self): # init Query super(Client, self).__init__() self.token = None self.server_info = None self.headers = {} self.config = Config().get_data() self.authentication = None data = 'data' in self.config.keys() and self.config['data'] or None if data: self.hostname = 'hostname' in data.keys() and \ data['hostname'] or '' self.sf_apikey = 'apikey' in data.keys() and \ data['apikey'] or '' self.username = '******' in data.keys() and \ data['username'] or '' self.password = '******' in data.keys() and \ data['password'] or '' self.impersonation_username = \ 'impersonation_username' in data.keys() and \ data['impersonation_username'] or '' self.token_life_time = 'token_life_time' in data.keys() and \ data['token_life_time'] or 0 self.handler = Handler(self.config) self.authentication = Authentication( hostname=self.hostname, sf_apikey=self.sf_apikey, username=self.username, password=self.password, impersonation_username=self.impersonation_username) def is_authenticated(self): if self.token: return True return False def get_server_info(self): ''' Server information after an API call with Home as a resource This resource should return information without extra header settings ''' return self._get_home('Home') def get_token(self, ticket_username='', resource_id='', ): ''' Get token if self.authentication is not None, which means that the configuration file is successfully parsed @param ticket_username: can be any name - ticket will be issued with this username attached @param resource_id: ID of the resource in URL string format e.g. "21a7a4520b75404dbc1be3b223c6612a1d" @param minutes_to_live: number of minutes after creation that the ticket will be valid for ''' try: self.token = self.authentication.get_token( config=self.config, ticket_username=ticket_username, resource_id=resource_id, minutes_to_live=self.token_life_time) return self.token except: self.token = None return self.token def do(self, resource='', method='GET', **kwargs): ''' Checks the availability of a access token and does the request via the resource_dispatcher to the right resource with the correct request-headers. The final goal is something like: GET /api/v1/Presentations('id1')/Presenters(id2) @param resource: Resource name as mentioned in the API documentation http://demo7.mediasite.com/mediasite/api/v1/$metadata @param **kwargs: Valid keyword arguments are properties: Properties of the resource resource_id: resource identifier link_id: resource_link identifier link: dictionary, contains resource-specific options. The resource_link itself is a dictionary (see: CatalogSettings) query_options: odata query_options, (e.g. $filter=) (http://www.odata.org/documentation) sf_apikey: string, necessary for every request in the header, comes from the application that uses this Client class ''' if self.authentication: if not self.token: # create token with Basic access self.headers = self.authentication.basic_header() else: sf_auth_ticket = self.token # authentication.get_token() self.headers = self.authentication.authorization_ticket_header( sf_auth_ticket) result = self.handler.handle(headers=self.headers, resource=resource, method=method, **kwargs) else: error_message = '' try: error_message = 'error' in self.config.keys() and \ self.config['error'] except: error_message = 'Configuration module failed' raise Exception('Authentication failed: %s' % error_message) return result
class Connection(object): """ Manages the connection to the storage system and serves as a factory for Container instances. @undocumented: http_connect @undocumented: make_request @undocumented: _check_container_name """ def __init__(self, username=None, api_key=None, timeout=10, **kwargs): """ Accepts keyword arguments for Rackspace Cloud username and api key. Optionally, you can omit these keywords and supply an Authentication object using the auth keyword. @type username: str @param username: a Rackspace Cloud username @type api_key: str @param api_key: a Rackspace Cloud API key """ self.connection_args = None self.connection = None self.token = None self.debuglevel = int(kwargs.get('debuglevel', 0)) self.user_agent = kwargs.get('useragent', consts.user_agent) self.timeout = timeout self.auth = 'auth' in kwargs and kwargs['auth'] or None if not self.auth: authurl = kwargs.get('authurl', consts.us_authurl) if username and api_key and authurl: self.auth = Authentication(username, api_key, authurl=authurl, useragent=self.user_agent) else: raise TypeError("Incorrect or invalid arguments supplied") self._authenticate() def _authenticate(self): """ Authenticate and setup this instance with the values returned. """ (url, self.token) = self.auth.authenticate() self.connection_args = parse_url(url) if version_info[0] <= 2 and version_info[1] < 6: self.conn_class = self.connection_args[3] and THTTPSConnection or \ THTTPConnection else: self.conn_class = self.connection_args[3] and HTTPSConnection or \ HTTPConnection self.http_connect() def convert_iso_datetime(self, dt): """ Convert iso8601 to datetime """ isoFormat = "%Y-%m-%dT%H:%M:%S.000+0000" if type(dt) is datetime.datetime: return dt if dt.endswith("Z"): dt = dt.split('Z')[0] isoFormat = "%Y-%m-%dT%H:%M:%S" return datetime.datetime.strptime(dt, isoFormat) def http_connect(self): """ Setup the http connection instance. """ (host, port, self.uri, is_ssl) = self.connection_args self.connection = self.conn_class(host, port=port, \ timeout=self.timeout) self.connection.set_debuglevel(self.debuglevel) def make_request(self, method, path=[], data='', hdrs=None, parms=None): """ Given a method (i.e. GET, PUT, POST, etc), a path, data, header and metadata dicts, and an optional dictionary of query parameters, performs an http request. """ query_args = "" path = '/%s/%s' % \ (self.uri.rstrip('/'), '/'.join( [unicode_quote(i) for i in path])) if isinstance(parms, dict) and parms: query_args = \ ['%s=%s' % (quote(x), quote(str(y))) for (x, y) in parms.items()] elif isinstance(parms, list) and parms: query_args = \ ["%s" % x for x in parms] path = '%s?%s' % (path, '&'.join(query_args)) headers = {'Content-Length': str(len(data)), 'User-Agent': self.user_agent, 'X-Auth-Token': self.token} isinstance(hdrs, dict) and headers.update(hdrs) def retry_request(): '''Re-connect and re-try a failed request once''' self.http_connect() self.connection.request(method, path, data, headers) return self.connection.getresponse() try: if 'PYTHON_CLOUDDNS_DEBUG' in os.environ and \ os.environ['PYTHON_CLOUDDNS_DEBUG'].strip(): import sys url = "https://%s%s\n" % \ (self.connection_args[0], path) sys.stderr.write("METHOD: %s\n" % (str(method))) sys.stderr.write("URL: %s" % (url)) sys.stderr.write("HEADERS: %s\n" % (str(headers))) sys.stderr.write("DATA: %s\n" % (str(data))) sys.stderr.write("curl -X '%s' -H 'X-Auth-Token: %s' %s %s" % \ (method, self.token, url, str(data))) self.connection.request(method, path, data, headers) response = self.connection.getresponse() except (socket.error, IOError, HTTPException): response = retry_request() if response.status == 401: self._authenticate() headers['X-Auth-Token'] = self.token response = retry_request() return response def get_domains(self): return DomainResults(self, self.list_domains_info()) def list_domains_info(self, filter_by_name=None): parms = {} if filter_by_name: parms = {'name': filter_by_name} response = self.make_request('GET', ['domains'], parms=parms) if (response.status < 200) or (response.status > 299): response.read() raise ResponseError(response.status, response.reason) read_output = response.read() return json.loads(read_output)['domains'] def get_domain(self, id=None, **dico): filter_by_name = "" if id: dico['id'] = id if 'name' in dico: dico['name'] = dico['name'].lower() filter_by_name = dico['name'] domains = self.list_domains_info(filter_by_name=filter_by_name) for domain in domains: for k in dico: if k in domain and domain[k] == dico[k]: return Domain(self, **domain) raise UnknownDomain("Not found") def get_zone(self, **dico): filter_by_name_split = dico['name'].split('.') ret = None for i in range(len(filter_by_name_split),1,-1): dico['name'] = ".".join(filter_by_name_split[-i:]) try: ret = self.get_domain(**dico) except UnknownDomain: pass if not ret: raise UnknownDomain else: return ret def get_domain_details(self, id=None): """Get details on a particular domain""" parms = { 'showRecords': 'false', 'showSubdomains': 'false' } response = self.make_request('GET', ['domains', str(id)], parms=parms) if (response.status < 200) or (response.status > 299): response.read() raise ResponseError(response.status, response.reason) read_output = response.read() domains = json.loads(read_output) return Domain(self, **domains) # Take a reponse parse it if there is asyncResponse and wait for # it (TODO: should offer to not) def wait_for_async_request(self, response): if (response.status < 200) or (response.status > 299): _output = response.read().strip() try: output = json.loads(_output) except ValueError: output = None api_reasons = "" if output and 'validationErrors' in output: for msg in output['validationErrors']['messages']: api_reasons += " (%s)" % msg raise ResponseError(response.status, response.reason+api_reasons) output = json.loads(response.read()) jobId = output['jobId'] while True: response = self.make_request('GET', ['status', jobId], parms=['showDetails=True']) if (response.status < 200) or (response.status > 299): response.read() raise ResponseError(response.status, response.reason) _output = response.read().strip() output = json.loads(_output) if output['status'] == 'COMPLETED': try: return output['response'] except KeyError: return output if output['status'] == 'ERROR': if (output['error']['code'] == 409 and output['error']['details'] == 'Domain already exists'): raise DomainAlreadyExists if (output['error']['code'] == 409 and output['error']['details'].find('belongs to another owner')): raise NotDomainOwner raise ResponseError(output['error']['code'], output['error']['details']) time.sleep(1) continue def _domain(self, name, ttl, emailAddress, comment=""): if not ttl >= 300: raise Exception("Ttl is a minimun of 300 seconds") s = '<domain name="%s" ttl="%s" emailAddress="%s" comment="%s"></domain>' return s % (name, ttl, emailAddress, comment) def create_domain(self, name, ttl, emailAddress, comment=""): domain = [name, ttl, emailAddress, comment] return self.create_domains([domain])[0] def create_domains(self, domains): xml = '<domains xmlns="http://docs.rackspacecloud.com/dns/api/v1.0">' ret = [] for dom in domains: ret.append(self._domain(*dom)) xml += "\n".join(ret) xml += "</domains>" response = self.make_request('POST', ['domains'], data=xml) output = self.wait_for_async_request(response) ret = [] for domain in output['domains']: ret.append(Domain(connection=self, **domain)) return ret def delete_domain(self, domain_id): return self.delete_domains([domain_id]) def delete_domains(self, domains_id): ret = ["id=%s" % (i) for i in domains_id] response = self.make_request('DELETE', ['domains'], parms=ret, ) return self.wait_for_async_request(response) def import_domain(self, bind_zone): """ Allows for a bind zone file to be imported in one operation. The bind_zone parameter can be a string or a file object. """ if type(bind_zone) is file: bind_zone = bind_zone.read() xml = '<domains xmlns="http://docs.rackspacecloud.com/dns/api/v1.0">' xml += '<domain contentType="BIND_9">' xml += '<contents>%s</contents>' % bind_zone xml += '</domain></domains>' response = self.make_request('POST', ['domains', 'import'], data=xml) output = self.wait_for_async_request(response) ret = [] for domain in output['domains']: ret.append(Domain(self, **domain)) return ret
def test_not_authenticated_if_password_doesnt_matches( authentication: Authentication) -> None: assert authentication.is_valid(username=EXISTING_USERNAME, password="******") is False
def test_authenticated_if_credentials_correct( authentication: Authentication) -> None: assert authentication.is_valid(username=EXISTING_USERNAME, password=CORRECT_PASSWORD) is True
def back_to_auth_screen(self): self.root.destroy() screen = Tk() from authentication import Authentication sign_up = Authentication(screen) screen.mainloop()
def test_retrieve_user_data(authentication: Authentication) -> None: user = authentication.user_data(username=EXISTING_USERNAME) assert user is not None for key in ["username", "password", "default_calendar"]: assert key in user.keys() assert user[key] is not None
def test_not_authenticated_if_username_doesnt_exists( authentication: Authentication) -> None: assert authentication.is_valid(username="******", password="******") is False
class SettingsActions: def __init__(self): self.authentication = Authentication() self.authentication.session_init() self.writer = response.getPrintWriter("text/html; charset=UTF-8") if self.authentication.is_logged_in() and self.authentication.is_admin(): self.process() else: print " * settings.py : AJAX : Unauthorised access" self.throw_error("Only administrative users can access this feature") def getWatcherFile(self): configFile = FascinatorHome.getPathFile("watcher/config.json") if configFile.exists(): return JsonConfigHelper(configFile) return None def process(self): print " * settings.py: formData=%s" % formData result = "{}" portalManager = Services.getPortalManager() portal = portalManager.get(portalId) func = formData.get("func") if func == "view-update": portal.setDescription(formData.get("view-description")) portal.setQuery(formData.get("view-query")) portal.setSearchQuery(formData.get("view-search-query")) print " *** ", formData.get("view-records-per-page") portal.setRecordsPerPage(int(formData.get("view-records-per-page"))) portal.setFacetCount(int(formData.get("view-facet-count"))) portal.setFacetSort(formData.get("view-facet-sort") is not None) portalManager.save(portal) elif func == "general-update": config = JsonConfig() email = StringUtils.trimToEmpty(formData.get("general-email")) systemEmail = StringUtils.trimToEmpty(config.get("email")) print email, systemEmail if systemEmail != email: config.set("email", formData.get("general-email"), True) config.set("configured", "true", True) config.store(NullWriter(), True) # mark restart Services.getHouseKeepingManager().requestUrgentRestart() else: print " * settings.py: email not updated: did not change" self.throw_error("Email address is the same! No change saved.") elif func == "facets-update": portal.removePath("portal/facet-fields") fields = formData.getValues("field") labels = formData.getValues("label") displays = formData.getValues("display") deletes = formData.getValues("delete") for i in range(0, len(fields)): field = fields[i] if deletes[i] == "false": portal.set("portal/facet-fields/%s/label" % field, labels[i]) portal.set("portal/facet-fields/%s/display" % field, displays[i]) portalManager.save(portal) elif func == "backup-update": pathIds = formData.get("pathIds").split(",") actives = formData.getValues("backup-active") deletes = formData.getValues("backup-delete") if actives is None: actives = [] # renditions = formData.getValues("backup-rendition") # if renditions is None: # renditions = [] queries = formData.getValues("backup-queries") if queries is None: queries = [] paths = HashMap() for pathId in pathIds: if deletes is None or pathId not in deletes: path = formData.get("%s-path" % pathId) pathName = path.replace("/", "_").replace("${user.home}", "") active = str(pathId in actives).lower() # rendition = str(pathId in renditions).lower() query = str(pathId in queries).lower() ignoreFilter = formData.get("%s-ignore" % pathId) json = HashMap() json.put("path", path) json.put("active", active) json.put("include-portal-query", query) json.put("ignoreFilter", ignoreFilter) storage = HashMap() storage.put("type", "file-system") filesystem = HashMap() filesystem.put("home", path) filesystem.put("use-link", "false") storage.put("file-system", filesystem) json.put("storage", storage) paths.put(pathName, json) # reset the path first portal.setMap("portal/backup/paths", HashMap()) portal.setMultiMap("portal/backup/paths", paths) portalManager.save(portal) elif func == "watcher-update": configFile = self.getWatcherFile() if configFile is not None: pathIds = formData.get("pathIds").split(",") actives = formData.getValues("watcher-active") if actives is None: actives = [] deletes = formData.getValues("watcher-delete") if deletes is None: deletes = [] watchDirs = HashMap() for pathId in pathIds: if pathId not in deletes: path = formData.get("%s-path" % pathId) stopped = str(pathId not in actives).lower() watchDir = HashMap() watchDir.put("ignoreFileFilter", formData.get("%s-file" % pathId)) watchDir.put("ignoreDirectories", formData.get("%s-dir" % pathId)) watchDir.put("cxtTags", []) watchDir.put("stopped", stopped) watchDirs.put(path, watchDir) json = JsonConfigHelper(self.getWatcherFile()) json.setMap("watcher/watchDirs", watchDirs) json.store(FileWriter(configFile), True) else: result = "The Watcher is not installed properly." elif func == "restore-default-config": # backup the file JsonConfig.backupSystemFile() # delete the file JsonConfig.getSystemFile().delete() # restore default JsonConfig.getSystemFile() # mark restart Services.getHouseKeepingManager().requestUrgentRestart() elif func == "housekeeping-update": config = JsonConfig() freq = StringUtils.trimToEmpty(formData.get("housekeeping-timeout")) systemFreq = StringUtils.trimToEmpty(config.get("portal/houseKeeping/config/frequency")) result = "House Keeper refreshed" if systemFreq != freq: config.set("portal/houseKeeping/config/frequency", freq, True) config.store(NullWriter(), True) result = "Frequency updated, refreshing House Keeper" # Refresh the HouseKeeper message = JsonConfigHelper() message.set("type", "refresh") Services.getHouseKeepingManager().sendMessage(message.toString()) self.writer.println(result) self.writer.close() def throw_error(self, message): response.setStatus(500) self.writer.println("Error: " + message) self.writer.close()
__author__ = 'bijan' from PIL import Image from io import BytesIO from authentication import Authentication import os GFX_URL = 'http://www.pythonchallenge.com/pc/return/evil2.gfx' auth = Authentication(GFX_URL, 'huge', 'file') gfx_read = auth.access() if not os.path.exists('/12solution'): os.makedirs('12solution') for i in range(5): image = gfx_read[i::5] image_object = Image.open(BytesIO(image)) with open("12solution/%d.%s" % (i, image_object.format.lower()), "wb") as imagefile: imagefile.write(image)
import sys, os.path sys.path.append('/home/ruijzhan/weibo_py') from authentication import Authentication Authentication.login_by_alias('qiuqiu') # Django settings for weiborss project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '*****@*****.**'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts ALLOWED_HOSTS = []