Mobx model type for hashmap - mobx

I want my model variable to look like
{
"foo": {
"viewed": false,
"url": "https://www.google.com"
},
"bar": {
"viewed": false,
"url": "https://www.google.com"
},
"baz": {
"viewed": false,
"url": "https://www.google.com"
}
}
I have a separate model like this
import { types as t } from "mobx-state-tree"
export const deviceInstruction = t.model({
viewed: t.boolean,
url: t.string
})
type DeviceInstructionType = typeof deviceInstruction.Type
export interface IDeviceInstruction extends DeviceInstructionType {}
And was hoping to something like
export const exampleStore = t
.model({
devices: t.optional(deviceInstruction), {}),
})
But that doesn't work. I'm not sure how to situate it so it has the proper key. Thanks for your help

Object literals fits nicely with a map:
import { types as t } from "mobx-state-tree";
const DeviceInstruction = t.model({
viewed: t.boolean,
url: t.string
});
const ExampleStore = t.model({
devices: t.map(DeviceInstruction)
});
const exampleStore = ExampleStore.create({
devices: {
foo: {
viewed: false,
url: "https://www.google.com"
},
bar: {
viewed: false,
url: "https://www.google.com"
},
baz: {
viewed: false,
url: "https://www.google.com"
}
}
});
console.log(exampleStore.devices.get("foo"));
// { viewed: false, url: "https://www.google.com" }

Related

Can I use Supertokens with linkedin login oauth 2.0 as Third party provider ? How to do so?

I was researching about identity providers and I found supertokens (https://supertokens.com/docs/guides), it seems a nice solution but I would like to know if it also accepts LinkedIn as a third party provider because I couldn't see any info about this in docs or in any other related post. Also if you have any example code would be awesome
Find documentation about integration between supertokens and LinkedIn auth, couldn't find any.
The documentation for implementing custom providers is available here - https://supertokens.com/docs/thirdparty/common-customizations/sign-in-and-up/custom-providers. Based on that, here is a sample implementation for linkedin that you could use:
Frontend:
export const SuperTokensConfig = {
appInfo: {
appName: "SuperTokens Demo App",
apiDomain: "http://localhost:3001",
websiteDomain: "http://localhost:3000",
},
// recipeList contains all the modules that you want to
// use from SuperTokens. See the full list here: https://supertokens.com/docs/guides
recipeList: [
ThirdParty.init({
signInAndUpFeature: {
providers: [
{
id: "linkedin",
name: "Linkedin",
buttonComponent: <div style={{
cursor: "pointer",
border: "1",
paddingTop: "5px",
paddingBottom: "5px",
borderRadius: "5px",
borderStyle: "solid"
}}>Login with Linkedin</div>
}
],
},
}),
Session.init(),
],
};
Backend:
const Linkedin = (config: any): TypeProvider => {
return {
id: "linkedin",
get: (redirectURI: string | undefined, authCodeFromRequest: string | undefined, userContext: any) => {
const accessTokenParams: any = {
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: "authorization_code",
}
if (redirectURI !== undefined) accessTokenParams["redirect_uri"] = redirectURI;
if (authCodeFromRequest !== undefined) accessTokenParams["code"] = authCodeFromRequest;
const authRedirectParams: any = {
client_id: config.clientId,
scope: "r_liteprofile r_emailaddress",
response_type: "code",
}
if (redirectURI !== undefined) authRedirectParams["redirect_uri"] = redirectURI;
return {
accessTokenAPI: {
url: "https://www.linkedin.com/oauth/v2/accessToken",
params: accessTokenParams,
},
authorisationRedirect: {
url: "https://www.linkedin.com/oauth/v2/authorization",
params: authRedirectParams,
},
getClientId: () => config.clientId,
getProfileInfo: async (authCodeResponse: any, userContext: any) => {
const headers = {
Authorization: `Bearer ${authCodeResponse.access_token}`,
}
const userInfo = (await axios.get("https://api.linkedin.com/v2/me", { headers })).data
const emailInfo = (await axios.get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))", { headers })).data
let email = ''
for (const element of emailInfo.elements) {
if (element['handle~'].emailAddress) {
email = element['handle~'].emailAddress
break
}
}
return {
id: userInfo.id,
email: {
id: email,
isVerified: false,
}
}
},
}
},
}
}
export const SuperTokensConfig: TypeInput = {
supertokens: {
connectionURI: "https://try.supertokens.com",
},
appInfo: {
appName: "SuperTokens Demo App",
apiDomain: "http://localhost:3001",
websiteDomain: "http://localhost:3000",
},
recipeList: [
ThirdParty.init({
signInAndUpFeature: {
providers: [
Linkedin({
clientId: "...",
clientSecret: "..."
}),
],
},
}),
Session.init(),
],
};
If you are using python or the golang SDK, a similar implementation in that language should work.

