Nuxt Auth Custom Scheme with local strategies using Bearer Authorization - vue.js

I want to make a custom scheme with local strategies but I don't know how can I do it using customScheme. Documentation of nuxt/auth v5 doest not help me
I want to execute two endpoint:
1st- request
POST /oauth/v2/token
HEAD:
Content-Type: application/x-www-form-urlencoded
body of the request:
clientId : string
clientSecret: string
grantType: string
username: string
password: string
response:
{
"accessToken": "string",
"expireTime": "2022-01-10T20:29:10.721Z",
"refreshToken": "string"
}
2nd- request
GET /security/users/me
HEAD
x-locale: fr|en
authorization: Bearer <TOKEN>
response:
{
"username": "string",
"firstname": "string",
"lastname": "string",
"email": "string",
"phone": "string",
"locale": "fr",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"expiresAt": "2022-01-10T20:38:36.478Z",
"loggedAt": "2022-01-10T20:38:36.478Z",
"roles": [
{
"name": "string",
"description": "string",
"code": "string",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"translations": {
"fr": {
"name": "string",
"description": "string"
},
"en": {
"name": "string",
"description": "string"
}
},
"permissions": [
{
"id": 1,
"code": "string",
"endUI": {
"name": "string",
"title": "string",
"id": 1,
"code": "string",
"type": {
"name": "string",
"code": "string",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"translations": {
"fr": {
"name": "string"
},
"en": {
"name": "string"
}
}
},
"module": {
"name": "string",
"description": "string",
"code": "string",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"translations": {
"fr": {
"name": "string",
"description": "string"
},
"en": {
"name": "string",
"description": "string"
}
}
},
"icon": "string",
"uri": "string",
"translations": {
"fr": {
"name": "string",
"title": "string"
},
"en": {
"name": "string",
"title": "string"
}
}
}
}
]
}
],
"avatar": {
"id": 1,
"url": "string"
}
}
nuxt.config.js
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/auth-next',
'#nuxtjs/dotenv',
'#nuxtjs/i18n', [
'nuxt-vuex-localstorage',
{
mode: 'debug',
localStorage: [
'user',
'service',
'location',
'storeType',
'warehouse',
'openingRange',
'store',
'holiday',
'taxon',
'provider',
'productOption',
'productAttribute',
'product',
'productVariant',
'glassesCatalog'
],
},
],
],
router: {
middleware: ['auth']
},
// Auth Strategies
auth: {
strategies: {
customStrategy: {
_scheme: '~/schemes/customScheme',
endpoints: {
login: {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: '/oauth/v2/token',
method: 'post'
},
user: {
url: '/security/users/me',
method: 'get',
propertyName: '',
headers: {
'x-locale': 'fr',
'Authorization': `Bearer ${It should be a token (accessToken) for the first request}`
}
}
}
}
}
}
~/schemes/customeScheme.js
import { LocalScheme } from '~auth/runtime'
export default class CustomScheme extends LocalScheme {
// Override `fetchUser` method of `local` scheme
async fetchUser (endpoint) {
// Token is required but not available
if (!this.check().valid) {
return
}
// User endpoint is disabled.
if (!this.options.endpoints.user) {
this.$auth.setUser({})
return
}
// Try to fetch user and then set
return this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.user
).then((response) => {
const user = getProp(response.data, this.options.user.property)
// Transform the user object
const customUser = {
...user,
fullName: user.firstName + ' ' + user.lastName,
roles: ['user']
}
// Set the custom user
// The `customUser` object will be accessible through `this.$auth.user`
// Like `this.$auth.user.fullName` or `this.$auth.user.roles`
this.$auth.setUser(customUser)
return response
}).catch((error) => {
this.$auth.callOnError(error, { method: 'fetchUser' })
})
}
}
~/login.vue
onSubmit(){
this.isSubmitting = true;
this.isDisabled= true;
let formData = new FormData();
formData.append("clientId", process.env.CLIENT_ID);
formData.append("clientSecret", process.env.CLIENT_SECRET);
formData.append("grantType", "password");
formData.append("username", this.dataUser.username);
formData.append("password", this.dataUser.password);
this.$refs.dataUser.validate(async (valid, fieldsError) => {
this.validate = valid;
if(valid){
try {
let response = await this.$auth.loginWith('customStrategy', { data: formData })
console.log(response);
this.$store.dispatch('storeSecurity/storeUserToken', response.data);
} catch (error) {
this.$message.error({content: this.$t("login.error"), key, duration: 3});
}
}
});
},
If I want to fetch user, how can i do please ???
everything I do gives me errors that have no answers in the doc
I need help please

