Create user automatically with Sync Gateway and OIDC Implicit Flow - couchbase

I’m setting up Couchbase Lite on android with Sync Gateway 2.1 and Couchbase Server 6.0.
I've implemented authentication with Google Sign-in by using the OpenID Connect Implicit flow and I'm able to get the session cookie for authentication.
Now I need authorization to use the "requireUser()" function in the SGW config file's javascript, but I can't get SGW to create the User for me.
From what I read in the docs, setting "register":true in the config file should make SGW automatically create the user when it doesn't exist, but I keep getting an Unauthorized response when sending a request to /_session with as body { "name": "new_user_name" }.
What am I missing to be able to create the user with SGW automatically? I have setup Implicit Flow auth to avoid having to manage my own web app for authorization, so I would like to avoid having to use the Admin rest API for user creation.
Here's my SGW config file:
{
"log": ["*"],
"adminInterface": ":4985",
"databases": {
"lucidity": {
"server": "http://xxx.xxx.xxx.xxx:8091",
"bucket": "bucketname",
"username": "syncgateway",
"password": "***********",
"num_index_replicas": 0,
"enable_shared_bucket_access": true,
"import_docs": "continuous",
"oidc": {
"providers": {
"GoogleAuthFlow": {
"issuer":"https://accounts.google.com",
"client_id":"xxxxxxxxxxxxx.apps.googleusercontent.com ",
"validation_key":" xxxxxxxxxxxx",
"callback_url": "http://xxx.xxx.xxx.xxx:4984/bucketname/_oidc_callback",
"register":true
}
}
},
"users": { "GUEST": { "disabled": false, "admin_channels": ["*"] } },
"sync": `function (doc, oldDoc) {
}`
}
}
EDIT:
Here's the log for my request:
POST http://xx.xx.xx.xx:4984/bucketname/_session
Content-Type: application/json
Content-Length: 2
Authorization: [MY_ID_TOKEN_HERE]
Body: { }
And the response is
{
"authentication_handlers" : [ "default", "cookie" ],
"ok" : true,
"userCtx" : {
"channels" : {
"!" : 1,
"*" : 1
},
"name" : null
}
}
with the following Set-Cookie header:
Set-Cookie: SyncGatewaySession=xxxx; Path=/bucketname; Expires=Fri, 18 Jan 2019 08:50:36 GMT

Related

Migrating webRequest to declarativeNetRequest

Hi I was using webRequest in manifest V2 , I started getting below error
'webRequestBlocking' requires manifest version of 2 or lower.
So I am trying to convert my below existing code to declarativenetrequest
var responseListener = function (details) {
var rule = {
name: "Access-Control-Allow-Origin",
value: "*",
};
details.responseHeaders.push(rule);
var rule1 = {
name: "Access-Control-Allow-Methods",
value: "GET, PUT, POST, DELETE, HEAD, OPTIONS",
};
details.responseHeaders.push(rule1);
return { responseHeaders: details.responseHeaders };
};
chrome.webRequest.onHeadersReceived.addListener(
responseListener,
{
urls: [
"https://example.com/*",
"*://*.example1.com?test",
],
},
// extraInfoSpec
["blocking", "responseHeaders", "extraHeaders"]
);
So i tried replacing to chrome.declarativeNetRequest.onHeadersReceived.addListener(
And I got Uncaught TypeError: Cannot read properties of undefined (reading 'addListener').Can some one help me how the current function can be migrated to declarativeNetRequest.
The error you're seeing is because declarativeNetRequest provides a different API to webRequest and there are some additional steps for migration. You can learn more about the API in general here: https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/
For your use case, you can actually setup a rule declaratively in the manifest without needing to call any APIs at all! This is one of the benefits of the new API in general, which tries to move towards declarative rules rather than giving extensions access to web requests in-flight.
To start with, add the following to your extension manifest:
Copyright 2023 Google LLC.
SPDX-License-Identifier: Apache-2.0
"declarative_net_request" : {
"rule_resources" : [{
"id": "ruleset_1",
"enabled": true,
"path": "rules_1.json"
}]
},
"permissions": [
"declarativeNetRequest"
],
"host_permissions": [
"https://example.com/*"
]
This defines a new "ruleset" and also adds the required API and host permissions.
You can then create the file rules_1.json and put the desired rule inside:
Copyright 2023 Google LLC.
SPDX-License-Identifier: Apache-2.0
[
{
"id" : 1,
"priority": 1,
"action": {
"type": "modifyHeaders",
"responseHeaders": [
{ "header": "Access-Control-Allow-Origin", "operation": "set", "value": "*" },
{ "header": "Access-Control-Allow-Methods", "operation": "set", "value": "GET, PUT, POST, DELETE, HEAD, OPTIONS" }
]
},
"condition" : {
"urlFilter": "||example.com"
}
}
]
This adds the two headers as required. You can then reload your extension and should be good to go!
As a note, you won't see these headers reflected in Dev Tools. This is a bug which will hopefully be fixed in the future: https://bugs.chromium.org/p/chromium/issues/detail?id=1247400
If you want to check it's working, going to https://example.com and running the following in the console will output a list of headers, including the ones added by your extension: [...(await fetch("https://example.com")).headers].

Not supporting NGSIv2 metadata in device provisioned attributes

We have used IoT agent -1.14.0 version from docker hub.
We have given the service and servicepath as follows
fiware-service:testiotagent
fiware-servicepath:/
Device registration payload :
{
"devices": [
{
"device_id":"Motion-10",
"entity_name":"urn:ngsi-ld:SENSOR:Motion-10",
"entity_type":"SENSOR",
"transport": "MQTT",
"attributes": [
{"object_id": "s", "name": "state", "type":"Text"},
{"object_id": "l", "name": "luminosity", "type":"Integer",
"metadata":{ "unitCode":{"type": "Text", "value" :"CAL"}
}
}
]
}
]
}
As per iotagent node lib version 2.12.0 ,IoT agent json -1.14.0 version should support the metadata in device provisioned attributes. But still facing issue.
When we try to provision the above device we are getting the below error:
{
"name": "WRONG_SYNTAX",
"message": "Wrong syntax in request: Errors found validating request."
}
I found that iotagent-node-lib have the schema to validate against device registration payload
https://github.com/telefonicaid/iotagent-node-lib/blob/master/lib/templates/createDevice.json
In this json schema there is no metadata schema mentioned in attributes.
I have followed the below steps for metadata in Entity level:
I have removed the metadata in IoT agent
Updated the entity 'urn:ngsi-ld:SENSOR:Motion-10' as below
{
"id":"urn:ngsi-ld:SENSOR:Motion-10",
"type":"SENSOR",
"luminosity":{
"type":"Integer",
"value":"0",
"metadata":{ "unitCode":{"type": "Text", "value" :"CAL"}
}
}
Tried to send measurement and metadata got overriden and got the empty metadata
{
"id":"urn:ngsi-ld:SENSOR:Motion-10",
"type":"SENSOR",
"luminosity":{
"type":"Integer",
"value":"15",
"metadata":{}
}
}
Is it due to the fix given for issue 1788 in fiware-orion ,https://github.com/telefonicaid/fiware-orion/issues?q=1788.
Need some qucik confirmation and help from Fiware experts to overcome this issue, it is very much appreciated.
The templates checking a valid provisioning request currently does not accept the metadata attribute. There is an outstanding PR for this. At the moment you would be better off defining the Entities with the metadata in a config.js file instead.
e.g.:
iotAgentConfig = {
contextBroker: {
host: '192.168.1.1',
port: '1026',
ngsiVersion: 'v2'
},
server: {
port: 4041
},
types: {
'WeatherStation': {
commands: [],
type: 'WeatherStation',
lazy: [],
active: [
{
object_id: 'p',
name: 'pressure',
type: 'Hgmm'
},
{
object_id: 'h',
name: 'humidity',
type: 'Percentage',
entity_name: 'Higro2000',
entity_type: 'Higrometer',
metadata:{
unitCode:{
type: "Text", value :"Hgmm"
}
}
}
]
},
....etc

Trying to send access token from loopback to third party api

I have my API in loopback 3.x. First I created an empty project and right after that I ran npm install loopback-connector-rest --save and lb datasource in the console to have a link to an external API called Userlike. It this URL https://www.userlike.com/api/external/message/chat_meta/.
Then I created a model with no parameters called Messages.
I had no problems executing as I used node . and there was no error, and in localhost:3000 I could visualize my API.
But I had a problem when I clicked GET in the page a 401 error because to access the API in Userlike I needed to send my token so I could get the data, so I modified the datasources.json file and I had this:
{
"userlikeRESTdatasource": {
"name": "userlikeRESTdatasource",
"baseURL": "https://www.userlike.com/api/external/message/chat_meta/",
"crud": false,
"connector": "rest",
"operations": [
{
"functions": {
"getMessages": []
},
"template": {
"method": "GET",
"url": "https://www.userlike.com/api/external/message/chat_meta/",
"headers": {
"accepts": "application/json",
"content-type": "application/json",
"authorization": "8c149a3d-4acf-362e-880c-30ec2f5ecaf"
},
"responsePath": "$.results.*"
}
}
]
}
}
The authorization field I put in the header didn't work as I still received
{
"error": {
"statusCode": 401,
"name": "Error",
"message": "Authorization Required",
"stack": "Error: Authorization Required\n
}
}
My idea was to do something like:
headers.append('Authorization', '8c149a3d-4acf-362e-880c-30ec2f5ecaf7');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
headers.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Authorization, Accept');
But with loopback. So I could receive the data from the Userlike API and next I could modify or just use the data I wanted.
But I still can't figure out how can I modify my datasources.json or if I need to create something in another file to make it possible to send the token as the authorization to that URL I'm using.
Pass access token with HTTP header by using this
headers.append('X-Access-Token', '8c149a3d-4acf-362e-880c-30ec2f5ecaf7');
or also pass this token as a parameter.
?access_token=8c149a3d-4acf-362e-880c-30ec2f5ecaf7
This will help.

Cannot load material design css from CDN using Firebase Hosting

I am getting the following error:
XMLHttpRequest cannot load
https://code.getmdl.io/1.3.0/material.indigo-pink.min.css. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://nhalistonfirebase.firebaseapp.com' is
therefore not allowed access.
Here's my firebase.json file:
{
"hosting": {
"public": "public",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
// Add the "headers" section within "hosting".
"headers": [
{
"source": "**/*.#(eot|otf|ttf|ttc|woff|font.css)",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
}
]
},
{
"source": "**/*.#(jpg|jpeg|gif|png)",
"headers": [
{
"key": "Cache-Control",
"value": "max-age=7200"
}
]
}
]
}
}
How should this be corrected?
code.getmdl.io doesn’t send the Access-Control-Allow-Origin response header that’s necessary to make browsers allow your frontend JavaScript code to access the response.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.
The firebase.json file shown in the question is for the https://nhalistonfirebase.firebaseapp.com site I guess? If so, it doesn’t matter what CORS config you do there—what instead matters is what CORS config is set on the site your code is sending the request to.
And the code.getmdl.io site apparently has no CORS config to allow cross-origin requests.
But you can get around this by using a CORS proxy. You can instead use this request URL:
https://cors-anywhere.herokuapp.com/https://code.getmdl.io/1.3.0/material.indigo-pink.min.css
That sends the request through https://cors-anywhere.herokuapp.com, which forwards the request to https://code.getmdl.io/1.3.0/material.indigo-pink.min.css and then receives the response. The https://cors-anywhere.herokuapp.com backend adds the Access-Control-Allow-Origin header to the response and passes that back to your requesting frontend code.
The browser will then allow your frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.
You can also easily set up your own CORS proxy using https://github.com/Rob--W/cors-anywhere/

Generate POSTMAN in webpage with JSON or something

I have a restAPI code from a programmer from JNE, company stands for delivery service.
They say that this API can be run in POSTMAN (Google Chrome Application)
It works fine in the POSTMAN, where in this application I just need to insert the request URL (which I have got from the JNE company) and two header of keys and values as follow;
KEY VALUE
----------------------------------------------
username mycompany
api key 4534645756864234523424
The method for this is POST and when I posted it, it gives me the results as how expected.
My problem now is, how can I run this code in my page, so that I don't need to run this in postman.
I am just this day going to learn JSON if anybody can help me out with this.
[UPDATE QUESTION 1]
{
"version":1,
"collections":
[
{
"id":"c8b12431-8586-cbdd-aef7-056ec177509a",
"name":"asdasdadasdasdasd",
"timestamp":1415593872130,
"requests":
[
{
"collectionId":"c8b12431-8586-cbdd-aef7-056ec177509a",
"id":"d1b2ed66-781d-d02e-c4eb-0416dd3e07a1",
"name":"http://api.jne.co.id:8889/tracing/mycompany/origin/key/jak",
"description":"",
"url":"http://api.jne.co.id:8889/tracing/mycompany/origin/key/jak",
"method":"POST",
"headers":"username: mycompany\napi_key:089a12ffb8cd5009bdfa4ba5bdb9ee26\n",
"data":
[
{
"key":"username",
"value":"mycompany",
"type":"text"
},
{
"key":"api_key",
"value":"dsfsdfsdfs98d98sdfsdf9898dsfs",
"type":"text"
}
],
"dataMode":"params",
"timestamp":0,
"responses":[],
"version":2
}
]
}
],
"environments":[],
"headerPresets":[],
"globals":[]
}
From the update question above; my first question is: ]
In what format I have to save this file: JSON? or WHAT?
Should I save this file in one file with my webpage? or Can I save it as external file?
From the code above, I get the result as follow:
{
"detail": [
{
"code": "CGK10000",
"label": "JAKARTA"
},
{
"code": "CGK10100",
"label": "JAKARTA BARAT"
},
{
"code": "CGK10300",
"label": "JAKARTA PUSAT"
},
{
"code": "CGK10200",
"label": "JAKARTA SELATAN"
},
{
"code": "CGK10500",
"label": "JAKARTA TIMUR"
},
{
"code": "CGK10400",
"label": "JAKARTA UTARA"
}
]
}
If you have a look to the "label" it is generated from the key of the last string in the: "name":"http://api.jne.co.id:8889/tracing/mycompany/origin/key/jak",
The result of the label from the last string of jak, is what I want to insert in a dropdown html tag, in where the user will choose that (the name of the location).
[Update with complete code]
POST /tracing/mycompany/origin/key/jak HTTP/1.1
Host: api.jne.co.id:8889
Content-Type: application/json
username: mycompany
api_key: 089a12ffb8cd5009bdfa4ba5bdb9ee26
{
"version":1,
"collections":
[
{
"id":"c8b12431-8586-cbdd-aef7-056ec177509a",
"name":"asdasdadasdasdasd",
"timestamp":1415593872130,
"requests":
[
{
"collectionId":"c8b12431-8586-cbdd-aef7-056ec177509a",
"id":"d1b2ed66-781d-d02e-c4eb-0416dd3e07a1",
"name":"http://api.jne.co.id:8889/tracing/mycompany/origin/key/jakarta",
"description":"",
"url":"http://api.jne.co.id:8889/tracing/mycompany/origin/key/jakarta",
"method":"POST",
"headers":"username: mycompany\napi_key:089a12ffb8cd5009bdfa4ba5bdb9ee26\n",
"data":
[
{
"key":"username",
"value":"mycompany",
"type":"text"
},
{
"key":"api_key",
"value":"089a12ffb8cd5009bdfa4ba5bdb9ee26",
"type":"text"
}
],
"dataMode":"params",
"timestamp":0,
"responses":[],
"version":2
}
]
}
],
"environments":[],
"headerPresets":[],
"globals":[]
}
I have saved this file as jne.json and jne.html but the browser just show the full code insted show the result as how the postman does. I think there are many things I am missing here.
The POST request would look something like the following
POST /tracing/mycompany/origin/key/jak HTTP/1.1
Host: api.jne.co.id:8889
Content-Type: application/json
username: mycompany
api_key: 089a12ffb8cd5009bdfa4ba5bdb9ee26
{
... your JSON ...
}
You can save JSON with the .json file extension. If your request is always the same you can save this file with your webpage, but normally an HTTP request is constructed before sending (that means you normally send different requests).
To fill the dropdown list you just have to parse the JSON response.