How to prevent to lost session after refresh in nuxt?

I am currently working on a nuxtJS app in which the session seems to be lost after any refresh (although only in dev, not while deployed). I've tried to look up in the auth module of nuxt, and have tried many answers on google, but nothing seems to work and I'm a bit lost.
nuxt.config.js
auth: {
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'token',
maxAge: 3600,
global: true,
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
user: {
property: 'user',
},
endpoints: {
login: { url: '/authentication_token', method: 'post' },
refresh: { url: '/refresh/token', method: 'post' },
logout: false,
user: { url: '/api/user', method: 'get' },
},
autoLogout: true,
},
},
},
LoginMenu.js
methods: {
async onSubmit() {
try {
const response = await this.$auth.loginWith('local', {
data: this.login,
});
if (response.status === 200) {
await this.$auth.setUser({
email: this.login.email,
password: this.login.password,
});
await this.$router.push('/');
}
else {
this.loginFail();
}
}
catch (e) {
this.loginFail();
}
},
loginFail() {
this.showError = true;
},
},
nuxt auth.js
import Middleware from './middleware'
import { Auth, authMiddleware, ExpiredAuthSessionError } from '~auth/runtime'
// Active schemes
import { RefreshScheme } from '~auth/runtime'
Middleware.auth = authMiddleware
export default function (ctx, inject) {
// Options
const options = {
"resetOnError": false,
"ignoreExceptions": false,
"scopeKey": "scope",
"rewriteRedirects": true,
"fullPathRedirect": false,
"watchLoggedIn": true,
"redirect": {
"login": "/login",
"logout": "/",
"home": "/",
"callback": "/login"
},
"vuex": {
"namespace": "auth"
},
"cookie": {
"prefix": "auth.",
"options": {
"path": "/"
}
},
"localStorage": {
"prefix": "auth."
},
"defaultStrategy": "local"
}
// Create a new Auth instance
const $auth = new Auth(ctx, options)
// Register strategies
// local
$auth.registerStrategy('local', new RefreshScheme($auth, {
"token": {
"property": "token",
"maxAge": 3600,
"global": true
},
"refreshToken": {
"property": "refresh_token",
"data": "refresh_token",
"maxAge": 2592000
},
"user": {
"property": "user"
},
"endpoints": {
"login": {
"url": "/authentication_token",
"method": "post"
},
"refresh": {
"url": "/refresh/token",
"method": "post"
},
"logout": false,
"user": {
"url": "/api/user",
"method": "get"
}
},
"autoLogout": true,
"name": "local"
}))
// Inject it to nuxt context as $auth
inject('auth', $auth)
ctx.$auth = $auth
// Initialize auth
return $auth.init().catch(error => {
if (process.client) {
// Don't console log expired auth session errors. This error is common, and expected to happen.
// The error happens whenever the user does an ssr request (reload/initial navigation) with an expired refresh
// token. We don't want to log this as an error.
if (error instanceof ExpiredAuthSessionError) {
return
}
console.error('[ERROR] [AUTH]', error)
}
})
}

Vue data fetched object not available in setup()

I am rendering a jspreadsheet component with data fetched from fastapi.
<template>
<h1>Synthèse évaluation fournisseur</h1>
<VueJSpreadsheet v-model="data.table" :options="myOption" />
{{ data.columns }}
</template>
<script>
import { reactive, onMounted, isProxy, toRaw, ref } from "vue";
import VueJSpreadsheet from "vue3_jspreadsheet";
import "vue3_jspreadsheet/dist/vue3_jspreadsheet.css";
export default {
components: {
VueJSpreadsheet,
},
setup() {
// var intervalID = setInterval(init, 3000);
var data = reactive({
table: [],
columns: [],
});
async function load_data() {
const response = await fetch("http://LOCALHOST:8080/supplier_overview");
return await response.json();
}
load_data().then((response)=>{
data.table=JSON.parse(response.result.data)
data.columns=(response.result.columns)
});
console.log(data.columns)
const myOption = ref({
columns: data.columns,
search: true,
filters: true,
includeHeadersOnDownload: true,
includeHeadersOnCopy: true,
defaultColAlign: "left",
tableOverflow: true,
tableHeight: "800px",
parseFormulas: true,
copyCompatibility: true,
});
return {
data,
myOption,
};
},
};
</script>
whereas data.columns is rendered correctly in the template, I cannot pass it to myOptions .
The proxy is empty with console.log(data.columns) whereas {{data.columns}} returns the correct array :
[ { "title": "period" }, { "title": "fournisseur" }, { "title": "Qualité" }, { "title": "Rques Qualité" }, { "title": "Logistique" }, { "title": "Rques Logistique" }, { "title": "Cout" }, { "title": "Rques Cout" }, { "title": "Système" }, { "title": "Rques Système" }, { "title": "Mot QLCS" }, { "title": "Note" }, { "title": "Rques" } ]
Any ideas why I cannot passed it correctly to myOptions ?
This problem has nothing to do with the variable myOptions
setup() {
async function load_data() {
const response = await fetch("http://LOCALHOST:8080/supplier_overview");
return await response.json();
}
//the function is async, 1 will be called after 2, so the result is empty
load_data().then((response)=>{
data.table=JSON.parse(response.result.data)
//1
data.columns=(response.result.columns)
});
//2
console.log(data.columns)
}

