I approach the folder using Shapoint API with python
The question is how can I read the file itself?
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
app_settings = {
'url': 'url',
'client_id': '',
'client_secret': '',
}
context_auth = AuthenticationContext(app_settings['url'])
context_auth.acquire_token_for_app(app_settings['client_id'], app_settings['client_secret'])
ctx = ClientContext(app_settings['url'], context_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web site title: {0}".format(web.properties['Title']))
print("Web site title: {0}".format(web.properties['Title']))
Related
I am trying to setup an event Notification system on s3 to publish notifications to SNS when a file is being uploaded to s3. Here 's how I implemented it via CDK :
import * as sns from "monocdk/aws-sns";
import * as iam from "monocdk/aws-iam";
import {
GAMMA_ACCOUNT,
PROD_ACCOUNT,
UAT1_ACCOUNT,
UAT2_ACCOUNT,
PERFECT_MILE_ACCOUNT,
} from "../utils/constants/awsAccounts";
import { Construct } from "monocdk";
import * as s3 from "monocdk/aws-s3";
import * as s3n from "monocdk/aws-s3-notifications";
import { CommonResourceStackProps, Stage } from "../stack/CommonResourcesStack";
export class S3NotificationToSNSCustomResource extends Construct {
constructor(
scope: Construct,
id: string,
bucket: s3.IBucket,
stackProps: CommonResourceStackProps
) {
super(scope, id);
const topic = new sns.Topic(this, "Topic", {
displayName: "Sherlock-s3-Event-Notifications-Topic",
topicName: "Sherlock-s3-Event-Notifications-Topic",
});
const topicPolicy = new sns.TopicPolicy(this, "TopicPolicy", {
topics: [topic],
});
const s3ServicePrincipal = new iam.ServicePrincipal("s3.amazonaws.com");
topicPolicy.document.addStatements(
new iam.PolicyStatement({
sid: "0",
actions: ["sns:Publish"],
principals: [s3ServicePrincipal],
resources: [topic.topicArn],
conditions: {
StringEquals: {
"AWS:SourceOwner":
stackProps.stage == Stage.Prod
? PROD_ACCOUNT
: stackProps.stage == Stage.Gamma
? GAMMA_ACCOUNT
: stackProps.stage == Stage.UAT1
? UAT1_ACCOUNT
: UAT2_ACCOUNT,
},
ArnLike: { "AWS:SourceArn": bucket.bucketArn },
},
}),
new iam.PolicyStatement({
sid: "1",
actions: ["sns:Subscribe"],
principals: [new iam.AccountPrincipal(PERFECT_MILE_ACCOUNT)],
resources: [topic.topicArn],
})
);
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.SnsDestination(topic),
{ prefix: "output/reportingData/openItems/", suffix: "_SUCCESS" }
);
}
}
But, when I try to deploy this, I am getting the following error : An error occurred (InvalidArgument) when calling the PutBucketNotificationConfiguration operation: Unable to validate the following destination configurations
Can anyone help me with it?
I read this post(https://aws.amazon.com/premiumsupport/knowledge-center/unable-validate-destination-s3/) but its resolution is using the templates and I am implementing using the CDK package. Also I have added all the access policies to publish and subscribe.
aws:SourceAccount and aws:SourceOwner are condition keys which are not supported by all services. Amazon S3 notifications use aws:SourceAccount Refer - https://docs.aws.amazon.com/sns/latest/dg/sns-access-policy-use-cases.html#source-account-versus-source-owner
Below is my code snippet part of google drive API integration.
var picker = new FilePicker({
apiKey: 'here_is_my_api_key',
clientId: 'here_is_my_clientid',
buttonEl: document.getElementById('<%= btnUploadPhotoGD.ClientID %>'),
onClick: function (file) {
link.title = file.title;
link.url = file.alternateLink;
linksAry.push({ "title": file.title, "url": file.alternateLink, "thumbnail": file.thumbnailLink });
document.getElementById('<%= linkJSON.ClientID %>').value = JSON.stringify(linksAry);
bindDriveTable();
}
});
I'm working with Laravel 8 + inertiajs. I can create a product with or without an image. But when I try to update a product and upload a new image, the validation looks for the required field even they're already filled.
here is my input field:
<input name="images" type="file" #input="form.images = $event.target.files[0]" />
in my vue:
props: {
product: Object,
categories: Array
},
data() {
return {
form: this.$inertia.form({
name: this.product.name,
category_id: this.product.category_id,
description: this.product.description,
date: this.product.date,
images: this.product.images
})
}
},
methods: {
update() {
this.form.put(this.route('products.update', this.product.id, {
preserveState: true
}))
},
}
})
my update controller:
public function update(UpdateProductRequest $request, Product $product)
{
$inputs = $request->validated();
if ($request->hasFile('images')) {
$filename = $request->images->getClientOriginalName();
$file = $request->images->storeAs(('images'), $filename);
$product->images = $file;
$inputs['images'] = $product->images;
}
$product->name = $inputs['name'];
$product->category_id = $inputs['category_id'];
$product->description = $inputs['description'];
$product->date = $inputs['date'];
$product->update();
session()->flash('flash.banner', 'Product Updated Successfuly');
session()->flash('flash.bannerStyle', 'success');
return redirect()->route('products.index');
}
multipart/form-data request is not natively supported in some languages for the put,patch or delete methods. The workaround here is to simply upload files using post instead.
Some frameworks, such as Laravel and Rails, support form method spoofing, which allows you to upload the files using post, but have the framework handle the request as a put or patch request. This is done by including a _method attribute in the data of your request.
Inertia.post(`/users/${user.id}`, {
_method: 'put',
avatar: form.avatar,
})
https://github.com/apache/superset/issues/13948
I am configuring Okta with Apache Superset but it's redirecting me to the login page after authentication with message 'invalid login. Please try again.'
Below is my superset_config.py file:
AUTH_TYPE = AUTH_OAUTH
OAUTH_PROVIDERS = [
{
'name': 'okta', 'icon': 'fa-circle-o',
'token_key': 'access_token',
'remote_app': {
'client_id': '0oa8hoe9t1c8LfB1z357',
'client_secret': 'b8exxJID0BQOXlvMlQa5To5frU4EY7FX3cXDOMLM',
'api_base_url': 'https://dev-514411.okta.com/oauth2/v1/',
'client_kwargs': {
'scope': 'openid profile email groups'
},
'access_token_url': 'https://dev-514411.okta.com/oauth2/v1/token',
'authorize_url': 'https://dev-514411.okta.com/oauth2/v1/authorize'
}
}
]
Okta integration was supposed to work out of the box since Flask-AppBuilder 3.2.2, but it's not the case.
Here's what worked for me:
On your Okta's app settings, the field Sign-in redirect URIs should look something like this:
http://localhost:8088/oauth-authorized/okta
Your superset_config.py should contain something similar to this:
OKTA_BASE_URL = 'https://dev-<your-okta-id>.okta.com'
AUTH_TYPE = AUTH_OAUTH
OAUTH_PROVIDERS = [
{
'name': 'okta',
'token_key': 'access_token',
'icon': 'fa-circle-o',
'remote_app': {
'client_id': OKTA_CLIENT_ID,
'client_secret': OKTA_CLIENT_SECRET,
'client_kwargs': {
'scope': 'openid profile email groups'
},
'access_token_method': 'POST',
'api_base_url': f'{OKTA_BASE_URL}/oauth2/v1/',
'access_token_url': f'{OKTA_BASE_URL}/oauth2/v1/token',
'authorize_url': f'{OKTA_BASE_URL}/oauth2/v1/authorize',
'server_metadata_url': f'{OKTA_BASE_URL}/.well-known/openid-configuration',
},
}
]
from custom_sso_security_manager import CustomSsoSecurityManager
CUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager
And finally, your custom_sso_security_manager.py, that must live on the same directory as your superset_config.py, should contain something like this:
from superset.security import SupersetSecurityManager
class CustomSsoSecurityManager(SupersetSecurityManager):
def oauth_user_info(self, provider, response=None):
if provider == 'okta':
user_info = self.appbuilder.sm.oauth_remotes[provider].parse_id_token(
response)
return {
'name': user_info['name'],
'email': user_info['email'],
'id': user_info['email'],
'username': user_info['email']
}
The important attributes on the object oauth_user_info returns are email and username, which will be used to match against your database's ab_user table records. If there isn't a matching record then the login will fail.
I got the token.But it is not possible to get data this user. which URL to get data .
token work. //simplejwt simplejwt
class CustomerRetrieveView(generics.RetrieveAPIView):
queryset = Customer.objects.all()
permission_classes=(IsAuthenticated,)
def get(self,request):
???here correct?????
queryset=Customer.objects.get(id=request.user)
serializer=CustomerSerializer(queryset)
return Response(serializer.data)
url
??here correct?????
path('customers/????<int:id>???', views.CustomerRetrieveView.as_view()),
frontend
created() {
getAPI.get('???????????/customers????????', { headers: { Authorization: `Bearer ${this.$store.state.accessToken}` } })
.then(response => {
this.$store.state.APIData = response.data
})
.catch(err => {
console.log(err)
console.log(`Bearer ${this.$store.state.accessToken}`)
})
},
models
class Customer(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=11)
likecus=models.ManyToManyField(smartphone ,verbose_name="b")
def __str__(self):
return "User: {}, phone: {}".format(self.user, self.phone)
Serializer
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = '__all__'
I got the token.But it is not possible to get data this user. which URL to get data .
token workI got the token.But it is not possible to get data this user. which URL to get data .
token workI got the token.But it is not possible to get data this user. which URL to get data .
token work
you can do this
pip install djangorestframework-jwt
settings.py
from django.conf import settings
import datetime
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_SECRET_KEY': settings.SECRET_KEY,
'JWT_GET_USER_SECRET_KEY': None,
'JWT_PUBLIC_KEY': None,
'JWT_PRIVATE_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': False,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': None,
}
urls.py
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
urlpatterns = [
path(r'^api-token-refresh/', refresh_jwt_token),
path(r'^api-token-auth/', obtain_jwt_token),
path(r'^api-token-verify/', verify_jwt_token),
]
curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/