Null values in address, county, state and city keys - alexa

LOG:
2018-03-06T16:45:22.452Z c24b7465-215d-11e8-aefd-bfbf7ac6d9a8
{
addressLine1: null,
addressLine2: null,
addressLine3: null,
districtOrCounty: null,
stateOrRegion: null,
city: null,
countryCode: 'US',
postalCode: '63101'
}
Permission was granted through the companion app,
I got a valid consent Token, apiEndpoint and deviceId
Token: eyJ0eXAiOiJKV1QiLCJhXXX
Api Endpoint: https://api.amazonalexa.com
Device ID: amzn1.ask.device.AETPMACRXXX
My Code:
const token = event.context.System.apiAccessToken
const apiEndpoint = event.context.System.apiEndpoint
const deviceId = event.context.System.device.deviceId
console.log(
`Token: ${token} \n
Api Endpoint: ${apiEndpoint}
Device ID: ${deviceId}`)
const deviceAddressService = new Alexa.services.DeviceAddressService()
const fullAddress = deviceAddressService.getFullAddress(deviceId,apiEndpoint,token).then(data => {
resolve(data)
})
.catch(err => {
reject(err.message)
})
})
Permission in Developer Portal enabled
I only get the postal and country code... any ideas?

The reason why I got only the postal code and country had nothing to do with the code or any settings in the developer portal but with the echo dot itself. In my alexa app under my echo dot the address given only contained the postal code and country

Related

Google Registration, jwt staying logged in

I just added a feature to be able to register with Google. For security reasons I added a field in the db that is false if the user is registered the usal way(Username & PW) and true if he is registered with google.
class CustomUser(AbstractUser):
objects = UserManager()
REQUIRED_FIELDS = []
USERNAME_FIELD = 'email'
username = models.CharField(max_length=40, unique=False,null=True, blank=True)
email = models.EmailField(_('email address'), unique=True)
profile_image = models.ImageField(null=True,blank=True,default = "users.png",upload_to='',)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False)
telephone = models.CharField(blank=True, max_length=20, null=True)
email_is_verified = models.BooleanField(default = False, null=False, blank = False)
currentVerificationToken = models.CharField(max_length = 6, default="000000")
withGoogleRegistered = models.BooleanField(default = False)
def __str__(self):
return self.email
So if you try to login the usal way but the email adress is bounded to an google registered account, you wont be able to. If you try to login with a usal way bounded email adress, but its connected to a google bounded account , you wont be able to. So, I made this in order to seperate betweena accounts with a password and accounts without a password... But there is a little problem now. In Order to obtain an refresh token (JWT) I have to give a username and a password, otherwise I wont be able to get one in the first place...
function fetchToken() {
if (user && !Object.hasOwn(user, "fromBackend")) {
fetch("http://127.0.0.1:8000/token/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: user.email,
password: user.password,
}),
})
.then((response) => response.json())
.then((data) => {
if (data.access) {
setRemoveTokens(data);
updateUser();
}
});
} else if (localStorage.getItem("refreshToken-allkids") != null) {
getNewTokens();
updateUser();
}
For this I am using rest_framework_simplejw
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("user/", include("User.urls")),
path("token/", TokenObtainPairView.as_view(), name="obtain_token"),
path("token/refresh/", TokenRefreshView.as_view(), name="refresh_token"),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So that beeing said, lets move on to the question: how can I obtain a refresh token for Google registered Accounts without having a Password?
Here is the way I create a google registered account:
#api_view(["POST"])
def googleRegistrationOrLogin(request):
body = request.body.decode('utf-8')
token = json.loads(body)
CLIENT_ID = "591603096190-1fv6asqdpmm6td8t66as5temri420j8b.apps.googleusercontent.com"
try:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
except:
print("Failure")
return Response("Failure")
try:
user = CustomUser.objects.get(email = idinfo["email"])
if user.withGoogleRegistered:
login(request, user)
user = CustomUserLoggedSerializer(user, many = False)
return Response(user.data)
else:
return Response("Email already in use, please create an account the usal way.")
except:
randomEmailToken = random.randrange(100000,999999)
try:
user = CustomUser.objects.create(username = idinfo["name"],profile_image = idinfo["picture"],withGoogleRegistered = True,password="GoogleRegistered", email = idinfo["email"],currentVerificationToken=randomEmailToken, email_is_verified = True if idinfo["email_verified"] else False)
except:
return Response("Fatal Error")
user = CustomUserLoggedSerializer(user, many = False)
return Response(user.data)
I know its currently not clean, but fair enough for now.

