def upload_photos(set, photos, key, secret, checkpoint): try: auth = Auth(key, secret) auth.authenticate() except urllib2.HTTPError as e: print e.read() raise set_controller = Photosets(auth) # Work queue to print upload status ui_wq = WorkQueue(print_status, num_workers = 1) upload_and_add(photos[0], set, auth, set_controller, ui_wq, checkpoint) wq = WorkQueue(upload_and_add, num_workers = 16, max_queue_size = 50, set = set, auth = auth, set_controller = set_controller, ui_wq = ui_wq, checkpoint = checkpoint) for photo in photos[1:]: wq.add(photo) wq.done() ui_wq.done()
def __init__(self): Auth.__init__(self) self._auth_provider = 'ptc' self._session = requests.session() self._session.verify = True
def verify_token(token): if not token: token = request.args.get('token') verify = Auth().verify_token(token) g.user = verify.get('user') g.user['password'] = '' return True
def _authenticate(co, ch, remote, srp, txn): stuple = (remote[0], remote[1], '') server = tuple_to_server(stuple) auth = Auth(co, co.user, server, txn) ch.auth = auth s = ch.start_connection((remote[0], remote[1])) if srp: ch.srp_auth(s) return s hash = ch.get_hash(s) if not auth.check_hash(hash): # we don't know about the secret, fall back to SRP ch.srp_auth(s) ch.get_secret(s) s = ch.start_connection((remote[0], remote[1])) ch.secret_auth(s) auth.forget() return s
def send_url(url, reauth): """Sends a URL to the phone""" params = {'url': url, 'title': '', 'sel': '', 'type': '', 'deviceType': 'ac2dm'} auth = Auth(reauth=reauth) auth.request(baseUrl, params)
def on_accept(self): auth = Auth() if auth.doLogin(str(self.userNameLineEdit.text()), str(self.passwordLineEdit.text())): self.setResult(self.Success) else: msgBox = QMessageBox(self) msgBox.setIcon(QMessageBox.Warning) msgBox.setWindowTitle(_translate("LoginDialog", "PAT Login message", None)) msgBox.setText(_translate("LoginDialog", "Either incorrect username and/or password. Try again!", None)) msgBox.setStandardButtons(QMessageBox.Ok) msgBox.exec_() self.setResult(self.Failed)
def on_accept(self): auth = Auth() if auth.do_login(self.txtUsername.text(), self.txtPassword.text()): self.setResult(self.Success) else: msg_box = QMessageBox(self) msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle(_translate("LoginDialog", "Pythonthusiast", None)) msg_box.setText(_translate("LoginDialog", "Either incorrect username and/or password. Try again!", None)) msg_box.setStandardButtons(QMessageBox.Ok) msg_box.exec_() self.setResult(self.Failed)
def get_session_key(self, connection): ''' Queries the publisher's server and returns a session key for use in future queries. ''' # Create an Auth object to create the request to the publisher. auth = Auth() auth.config = self.config schemas = AUTH_SCHEMAS url, status, headers, body = auth.request(connection, schemas=schemas) return body['sessionKey']
def test2(self): # test a faulty login, with unknown user creds = MemoryCredentialStore() chals = MemoryChallengeStore() a = Auth(creds, chals) # client asks for challenge c = a.new_challenge() # client calculates response res = hashlib.sha1(c + "pwdhash").hexdigest() # check response v = a.validate(c, "uid", res) self.assertFalse(v)
def ajaxpost(self, url, data): try: data except: data = {} try: self.auth = Auth() self.cookie = self.auth.get_cookies() if(self.cookie != None): self.cookie.set('mycook', self.currentFingerPrint['hash']) if(self.noAuthCookie != None): try: self.noAuthCookie.set('mycook', self.currentFingerPrint['hash']) except: pass reqCookie = self.noAuthCookie if self.cookie==None else self.cookie headers = { 'Referer' : SITE_URL, 'X-Requested-With' : 'XMLHttpRequest', 'User-agent' : self.currentFingerPrint['useragent'] } response = xbmcup.net.http.post(url, data, cookies=reqCookie, headers=headers) #After saving the fingerprint, you do not need to remember cookies if(url != SITE_URL+'/film/index/imprint'): self.noAuthCookie = response.cookies except xbmcup.net.http.exceptions.RequestException: print traceback.format_exc() return None else: if(response.status_code == 200): return response.text return None
def info(inData): from auth import Auth pureData=Sensor.select(inData) stationInfo={} authInfo={} userInfo={} stationQuery=session.query(Station) authQuery=session.query(Auth) userQuery=session.query(User) for tmp in pureData['data']: t=tmp['stationId'] tmpAllStation=Station.select({'id': int(t)}) if(len(tmpAllStation['data'])==0): tmp['stationName']='not find' else: tmp['stationName']=tmpAllStation['data'][0]['name'] tmpAllAuth=Auth.select({'sensorId': int(tmp['id'])}) if(len(tmpAllAuth['data'])==0): tmp['username']='******' tmp['userId']=-1 else: tmpAllUser=User.select({'id': int(tmpAllAuth['data'][0]['userId'])}) if(len(tmpAllUser['data'])==0): tmp['username']='******' tmp['userId']=-1 else: tmp['username']=tmpAllUser['data'][0]['username'] tmp['userId']=tmpAllUser['data'][0]['id'] return pureData
def ajax(self, url): self.currentFingerPrint = self.getFingerPrint() try: self.auth = Auth() self.cookie = self.auth.get_cookies() if(self.cookie != None): self.cookie.set('mycook', self.currentFingerPrint['hash']) if(self.noAuthCookie != None): try: self.noAuthCookie.set('mycook', self.currentFingerPrint['hash']) except: pass reqCookie = self.noAuthCookie if self.cookie==None else self.cookie headers = { 'X-Requested-With' : 'XMLHttpRequest', 'Referer' : SITE_URL, 'User-agent' : self.currentFingerPrint['useragent'] } response = xbmcup.net.http.get(url, cookies=reqCookie, headers=headers) self.noAuthCookie = response.cookies except xbmcup.net.http.exceptions.RequestException: print traceback.format_exc() return None else: return response.text if response.status_code == 200 else None
def ajax(self, url, data={}, referer=False): try: self.auth = Auth() self.cookie = self.auth.get_cookies() headers = { 'X-Requested-With' : 'XMLHttpRequest' } if(referer): headers['Referer'] = referer cook = self.mycookie if self.cookie == None else self.cookie if(len(data) > 0): response = xbmcup.net.http.post(url, data, cookies=cook, headers=headers, verify=False) else: response = xbmcup.net.http.get(url, cookies=cook, headers=headers, verify=False) if(self.cookie == None): self.mycookie = response.cookies except xbmcup.net.http.exceptions.RequestException: print traceback.format_exc() return None else: return response.text if response.status_code == 200 else None
def post(self, url, data): self.currentFingerPrint = self.getFingerPrint() try: data except: data = {} try: self.auth = Auth() self.cookie = self.auth.get_cookies() reqCookie = self.noAuthCookie if self.cookie==None else self.cookie headers = { 'Referer' : url, 'User-agent' : self.currentFingerPrint['useragent'] } response = xbmcup.net.http.post(url, data, cookies=reqCookie, headers=headers) self.noAuthCookie = response.cookies except xbmcup.net.http.exceptions.RequestException: print traceback.format_exc() return None else: if(response.status_code == 200): if(self.auth.check_auth(response.text) == False): self.auth.autorize() return response.text return None
def load_members(congress): for chamber in ['house', 'senate']: resp = requests.get(Auth.times_api_route(congress, chamber)) assert resp.status_code == 200, ('bad response getting list for %s: %d' % (chamber, resp.status_code)) results = json.loads(resp.text) for member_json in results["results"][0]["members"]: member = create_new_member(congress, chamber, member_json)
def run_tests(key, secret): try: x = Auth(key, secret) x.authenticate() except urllib2.HTTPError as e: print e.read() raise filename = "/Users/riyer/Desktop/Screen Shot 2013-06-28 at 7.36.02 PM.png" f = open(filename, "rb") pic = f.read() u = Uploader("test_pic", pic, x) u.addTitle("test pic") u.setPublic() req = u.getRequest() try: handle = urllib2.urlopen(req) res = handle.read() except urllib2.HTTPError as e: print e.read() raise photo_id = u.getPhotoIdFromResponse(res) p = Photosets(x) r = p.createGetListRequest() res = execute(r, "createGetListRequest") names = p.getPhotosetList(res) r = p.createNewSetRequest("test set", "test desc", '9404583236') res = execute(r, "createNewSetRequest") set_id = p.getPhotosetIdFromResult(res) r = p.createAddPhotoRequest(photo_id, set_id) execute(r, "createAddPhotoRequest") r = p.createPhotosetDeleteRequest(set_id) execute(r, "createPhotosetDeleteRequest") photos = Photos(x) r = photos.createDeletePhotoRequest(photo_id) execute(r, "createDeletePhotoRequest")
def generate_headers(namespace, repository, access): registry_endpoints = get_endpoints() # The token generated will be invalid against a real Index behind. token = 'Token signature={0},repository="{1}/{2}",access={3}'.format( Auth.generate_token(), namespace, repository, access) return {'X-Docker-Endpoints': registry_endpoints, 'WWW-Authenticate': token, 'X-Docker-Token': token}
def test1(self): # test a proper login creds = MemoryCredentialStore() creds.add("uid", "pwdhash") chals = MemoryChallengeStore() a = Auth(creds, chals) # client asks for challenge c = a.new_challenge() # client calculates response res = hashlib.sha1(c + "pwdhash").hexdigest() # check response v = a.validate(c, "uid", res) self.assertTrue(v)
def test5(self): # test a faulty login, with invalid resopnse creds = MemoryCredentialStore() creds.add("uid", "pwdhash") chals = MemoryChallengeStore() a = Auth(creds, chals) # client asks for challenge c = a.new_challenge() # client calculates response res = hashlib.sha1(c + "pwdhash" + "this is wrong").hexdigest() # check response v = a.validate(c, "uid", res) self.assertFalse(v)
def get_post_users(): if flask.request.method == 'GET': return toolkit.response('OK', 200) try: data = json.loads(flask.request.data) if Auth.signin(data): return toolkit.response('OK', 200) else: cfg = config.load() if not cfg.allow_signup: return toolkit.api_error('Signup is not allowed', 400) else: if Auth.signup(data): return toolkit.response('User Created', 201) else: return toolkit.response('User Not Created', 400) except json.JSONDecodeError: return toolkit.api_error('Error Decoding JSON', 400)
def __init__(self,conf,log,db): self.conf=conf self.log=log self.db=db self.global_cfg=GlobalConfig(self.conf,self.log,self.db) self.proxy_mgr=ProxyMgr(self.conf,self.log,self.db) self.trans_proxy_mgr=TransparentProxyMgr(self.conf,self.log,self.db) self.nginx_mgr=NginxManager(self.conf,self.log, self.db,self.global_cfg, self.proxy_mgr,self.trans_proxy_mgr) self.token_mgr=TokenMgr(self.conf,self.log,self.db) self.user_mgr=UserMgr(self.conf,self.log,self.db) self.auth=Auth(self.conf,self.log,self.token_mgr,self.user_mgr,self.proxy_mgr) self.app=Flask(__name__) self.app.add_url_rule(self.conf.url_prefix+'/trans_proxy', 'add_trans_proxy', self._add_trans_proxy, methods=['POST']) self.app.add_url_rule(self.conf.url_prefix+'/trans_proxy/<string:location>', 'del_trans_proxy', self._del_trans_proxy, methods=['DELETE']) self.app.add_url_rule(self.conf.url_prefix+'/trans_proxy_sync', 'trans_proxy_sync', self._sync_trans_proxy, methods=['POST']) self.app.add_url_rule(self.conf.url_prefix+'/basic_auth', 'basic_auth', self._basic_auth, methods=['GET','POST']) self.app.add_url_rule(self.conf.url_prefix+'/token_auth', 'token_auth', self._token_auth, methods=['GET']) self.app.add_url_rule(self.conf.url_prefix+'/global-config', 'global_config', self._global_config, methods=['POST']) self.app.add_url_rule(self.conf.url_prefix+'/token', 'add_token', self._add_token, methods=['POST']) self.app.add_url_rule(self.conf.url_prefix+'/sync', "sync", self._sync, methods=['POST']) self.app.add_url_rule(self.conf.url_prefix+'/', 'add_proxy_config', self._add_proxy_config, methods=['POST']) self.app.add_url_rule(self.conf.url_prefix+'/<string:uri_prefix>', 'del_proxy_config', self._del_proxy_config, methods=['DELETE'])
def __init__(self): self.__config = Config('config.ini') server = self.__config.get_server() domain = self.__config.get_domain() username = self.__config.get_username() password = self.__config.get_password() self.__network_name = self.__config.get_internal_network() auth = Auth(server, 5000, username, password, domain) auth_token = auth.get_auth_token() tenant_id = auth.get_tenant_id() self.__nova = Nova(server, 8774, auth_token, tenant_id) self.__glance = Glance(server, 9292, auth_token) self.__network = Network(server, 9696, auth_token) self.__key_pair = self.__config.get_key_pair() self.__user_vm = self.__config.get_user_vm()
def test3(self): # test a faulty login, with expired challenge creds = MemoryCredentialStore() creds.add("uid", "pwdhash") chals = MemoryChallengeStore() a = Auth(creds, chals, challenge_ttl=1) # client asks for challenge c = a.new_challenge() time.sleep(a.challenge_ttl.seconds) # client calculates response res = hashlib.sha1(c + "pwdhash").hexdigest() # check response v = a.validate(c, "uid", res) self.assertFalse(v)
def ajax(self, url): try: self.auth = Auth() self.cookie = self.auth.get_cookies() headers = {"X-Requested-With": "XMLHttpRequest", "Referer": SITE_URL} response = xbmcup.net.http.get(url, cookies=self.cookie, headers=headers) print url except xbmcup.net.http.exceptions.RequestException: print traceback.format_exc() return None else: return response.text if response.status_code == 200 else None
def deleteUser(inData): ''' :param inData: :return: {1:'success', 2:'no user', 3:'permission denied', 4:'failed'} ''' from auth import Auth if(('updateId' in inData) and ('delId' in inData)): updateUserLevel = session.query(User.level).filter(User.id == inData['updateId'], User.valid == 1).first() if(updateUserLevel == None or int(updateUserLevel[0]) != 0): return 3 else: chgUser = session.query(User).filter(User.id == inData['delId'], User.valid == 1).first() if(chgUser == None): return 2 else: session.query(User).filter(User.id == inData['delId']).update({'valid':0, 'time':datetime.now()}) session.commit() Auth.delAuth({'UserId':inData['delId']}) return 1 else: return 4
def test6(self): # test a faulty login, re-using challenge creds = MemoryCredentialStore() creds.add("uid", "pwdhash") chals = MemoryChallengeStore() a = Auth(creds, chals) # client asks for challenge c = a.new_challenge() # client calculates response res = hashlib.sha1(c + "pwdhash").hexdigest() # check response v = a.validate(c, "uid", res) self.assertTrue(v) # try to use it again v = a.validate(c, "uid", res) self.assertFalse(v)
def delSensor(inData): ''' :param: inData :return: {1:'success', 2:'permission denied', 3:'no sensor', 4:'wrong param', 5:''} ''' from auth import Auth from eqp import Eqp if(('UserId' in inData) and ('SensorId' in inData)): updateUser = session.query(Auth).filter(Auth.userId == inData['UserId'], Auth.sensorId == inData['SensorId'], Auth.valid == 1).first() if(updateUser == None): updateUserLevel = session.query(User.level).filter(User.id == inData['UserId'], User.valid == 1).first() if(updateUserLevel == None or int(updateUserLevel[0]) != 0): return 2 tmpSensor = session.query(Sensor).filter(Sensor.id == inData['SensorId'], Sensor.valid == 1).first() if(tmpSensor == None): return 3 session.query(Sensor).filter(Sensor.id == inData['SensorId'], Sensor.valid == 1).update({'valid':0, 'time':datetime.now()}) Auth.delAuth({'SensorId':inData['SensorId']}) Eqp.delEqp({'SensorId':inData['SensorId']}) session.commit() return 1 else: return 4
def load(self, url): try: self.auth = Auth() self.cookie = self.auth.get_cookies() response = xbmcup.net.http.get(url, cookies=self.cookie) except xbmcup.net.http.exceptions.RequestException: print traceback.format_exc() return None else: if(response.status_code == 200): if(self.auth.check_auth(response.text) == False): self.auth.autorize() return response.text return None
def shutdown(): """ Shutdown the instance where this method is called. Returns: True if there are no errors. """ try: auth = Auth() instance = _get(_INSTANCE + "hostname").split(".")[0] zone = _get(_INSTANCE + "zone").split("/")[-1] project = _get(_PROJECT + "project-id") logging.info("Instance %s will be shut down.", instance) sp = discovery.build("compute", "v1") req = sp.instances().delete(project=project, zone=zone, instance=instance) # pylint: disable=no-member req.headers["Authorization"] = auth.header_str() req.execute() return True except urllib2.URLError as e: LOGGER.warning("Shutdown was interrupted. (%s)", e) return False
def ajax(self, url, data={}): try: self.auth = Auth() self.cookie = self.auth.get_cookies() headers = { 'X-Requested-With' : 'XMLHttpRequest' } if(len(data) > 0): response = xbmcup.net.http.post(url, data, cookies=self.cookie, headers=headers) else: response = xbmcup.net.http.get(url, cookies=self.cookie, headers=headers) except xbmcup.net.http.exceptions.RequestException: print traceback.format_exc() return None else: return response.text if response.status_code == 200 else None
def get(self): parser = reqparse.RequestParser() parser.add_argument('username', location='headers') parser.add_argument('password', location='headers') params = parser.parse_args() if params['username'] is None or params['password'] is None: response = jsonify({"error": "no username and/or password"}) response.status_code = 400 return response if Auth.check(params['username'], params['password']) == False: response = jsonify({"error": "user unauthorized"}) response.status_code = 401 return response c.cursor.execute( "select EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, Country, HomePhone, Extension, Notes from employees" ) records = c.cursor.fetchall() rows = len(records) result = { 'count': rows, 'employees': [{ 'EmployeeID': id, 'LastName': lname, 'FirstName': fname, 'Title': title, 'TitleOfCourtesy': toc, 'BirthDate': str(bdate), 'HireDate': str(hdate), 'Address': address, 'City': city, 'Region': region, 'PostalCode': pcode, 'Country': country, 'HomePhone': hphone, 'Extension': extension, 'Notes': notes } for (id, lname, fname, title, toc, bdate, hdate, address, city, region, pcode, country, hphone, extension, notes) in records] } return result
def add_recipe(): if request.method == 'GET': return render_template('add_recipe.html') title = request.form.get('title', None) description = request.form.get('description') image = request.form.get('image', None) ingredients = request.form.get('ingredients', None) user_id = Auth().get_current_user()['user_id'] recipe_manager = Recipes() recipe_manager.add_recipe( { 'title': title, 'description': description, 'image': image, 'ingredients': ingredients }, user_id) return redirect(url_for('show_recipes'))
def elasticsearch_client(conf): """ returns an Elasticsearch instance configured using an es_conn_config """ es_conn_conf = build_es_conn_config(conf) auth = Auth() es_conn_conf['http_auth'] = auth(host=es_conn_conf['es_host'], username=es_conn_conf['es_username'], password=es_conn_conf['es_password'], aws_region=es_conn_conf['aws_region'], boto_profile=es_conn_conf['boto_profile']) return Elasticsearch(host=es_conn_conf['es_host'], port=es_conn_conf['es_port'], url_prefix=es_conn_conf['es_url_prefix'], use_ssl=es_conn_conf['use_ssl'], verify_certs=es_conn_conf['verify_certs'], connection_class=RequestsHttpConnection, http_auth=es_conn_conf['http_auth'], timeout=es_conn_conf['es_conn_timeout'], send_get_body_as=es_conn_conf['send_get_body_as'])
def handle(self): Auth().autorize() self.item(xbmcup.app.lang[30112], self.link('search'), folder=True, cover=cover.search) self.item(xbmcup.app.lang[30120], self.link('filter', {'window': ''}), folder=True, cover=cover.treetv) self.item(xbmcup.app.lang[30146], self.link('bookmarks', {'url': ''}), folder=True, cover=cover.treetv) self.item(xbmcup.app.lang[30160], self.link('null', {}), folder=True, cover=cover.treetv) self.item(' - ' + xbmcup.app.lang[30114], self.link('list', {'dir': 'films'}), folder=True, cover=cover.treetv) self.item(' - ' + xbmcup.app.lang[30115], self.link('list', {'dir': 'serialy'}), folder=True, cover=cover.treetv) self.item(' - ' + xbmcup.app.lang[30116], self.link('list', {'dir': 'multfilmy'}), folder=True, cover=cover.treetv) self.item(' - ' + xbmcup.app.lang[30117], self.link('list', {'dir': 'multserialy'}), folder=True, cover=cover.treetv) if (xbmcup.app.setting['hide_donate'] == 'false'): self.item(xbmcup.app.lang[37000], self.link('donate', {'hide': '1'}), folder=True, cover=cover.treetv)
def handle(self): Auth().autorize() try: params = self.argv[0] except: params = {} try: url = params['url'] except: url = '' try: page = params['page'] except: page = 0 if (xbmcup.app.setting['is_logged'] == 'false'): xbmcup.gui.message(xbmcup.app.lang[30149].encode('utf-8')) return False if url == '': collectionsInfo = self.get_collections_info() if collectionsInfo == []: self.item(u'[COLOR red][' + xbmcup.app.lang[30174] + '][/COLOR]', self.link('null'), folder=False, cover=cover.info) else: for collectionInfo in collectionsInfo: self.item(collectionInfo['title'], self.link('collections', {'url': collectionInfo['url']}), folder=True, cover=collectionInfo['img']) else: self.show_movies(url, page) self._variables['is_item'] = False self.render(cache=False)
def parseLegacyURI(self, uristring, requestors): """Parses previous CUPS Cloud Print URIs, only used for upgrades Args: uristring: string, uri of the Cloud Print device Returns: string: account name string: google cloud print printer name string: google cloud print printer id int: format id """ formatId = None printerName = None accountName = None printerId = None uri = urlparse(uristring) pathparts = uri.path.strip('/').split('/') if uri.scheme == Utils.OLD_PROTOCOL_NAME: if len(pathparts) == 2: formatId = PrinterManager.URIFormat20140307 printerId = urllib.unquote(pathparts[1]) accountName = urllib.unquote(pathparts[0]) printerName = urllib.unquote(uri.netloc) else: if urllib.unquote( uri.netloc) not in Auth.GetAccountNames(requestors): formatId = PrinterManager.URIFormat20140210 printerName = urllib.unquote(uri.netloc) accountName = urllib.unquote(pathparts[0]) else: formatId = PrinterManager.URIFormat20140308 printerId = urllib.unquote(pathparts[0]) printerName = None accountName = urllib.unquote(uri.netloc) elif uri.scheme == Utils.PROTOCOL_NAME: formatId = PrinterManager.URIFormatLatest printerId = urllib.unquote(pathparts[0]) printerName = None accountName = urllib.unquote(uri.netloc) return accountName, printerName, printerId, formatId
def testUpdateAuth(self): """ Test that we can update an Auth. """ rc, msg = self.testInsertAuthSmoke() self.assertTrue(rc) newAuth = Auth("*****@*****.**", "Fcpmy1lEbwaNoIqZmkjBkkzOtskzYquyL11ISH5ij9iRL", "F9R51hFTGUgV0LeyJJAkwbSiZL1dfennuGDlPcUJnnNm9", "2021-01-01 01:01:01") self.dao = AuthDao() rc = self.dao.updateAuth(newAuth) self.assertTrue(rc) rc, updat = self.dao.selectByEmail(newAuth.user) self.assertTrue(rc) self.assertEqual(newAuth.auth_token, updat.auth_token)
def test_setupAuthOwnership(): assert Auth.SetupAuth(False) == (False, False) # ensure ownership is correct after creating config assert Utils.GetLPID() == os.stat(Auth.config).st_gid # add dummy details storage = multistore_file.get_credential_storage( Auth.config, Auth.clientid, 'testuseraccount', ['https://www.googleapis.com/auth/cloudprint']) credentials = client.OAuth2Credentials('test', Auth.clientid, 'testsecret', 'testtoken', 1, 'https://www.googleapis.com/auth/cloudprint', 'testaccount1') storage.put(credentials) # ensure ownership is correct after populating config assert Utils.GetLPID() == os.stat(Auth.config).st_gid
def user(): token = request.get_json(force=True).get('access_token', None) _auth = Auth(None) client_id = _auth.get_client_id_from_token(token) if None not in [token, client_id]: _auth = Auth(client_id) person_id = _auth.get_user_id(token) if person_id is not False and person_id > 0: return json.dumps({ 'person_id': person_id, }), 200 return json.dumps({'error': 'access_denied'}), 401
def is_auth_user_ok(request): # type: (object) -> object headers = request.headers try: if 'Authorization' in headers: token = headers["Authorization"] else: raise ValueError except ValueError: return -1 payload = Auth.decode_auth_token(token) try: if 'data' in payload and AuthConstant.token_id in payload['data']: user_id = payload['data'][AuthConstant.token_id] else: raise ValueError except ValueError: return -1 return user_id
async def handle_modify_note(self, request): try: data = await self._json_content(request.content) note_id = data["note_id"] user_id = db.get_user_id(data["username"]) token = data["token"] token_expiration_date = db.get_token_expiration_date(token) title = data["title"] content = data["content"] except Exception as err: return web.json_response( { "status": "error", "msg": str(err) }, status=400 ) else: if Auth().verify_token(token, token_expiration_date): db.modify_note(note_id, user_id, title, content) note = db.get_note(note_id, user_id) note["creation_date"] = note["creation_date"].timestamp() return web.json_response( { "status": "OK", "msg": "Note modified successfully", "note": note }, status=200 ) else: db.remove_token(token) return web.json_response( { "status": "error", "msg": "Authorization failed" }, status=401 )
def main(): #Authentication setup auth = Auth() auth.setAccessToken(TOKEN) token = auth.getAccessToken() # init and clear db db = Database() # db.clearDB() subreddits = ["wallstreetbets", "pennystocks", "stocks"] headers = auth.getHeaders() for sub in subreddits: stock_list = scrape(sub, 100, headers) db.insert(stock_list)
async def handle_register(self, request): try: data = await self._json_content(request.content) username = data["username"] password = Auth().generate_hash(data["password"]) db.register(username, password) except Exception as err: return web.json_response( { "status": "error", "msg": str(err) }, status=400 ) else: return web.json_response( { "status": "OK", "msg": "Account created successfully" }, status=200 )
def validate_credentials(): body = request.get_json() if body is None: abort(400) user = User(body) # the result is a user on success # this will delete the token from ram # (as posted user is not used and db user doesn't store token) result = Connector.validate_hash(user) if result is None: abort(403) elif result == -1: abort(404) elif isinstance(result, User): # generate jwt token return Auth.gen_token(result), 200 else: abort(422)
def apply(): """ 加密并使用appkey: """ # 用户名字 并设置默认值 name = request.args.get('name', 'alex') params = request.args.get('params', 'hello') data = db.user_key.find_one({'name': name}) # 如果没有该用户的keyinfo,就创建并插入 if not bool(data): data = initUserKey(name) access_key = data['access_key'] secret_key = data['secret_key'] # @todo # 请求参数 去重,排序 # 构造请求参数 request_data = { 'params': params, } token = Auth.genToken(access_key, secret_key, request_data) # 构造调用请求 headers = { 'Authorization': token, } host = 'http://localhost/' url = host + 'cgi' resp = requests.post(url, request_data, headers=headers) text = resp.text return text
def handle(self): Auth().autorize() try: params = self.argv[0] except: params = {} try: url = params['url'] except: url = '' try: page = params['page'] except: page = 1 try: params['keyboard'] except: params['keyboard'] = False if (params['keyboard']): self.add_dir() return False if (url == ''): if (xbmcup.app.setting['is_logged'] == 'false'): xbmcup.gui.message(xbmcup.app.lang[30149].encode('utf-8')) return False self.show_dirs() self._variables['is_item'] = False self.render(cache=False) else: self.show_movies(url, page) self._variables['is_item'] = False self.render(cache=False)
def get(self): if not Auth().validate_key(self.request): self.response.status = 401 return name = self.request.get("name") ## url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxGetQuoteJSON.jsp?symbol='+name.replace(" ", "%20")+'&series=EQ' url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol='+name.replace(" ", "%20")+'&illiquid=0&smeFlag=0&itpFlag=0' logging.info(url) try: result = urlfetch.fetch(url) logging.info(result) if result.status_code == 200: regex = '{"futLink".*' pattern = re.compile(regex) data = re.findall(pattern, result.content) jsonData = json.loads(data[0]) logging.info(jsonData) self.response.write(json.dumps(jsonData['data'][0])) else: self.response.status_code = result.status_code except urlfetch.Error: logging.exception('Caught exception fetching url') self.response.headers['Content-Type'] = 'application/json'
def login(self, user): if (self.conn.is_connected()): cursor = self.conn.cursor() token = None try: cursor.execute( 'SELECT * FROM users WHERE email="{}" AND password="******"'. format(user['email'], user['password'])) resultado = cursor.fetchall() if (len(resultado) == 1): token = Auth().criarToken(resultado[0]) success, message = True, 'usuário logado' else: success, message = False, 'credenciais inválidas' except Error as e: success, message = False, str(e) else: success, message = False, 'sem conexão com db' cursor.close() self.conn.close() return {'success': success, 'message': message, 'token': token}
def add_customer(): if not is_logged_in(): return redirect(url_for('login')) if request.method == 'GET': return render_template('customer/add.html') else: first_name = request.form.get('first_name') last_name = request.form.get('last_name') phone = request.form.get('phone') email = request.form.get('email') address1 = request.form.get('address1') address2 = request.form.get('address2') postal_code = request.form.get('postal_code') city = request.form.get('city') country = request.form.get('country') user = Auth().get_current_user() added_by = user['user_id'] customer = Customer(first_name, last_name, phone, email, address1, address2, postal_code, city, country, None, added_by) customer.save() return redirect(url_for('show_customers'))
def get(self): if not Auth().validate_key(self.request): self.response.status = 401 return name = self.request.get("name") url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxCompanySearch.jsp?search='+name.replace(" ", "%20") logging.info(url) try: result = urlfetch.fetch(url) logging.info(result) if result.status_code == 200: # regex = "itpFlag=0(.*?)<span class='symbol'" regex = "(symbol=.*?&illiquid).*?(itpFlag=0'>.*?<span)" pattern = re.compile(regex) companies = {} for (x,y) in re.findall(pattern, result.content): companies[x[7:][:-9]] = y[11:].replace('<b >','').replace('</b>','')[:-5] ## names.append(name[6:].replace('<b >','').replace('</b>','')) self.response.write(json.dumps(companies)) else: self.response.status_code = result.status_code except urlfetch.Error: logging.exception('Caught exception fetching url') self.response.headers['Content-Type'] = 'application/json'
async def handle_create_note(self, request): try: data = await self._json_content(request.content) title = data["title"] content = data["content"] user_id = db.get_user_id(data["username"]) token = data["token"] except Exception as err: return web.json_response( { "status": "error", "msg": str(err) }, status=400 ) else: creation_date = datetime.now() token_expiration_date = db.get_token_expiration_date(token) if Auth().verify_token(token, token_expiration_date): db.create_note(title, creation_date, user_id, content) return web.json_response( { "status": "ok", "msg": "note created successful" }, status=200 ) else: return web.json_response( { "status": "error", "msg": "Authorization failed" }, status=401 )
def main(): args = parseArgs() port = args.port Auth().loadAuth() TunnelMgr().init() print 'begin to listen port %d' % (port) application = tornado.web.Application([ (r'/tunnel', TunnelHandler), (r'/agent/client', ClientAgentHandler), (r'/agent/remote', RemoteAgentHandler), ]) application.listen(port) def onTunnelCheck(): TunnelMgr().check() IOLoop.instance().add_timeout(int(time.time()) + 30, onTunnelCheck) IOLoop.instance().add_timeout(int(time.time()) + 30, onTunnelCheck) IOLoop.instance().start()
def create_app(): app = Flask(__name__, static_folder=config.App.STATIC_FOLDER, template_folder=config.App.TEMPLATE_FOLDER) app.config.from_object(config) CORS(app) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RR' from auth import Auth auth_instance = Auth() auth_instance.init_app(app) #init router from routers import JudgeClient_Router, WebClient_Router route_instance = JudgeClient_Router() route_instance.init_app(app, auth_instance.get_auth()) route_instance = WebClient_Router() route_instance.init_app(app, auth_instance.get_auth()) from db import Database redis_instance = Database() redis_instance.init_app(app) #redis_instance._put_problem_id_into_unsolved_queue('1000') #redis_instance._put_problem_id_into_unsolved_queue('1001') #for i in range(5): # output = redis_instance.get_problem() # print(output) ''' from storage import Storage storage_instance = Storage() storage_instance.init_app(app) #从gunicorn获得loglevel等级,并将其设置到app中 gunicorn_logger = logging.getLogger("gunicorn.error") app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) ''' #if logger.getEffectiveLevel()==logging.DEBUG: # logger.critical("The app is in debug mode, the merge process will execute slowly !") return app
def sign_up(): if request.method == 'GET': return render_template('sign-up.html') username = request.form.get('username', None) password = request.form.get('password', None) password2 = request.form.get('password2', None) auth = Auth() error = None if auth.has_user(username): error = 'There is already a user with that name' elif password != password2: error = 'Passwords must match' if error: flash(error) return redirect(url_for('sign_up')) auth.create_user(username, password) auth.login(username, password) return redirect(url_for('show_recipes'))
#!/usr/bin/env python3 """ a basic Flask app. """ from flask import Flask, jsonify, request, abort, make_response, redirect from auth import Auth AUTH = Auth() app = Flask(__name__) @app.route('/', methods=['GET']) def welcome(): """ returns a message when the route / is requested """ return jsonify({"message": "Bienvenue"}) @app.route('/users', methods=['POST']) def users(): """ registers a new user """ email = request.form.get('email') password = request.form.get('password') try: user = AUTH.register_user(email, password) return jsonify({"email": email, "message": "user created"}) except ValueError: return jsonify({"message": "email already registered"}) @app.route('/sessions', methods=['POST']) def sessions(): """ create a new session for the user, store it the session ID as a cookie with key "session_id" on the response
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. if __name__ == '__main__': # pragma: no cover import sys from auth import Auth from printermanager import PrinterManager from ccputils import Utils Utils.SetupLogging() # line below is replaced on commit CCPVersion = "20140501 203545" Utils.ShowVersion(CCPVersion) requestors, storage = Auth.SetupAuth(True) printer_manager = PrinterManager(requestors) printers = printer_manager.getPrinters() if printers is None: print "No Printers Found" sys.exit(1) for printer in printers: print printer.getListDescription()
def revoke(self): try: auth = Auth(os.environ['NEST_CONTACT_EMAIL'], None) auth.save() except Exception as e: print(e)
import os import glob from auth import Auth auth = Auth() drive = auth.connect_drive() filepath = #folder that contains the files need to be uploaded folder_id = #<folder id> query = {'q':f"'{folder_id}' in parents and trashed=false"} def main(): drive_files = list() drive_content = drive.ListFile(query).GetList() for content in drive_content: drive_files.append(content['title']) os.chdir(filepath) for file in glob.glob("*.pdf"): if (file not in drive_files): file_creds = {'title': file,'mimeType':'application/pdf','parents':[{"id": f"{folder_id}"}]} file_drive = drive.CreateFile(file_creds) file_drive.Upload() print (f"The file: {file} has been uploaded") if __name__ == "__main__": main()
def logout(): auth = Auth() auth.logout() return redirect(url_for('login'))
def main(): parser = argparse.ArgumentParser() parser.add_argument('--host', default=os.environ.get('ES_HOST', None), help='Elasticsearch host') parser.add_argument('--port', default=os.environ.get('ES_PORT', None), type=int, help='Elasticsearch port') parser.add_argument('--username', default=os.environ.get('ES_USERNAME', None), help='Elasticsearch username') parser.add_argument('--password', default=os.environ.get('ES_PASSWORD', None), help='Elasticsearch password') parser.add_argument('--url-prefix', help='Elasticsearch URL prefix') parser.add_argument('--no-auth', action='store_const', const=True, help='Suppress prompt for basic auth') parser.add_argument('--ssl', action='store_true', default=env('ES_USE_SSL', None), help='Use TLS') parser.add_argument('--no-ssl', dest='ssl', action='store_false', help='Do not use TLS') parser.add_argument('--verify-certs', action='store_true', default=None, help='Verify TLS certificates') parser.add_argument('--no-verify-certs', dest='verify_certs', action='store_false', help='Do not verify TLS certificates') parser.add_argument('--index', help='Index name to create') parser.add_argument('--old-index', help='Old index name to copy') parser.add_argument('--send_get_body_as', default='GET', help='Method for querying Elasticsearch - POST, GET or source') parser.add_argument( '--boto-profile', default=None, dest='profile', help='DEPRECATED: (use --profile) Boto profile to use for signing requests') parser.add_argument( '--profile', default=None, help='AWS profile to use for signing requests. Optionally use the AWS_DEFAULT_PROFILE environment variable') parser.add_argument( '--aws-region', default=None, help='AWS Region to use for signing requests. Optionally use the AWS_DEFAULT_REGION environment variable') parser.add_argument('--timeout', default=60, help='Elasticsearch request timeout') parser.add_argument('--config', default='config.yaml', help='Global config file (default: config.yaml)') parser.add_argument('--recreate', type=bool, default=False, help='Force re-creation of the index (this will cause data loss).') args = parser.parse_args() if os.path.isfile('config.yaml'): filename = 'config.yaml' elif os.path.isfile(args.config): filename = args.config else: filename = '' if filename: with open(filename) as config_file: data = yaml.load(config_file) host = args.host if args.host else data.get('es_host') port = args.port if args.port else data.get('es_port') username = args.username if args.username else data.get('es_username') password = args.password if args.password else data.get('es_password') url_prefix = args.url_prefix if args.url_prefix is not None else data.get('es_url_prefix', '') use_ssl = args.ssl if args.ssl is not None else data.get('use_ssl') verify_certs = args.verify_certs if args.verify_certs is not None else data.get('verify_certs') is not False aws_region = data.get('aws_region', None) send_get_body_as = data.get('send_get_body_as', 'GET') ca_certs = data.get('ca_certs') client_cert = data.get('client_cert') client_key = data.get('client_key') index = args.index if args.index is not None else data.get('writeback_index') old_index = args.old_index if args.old_index is not None else None else: username = args.username if args.username else None password = args.password if args.password else None aws_region = args.aws_region host = args.host if args.host else raw_input('Enter Elasticsearch host: ') port = args.port if args.port else int(raw_input('Enter Elasticsearch port: ')) use_ssl = (args.ssl if args.ssl is not None else raw_input('Use SSL? t/f: ').lower() in ('t', 'true')) if use_ssl: verify_certs = (args.verify_certs if args.verify_certs is not None else raw_input('Verify TLS certificates? t/f: ').lower() not in ('f', 'false')) else: verify_certs = True if args.no_auth is None and username is None: username = raw_input('Enter optional basic-auth username (or leave blank): ') password = getpass.getpass('Enter optional basic-auth password (or leave blank): ') url_prefix = (args.url_prefix if args.url_prefix is not None else raw_input('Enter optional Elasticsearch URL prefix (prepends a string to the URL of every request): ')) send_get_body_as = args.send_get_body_as ca_certs = None client_cert = None client_key = None index = args.index if args.index is not None else raw_input('New index name? (Default elastalert_status) ') if not index: index = 'elastalert_status' old_index = (args.old_index if args.old_index is not None else raw_input('Name of existing index to copy? (Default None) ')) timeout = args.timeout auth = Auth() http_auth = auth(host=host, username=username, password=password, aws_region=aws_region, profile_name=args.profile) es = Elasticsearch( host=host, port=port, timeout=timeout, use_ssl=use_ssl, verify_certs=verify_certs, connection_class=RequestsHttpConnection, http_auth=http_auth, url_prefix=url_prefix, send_get_body_as=send_get_body_as, client_cert=client_cert, ca_certs=ca_certs, client_key=client_key) esversion = es.info()["version"]["number"] print("Elastic Version:" + esversion.split(".")[0]) elasticversion = int(esversion.split(".")[0]) if(elasticversion > 5): mapping = {'type': 'keyword'} else: mapping = {'index': 'not_analyzed', 'type': 'string'} print("Mapping used for string:" + str(mapping)) silence_mapping = { 'silence': { 'properties': { 'rule_name': mapping, 'until': { 'type': 'date', 'format': 'dateOptionalTime', }, '@timestamp': { 'type': 'date', 'format': 'dateOptionalTime', }, }, }, } ess_mapping = { 'elastalert_status': { 'properties': { 'rule_name': mapping, '@timestamp': { 'type': 'date', 'format': 'dateOptionalTime', }, }, }, } es_mapping = { 'elastalert': { 'properties': { 'rule_name': mapping, '@timestamp': { 'type': 'date', 'format': 'dateOptionalTime', }, 'alert_time': { 'type': 'date', 'format': 'dateOptionalTime', }, 'match_time': { 'type': 'date', 'format': 'dateOptionalTime', }, 'match_body': { 'type': 'object', 'enabled': False, }, 'aggregate_id': mapping, }, }, } past_mapping = { 'past_elastalert': { 'properties': { 'rule_name': mapping, 'match_body': { 'type': 'object', 'enabled': False, }, '@timestamp': { 'type': 'date', 'format': 'dateOptionalTime', }, 'aggregate_id': mapping, }, }, } error_mapping = { 'elastalert_error': { 'properties': { 'data': { 'type': 'object', 'enabled': False, }, '@timestamp': { 'type': 'date', 'format': 'dateOptionalTime', }, }, }, } es_index = IndicesClient(es) if not args.recreate: if es_index.exists(index): print('Index ' + index + ' already exists. Skipping index creation.') return None # (Re-)Create indices. if (elasticversion > 5): index_names = ( index, index + '_status', index + '_silence', index + '_error', index + '_past', ) else: index_names = ( index, ) for index_name in index_names: if es_index.exists(index_name): print('Deleting index ' + index_name + '.') try: es_index.delete(index_name) except NotFoundError: # Why does this ever occur?? It shouldn't. But it does. pass es_index.create(index_name) # To avoid a race condition. TODO: replace this with a real check time.sleep(2) if(elasticversion > 5): es.indices.put_mapping(index=index, doc_type='elastalert', body=es_mapping) es.indices.put_mapping(index=index + '_status', doc_type='elastalert_status', body=ess_mapping) es.indices.put_mapping(index=index + '_silence', doc_type='silence', body=silence_mapping) es.indices.put_mapping(index=index + '_error', doc_type='elastalert_error', body=error_mapping) es.indices.put_mapping(index=index + '_past', doc_type='past_elastalert', body=past_mapping) print('New index %s created' % index) else: es.indices.put_mapping(index=index, doc_type='elastalert', body=es_mapping) es.indices.put_mapping(index=index, doc_type='elastalert_status', body=ess_mapping) es.indices.put_mapping(index=index, doc_type='silence', body=silence_mapping) es.indices.put_mapping(index=index, doc_type='elastalert_error', body=error_mapping) es.indices.put_mapping(index=index, doc_type='past_elastalert', body=past_mapping) print('New index %s created' % index) if old_index: print("Copying all data from old index '{0}' to new index '{1}'".format(old_index, index)) # Use the defaults for chunk_size, scroll, scan_kwargs, and bulk_kwargs elasticsearch.helpers.reindex(es, old_index, index) print('Done!')