Nuxt.js Oauth sometimes crashes whole webpage

I have created Nuxt.js application, I decided to build in Nuxt/auth module, everything works fine in web browsers, but somethimes when user navigates with mobile browser my application is crushed, simply it don't respond nothing, also there is no api calls, but after one refresh everything works fine, I can not guess what's happening, I could not find anything in the resources available on the Internet.
const axios = require('axios')
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'app',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
// { src: "//code-eu1.jivosite.com/widget/UoBOrMfSmm", async: true },
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [ '~/assets/css/transition.css', '~/assets/css/errors.css' ],
pageTransition: "fade",
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: "~/plugins/star-rating", ssr: false },
{ src: "~/plugins/mask", ssr: false },
{ src: "~/plugins/rangeSlider", ssr: false },
{ src: "~/plugins/vueSelect", ssr: false },
{ src: "~/plugins/vuelidate", ssr: false },
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
[ '#nuxtjs/google-analytics', {
id: 'xxx'
} ]
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/toast',
'#nuxtjs/auth-next',
[ 'nuxt-lazy-load', {
defaultImage: '/spin2.gif'
} ],
[ 'nuxt-facebook-pixel-module', {
/* module options */
track: 'PageView',
pixelId: '',
autoPageView: true,
disabled: false
} ],
'nuxt-moment',
'#nuxtjs/robots',
'#nuxtjs/sitemap'
],
moment: {
locales: ['ru', 'en']
},
toast: {
position: 'top-center',
},
robots: [
{
UserAgent: '*',
Disallow: ['/user', '/admin'],
},
],
axios: {
baseURL: 'https://api.test.com/', // Used as fallback if no runtime config is provided
},
sitemap:{
exclude:[
'/user',
'/admin',
'/admin/*',
'/user/*',
],
defaults: {
changefreq: 'daily',
priority: 1,
lastmod: new Date()
},
routes: async () => {
const { data } = await axios.get('https://api.test.com/api/cars/all')
return data.map((product) => `https://test.com/product/${product.id}/${product.name}`)
}
},
loading: {
color: '#F48245',
height: '4px'
},
target: 'server',
/* auth */
auth: {
plugins:[
{ src: "~/plugins/providers", ssr:false},
],
redirect: {
login: '/',
logout: '/',
home: '/',
callback: '/callback'
},
strategies: {
local: {
token: {
property: 'user.token',
},
user: {
property: false
},
endpoints: {
login: { url: 'api/login', method: 'post' },
logout: { url: 'api/logout', method: 'post' },
user: { url: 'api/user', method: 'get' }
},
},
facebook: {
endpoints: {
userInfo: 'https://graph.facebook.com/v6.0/me?fields=id,name,picture{url}',
},
redirectUri:'xxx',
clientId: '184551510189971',
scope: ['public_profile', 'email'],
},
google: {
responseType: 'token id_token',
codeChallengeMethod: '',
clientId: 'xxx',
redirectUri: 'https://test.com/callback',
scope: ['email'],
},
},
cookie: {
prefix: 'auth.',
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
};
This is my plugins directory file, where i am handling client oauth process.
export default async function ({ app }) {
console.log('auth executed')
if (!app.$auth.loggedIn) {
return
} else {
console.log('auth executed inside loop')
const auth = app.$auth;
const authStrategy = auth.strategy.name;
if (authStrategy === 'facebook') {
let data2 = {
fb_token: auth.user.id,
first_name: auth.user.name
}
try {
const response = await app.$axios.$post("/api/oauth", data2);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
} else if (authStrategy === 'google') {
let dataGoogle = {
google_token: auth.user.sub,
first_name: auth.user.given_name,
last_name:auth.user.family_name
}
try {
const response = await app.$axios.$post("/api/oauth", dataGoogle);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
}
}
}
For any issues related to DOM hydration, you can check my answer here: https://stackoverflow.com/a/67978474/8816585
It does have several possible cases (dynamic content with a difference between client side and server side rendered template, some random functions, purely wrong HTML structure etc...) and also a good blog article from Alex!

Can't be blank - Password - Loopback 4 - JWT authentication

When I want to signup on the loopback API Explorer with a JWT authentication and this json format:
{
"id": "string",
"nom": "string",
"prenom": "string",
"email": "string",
"sexe": true,
"dateNaissance": "string",
"password": "strifsvng"
}
I had that error message :
{
"error": {
"statusCode": 422,
"name": "ValidationError",
"message": "L'instance `User` n'est pas valide. Détails : `password` can't be blank (value: undefined).",
"details": {
"context": "User",
"codes": {
"password": [
"presence"
]
},
"messages": {
"password": [
"can't be blank"
]
}
}
}
}
Here the link of the documentation's loopback I've used.
You can see here the user modal :
import {Entity, model, property} from '#loopback/repository';
#model()
export class User extends Entity {
#property({
type: 'number',
id: true,
generated: true,
})
id?: number;
#property({
type: 'string',
required: true,
})
nom: string;
#property({
type: 'string',
required: true,
})
prenom: string;
#property({
type: 'string',
required: true,
})
dateNaissance: string;
#property({
type: 'string',
required: true,
})
sexe: string;
#property({
type: 'string',
required: true,
})
email: string;
#property({
type: 'string',
required: true,
})
password: string;
constructor(data?: Partial<User>) {
super(data);
}
}
export interface UserRelations {
// describe navigational properties here
}
export type UserWithRelations = User & UserRelations;
and the user controller :
// import {inject} from '#loopback/core';
import {inject} from '#loopback/core';
import {
Credentials,
MyUserService,
TokenServiceBindings,
User,
UserRepository,
UserServiceBindings,
} from '#loopback/authentication-jwt';
import {authenticate, TokenService} from '#loopback/authentication';
import {model, property, repository} from '#loopback/repository';
import {get, getModelSchemaRef, post, requestBody} from '#loopback/rest';
import {SecurityBindings, securityId, UserProfile} from '#loopback/security';
import {genSalt, hash} from 'bcryptjs';
import _ from 'lodash';
#model()
export class NewUserRequest extends User {
#property({
type: 'string',
required: true,
})
password: string;
}
const CredentialsSchema = {
type: 'object',
required: ['email', 'password'],
properties: {
email: {
type: 'string',
format: 'email',
},
password: {
type: 'string',
minLength: 8,
},
},
};
export const CredentialsRequestBody = {
description: 'The input of login function',
required: true,
content: {
'application/json': {schema: CredentialsSchema},
},
};
export class UserController {
constructor(
#inject(TokenServiceBindings.TOKEN_SERVICE)
public jwtService: TokenService,
#inject(UserServiceBindings.USER_SERVICE)
public userService: MyUserService,
#inject(SecurityBindings.USER, {optional: true})
public user: UserProfile,
#repository(UserRepository) protected userRepository: UserRepository,
) {}
#post('/users/login', {
responses: {
'200': {
description: 'Token',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
token: {
type: 'string',
},
},
},
},
},
},
},
})
async login(
#requestBody(CredentialsRequestBody) credentials: Credentials,
): Promise<{token: string}> {
// ensure the user exists, and the password is correct
const user = await this.userService.verifyCredentials(credentials);
// convert a User object into a UserProfile object (reduced set of properties)
const userProfile = this.userService.convertToUserProfile(user);
// create a JSON Web Token based on the user profile
const token = await this.jwtService.generateToken(userProfile);
return {token};
}
#authenticate('jwt')
#get('/whoAmI', {
responses: {
'200': {
description: '',
schema: {
type: 'string',
},
},
},
})
async whoAmI(
#inject(SecurityBindings.USER)
currentUserProfile: UserProfile,
): Promise<string> {
return currentUserProfile[securityId];
}
#post('/signup', {
responses: {
'200': {
description: 'User',
content: {
'application/json': {
schema: {
'x-ts-type': User,
},
},
},
},
},
})
async signUp(
#requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(NewUserRequest, {
title: 'NewUser',
}),
},
},
})
newUserRequest: NewUserRequest,
): Promise<User> {
const password = await hash(newUserRequest.password, await genSalt());
const savedUser = await this.userRepository.create(
_.omit(newUserRequest, 'password'),
);
await this.userRepository.userCredentials(savedUser.id).create({password});
return savedUser;
}
}
I don't know why there are that error as I write something in the password.
Thank you in advance :)