You should use $auth.setUser(user) to set the current user after successfully login. That is iif your endpoints.user doesn't work.

Related

Unomi use of UpdatePoperties event to enrich profil

We are tring to enrich a profil using UpdateProperties event.
Something wrong, it didn't work.
Step of our process :
Search of the profil :
Use of the prive API /profiles/search
So we find a profil and get the profilId "60de10fe-e6ff-11ec-8fea-0242ac120002" for next step.
Enrich profil :
Use of the API public /context.json to post the json
{
"sessionId": null,
"profileId": "60de10fe-e6ff-11ec-8fea-0242ac120002",
"events": [
{
"itemType": "event",
"scope": "myScope",
"eventType": "updateProperties",
"properties": {
"update": {
"properties.age": "24"
},
"add": {
"properties.kids" : "1"
}
}
}
]
}
Response :
{
"profileId": "60de10fe-e6ff-11ec-8fea-0242ac120002",
"sessionId": null,
"profileProperties": null,
"sessionProperties": null,
"profileSegments": null,
"profileScores": null,
"filteringResults": null,
"processedEvents": 1,
"personalizations": null,
"trackedConditions": [
{
"parameterValues": {
"operator": "and",
"subConditions": [
{
"parameterValues": {
"formId": "zoneLeadFormEvent"
},
"type": "formEventCondition"
}
]
},
"type": "booleanCondition"
},
{
"parameterValues": {
"formId": "testFormTracking",
"pagePath": "/tracker/"
},
"type": "formEventCondition"
},
{
"parameterValues": {
"formId": "searchForm"
},
"type": "formEventCondition"
},
{
"parameterValues": {
"formId": "advancedSearchForm"
},
"type": "formEventCondition"
}
],
"anonymousBrowsing": false,
"consents": {}
}
Validation of the profile changes
Get /cxs/profiles/60de10fe-e6ff-11ec-8fea-0242ac120002
So, the properties are not updated.
We use a rules the merge the profil on a custom identifier :
{
"metadata": {
"id": "update_with_custom_identifier",
"name": "UpdateWithCustomIdentifier",
"description": "Copy my properties to profile properties on update"
},
"condition": {
"parameterValues": {
"subConditions": [
{
"parameterValues": {
},
"type": "updatePropertiesEventCondition"
}
],
"operator": "and"
},
"type": "booleanCondition"
},
"actions": [
{
"parameterValues": {
"mergeProfilePropertyValue": "eventProperty::target.properties.myIdentifier",
"mergeProfilePropertyName": "mergeCustomIdentifier"
},
"type": "mergeProfilesOnPropertyAction"
},
{
"parameterValues": {
},
"type": "allEventToProfilePropertiesAction"
}
]
}
What's the good method ?
Thanks in advance

Realm sync not working for embedded objects in react native

This is my collection schema on realm -
{
"title": "testnote",
"properties": {
"_id": {
"bsonType": "objectId"
},
"_syncPartition": {
"bsonType": "string"
},
"title": {
"bsonType": "string"
},
"description": {
"bsonType": "string"
},
"subject": {
"bsonType": "string"
},
"tags": {
"bsonType": "array",
"items": {
"bsonType": "string"
}
},
"pages": {
"bsonType": "array",
"items": {
"title": "notespage",
"bsonType": "object",
"properties": {
"type": {
"bsonType": "string"
},
"data": {
"bsonType": "string"
}
}
}
},
"createdBy": {
"bsonType": "string"
}
}
}
This is how I've declared realm schema in react native. The code to initialize the Realm connection is also added below.
static NotesPage = {
name: "notespage",
embedded: true,
properties: {
type: "string",
data: "string"
}
}
static mainSchema = {
name: "testnote",
properties: {
_id: "objectId?",
_syncPartition: "string?",
createdBy: "string?",
title: "string?",
description: "string?",
subject: "string?",
tags: "string[]",
pages: { type: "list", objectType: "notespage" }
},
primaryKey: "_id"
};
const sampleNotesConfig = {
schema: [mainSchema NotesPage],
sync: {
user,
partitionValue: notesPartition,
newRealmFileBehavior: OpenRealmBehaviorConfiguration,
existingRealmFileBehavior: OpenRealmBehaviorConfiguration
}
};
Realm.open(sampleNotesConfig).then((notesRealm) => {
//// Some relevant code
}).catch((reason) => {
console.log("Error initializing realm");
console.log(reason);
});
When I create the realm object, it gets inserted in the local realm file but never gets synced to the server. I don't see any server errors or errors in local.
notesRealm.write(() => {
notesRealm.create(
SampleNote.schema.name,
{
"subject": "History",
"title": "Local to Remote Note 10",
"description": "Local to Remote Note 10 Description",
"tags": ["Tag 1", "Tag 2", "Tag 3"],
"pages": [{"type": "COVER_PAGE", "data": "Data 1"}, { "type": "PARAGRAPH", "data": "Data 2"}]
});
});
I have checked following things -
Partition values are correct.
User has permission to read/write to that partition.
If I just remove the pages section from the schema, the object starts syncing.

