def happening(): try: auth.authorize(request) except Exception: pass return redirect('/login') return render_template("happening.html")
def create_happening(): try: print('checking user has logged in') auth.authorize(request) except Exception: print('user attempted to post new happening when not logged in') abort(403) # create guid to use for image name when approved, and as id of firestore object image_name = str(uuid.uuid4()) url = URL + '/happenings/add/' + image_name data = request.form.to_dict(flat=True) # Default to empty image - shows No Image placeholder on site data['image'] = '' if 'image' in request.files.keys(): print('user uploaded an image, initalizing storage client') storage_client = storage.Client(project=PROJECT_NAME) bucket = storage_client.get_bucket(BUCKET) try: print('Saving image ' + image_name + '.jpg to bucket ' + BUCKET) blob = bucket.blob('{}.jpg'.format(image_name)) blob.upload_from_string( request.files["image"].read(), content_type=request.files["image"].content_type) data['image'] = 'pending' except Exception as err: # want to save the happening, even if image was not successfully saved # but do want a record of what went wrong print(str(err)) print(requests.post(url, data=data)) return redirect('/')
def happening(): logging.info('user wants to add a happening') try: auth.authorize(request) except Exception: pass return redirect('/login') return render_template("happening.html")
def test_authorize_looks_into_ldap_groups(self): import auth mock_udb = self.mock_UsersDB.return_value mock_udb.member_roles_info.return_value = [('eionet-nrc', None)] self.app.config['ROLE_NRC'] = ['ldap_group:eionet-nrc'] with self.app.test_request_context(): flask.g.username = '******' self.assertFalse(auth.authorize(['ROLE_ETC'])) self.assertTrue(auth.authorize(['ROLE_NRC']))
async def hangman(self, ctx): """Starts up a game of hangman""" authorize(ctx, "mentions") # check for a mentioned user p1 = ctx.author p2 = ctx.message.mentions[0] # first mentioned user if p1 == p2: raise UserInputError("Can't play against yourself")
def test_authorize_looks_into_ldap_groups(self): import auth mock_udb = self.mock_UsersDB.return_value mock_udb.member_roles_info.return_value = [("eionet-nrc", None)] self.app.config["ROLE_NRC"] = ["ldap_group:eionet-nrc"] with self.app.test_request_context(): flask.g.username = "******" self.assertFalse(auth.authorize(["ROLE_ETC"])) self.assertTrue(auth.authorize(["ROLE_NRC"]))
async def battleship(self, ctx): """Starts up a game of battleship.""" authorize(ctx, "mentions") # check for a mentioned user. p1 = Player.get(ctx.author.id) p2 = Player.get(ctx.message.mentions[0].id) if p1 == p2: raise UserInputError("Can't play against yourself") game = BattleShip(ctx.channel, p1, p2)
async def tictactoe(self, ctx): """Starts up a game of tic tac toe with another user""" authorize(ctx, "mentions") # check for a mentioned user p1 = Player.get(ctx.author.id) p2 = Player.get(ctx.message.mentions[0].id) if p1 == p2: raise UserInputError("You can't play against yourself") # Create new game game = TicTacToe(ctx.channel, p1, p2) # draw and send board await game.update()
def test_authorize_for_anonymous_returns_false(self): import auth self.app.config["ROLE_ETC"] = ["user_id:somebody"] with self.app.test_request_context(): self.app.preprocess_request() self.assertFalse(auth.authorize(["ROLE_ETC"]))
def init(argv, doc, parents=None, sandbox=False): """A common initialization routine for the Content API samples. Args: argv: list of string, the command-line parameters of the application. doc: string, description of the application. Usually set to __doc__. parents: list of argparse.ArgumentParser, additional command-line flags. sandbox: boolean, whether to use the sandbox API endpoint or not. Returns: A tuple of (service, config, flags), where service is the service object, config is the configuration JSON in Python form, and flags are the parsed command-line flags. """ service = None flags = None parent_parsers = [tools.argparser] if parents is not None: parent_parsers.extend(parents) parser = argparse.ArgumentParser( description=doc, formatter_class=argparse.RawDescriptionHelpFormatter, parents=parent_parsers) parser.add_argument( '--config_path', metavar='PATH', default=os.path.expanduser('~/shopping-samples'), help='configuration directory for the Shopping samples') flags = parser.parse_args(argv[1:]) if not os.path.isdir(flags.config_path): print('Configuration directory "%s" does not exist.' % flags.config_path, file=sys.stderr) sys.exit(1) content_path = os.path.join(flags.config_path, 'content') if not os.path.isdir(content_path): print('Content API configuration directory "%s" does not exist.' % content_path, file=sys.stderr) sys.exit(1) config_file = os.path.join(content_path, 'merchant-info.json') if not os.path.isfile(config_file): print('No sample configuration file found. Checked:', file=sys.stderr) print(' - %s' % config_file, file=sys.stderr) print('Please read the accompanying documentation.', file=sys.stderr) sys.exit(1) config = json.load(open(config_file, 'r')) config['path'] = content_path credentials = auth.authorize(config, flags) http = credentials.authorize(http=httplib2.Http()) service = discovery.build(_constants.SERVICE_NAME, (_constants.SANDBOX_SERVICE_VERSION if sandbox else _constants.SERVICE_VERSION), http=http) return (service, config, flags)
def delete(name): wh = get_warehouse() app = flask.current_app parcel = get_or_404(wh.get_parcel, name, _exc=KeyError) if not app.config['ALLOW_PARCEL_DELETION']: flask.abort(403) if not auth.authorize(['ROLE_ADMIN']): return flask.abort(403) if flask.request.method == 'POST': delete_parcel_and_followers(wh, parcel.name) flask.flash("Parcel %s was deleted." % name, 'system') return flask.redirect(flask.url_for('parcel.index')) else: will_remove = list(walk_parcels(wh, name)) will_not_remove = list(walk_parcels(wh, name, 'prev_parcel'))[1:] will_not_remove.reverse() return flask.render_template( 'parcel_delete.html', **{ 'parcel': parcel, 'will_remove': will_remove, 'will_not_remove': will_not_remove, })
def createQuestSeekAndAnswer(request): data = {} data['status'] = 1 if(auth.authorize(request.POST.get('facebook_id', "0a"), request.POST.get('api_key', ""))): quest = SeekAndAnswer() try: quest.title = request.POST['title'] quest.description = request.POST['description'] quest.place_name = request.POST['place_name'] quest.latitude = request.POST['latitude'] quest.longitude = request.POST['longitude'] quest.points = int(ufvquest_utils.distance_to_centro_de_vivencia(request.POST['latitude'], request.POST['longitude']) * 0.5 + 25) quest.created_on = timezone.now() quest.expiration_date = timezone.now() + datetime.timedelta(days=7) quest.diary = False quest.created_by = User.objects.get(facebook_id = request.POST['facebook_id']) quest.quest_type = QuestType.objects.get(id=2) quest.question = request.POST['question'] quest.answer = request.POST['answer'] quest.save() except Exception as e: data['status'] = 0 data['message'] = str(e) else: data['status'] = -77 data['message'] = "User not authorized" return HttpResponse(json.dumps(data), content_type="application/json")
def get(self, resource): logging.info("static " + resource) resource=str(urllib.unquote(resource)) resourcelist=resource.split("/") if(self.request.cookies.get("LoginStatus") == "LoggedIn"): user = auth.authorize(self.request.cookies.get("authKey")) else: user = auth.publicUser try: fileResult = db.GqlQuery("SELECT * " "FROM File " "WHERE ANCESTOR IS :1 AND Name = :2 " "ORDER BY Date DESC LIMIT 10", getFolder(resourcelist[0])[0],resourcelist[1])[0] if(fileResult.Restricted and user.permissions == 0): logging.info("not allowed, " + str(user.permissions)) return if(fileResult.Type == "image"): if(self.request.get("resize")=="true"): img = images.Image(blob_key=fileResult.Key) img.resize( width=int(self.request.get("width")), height=int(self.request.get("height"))) image = img.execute_transforms(output_encoding=images.PNG) self.response.headers['Content-Type'] = "image/png" self.response.out.write(image) else: self.send_blob(blobstore.BlobInfo.get(fileResult.Key)) logging.info("done") return else: blob_info = blobstore.BlobInfo.get(fileResult.Key) self.send_blob(blob_info) except IndexError: return
def executeRequest(vm_uuid, vm_name, config_path, cmd, full_vol_name, opts): """ Executes a <cmd> request issused from a VM. The request is about volume <full_volume_name> in format volume@datastore. If @datastore is omitted, the one where the VM resides is used. For VM, the function gets vm_uuid, vm_name and config_path <opts> is a json options string blindly passed to a specific operation Returns None (if all OK) or error string """ vm_datastore = get_datastore_name(config_path) error_info, tenant_uuid, tenant_name = auth.authorize(vm_uuid, vm_datastore, cmd, opts) if error_info: return err(error_info) if cmd == "list": return listVMDK(vm_datastore, tenant_name) try: vol_name, datastore = parse_vol_name(full_vol_name) except ValidationError as ex: return err(str(ex)) if not datastore: datastore = vm_datastore elif datastore not in known_datastores(): return err("Invalid datastore '%s'.\n" \ "Known datastores: %s.\n" \ "Default datastore: %s" \ % (datastore, ", ".join(known_datastores()), vm_datastore)) # get /vmfs/volumes/<volid>/dockvols path on ESX: path = get_vol_path(datastore, tenant_name) logging.debug("executeRequest %s %s", tenant_name, path) if path is None: return err("Failed to initialize volume path {0}".format(path)) vmdk_path = vmdk_utils.get_vmdk_path(path, vol_name) if cmd == "get": response = getVMDK(vmdk_path, vol_name, datastore) elif cmd == "create": response = createVMDK(vmdk_path, vm_name, vol_name, opts) # create succeed, insert infomation of this volume to volumes table if not response: if tenant_uuid: vol_size_in_MB = convert.convert_to_MB(auth.get_vol_size(opts)) auth.add_volume_to_volumes_table(tenant_uuid, datastore, vol_name, vol_size_in_MB) else: logging.warning(" VM %s does not belong to any tenant", vm_name) elif cmd == "remove": response = removeVMDK(vmdk_path) elif cmd == "attach": response = attachVMDK(vmdk_path, vm_uuid) elif cmd == "detach": response = detachVMDK(vmdk_path, vm_uuid) else: return err("Unknown command:" + cmd) return response
def run_update(username, password, filename, userEmail): now = datetime.datetime.now() #declare some variables for dataToSendBack so they can be set to (+=) and added to (++) dataToSendBack = {} dataToSendBack["assetsFailed"] = 0 #acts as "pass-by-reference" dataToSendBack["DNE"] = "" dataToSendBack["duplicate"] = "" dataToSendBack["multiple_records"] = "False" dataToSendBack["notFound"] = "False" dataToSendBack["finished"] = "False" dataToSendBack["excel"] = "" auth_value = auth.authorize(username, password, dataToSendBack, userEmail, now) if(auth_value == -1): return dataToSendBack print("auth") read_update.read_excel(filename, username, dataToSendBack, userEmail, now) if(auth_value == -1): return dataToSendBack print("excel") #to end the script, send the user an email and print info if needed by using echo in php dataToSendBack["finished"] = "True" print(dataToSendBack) sys.stdout.flush() #message = email_user.email_message(dataToSendBack) #email_user.emailsponsor(message, userEmail, now) return dataToSendBack
def authorize_for_parcel(parcel): # New delivery tab should be visible only for users that can # create a delivery( have access to the first stage) - in this case parcel # will be None stage = INITIAL_STAGE[LOT] \ if parcel is None else parcel.metadata['stage'] DELIVERY_STAGES, _ = _get_stages_for_parcel(parcel) return auth.authorize(DELIVERY_STAGES[stage]['roles'])
def __init__(self, name, extension, separator): self.extension = extension self.name = name self.separator = separator self.file = os.path.join("csv", name + "." + extension) self.client = auth.authorize() self.project = models.TrelloProject(self.name, self.client) self.csv = None
def update(self, table, features): """ Updates a feature with corresponding values. Only properties of the feature that have a value will be updated. If geometry is given, it is replaced. Args: table: The Table to use. features: String of GeoJSON features. Returns: On success an empty dictionary is returned. On error, a dictionary with error information is returned. """ if not auth.authorize("write", table): return error_message('Unauthorized', status=401) #attempt to parse geojson try: features = geojson.loads(features)['features'] except ValueError as e: return error_message("Unable to parse request data. %s" % (e)) tbl = self.initialize_table(table) primary_key = get_primary_key(tbl) if primary_key is None: return error_message('Primary key is not defined for table') index = None feature_id = None try: connection = self._engine.connect() transaction = connection.begin() for index, feature in enumerate(features): query = tbl.update() feature_id = get_feature_id(primary_key.name, feature) if feature_id is None: return error_message("No primary key", index=index) #Make sure all attributes are columns in the table try: verify_attributes(tbl.columns, feature['properties']) except ValueError as e: return error_message(e, index=index, feature_id=feature_id) query = query.where(primary_key == feature_id) del (feature['properties'][primary_key.name]) if 'geometry' in feature and feature['geometry'] is not None: feature['properties'][ self._geometry_field] = feature['geometry'] query = query.values(feature['properties']) connection.execute(query) transaction.commit() except sqlalchemy.exc.SQLAlchemyError as e: transaction.rollback() return error_message(("Database error: %s" % e), feature_id=feature_id, index=index) return []
def calc_url(client: FlaskClient, auth_token): """Request a new calculator be created.""" url = '/calculator/v0' response = authorize(client.post, url, auth_token=auth_token) assert 201 == response.status_code response_data = response.get_json() url = response_data['location'] return url
async def rock_paper_scissors(self, ctx): """Starts up a game of rock paper scissors with another user""" authorize(ctx, "mentions") # check for a mentioned user p1 = Player.get(ctx.author.id) p2 = Player.get(ctx.message.mentions[0].id) # Ensure player is someone else if p1 == p2: raise UserInputError("You can't play against yourself") # Create new game embed = discord.Embed( title="Rock Paper Scissors", description= f"{p1.name} **VS** {p2.name}\n\nCheck DMs for how to play") await ctx.send(embed=embed) game = RPS(ctx.channel, p1, p2) await game.send_dms()
def login(): if request.method == "POST": if auth.authorize(str(request.form["username"]), str(request.form["password"])): session["username"] = request.form["username"] session["password"] = request.form["password"] return redirect(url_for("index")) else: return render_template("login.html",type=1) else: return render_template("login.html")
def zodb_pack(): if not auth.authorize(['ROLE_ADMIN']): return flask.abort(403) db = connector._get_db() if flask.request.method == 'POST': db.pack(days=float(flask.request.form['days'])) return flask.redirect(flask.url_for('zodb_pack')) return flask.render_template('zodb_pack.html', db=db)
def update(self, table, features): """ Updates a feature with corresponding values. Only properties of the feature that have a value will be updated. If geometry is given, it is replaced. Args: table: The Table to use. features: String of GeoJSON features. Returns: On success an empty dictionary is returned. On error, a dictionary with error information is returned. """ if not auth.authorize("write", table): return error_message('Unauthorized', status=401) #attempt to parse geojson try: features = geojson.loads(features)['features'] except ValueError as e: return error_message("Unable to parse request data. %s" % (e)) tbl = self.initialize_table(table) primary_key = get_primary_key(tbl) if primary_key is None: return error_message('Primary key is not defined for table') index = None feature_id = None try: connection = self._engine.connect() transaction = connection.begin() for index, feature in enumerate(features): query = tbl.update() feature_id = get_feature_id(primary_key.name, feature) if feature_id is None: return error_message("No primary key", index=index) #Make sure all attributes are columns in the table try: verify_attributes(tbl.columns, feature['properties']) except ValueError as e: return error_message(e, index=index, feature_id=feature_id) query = query.where(primary_key == feature_id) del(feature['properties'][primary_key.name]) if 'geometry' in feature and feature['geometry'] is not None: feature['properties'][self._geometry_field] = feature['geometry'] query = query.values(feature['properties']) connection.execute(query) transaction.commit() except sqlalchemy.exc.SQLAlchemyError as e: transaction.rollback() return error_message(("Database error: %s" % e), feature_id=feature_id, index=index) return []
def zodb_pack(): if not auth.authorize(["ROLE_ADMIN"]): return flask.abort(403) db = connector._get_db() if flask.request.method == "POST": db.pack(days=float(flask.request.form["days"])) return flask.redirect(flask.url_for("zodb_pack")) return flask.render_template("zodb_pack.html", db=db)
def login(): nav = utils2.nav([["/","Home"],["Login"]]) if request.method == "POST": uu = auth.authorize(str(request.form["username"]), str(request.form["password"])) if uu: session["uid"] = uu session["username"] = request.form["username"] session["password"] = request.form["password"] return redirect("/?type=2") else: return render_template("login.html",type='1',nav=nav) else: return render_template("login.html",type=request.args.get("type"),nav=nav)
def delete_report(report_id): if not auth.authorize(['ROLE_ADMIN']): return flask.abort(403) wh = get_warehouse() report = get_or_404(wh.get_report, report_id, _exc=KeyError) lot_code = report.lot if flask.request.method == 'POST': file_path = safe_join(wh.reports_path, report.filename) if file_path.exists(): file_path.unlink() wh.delete_report(report_id) flask.flash('Report was deleted.', 'system') url = flask.url_for('parcel.lot', code=lot_code) return flask.redirect(url) return flask.render_template('report_delete.html', report=report)
def zodb_undo(): if not auth.authorize(["ROLE_ADMIN"]): return flask.abort(403) db = connector._get_db() if flask.request.method == "POST": undo = flask.request.form.getlist("undo") db.undoMultiple(undo) transaction.get().note("undo %d" % len(undo)) transaction.commit() flask.flash("Rolled back %d transactions" % len(undo), "system") return flask.redirect(flask.request.url) count = flask.request.args.get("count", 20, type=int) return flask.render_template("zodb_undo.html", db=db, count=count)
def zodb_undo(): if not auth.authorize(['ROLE_ADMIN']): return flask.abort(403) db = connector._get_db() if flask.request.method == 'POST': undo = flask.request.form.getlist('undo') db.undoMultiple(undo) transaction.get().note("undo %d" % len(undo)) transaction.commit() flask.flash("Rolled back %d transactions" % len(undo), 'system') return flask.redirect(flask.request.url) count = flask.request.args.get('count', 20, type=int) return flask.render_template('zodb_undo.html', db=db, count=count)
def create(self, table, features): """ Creates new records in table corresponding to the pass GeoJSON features. Args: table: The Table to use. features: String of GeoJSON features. Returns: On success an empty dictionary is returned. On error, a dictionary with error information is returned. """ if not auth.authorize("write", table): return error_message('Unauthorized', status=401) #attempt to parse geojson try: features = geojson.loads(features)['features'] except ValueError as e: return error_message("Unable to parse request data. %s" % (e)) #loads the table schema from the database tbl = self.initialize_table(table) data = [] for index, feature in enumerate(features): #Make sure all attributes are columns in the table try: verify_attributes(tbl.columns, feature['properties']) except ValueError as e: return error_message(e, index=index) properties = feature['properties'] #Add the geometry field properties[self._geometry_field] = geomet.wkt.dumps( feature['geometry']) data.append(properties) try: connection = self._engine.connect() transaction = connection.begin() connection.execute(tbl.insert(), data) transaction.commit() except sqlalchemy.exc.SQLAlchemyError as e: transaction.rollback() return error_message("Database error: %s" % e) return []
def tryQuest(request): data = {} data['status'] = 1 if auth.authorize(request.POST.get('facebook_id', "0a"), request.POST.get('api_key', "")): attempt = UserAttemptsQuest() try: attempt.user = User.objects.get(facebook_id = request.POST['facebook_id']) attempt.quest = Quest.objects.get(id = request.POST['quest_id']) attempt.timestamp = timezone.now() if request.POST['quest_type'] == "gtaa": quest = GoToAndAnswer.objects.get(quest_ptr = attempt.quest) attempt.solved = True if str(quest.correct_answer) == request.POST['answer'] else False elif request.POST['quest_type'] == "saa": quest = SeekAndAnswer.objects.get(quest_ptr = attempt.quest) attempt.solved = False for correct_answer in quest.answer.split(','): if correct_answer == request.POST['answer']: attempt.solved = True previous_attempts = UserAttemptsQuest.objects.filter(user = attempt.user, quest = attempt.quest) points_won = int(attempt.quest.points - (attempt.quest.points * 0.05 * previous_attempts.count())) attempt.points_won = points_won if points_won > 10 else 10 data['status'] = 1 if attempt.solved == True else 2 data['points_won'] = points_won attempt.save() except Exception as e: data['status'] = 0 data['message'] = str(e) else: data['status'] = -77 data['message'] = "User not authorized" return HttpResponse(json.dumps(data), content_type="application/json")
def create(self, table, features): """ Creates new records in table corresponding to the pass GeoJSON features. Args: table: The Table to use. features: String of GeoJSON features. Returns: On success an empty dictionary is returned. On error, a dictionary with error information is returned. """ if not auth.authorize("write", table): return error_message('Unauthorized', status=401) #attempt to parse geojson try: features = geojson.loads(features)['features'] except ValueError as e: return error_message("Unable to parse request data. %s" % (e)) #loads the table schema from the database tbl = self.initialize_table(table) data = [] for index, feature in enumerate(features): #Make sure all attributes are columns in the table try: verify_attributes(tbl.columns, feature['properties']) except ValueError as e: return error_message(e, index=index) properties = feature['properties'] #Add the geometry field properties[self._geometry_field] = geomet.wkt.dumps(feature['geometry']) data.append(properties) try: connection = self._engine.connect() transaction = connection.begin() connection.execute(tbl.insert(), data) transaction.commit() except sqlalchemy.exc.SQLAlchemyError as e: transaction.rollback() return error_message("Database error: %s" % e) return []
def test_auth() -> None: from server import CalculatorServer calculator = CalculatorServer() client = calculator.app.test_client() url = "auth" response = client.post(url, json={"username": "******", "password": "******"}) assert 200 == response.status_code auth_token = response.get_json()["access_token"] url = '/calculator/v0' response = authorize(client.post, url, auth_token=auth_token, json={}) assert 201 == response.status_code response_data = response.get_json() url = response_data['location'] print(url)
def delete(self, table, keys, where=None, limit=None, order_by=None): """ Deletes all features with id in list of keys Args: table: The Table to use. keys: primary keys to remove where: filter to delete matching records limit: max records to delete order_by: order of records to delete Returns: On success an empty dictionary is returned. On error, a dictionary with error information is returned. """ if not auth.authorize("write", table): return error_message('Unauthorized', status=401) if keys is not None or where is not None: tbl = self.initialize_table(table) primary_key = get_primary_key(tbl) query = tbl.delete() if where is not None: query = query.where(sqlalchemy.text(where)) if limit is not None: query = query.limit(limit) if order_by is not None: query = query.order(order_by) if keys is not None: query = query.where(primary_key.in_(keys)) try: connection = self._engine.connect() transaction = connection.begin() connection.execute(query) transaction.commit() except sqlalchemy.exc.SQLAlchemyError as e: transaction.rollback() return error_message("Database error: %s" % e) return [] else: return error_message( "Either list of keys or where statement required")
def delete(self, table, keys, where=None, limit=None, order_by=None): """ Deletes all features with id in list of keys Args: table: The Table to use. keys: primary keys to remove where: filter to delete matching records limit: max records to delete order_by: order of records to delete Returns: On success an empty dictionary is returned. On error, a dictionary with error information is returned. """ if not auth.authorize("write", table): return error_message('Unauthorized', status=401) if keys is not None or where is not None: tbl = self.initialize_table(table) primary_key = get_primary_key(tbl) query = tbl.delete() if where is not None: query = query.where(sqlalchemy.text(where)) if limit is not None: query = query.limit(limit) if order_by is not None: query = query.order(order_by) if keys is not None: query = query.where(primary_key.in_(keys)) try: connection = self._engine.connect() transaction = connection.begin() connection.execute(query) transaction.commit() except sqlalchemy.exc.SQLAlchemyError as e: transaction.rollback() return error_message("Database error: %s" % e) return [] else: return error_message("Either list of keys or where statement required")
def init(argv, doc, parents=None, sandbox=False): """A common initialization routine for the Content API samples. Args: argv: list of string, the command-line parameters of the application. doc: string, description of the application. Usually set to __doc__. parents: list of argparse.ArgumentParser, additional command-line flags. sandbox: boolean, whether to use the sandbox API endpoint or not. Returns: A tuple of (service, config, flags), where service is the service object, config is the configuration JSON in Python form, and flags are the parsed command-line flags. """ service = None flags = None parent_parsers = [tools.argparser] if parents is not None: parent_parsers.extend(parents) parser = argparse.ArgumentParser( description=doc, formatter_class=argparse.RawDescriptionHelpFormatter, parents=parent_parsers) flags = parser.parse_args(argv[1:]) if not os.path.isfile(_constants.CONFIG_FILE): print('No sample configuration file found. Checked:', file=sys.stderr) print(' - %s' % _constants.CONFIG_FILE, file=sys.stderr) print('Please read the accompanying documentation.', file=sys.stderr) sys.exit(1) config = json.load(open(_constants.CONFIG_FILE, 'r')) credentials = auth.authorize(config, flags) http = credentials.authorize(http=httplib2.Http()) service = discovery.build(_constants.SERVICE_NAME, (_constants.SANDBOX_SERVICE_VERSION if sandbox else _constants.SERVICE_VERSION), http=http) return (service, config, flags)
def getQuestHistory(request): data = {} data['status'] = 1 data['history'] = list() if(auth.authorize(request.POST.get('facebook_id', "0a"), request.POST.get('api_key', ""))): try: user = User.objects.get(facebook_id = request.POST['facebook_id']) attempts = UserAttemptsQuest.objects.filter(user=user).order_by('-timestamp') for a in attempts: data['history'].append({'solved': a.solved, 'points': a.points_won, 'timestamp': a.timestamp.isoformat(), 'quest_title': a.quest.title, 'quest_type': a.quest.quest_type.alias, 'quest_description': a.quest.description}) except Exception as e: data['status'] = 0 data['message'] = str(e) else: data['status'] = -77 data['message'] = "User not authorized" return HttpResponse(json.dumps(data), content_type="application/json")
def do_login(): username = request.form.get("username", type=str) password = request.form.get("password", type=str) cur = bean.get_db().cursor() res = cur.execute("SELECT COUNT(*) AS count FROM usergroup").fetchone() print(res["count"]) if res["count"] < 1: new_user = auth.register_usergroup(username, password) new_user.privilege = 1 try: token = auth.authorize(username, password) except Exception as e: print(e) return render_template("login.html", err=True) redirect_to_index = redirect('templates') response = current_app.make_response(redirect_to_index) response.set_cookie('auth_token', value=token) return response
def spendEnergy(request): data = {} data['status'] = 1 if(auth.authorize(request.POST.get('facebook_id', "0a"), request.POST.get('api_key', ""))): try: user = User.objects.get(facebook_id = request.POST['facebook_id']) user.energy_left = user.energy_left - 1 if (user.energy_left < 0): user.energy_left = 0 data['message'] = "You already have 0 energy" user.save() except Exception as e: data['status'] = 0 data['message'] = str(e) else: data['status'] = -77 data['message'] = "User not authorized" return HttpResponse(json.dumps(data), content_type="application/json")
def delete(name): wh = get_warehouse() app = flask.current_app parcel = get_or_404(wh.get_parcel, name, _exc=KeyError) if not app.config['ALLOW_PARCEL_DELETION']: flask.abort(403) if not auth.authorize(['ROLE_ADMIN']): return flask.abort(403) if flask.request.method == 'POST': delete_parcel_and_followers(wh, parcel.name) flask.flash("Parcel %s was deleted." % name, 'system') return flask.redirect(flask.url_for('parcel.index')) else: will_remove = list(walk_parcels(wh, name)) will_not_remove = list(walk_parcels(wh, name, forward=False))[1:] will_not_remove.reverse() return flask.render_template('parcel_delete.html', **{ 'parcel': parcel, 'will_remove': will_remove, 'will_not_remove': will_not_remove, })
def get(self, resource): logging.info("static " + resource) resource = str(urllib.unquote(resource)) resourcelist = resource.split("/") if (self.request.cookies.get("LoginStatus") == "LoggedIn"): user = auth.authorize(self.request.cookies.get("authKey")) else: user = auth.publicUser try: fileResult = db.GqlQuery( "SELECT * " "FROM File " "WHERE ANCESTOR IS :1 AND Name = :2 " "ORDER BY Date DESC LIMIT 10", getFolder(resourcelist[0])[0], resourcelist[1])[0] if (fileResult.Restricted and user.permissions == 0): logging.info("not allowed, " + str(user.permissions)) return if (fileResult.Type == "image"): if (self.request.get("resize") == "true"): img = images.Image(blob_key=fileResult.Key) img.resize(width=int(self.request.get("width")), height=int(self.request.get("height"))) image = img.execute_transforms(output_encoding=images.PNG) self.response.headers['Content-Type'] = "image/png" self.response.out.write(image) else: self.send_blob(blobstore.BlobInfo.get(fileResult.Key)) logging.info("done") return else: blob_info = blobstore.BlobInfo.get(fileResult.Key) self.send_blob(blob_info) except IndexError: return
def authorize_for_view(): if flask.g.username is None: url = flask.request.url return flask.redirect(flask.url_for('auth.login', next=url)) if not auth.authorize(ALL_ROLES): return flask.render_template('not_authorized.html')
def getQuestIStillCanComplete(request): data = {} data['status'] = 1 if(auth.authorize(request.POST.get('facebook_id', "0a"), request.POST.get('api_key', ""))): data['quests'] = list() try: user = User.objects.get(facebook_id = request.POST['facebook_id']) for model in SeekAndAnswer.objects.all(): if model.expiration_date >= timezone.now() or model.diary == True: successful_attempt = UserAttemptsQuest.objects.filter(user = user, solved = True, quest = model.quest_ptr) fail_attempts = UserAttemptsQuest.objects.filter(user = user, solved = False, quest = model.quest_ptr).order_by('-timestamp') total_successful = UserAttemptsQuest.objects.filter(solved = True, quest = model.quest_ptr).count() total_fail = UserAttemptsQuest.objects.filter(solved = False, quest = model.quest_ptr).count() total_quests = total_successful + total_fail if total_successful + total_fail > 0 else 1 tried_today = False if fail_attempts: last_fail = fail_attempts[0] if last_fail.timestamp.date() == timezone.now().date(): tried_today = True if not successful_attempt and not tried_today: data['quests'].append(model_to_dict(model)) data['quests'][-1]['type'] = "saa" points = int(model.quest_ptr.points - (model.quest_ptr.points * 0.05 * fail_attempts.count())) data['quests'][-1]['points'] = points if points > 10 else 10 data['quests'][-1]['percent_loss'] = 5 * fail_attempts.count() data['quests'][-1]['success_rate'] = (total_successful*100)/(total_quests) for model in GoToAndAnswer.objects.all(): if model.expiration_date >= timezone.now() or model.diary == True: successful_attempt = UserAttemptsQuest.objects.filter(user = user, solved = True, quest = model.quest_ptr) fail_attempts = UserAttemptsQuest.objects.filter(user = user, solved = False, quest = model.quest_ptr) total_successful = UserAttemptsQuest.objects.filter(solved = True, quest = model.quest_ptr).count() total_fail = UserAttemptsQuest.objects.filter(solved = False, quest = model.quest_ptr).count() total_quests = total_successful + total_fail if total_successful + total_fail > 0 else 1 tried_today = False if fail_attempts: last_fail = fail_attempts[0] if last_fail.timestamp.date() == timezone.now().date(): tried_today = True if not successful_attempt and not tried_today: data['quests'].append(model_to_dict(model)) data['quests'][-1]['type'] = "gtaa" points = int(model.quest_ptr.points - (model.quest_ptr.points * 0.05 * fail_attempts.count())) data['quests'][-1]['points'] = points if points > 10 else 10 data['quests'][-1]['percent_loss'] = 5 * fail_attempts.count() data['quests'][-1]['success_rate'] = (total_successful*100)/(total_quests) except Exception as e: data['status'] = -1 data['message'] = str(e) else: data['status'] = -77 data['message'] = "User not authorized" return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json")
def authorize_for_parcel(parcel): stage = INITIAL_STAGE if parcel is None else parcel.metadata['stage'] return auth.authorize(STAGES[stage]['roles'])
def test_vmdkop_authorize(self): vm_ds = 'datastore1' vms = [(self.vm_uuid, self.vm_name)] privileges = [] default_datastore='default_ds' default_privileges = {'datastore': default_datastore, 'global_visibility': 0, 'create_volume': 0, 'delete_volume': 0, 'mount_volume': 0, 'max_volume_size': 0, 'usage_quota': 0} error_info, tenant1 = self.auth_mgr.create_tenant('vmdk_auth_test', 'Tenant used to vmdk_auth_test', default_datastore, default_privileges, vms, privileges) self.assertEqual(error_info, None) self.assertTrue(uuid.UUID(tenant1.id)) # test CMD_CREATE without "create_volume" set privileges = [{'datastore': vm_ds, 'global_visibility': 0, 'create_volume': 0, 'delete_volume': 0, 'mount_volume': 1, 'max_volume_size': 500, 'usage_quota': 1000}] error_info = tenant1.set_datastore_access_privileges(self.auth_mgr.conn, privileges) self.assertEqual(error_info, None) opts={u'size': u'100MB', u'fstype': u'ext4'} error_info, tenant_uuid, tenant_name = auth.authorize(self.vm_uuid, vm_ds, auth.CMD_CREATE, opts) self.assertEqual(error_info, "No create privilege" ) # set "create_volume" privilege to true privileges = [{'datastore': vm_ds, 'global_visibility': 0, 'create_volume': 1, 'delete_volume': 0, 'mount_volume': 1, 'max_volume_size': 500, 'usage_quota': 1000}] error_info = tenant1.set_datastore_access_privileges(self.auth_mgr.conn, privileges) self.assertEqual(error_info, None) error_info, tenant_uuid, tenant_name = auth.authorize(self.vm_uuid, vm_ds, auth.CMD_CREATE, opts) self.assertEqual(error_info, None) if not error_info: error_info = auth.add_volume_to_volumes_table(tenant1.id, vm_ds, "VmdkAuthorizeTestVol1", 100) self.assertEqual(error_info, None) opts={u'size': u'600MB', u'fstype': u'ext4'} error_info, tenant_uuid, tenant_name = auth.authorize(self.vm_uuid, vm_ds, auth.CMD_CREATE, opts) # create a volume with 600MB which exceed the"max_volume_size", command should fail self.assertEqual(error_info, "volume size exceeds the max volume size limit") opts={u'size': u'500MB', u'fstype': u'ext4'} error_info, tenant_uuid, tenant_name = auth.authorize(self.vm_uuid, vm_ds, auth.CMD_CREATE, opts) self.assertEqual(error_info, None) if not error_info: error_info = auth.add_volume_to_volumes_table(tenant1.id, vm_ds, "VmdkAuthorizeTestVol2", 500) self.assertEqual(error_info, None) opts={u'size': u'500MB', u'fstype': u'ext4'} error_info, tenant_uuid, tenant_name = auth.authorize(self.vm_uuid, vm_ds, auth.CMD_CREATE, opts) self.assertEqual(error_info, "The total volume size exceeds the usage quota") # delete volume error_info, tenant_uuid, tenant_name = auth.authorize(self.vm_uuid, vm_ds, auth.CMD_REMOVE, opts) self.assertEqual(error_info, "No delete privilege") privileges = [{'datastore': vm_ds, 'global_visibility': 0, 'create_volume': 1, 'delete_volume': 1, 'mount_volume': 1, 'max_volume_size': 500, 'usage_quota': 1000}] error_info = tenant1.set_datastore_access_privileges(self.auth_mgr.conn, privileges) self.assertEqual(error_info, None) error_info, tenant_uuid, tenant_name = auth.authorize(self.vm_uuid, vm_ds, auth.CMD_REMOVE, opts) self.assertEqual(error_info, None) # remove the tenant error_info = self.auth_mgr.remove_tenant(tenant1.id, False) self.assertEqual(error_info, None) error_info = self.auth_mgr.remove_volumes_from_volume_table(tenant1.id) self.assertEqual(error_info, None)
status_code=203) except KeyError as e: return resp_fail(f"Missing parameter : {e.args[0]}") except IntegrityError as e: db.session.rollback() logger.info(f"Duplicate contact {data['name']}:{data['email']}") return resp_fail(f"Contact with same email-id already exists.", status_code=203) except Exception as e: logger.exception(e) db.session.rollback() return resp_fail("Something went wrong.", status_code=500) def delete(self, cid=None): try: contact = Contact.query.filter_by(id=cid).first() if cid and contact: db.session.delete(contact) db.session.commit() return resp_success("Contact was successfully deleted") return resp_fail("Contact not found", status_code=203) except Exception as e: logger.exception(e) db.session.rollback() return resp_fail("Something went wrong.", status_code=500) app.add_url_rule('/contact', view_func=authorize(ContactAPI.as_view('contacts'))) app.add_url_rule('/contact/<cid>', view_func=authorize(ContactAPI.as_view('contacts-detail')))
from datetime import timezone, datetime import requests from flask import render_template, Blueprint, request, jsonify, abort from requests import RequestException from auth import authorize from forms import AddPersonForm, AddFaceForm from models import Person, db from settings import FACE_RECOGNITION_SERVER from utils import format_datetime bp = Blueprint('views', __name__) recognition_api = authorize() @bp.route('/') def index(): return render_template('index.html') @bp.route('/identification', methods=['GET', 'POST']) def identification(): image = None if request.method == 'GET': image_url = request.args.get('image_url') if image_url: try: img_data = requests.get(image_url).content except RequestException: return jsonify({'error': 'invalid image URL'})
if words[x].lower() == teamAName.lower(): teamA = words[x+1] elif words[x].lower() == teamBName.lower(): teamB = words[x+1] tup = (teamA, teamB) if tup not in possible_scores.keys() and (teamA != teamAScore or teamBScore != teamBScore): possible_scores[tup] = 0 if tup in possible_scores: possible_scores[tup] += 1 verify() def printScore(): print teamAName + " " + str(teamAScore) print teamBName + " " + str(teamBScore) class StdOutListener(StreamListener): def on_status(self, status): tweet = status.text if teamAName.lower() in tweet.lower() and teamBName.lower() in tweet.lower(): processScore(tweet) return True def on_error(self, status): return True l = StdOutListener() auth = authorize() stream = tweepy.Stream(auth, l) stream.filter(track=['dawson'])
def list(self, table, select, where, limit=None, offset=None, order_by=None, intersects=None): """Send the query to the database and return the result as GeoJSON. Args: table: The Table to use. select: A comma-separated list of columns to use. Anything that is valid SQL is accepted. This value needs rigorous error checking. where: A valid SQL where statement. Also needs a lot of checking. limit: The limit the number of returned entries. offset: Result offset order_by: A valid SQL order by statement. intersects: A geometry that the result should intersect. Supports both WKT and GeoJSON Returns: A GeoJSON FeatureCollection representing the returned features, or a dict explaining the error. """ if not auth.authorize("read", table): return error_message('Unauthorized', status=401) features = [] cols = [] tbl = self.initialize_table(table) primary_key = get_primary_key(tbl) select_list = [] if select: select = select.split(",") for s in select: if s != primary_key.name and s != '': if s in tbl.c: select_list.append(sqlalchemy.sql.column(s)) else: select_list.append(sqlalchemy.sql.literal_column(s)) # Also select geometry if not already selected. select_list.append(tbl.c[self._geometry_field]) select_list.append(primary_key.name) else: for column in tbl.columns.values(): select_list.append(column) query = sqlalchemy.sql.select(select_list) if intersects: logging.debug('Exploring the intersects parameter: %s', intersects) geometry = geometry_util.parse_geometry(intersects, True) if geometry is not None: query = query.where(sqlalchemy.sql.expression.func.ST_Intersects( tbl.columns[self._geometry_field], geometry) == True) if where: where = '(%s)' % where query = query.where(sqlalchemy.text(where)) if limit: query = query.limit(limit) if order_by: query = query.order(order_by) if offset: query = query.offset(offset) # Connect and execute the query try: connection = self._engine.connect() rows = connection.execute(query) except sqlalchemy.exc.SQLAlchemyError as e: # This error should probably be made better in a production system. return error_message('Something went wrong: {}'.format(e)) # now we read the rows and generate geojson out of them. for row in rows: wkbgeom = row[self._geometry_field] props = {} result_columns = row.items() for column in result_columns: if column[1] is not None and column[0] != self._geometry_field: if isinstance(column[1], decimal.Decimal): props[column[0]] = float(column[1]) elif (isinstance(column[1], type('str')) or isinstance(column[1], type(u'unicode'))): props[column[0]] = column[1].encode('utf-8', 'ignore') else: props[column[0]] = str(column[1]) # geomet.wkb.loads returns a dict which corresponds to the geometry # We dump this as a string, and let geojson parse it geom = geojson.loads(json.dumps(geomet.wkb.loads(wkbgeom))) feature_id = props[primary_key.name] # Turn the geojson geometry into a proper GeoJSON feature feature = geojson.Feature(geometry=geom, properties=props, id=feature_id) # Add the feature to our list of features. features.append(feature) # Return the list of features as a FeatureCollection. return geojson.FeatureCollection(features)
from auth import authorize from auth import open_a_spreadsheet global gc gc, wks = authorize() wks.update_acell('B2', "Example") def insert_data_by_row(start_point, list_of_dict, sheet_key = None, key_type = None): ''' :param start_point: tuple of start point. If start from A1, then (1, 1) :param list_of_dict: :param sheet_key: :param key_type: :return: ''' if sheet_key == None: wks = open_a_spreadsheet(gc, key = "1NqMxXEBGH9VR-Y8fqJFHfMdOwSHHBjHj6oPSyPOuqGA", type = "k") else: wks = open_a_spreadsheet(gc, key = sheet_key, type = key_type) sheet_x = start_point[0] sheet_y = start_point[1] for i in range(len(list(list_of_dict))): datum = str(list(list_of_dict)[i]) wks.update_cell(sheet_x, sheet_y, datum) print ("wrote", sheet_x, sheet_y, datum) sheet_y += 1
def init(argv, doc, parents=None, sandbox=False): """A common initialization routine for the Content API samples. Args: argv: list of string, the command-line parameters of the application. doc: string, description of the application. Usually set to __doc__. parents: list of argparse.ArgumentParser, additional command-line flags. sandbox: boolean, whether to use the sandbox API endpoint or not. Returns: A tuple of (service, config, flags), where service is the service object, config is the configuration JSON in Python form, and flags are the parsed command-line flags. """ service = None sandbox_service = None flags = None parent_parsers = [tools.argparser] if parents is not None: parent_parsers.extend(parents) parser = argparse.ArgumentParser( description=doc, formatter_class=argparse.RawDescriptionHelpFormatter, parents=parent_parsers) parser.add_argument( '--config_path', metavar='PATH', default=os.path.expanduser('~/shopping-samples'), help='configuration directory for the Shopping samples') flags = parser.parse_args(argv[1:]) if not os.path.isdir(flags.config_path): print('Configuration directory "%s" does not exist.' % flags.config_path, file=sys.stderr) sys.exit(1) content_path = os.path.join(flags.config_path, 'content') if not os.path.isdir(content_path): print('Content API configuration directory "%s" does not exist.' % content_path, file=sys.stderr) sys.exit(1) config_file = os.path.join(content_path, 'merchant-info.json') if not os.path.isfile(config_file): print('No sample configuration file found. Checked:', file=sys.stderr) print(' - %s' % config_file, file=sys.stderr) print('Please read the accompanying documentation.', file=sys.stderr) sys.exit(1) config = json.load(open(config_file, 'r')) config['path'] = content_path credentials = auth.authorize(config, flags) http = credentials.authorize(http=httplib2.Http()) if _constants.ENDPOINT_ENV_VAR in os.environ: # Strip off everything after the host/port in the URL. root_url = urlparse.urljoin(os.environ[_constants.ENDPOINT_ENV_VAR], '/') print('Using non-standard root for API endpoint: %s' % root_url) discovery_url = root_url + '/discovery/v1/apis/{api}/{apiVersion}/rest' service = discovery.build(_constants.SERVICE_NAME, _constants.SERVICE_VERSION, discoveryServiceUrl=discovery_url, http=http) if sandbox: sandbox_service = discovery.build( _constants.SERVICE_NAME, _constants.SANDBOX_SERVICE_VERSION, discoveryServiceUrl=discovery_url, http=http) else: service = discovery.build(_constants.SERVICE_NAME, _constants.SERVICE_VERSION, http=http) if sandbox: sandbox_service = discovery.build( _constants.SERVICE_NAME, _constants.SANDBOX_SERVICE_VERSION, http=http) # The sandbox service object only has access to the Orders service, so # we'll need to use the regular service object for this whether sandbox # is set or not. config['isMCA'] = retrieve_mca_status(service, config) return (sandbox_service if sandbox else service, config, flags)
def authorize_for_cdr(): return auth.authorize(['ROLE_ADMIN', 'ROLE_SP'])
def authorize(): auth_error = auth.authorize(g.eb_api) if auth_error is None: return redirect('/events') else: return auth_error
continue print("Wrote list to {}".format(fname)) def get_congresspeople(auth): """Get lists of congresspeople and writes information to CSV file.""" # Authorize API api = tweepy.API(auth, wait_on_rate_limit = True, wait_on_rate_limit_notify = True) # List of all Republicans in Congress from @SenateRepublicans and # @HouseRepublicans house_reps = tweepy.Cursor(api.list_members, "HouseGOP", "house-republicans").items() senate_reps = tweepy.Cursor(api.list_members, "senategop", "senaterepublicans").items() republicans = itertools.chain(house_reps, senate_reps) write_users(republicans, "R") # List of all Democrats in Congress from @TheDemocrats house_dems = tweepy.Cursor(api.list_members, "TheDemocrats", "house-democrats").items() senate_dems = tweepy.Cursor(api.list_members, "TheDemocrats", "senate-democrats").items() democrats = itertools.chain(house_dems, senate_dems) write_users(democrats, "D") if __name__ == "__main__": auth = authorize() get_congresspeople(auth)