How to insert data in child table from react to django rest framework models

I'm new to React and Django rest framework. I want to insert profile data into the Django model using fetch API in react. I'm continuously getting response header as:
{"user":["Incorrect type. Expected pk value, received str."]}
I've checked by printing response on console, and it gives status code '200 OK'. But it didn't update the database as well.
My submit form function in react is:
const handleSubmit = (e) => {
e.preventDefault();
const profile = profileObj(selectedProfileImg, contact, city, country, address);
localStorage.setItem('profile', JSON.stringify(profile))
let form_data = new FormData()
// *************************
// this is the foreign key in the model and it gives the problem.
// *************************
form_data.append('user',JSON.parse(localStorage.getItem('data')).id) // (foriegn key value) User added by signing up
form_data.append('profile_img', profile.prof_img)
form_data.append('contact',profile.contact)
form_data.append('city',profile.city)
form_data.append('country',profile.country)
form_data.append('address',profile.address)
form_data.append('store_title','storename') // (foriegn key value) Data with this key exists in database
form_data.append('cus_status',profile.cus_status)
// *********************************
// Also I want to know what the boundary means in content
// type. As I see it on google so I used it but removing it
// gives another boundary error.
// *********************************
fetch('http://localhost:8000/customer_apis/addCustomer/', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
},
body: form_data
})
.then(res => {
console.log(res)
console.log(res.status)
if (res.status !== 200)
document.getElementById('text-error').innerHTML = res.statusText
else {
navigate('/create_store')
}
})
}
My Django model is:
class CustomerData(models.Model):
CUS_STATUS=(
('A','Active'),
('B','Blocked'),
('X','Blacklist')
)
# I imported the user as (from django.contrib.auth.models import User)
user=models.ForeignKey(User, on_delete=models.CASCADE)
store_title=models.ForeignKey(StoreData, on_delete=models.CASCADE, null=True, default='')
city=models.CharField(max_length=50, default="")
country=models.CharField(max_length=50, default="")
address=models.CharField(max_length=200, default="")
phone=models.IntegerField(default=00)
profile_img=models.ImageField(upload_to=user_directory_path, blank=True,null=True)
cus_status=models.CharField(max_length=20,choices=CUS_STATUS, default='A')
def __str__(self):
return str(self.store_title)
And Django API view is:
#api_view(['POST','GET'])
def addCustomer(request):
serializer = CustomerSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response("Success")
else:
return Response(serializer.errors)
CustomerSerializer is:
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = CustomerData
fields='__all__'
How could I add data to the child table having foreign keys from React Apis to Django rest Framework?
Any help will be really appreciated.
I think you need to use some other field for uploading user and store_title data.
class CustomerSerializer(serializers.ModelSerializer):
user_id = serializers.IntegerField(write_only = True)
store_title_id = serializers.IntegerField(write_only = True)
user = UserSerializer(read_only = True)
store_title = StoreTitleSerializer(read_only = True)
class Meta:
model = CustomerData
fields=("user", "store_title", "city", "country", "address", "phone", "profile_img", "cus_status", "user_id", "store_title_id", )
And in frontend, you can upload user_id and store_title_id as the integer value.
const handleSubmit = (e) => {
...
form_data.append('user_id', parseInt(JSON.parse(localStorage.getItem('data')).id, 10))
...
form_data.append('store_title_id', 1) # for example
...

"'Image' object is not callable" when posting API object

Update 2, 13th Jan: After doing some bug searching and trying to post the object directly in the root API using json, I've come to the realisation that the image is what's giving me the posting error.
I used the HTML form to post an object and it gave me this error:
TypeError at /rats/
'Image' object is not callable
For context, I uploaded an image. Here are my serialisers for creating the object (rat) and for images:
class ImageSerializer(FlexFieldsModelSerializer):
image = VersatileImageFieldSerializer(
sizes='rat_headshot'
)
class Meta:
model = Image
fields = ['name', 'image']
class RatSerializer(FlexFieldsModelSerializer):
user = serializers.CharField(source='user.username', required=False)
userid = serializers.CharField(source='user.id', required=False)
body_colour = BodyColourSerializer()
eye_colour = EyeColourSerializer()
image = ImageSerializer(required=False)
class Meta:
model = rat
exclude = ['bio']
def create(self, data):
request = self.context.get("request")
print("I was here", data, request)
return rat.objects.create(
name = data["name"],
body_colour = BodyColour(name=data["body_colour"]["name"]),
eye_colour = EyeColour(name=data["eye_colour"]["name"]),
# bio = data["bio"],
image = Image(name=data["image"]["name"])(required=False),
user = request.user,
)
I've updated the title. Original title was "Can't manage to post an object via axios to django - possibly due to AnonymousUser object?", now it's " "'Image' object is not callable" when posting API object "
Update 8th Jan: I fixed the AnonymousUser error. Django wanted an ID but was instead getting the user class, I fixed it by changing user = request.user into user = request.user.id
However, I'm still unable to post the object. I'm getting the same res.data error as below. So now I'm not sure what's causing the error.
I'm trying to add a button in React which posts an object to django via axios when a user clicks on it. However, it seems like something's wrong backend.
Here's the button:
<button
id="add-rat"
type="button"
className="btn homeButton"
onClick={
(e) => submit(e)
}
>
Add rat
</button>
And here's the axios, in the same page:
const submit = (e) => {
const name = "namee";
const eyeColour = "Red";
const bodyColour = "White";
const bio = "hfff";
const image = "lineart.PNG";
const data = {
name: name,
eye_colour: eyeColour,
body_colour: bodyColour,
bio: bio,
image: image,
};
e.preventDefault();
console.log(data);
const token = localStorage.getItem("token");
axios
.post("http://127.0.0.1:8000/api/addObject", data, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => console.log(err));
};
This is my console output:
{name: 'namee',
eye_colour: 'Red', body_colour: 'White', bio: 'hfff', image: 'lineart.PNG'}
myRats.js:86 {res: 'Error Accured'}
(myRats.js:86 btw, is console.log(res.data); )
Here's my view for the object:
class AddRat(APIView):
def post(self,request):
data = request.data
user = request.user
print(data)
try:
user = rat( name = data['name'] , body_colour = data['bodyColour'] , eye_colour = data['eyeColour'],user= user, bio = data['bio'] , image = data['image'])
user.save()
return Response({'res':"Rat Saved Successfully"})
except:
return Response({'res':"Error Accured"})
def get(self,request):
user = request.user
data = rat.objects.filter(user = user)
data = RatSerializer(data, many = True)
return Response({'data':data.data})
When I go to the url it's posting to, I get this error:
TypeError at /api/addObject
Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x0000014641FD85B0>.
Could it possibly be due to that? What could be wrong?
The Anonymous User issue was solved by changing user = request.user into user = request.user.id
And my second issue, "'Image' object is not callable" was due to me putting (required=False) in another set of parenthesis, as if I was calling an Image as a function.
So I changed
image = Image(name=data["image"]["name"])(required=False)
into
image = Image(name=data["image"]["name"], required=False)

How do I retrieve the 'id' of an entry/row from an 'item' in the entry/row?

Building an app using React Native (for iOS) using AWS Amplify
I want to do something seemingly so simple, but i am a bit lost as to how to do it: I have a table with user information already in it. Here's the Schema:
type Users #model {
id: ID!
userName: String
firstname: String
weblink: String
email: String
mobileNum: String
.
.
.
}
//**Here's my current Query.js**
export const getUsers = `query GetUsers($id: ID!) {
getUsers(id: $id) {
id
userName
firstname
weblink
email
.
.
.
}
}
`;
This table is populated in DynamoDB when i check my AWS console. What i need is to be able to get the id from the table using the userName (not vice versa). The id is generated when i createUser() and it's used throughout my app to get all my user's information. However when a user signs in on a new phone, this id isn't available anymore. So when they sign in via Cognito, i do know the userName and all i need to do is retrieve this id. Because there's only one unique userName, it should only return one id
Here's what i'm thinking so far: use a GSI (global secondary index). So change my schema to:
type Users #model
#key(
name: "ByUsername"
fields: ["userName"]
queryField: "getIdFromUserName"
)
{
id: ID!
userName: String
firstname: String
weblink: String
email: String
mobileNum: String
.
.
.
}
Then call in my app:
const data = await API.graphql(graphqlOperation(getIdFromUserName, { userName }));
5 questions:
1) Is there a simpler way than GSI?
2) Is that how you add the GSI? Or is it more robust to do it in the AWS console?
3) What should my Query.js then look like?
4) Do i need to make a custom resolver, or is this sufficient?
5) Am i missing anything else, or can i just
amplify push ?
//11/04/2020
//Resolver
## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $util.time.nowISO8601())))
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601())))
$util.qr($context.args.input.put("__typename", "Users"))
#set( $condition = {
"expression": "attribute_not_exists(#id)",
"expressionNames": {
"#id": "id"
}
} )
#if( $context.args.condition )
#set( $condition.expressionValues = {} )
#set( $conditionFilterExpressions = $util.parseJson($util.transform.toDynamoDBConditionExpression($context.args.condition)) )
$util.qr($condition.put("expression", "($condition.expression) AND $conditionFilterExpressions.expression"))
$util.qr($condition.expressionNames.putAll($conditionFilterExpressions.expressionNames))
$util.qr($condition.expressionValues.putAll($conditionFilterExpressions.expressionValues))
#end
#if( $condition.expressionValues && $condition.expressionValues.size() == 0 )
#set( $condition = {
"expression": $condition.expression,
"expressionNames": $condition.expressionNames
} )
#end
{
"version": "2017-02-28",
"operation": "PutItem",
"key": #if( $modelObjectKey ) $util.toJson($modelObjectKey) #else {
"id": $util.dynamodb.toDynamoDBJson($util.defaultIfNullOrBlank($ctx.args.input.id, $util.autoId()))
} #end,
"attributeValues": $util.dynamodb.toMapValuesJson($context.args.input),
"condition": $util.toJson($condition)
}
## [End] Prepare DynamoDB PutItem Request. **
1) You dont need to create GSI (global secondary index).
2) You can update your createUser resolver, instead of using $util.autoId() you can pass $ctx.args.input.userName as id