After running my logic app, it shows some error message as" "We couldn't convert to Number.\r\n "

I am collecting data from sensors and upload to AZURE cosmo. My logic app on AZURE keep failing and show the following message
{
"status": 400,
"message": "We couldn't convert to Number.\r\n inner exception: We
couldn't convert to Number.\r\nclientRequestId:xxxxxxx",
"source": "sql-ea.azconn-ea.p.azurewebsites.net"
}
Below are the input data from cosmo. I saw that the input data has shown "ovf" and "inf". I have tried convert the data type of that column to other data type like bigiant and numeric and resubmitted. Still did not fixed that.
{
"Device": "DL084",
"Device_Group": "DLL",
"Time": "2019-09-04T11:45:20.0000000",
"acc_x_avg": "ovf",
"acc_x_stdev": "inf",
"acc_y_avg": "3832.88",
"acc_y_stdev": "2850.45",
"acc_z_avg": "13304.38",
"acc_z_stdev": "2289.86",
"cc_volt": "3.900293",
"cp_volt": "1.940371",
"fp_volt": "0.718475",
"id": "xxxxxxxxxxxxxxxxxxxx",
"ls_volt": "4.882698",
"millis": "1073760.00",
"rs_rpm": "0.00",
"smp_volt": "1.070381"
}
I have also tried to convert the data to string. And it will show
"Failed to execute query. Error: Operand type clash: numeric is
incompatible with ntext"
The question is how can I eliminate this error? How can I know the error is definitely due to the "inf" and "ovf" error?
The logic app code is as below
"definition": {
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
"actions": {
"For_each": {
"actions": {
"Delete_a_document": {
"inputs": {
"host": {
"connection": {
"name": "#parameters('$connections')['documentdb']['connectionId']"
}
},
"method": "delete",
"path": "/dbs/#{encodeURIComponent('iot')}/colls/#{encodeURIComponent('messages')}/docs/#{encodeURIComponent(items('For_each')['id'])}"
},
"runAfter": {
"Insert_row": [
"Succeeded"
]
},
"type": "ApiConnection"
},
"Insert_row": {
"inputs": {
"body": {
"Device": "#{item()['device']}",
"Device_Group": "#{items('For_each')['devicegroup']}",
"Time": "#{addHours(addSeconds('1970-01-01 00:00:00', int(items('For_each')['time'])), 8)}",
"acc_x_avg": "#items('For_each')['acc_x_avg']",
"acc_x_stdev": "#items('For_each')['acc_x_stdev']",
"acc_y_avg": "#items('For_each')['acc_y_avg']",
"acc_y_stdev": "#items('For_each')['acc_y_stdev']",
"acc_z_avg": "#items('For_each')['acc_z_avg']",
"acc_z_stdev": "#items('For_each')['acc_z_stdev']",
"cc_volt": "#items('For_each')['cc_volt']",
"cp_volt": "#items('For_each')['cp_volt']",
"fp_volt": "#items('For_each')['fp_volt']",
"id": "#{guid()}",
"ls_volt": "#items('For_each')['ls_volt']",
"millis": "#items('For_each')['millis']",
"rs_rpm": "#items('For_each')['rs_rpm']",
"smp_volt": "#items('For_each')['smp_volt']"
},
"host": {
"connection": {
"name": "#parameters('$connections')['sql']['connectionId']"
}
},
"method": "post",
"path": "/datasets/default/tables/#{encodeURIComponent(encodeURIComponent('[dbo].[RCD]'))}/items"
},
"runAfter": {},
"type": "ApiConnection"
}
},
"foreach": "#body('Query_documents')?['Documents']",
"runAfter": {
"Query_documents": [
"Succeeded"
]
},
"type": "Foreach"
},
"Query_documents": {
"inputs": {
"body": {
"query": "SELECT \t\t * \nFROM \t\t\tc \nWHERE \t\t\tc.devicegroup = 'DLL' ORDER BY c._ts"
},
"headers": {
"x-ms-max-item-count": 1000
},
"host": {
"connection": {
"name": "#parameters('$connections')['documentdb']['connectionId']"
}
},
"method": "post",
"path": "/dbs/#{encodeURIComponent('iot')}/colls/#{encodeURIComponent('messages')}/query"
},
"runAfter": {},
"type": "ApiConnection"
}
},
"contentVersion": "1.0.0.0",
"outputs": {},
"parameters": {
"$connections": {
"defaultValue": {},
"type": "Object"
}
},
"triggers": {
"Recurrence": {
"recurrence": {
"frequency": "Minute",
"interval": 30
},
"type": "Recurrence"
}
}
}
}

