def testDeleteAuthDoesntExist(self): """ Test that we can't delete an auth that doesn't exist """ rc, msg = self.testInsertAuthSmoke() self.assertTrue(rc) auth = Auth("*****@*****.**", "Fgpmy1lEbwaNoIqZmkjBkkzOtskzYquyL11ISH5ij9iRL", "F9R51hFTGUgV0LeyJJAkwbSiZL1dfennuGDlPcUJnnNm9", "2021-01-01 01:01:01") self.dao = AuthDao() rc, deleteAuth = self.dao.deleteAuth(auth) self.assertTrue(rc) rc, deleteAuth = self.dao.deleteAuth(auth) self.assertFalse(rc) auth = Auth("*****@*****.**", "Fgpmy1lEbwaNoIqZmkjBkkzOtskzYquyL11ISH5ij9iRL", "F9R51hFTGUgV0LeyJJAkwbSiZL1dfennuGDlPcUJnnNm9", "2021-01-01 01:01:01") rc, deleteAuth = self.dao.deleteAuth(auth) self.assertFalse(rc) rc, deleteAuth = self.dao.deleteAuth(None) self.assertFalse(rc)
def confluence_user(): try: authorzation = request.headers.get('Authorization') token = authorzation.strip().split('Bearer ')[1] _auth = Auth(None) client_id = _auth.get_client_id_from_token(token) if None not in [token, client_id]: _auth = Auth(client_id) if _auth.verify_token(token) is True: person_id = _auth.decoded_token.get('person_id', 0) if person_id is not False and person_id > 0: name, email = get_lungo_person(person_id) # @TODO get real name from Lungo return json.dumps({ 'person_id': person_id, 'email': email, 'name': name }), 200 except Exception as e: app.logger.exception('Could not get Confluence User') return json.dumps({'error': 'access_denied'}), 401
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 test_generateSession(self): """This test confirms that the session object defined to customize the HTTP configuration is setup properly""" auth = Auth(username='******', token=gitlabtoken.token) #activeGitlab = auth.getActiveGitlab() session = auth.generateSession() #print(session.verify) self.assertEqual(False, session.verify)
def checkSelectedMenuRoles(self, menu, value, menuType, userName): self.app.logger.debug("loading roles: " + value + "," + menuType + "," + userName) auth = Auth(self.app) roles = [] if (menuType == "select"): for option in menu[0]["actions"][0]["options"]: if ("value" in option and value == option["value"] and "roles" in option): roles = option["roles"] elif (menuType == "button"): for button in menu[0]["actions"]: if ("name" in button and value == button["name"] and "roles" in button): roles = button["roles"] elif ("value" in button and value == button["value"] and "roles" in button): roles = button["roles"] if (len(roles) == 0): return (True) self.app.logger.debug("roles calling auth") return (auth.checkUserInRoles(userName, roles))
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 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 self.show_movies(url, page) self._variables['is_item'] = False self.render(cache=False)
def update_files(self, update_old=False): a = Auth() a.login() self.session = a.get_session() self.headers = a.get_headers() content_pages = self.get_contents() print("Content Pages") print("="*40) print(content_pages) print("") for path, course_id, content_id in content_pages: download_dir = "{}/{}".format(self.base_dir, path) print("Downloaddir: {}".format(download_dir)) if course_id == "_237247_1": self.get_ml(download_dir) continue if course_id == "_237249_1": self.get_hpc(download_dir, update_old) continue if not os.path.isdir(download_dir): os.mkdir(download_dir) endings = [".pdf", ".zip"] #endings = [] text = scraper.download_bb_page(self.session, self.headers, course_id, content_id) self.download_urls(text, endings, download_dir, update_old=update_old, url_cwd="https://www.ole.bris.ac.uk/webapps/blackboard/content/")
def add_customer(): '''Check for logged in. If GET, show the page to add a customer. If POST, do the following: 1. Get data from the POST request. 2. Also get the current user's ID. 3. Create a new Customer object with all the above data. 4. Save it to the database. 5. Redirect to the /customers/ page.''' if not is_logged_in(): return redirect(url_for('login')) if request.method == 'POST': auth = Auth() current_user = auth.get_current_user() current_user = current_user['user_id'] cust = Customer(request.form.get('first_name'), request.form.get('last_name'), request.form.get('phone'), request.form.get('email'), request.form.get('address1'), request.form.get('address2'), request.form.get('postal_code'), request.form.get('city'), request.form.get('country'), added_by=current_user) cust.save() return redirect(url_for('show_customers')) return render_template('customer/add.html')
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 add_call(customer_id): '''Check for logged in user. Check for valid customer id. Get customer object that matches the given customer id. Get the user_id of the currently logged-in user. Get the current date-time. Get the notes from the POST request. Use the above data to create a new Call object. Save it. Redirect to the /customers/<customer_id>/ page.''' if check_for_logged_in() == True: if check_for_valid_customer_id(customer_id) == True: customer_id = customer_id c = Customer.get(customer_id) auth = Auth() current_user = auth.get_current_user() user_id = current_user['user_id'] current_dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") note = request.form.get('note') call_id = None new_call = Call(current_dt, note, call_id, customer_id, user_id) new_call.save() return redirect(url_for('show_customer', customer_id=customer_id)) else: return redirect(url_for('show_customers')) else: return redirect(url_for('login'))
def testInsertAuthSmoke(self): self.dao = AuthDao() auth = Auth("*****@*****.**", "Fgpmy1lEbwaNoIqZmkjBkkzOtskzYquyL11ISH5ij9iRL", "F9R51hFTGUgV0LeyJJAkwbSiZL1dfennuGDlPcUJnnNm9", "2021-01-01 01:01:01") return self.dao.insertAuth(auth)
def cli(context, u, k): context.ensure_object(dict) username=u accessKey=k auth = Auth(username= username, token=accessKey) activeGitlab = auth.getActiveGitlab() context.obj['active_gitlab'] = activeGitlab
def __init__(self): self.initial_channels = ['stashiocat'] self.auth = Auth('auth.json') super().__init__(token=self.auth.get_irc_token(), nick=self.auth.get_user(), prefix='!', initial_channels=self.initial_channels) self.rewards = ChannelRewards() self.pubsub = PubSubHandler(self, self.auth, self.initial_channels) self.translator = MessageTranslator() sm_callbacks = SuperMetroidCallbacks( run_started=self.run_started, run_reset=self.run_reset, enter_phantoon=self.enter_phantoon, enter_moat=self.enter_moat, phantoon_fight_end=self.phantoon_fight_end, samus_dead=None, ceres_start=self.ceres_start, ceres_end=self.ceres_end, ceres_timer=self.ceres_timer, ) self.sm_manager = SuperMetroidRunManager(sm_callbacks) self.sm_games = True self.is_phan_open = False self.is_ceres_open = False self.is_ceres_timer_ready = False self.pool_executor = concurrent.futures.ThreadPoolExecutor()
def load_to_cache(self, url): if not url: return False if self.db.url_exists(url): return True self.details = ImageDetails(url) if not self.fs.exists(self.details.file_path): try: self.auth = Auth() self.cookie = self.auth.get_cookies() cook = self.mycookie if self.cookie == None else self.cookie response = xbmcup.net.http.get(url, cookies=cook, verify=False, proxies=PROXIES) if (self.cookie == None): self.mycookie = response.cookies except xbmcup.net.http.exceptions.RequestException: print(traceback.format_exc()) else: if (response.status_code == 200): file = self.fs.file(self.details.file_path, "w") file.write(response.content) file.close() self.details.get_image_info() self.db.AddCachedTexture(self.details)
def batch_info(): try: auth = Auth() service = auth.get_service(request) zone = auth.region + '-' + request.args.get('zone') param = { 'project': auth.project, 'zone': zone, 'service': service, } instance_list = list(eval(request.args.get('instances'))) batch_res = [] for instance in instance_list: try: param['instance'] = instance res = gcp_instance_func("server_get", param) batch_res.append(res) except errors.HttpError as e: msg = json.loads(e.content) batch_res.append({ 'msg': msg['error']['message'], 'code': msg['error']['code'] }) return jsonify(items=batch_res, total=len(batch_res)) except errors.HttpError as e: msg = json.loads(e.content) return jsonify(msg=msg['error']['message']), msg['error']['code']
def instances_fee(): try: from gcp import fee auth = Auth() auth.get_service(request) data = request.args.to_dict() ebs = list(eval(data['ebs'])) instance_type = data['instance_type'] os = data['os'] quantity = int(data['quantity']) total_compute = round( fee.instance_price[instance_type]['price'][ Region().get_region_name(auth.region)] * quantity, 2) total_ebs = 0 for each_ebs in ebs: total_ebs += round( fee.disk_price[each_ebs['type']][Region().get_region_name( auth.region)] * int(each_ebs['size']), 2) total = total_compute + total_ebs res = {'compute': total_compute, 'ebs': total_ebs, 'total': total} return jsonify(res) except errors.HttpError as e: msg = json.loads(e.content) return jsonify(msg=msg['error']['message']), msg['error']['code']
def __init__(self, parent=None, width=0, height=0): super(App, self).__init__(parent) self.home = Home() self.resize(width, height) # self.showMaximized() self.home.setupUi(self) try: self.auth = Auth(self.home, self) except TypeError: settings = QSettings() settings.clear() QMessageBox.warning( parent, "Error", "Your Application Data is Corrupted, Restart the application") sys.exit() self.home.manLecturerBtn.clicked.connect(self.manLecturePage) self.home.manCoursesBtn.clicked.connect(self.manCoursePage) self.home.manLectHallBtn.clicked.connect(self.manLectHallPage) self.home.manClassRepsBtn.clicked.connect(self.manClassRepPage) self.home.courseGrading.clicked.connect(self.viewGradingPage) self.home.getGrading.clicked.connect(self.getRecentGrades) self.home.chngResource.clicked.connect(self.getCumulatedGrades) self.home.levelCombo.currentIndexChanged.connect(self.loadLecturers) self.home.lecturerCombo.currentIndexChanged.connect( self.loadCourseList) self.home.cr_level.currentIndexChanged.connect(self.loadcr) self.home.cr_list.itemDoubleClicked.connect(self.update_cr) self.home.lectList.itemDoubleClicked.connect(self.update_lect) self.home.aboutButton.clicked.connect(self.dispAbout) self.home.settingBtn.clicked.connect(self.settingsPage)
def edit_customer(customer_id): '''Check for logged in user. Check for valid customer id. If GET, show the page to edit the given customer. If POST, do the following: 1. Get data from the POST request. 2. Get a Customer object from the Customer class, that matches the given customer_id. This object will contain the OLD data. 3. Set the values for the customer object - use the data you got from the POST request. 4. Save the customer object. 5. Redirect to /customers/ page.''' if not is_logged_in(): return redirect(url_for('login')) if not is_valid_customer_id(customer_id): #flash message saying no cust exists return redirect(url_for('show_customers')) if request.method == 'POST': auth = Auth() current_user = auth.get_current_user() current_user = current_user['user_id'] cust = Customer(request.form.get('first_name'), request.form.get('last_name'), request.form.get('phone'), request.form.get('email'), request.form.get('address1'), request.form.get('address2'), request.form.get('postal_code'), request.form.get('city'), request.form.get('country'), customer_id, current_user) cust.save() return redirect(url_for('show_customers')) customer = Customer.get(customer_id) print(customer.email) return render_template('customer/edit.html', customer=customer)
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/,?RT' from auth import Auth auth_instance = Auth() auth_instance.init_app(app) from routes import Manager_Router route_instance = Manager_Router() route_instance.init_app(app, auth_instance.get_auth()) from storage import Storage storage_instance = Storage() storage_instance.init_app(app) from db import Database redis_instance = Database() redis_instance.init_app(app) #init finished read_upload_file_list_to_db(redis_instance, storage_instance) return app
def post(self, url, data): try: data except: data = {} try: self.auth = Auth() self.cookie = self.auth.get_cookies() cook = self.mycookie if self.cookie == None else self.cookie response = xbmcup.net.http.post(url, data, cookies=cook, verify=False) if (self.cookie == None): self.mycookie = 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
async def handle_get_notes_list(self, request): try: data = await self._json_content(request.content) user_id = db.get_user_id(data["username"]) token = data["token"] token_expiration_date = db.get_token_expiration_date(token) except Exception as err: return web.json_response( { "status": "error", "msg": str(err) }, status=400 ) else: if Auth().verify_token(token, token_expiration_date): notes = db.get_notes_list(user_id) for note in notes: note["creation_date"] = note["creation_date"].timestamp() return web.json_response( { "status": "OK", "notes": notes }, status=200 ) else: db.remove_token(token) return web.json_response( { "status": "error", "msg": "Authorization failed" }, status=401 )
def help(): # Issues authorization code client_id = request.args.get('client_id', None) redirect_uri = request.args.get('redirect_uri', None) response_type = request.args.get('response_type', None) scope = request.args.get('scope', None) shebang = request.args.get('shebang', 0) _auth = Auth(client_id) if len(_auth._get_client()) == 0: return process_error('invalid_request') # First verify redirect_uri if not _auth.verify_redirect_uri(redirect_uri): return process_error('invalid_request') if scope is None or _auth.verify_scope(scope) is False: return process_error('invalid_scope', redirect_uri=redirect_uri, shebang=shebang) if not _auth.verify_response_type(response_type): return process_error('invalid_request', redirect_uri=redirect_uri, shebang=shebang) return render_template('help.html', client_name=_auth.client.get('name', 'Unknown'), client_scope=scope, client_id=client_id, redirect_uri=redirect_uri, response_type=response_type, shebang=shebang)
async def handle_remove_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) 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.remove_note(note_id, user_id) return web.json_response( { "status": "OK", "msg": "note removed successfully" }, status=200 ) else: db.remove_token(token) return web.json_response( { "status": "error", "msg": "Authorization failed" }, status=401 )
def get(self): if not Auth().validate_key(self.request): self.response.status = 401 return name = self.request.get("name") startDate = self.request.get("startdate") endDate = self.request.get("enddate") datePeriod = self.request.get("dateperiod") ## 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/getHistoricalData.jsp?symbol='+name+'&series=EQ&fromDate='+startDate+'&toDate='+endDate+'' ## url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol='+name+'&series=EQ&fromDate=undefined&toDate=undefined&datePeriod=3months&hiddDwnld=true' ##url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol='+name+'&series=EQ&fromDate=01-Jul-2017&toDate=13-Jul-2017' url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol='+name+'&series=EQ&fromDate='+startDate+'&toDate='+endDate+'&datePeriod='+datePeriod+'' ## http://localhost:8080/getdata?name=TCS&startdate=01-07-2016&enddate=18-07-2017&dateperiod=3months logging.info(url) try: result = urlfetch.fetch(url) logging.info(result) if result.status_code == 200: regex = '"Date".*:' pattern = re.compile(regex) data = re.findall(pattern, result.content)[0].replace(':','\n') logging.info(data) ##fieldnames = ("Date","Symbol","Series","Open Price","High Price","Low Price","Last Traded Price ","Close Price","Total Traded Quantity","Turnover (in Lakhs)") reader = csv.DictReader(io.StringIO(unicode(data))) json_data = json.dumps(list(reader)) self.response.write(json_data) 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 post(self): data = UserSignup.parser.parse_args() result = db.session.query(Invite).filter(Invite.token.like(data['token'])) for row in result: val=row.token email=row.email if User.check_encrypted_token(token,val): user=User.find_by_email(email) if user: return {'Message':'You have already registered.Please Login'} else: invite=Invite.find_by_name(email) invite.confirmed=1 invite.save_to_db() return {'User_Email':email} else: return {'message':'Invalid user'} user = User(data['User_Name'],data['First_Name'],data['Last_Name'],data['User_Email'],data['phone_no'],None) user.save_to_db() userid=User.find_by_name(data['User_Name']) password=User.encrypt_password(data['password']) auth = Auth(userid.User_id,data['User_Name'],password) """ if User.find_by_name(data['User_Name']): return {'message': "A store with name '{}' already exists.".format(data['User_Name'])}, 400 """ auth.save_to_db() cur_user=User.find_by_name(data['User_Name']) return prepare_response(cur_user.json(),201)
def checkMenuRolesBeforeLoad(self, data, slackUserName): auth = Auth(self.app) options = [] self.app.logger.debug("checkMenuRolesBeforeLoad") self.app.logger.debug(slackUserName) self.app.logger.debug(data) if (len(data) > 0 and "actions" in data[0] and "options" in data[0]["actions"][0]): for option in data[0]["actions"][0]["options"]: if ("roles" in option): dataRoles = option["roles"] for role in dataRoles: if (auth.checkUserInRole(slackUserName, role)): options.append(option) break else: options.append(option) data[0]["actions"][0]["options"] = options return (data)
def login(email, password, dbsession): if email == "" or password == "": return flask.Response(status=400) try: appname = flask.request.args["appname"][:255] appdesc = flask.request.args["appdesc"][:255] version = flask.request.args["version"][:255] except KeyError: return flask.Response(status=400) try: user = dbsession.query(User).filter_by(Email=email).one() except NoResultFound: print("acct does not exist") return flask.Response(status=401) if user.Password is None: # login disabled print("login disabled") return flask.Response(status=401) if not bcrypt.checkpw(password.encode(), user.Password.encode()): print("password incorrect") return flask.Response(status=401) auth = Auth(dbsession, flask.request.remote_addr) return auth.create_session(user, appname, appdesc, version).Token
def allow(self, password): try: auth = Auth(os.environ['NEST_CONTACT_EMAIL'], password) auth.get_token() auth.save() except Exception as e: print(e)
async def run(): try: a = Auth(os.environ['email'], os.environ['email_password']) while True: usernames = input('\nEnter a username to search: ') if usernames == '': print('Quitting.') break elif usernames == 't': showLeaderboard() else: usernames = usernames.split(',') for username in usernames: username = username.strip() if checkUsername(username): startTime = time.perf_counter() await printPlayerStats(a, username) print('Done in {:.9f}s'.format( float(time.perf_counter() - startTime))) except aiohttp.client_exceptions.ServerDisconnectedError: print( '\n {Fore.RED}[Error]{Style.RESET_ALL} An error occured while connected to the UBISOFT API, please re-run the script to try and reconnect.' ) except KeyboardInterrupt: print('\nQuitting.') exit()