How I can create user with REST_API wordpress?

I need create user on Wordpress. I use WP_REST_API - this is default API for WP. You can look at it "YOU_SITE/wp-json/"
I have ionic3 project and have function.
onSubmit(values){
this.http.post(Config.WORDPRESS_URL + 'wp-json/jwt-auth/v1/token',{
username: 'admin',
password: 'pass'
})
.subscribe(
res => {
let token = res.json().token;
let header : Headers = new Headers();
header.append('Authorization','Basic ' + token);
this.http.post(Config.WORDPRESS_REST_API_URL + 'users?token=' + res.json().token,{
username: values.username,
name: values.displayName,
email: values.email,
password: values.password,
},header)
.subscribe(
result => {
console.log(result.json());
},
error => {
console.log(error.json());
}
)
},
err => {
console.log(err);
}
)
}
But I always get error:
code: "rest_cannot_create_user",
message: "Sorry, but you can't create new user"
status: 401
admin:pass - this is admin on site and has a role admin.
Also I added to .htaccess
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
Please help me to find a mistake
I found my issue and solution. I delete param TOKEN from URL and
create options header
let header = new Headers({"Authorization": "Bearer "+token});
let options = new RequestOptions({headers: header});
I have next request
this.http.post(Config.REGISTER, {
username: username,
name: displayName,
email: email,
password: password,
nonce: nonce
}, options)
it is work for me.

Resources