Pass an already existing Model to next in Loopback

There is Project model
{
"name": "Project",
"plural": "Projects",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"description": {
"type": "string"
},
"code": {
"type": "string"
},
"startDate": {
"type": "date",
"required": true
},
"endDate": {
"type": "date"
},
"value": {
"type": "number"
},
"infoEN": {
"type": "string"
},
"infoRU": {
"type": "string"
},
"infoAM": {
"type": "string"
},
"externalLinks": {
"type": [
"string"
]
}
},
"validations": [],
"relations": {
"industry": {
"type": "belongsTo",
"model": "Industry",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"service": {
"type": "belongsTo",
"model": "Service",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"tags": {
"type": "hasAndBelongsToMany",
"model": "Tag",
"foreignKey": "",
"options": {
"nestRemoting": true
}
}
},
"acls": [],
"methods": {}
}
And it hasAndBelongsToMany tags
here is Tag model
{
"name": "Tag",
"plural": "Tags",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Now when the relation is created loopback api gives this api endpoint.
POST /Projects/{id}/tags
This creates a new tag into the tags collection and adds it to the project.
But what about adding an already existing tag to the project?
So I figured maybe I add before save hook to the Tag
Here I'll check if the tag exists and then pass the existing one for the relation.
Something like this.
tag.js
'use strict';
module.exports = function(Tag) {
Tag.observe('before save', function(ctx, next) {
console.log(ctx.instance);
Tag.find({name: ctx.instance.name})
next();
});
// Tag.validatesUniquenessOf('name', {message: 'name is not unique'});
};
#HaykSafaryan it just demo to show you how to use tag inside project
var app = require('../../server/server');
module.exports = function(project) {
var tag=app.models.tags
//afterremote it just demo. you can use any method
project.afterRemote('create', function(ctx, next) {
tag.find({name: ctx.instance.name},function(err,result)){
if(err) throw err;
next()
}
});
};
this is just example code to show you how to use update,create ,find ,upsertwithwhere etc. tag for validation you have to setup condition over here it will not take validation which you defined in tags models

Failed to execute 'send' on 'XMLHttpRequest' for only one url in Loopback

Strongloop/Loopback node.js server used with 'ng-admin' editor and sqlite db. I need to get count of entities:
var Httpreq = new XMLHttpRequest();
Httpreq.open('GET', yourUrl, false);
Httpreq.send(null);
return Httpreq.responseText;
where yourUrl is like http://localhost:3000/api/v1/entity/count.
All urls works except one of entity named 'Advertisement', I have angular.js:12783 Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load http://localhost:3000/api/v1/advertisement/count. This url works in API explorer.
Advertisement.json:
{
"name": "Advertisement",
"base": "EntityBase",
"plural": "Advertisement",
"options": {
"validateUpsert": true,
"sqlite3": {
"table": "advertisement"
}
},
"properties": {
"name": {
"type": "string",
"required": true
},
"category_id": {
"type": "number"
},
"due_date": {
"type": "string"
},
"from_date": {
"type": "string"
},
"phone": {
"type": "string"
},
"site": {
"type": "string"
}
},
"validations": [],
"relations": {
"category": {
"type": "belongsTo",
"model": "Category",
"foreignKey": "category_id"
},
"photos": {
"type": "hasMany",
"model": "Photo",
"foreignKey": "advertisement_id"
}
},
"acls": [],
"methods": {},
"mixins": {
"Timestamp": {},
"SoftDelete": {},
"GenderAge": {},
"Descripted": {}
}
}
Renamed entity to Commercial to fix this.