How to change BaseStore from SAP Spartacus storefront - spartacus-storefront

As Spartacus is for B2C process there is no any option to change BaseStore from storefront. I have a drop down for different countries and now want to change BaseSite from it.

So finally I made it working. I am storing baseSite to session if its changed from dropdown and if user is coming back reading it first from session.
here what you have to do to make it working:
Override BaseSite service and change initialize method similar to the initialize method of LanguageService. (which check if baseStore is stored in session )
Listen to SET_ACTIVE_BASE_SITE action and set payload to session. (again similar like activeLanguage effect in LanguagesEffects)
Now in B2cStorefrontModule config add your other sites as
B2cStorefrontModule.withConfig({
context: {
baseSite: ['electronics','mystore2','mystore-uk', 'mystore-canada'],
language: ['en'],
currency: ['USD']
}
So the main solution is, you listen to basestore change action and store the value to session and on page load you read basestore from session

I think you are looking for this. Check full code on Building the Spartacus Storefront from Libraries
B2cStorefrontModule.withConfig({
backend: {
occ: {
baseUrl: 'https://localhost:9002',
prefix: '/rest/v2/',
legacy: false
}
},
authentication: {
client_id: 'mobile_android',
client_secret: 'secret'
},
context: {
baseSite: ['electronics']
},
i18n: {
resources: translations,
chunks: translationChunksConfig,
fallbackLang: 'en'
}
}),

Related

Nuxt auth with keycloak: ssr this.$auth.loggedIn always false on page load

I have a setup with nuxt and keycloak as auth strategy which in general is working. I can login via keycloak and then will have this.$auth.loggedIn === true on the page. When navigating via vue-router, this.$auth.loggedIn will also be true when switching to a new page.
But when I then reload the page (CMD+r/F5), server side rendering will have false for this.$auth.loggedIn, while on client side it will be true. This forced me to do a lot of <client-only> blocks in the templates to prevent ssr mismatches.
I wonder if it is possible that on first page load server side rendering can return a page with authorized content? I would think this should be possible since cookies with auth info are set and sent to the server.
Or is that never possible and efficient server side rendering can only be used for non-authorized content?
Versions:
nuxt: 2.15.8
#nuxtjs/auth-next: 5.0.0-1643791578.532b3d6
nuxt.config.js:
auth: {
strategies: {
keycloak: {
scheme: 'oauth2',
endpoints: {
authorization: `${ process.env.KEYCLOAK }/protocol/openid-connect/auth`,
userInfo: `${ process.env.KEYCLOAK }/protocol/openid-connect/userinfo`,
token: `${ process.env.KEYCLOAK }/protocol/openid-connect/token`,
logout: `${ process.env.KEYCLOAK }/protocol/openid-connect/logout`,
},
token: {
property: 'access_token',
type: 'Bearer',
maxAge: 1800,
},
refreshToken: {
property: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
responseType: 'code',
grantType: 'authorization_code',
clientId: process.env.CLIENT_ID,
scope: ['openid', 'profile', 'email', 'roles'],
codeChallengeMethod: 'S256',
redirect: {
logout: '/',
callback: '/',
home: '/',
},
},
},
},
Having a Vue component with this:
created() {
console.log(this.$auth.loggedIn);
},
Will return false for SSR and true on client side on page load/refresh when logged in.
After manually implementing a server side authenticator, I found out that the problem was my local docker setup.
Didn't think this was the problem before, so I forgot to mention it.
I have a local docker container with keycloak and a local docker container with nuxt.
Long story short, it seems that the nuxt server wasn't able to communicate with keycloak, hence wasn't able to fetch the user. After changing some addresses so that keycloak was available on the same address from the browser and from within my nuxt server docker container, the nuxt server did get $auth.loggedIn=true automatically on page load if the is was logged in.
Not sure if I didn't see it, but I wished nuxt auth would give me an error if the nuxt server failed to communicate with the authorization server. Would have saved me a lot of debugging.

Strapi v4 Extending Server API for Plugins does not work

I am trying to follow the Strapi v4.0.0 guide on https://docs.strapi.io/developer-docs/latest/developer-resources/plugin-api-reference/server.html#entry-file for extending the users-permission plugin to add a custom route/controller, but so far have been unsuccessful. I add the custom files as stated in the docs, but there is no change in the UI.
I managed to get this to work for normal API highlighted in yellow, but was unable to do so for the users-permission plugin
In the previous version 3.6.8 this functionality was allowed through the extensions folder.
Am I missing something from the new guide, I even tried copying the files from node_modules > #strapi > plugin-users-permission and adding a new route and method to the exiting controller file but it still does not reflect the change in the section where we assign different route permission to roles. The user-permission plugin still shows the original routes, with no change.
Thanks,
I ran into this thread while researching pretty much the same issue, and I wanted to share my solution.
First of all, I found this portion of the documentation more useful than the one you referenced: https://docs.strapi.io/developer-docs/latest/development/plugins-extension.html
My goal was the write a new route to validate JWT tokens based on the comment made here: https://github.com/strapi/strapi/issues/3601#issuecomment-510810027 but updated for Strapi v4.
The solution turned out to be simple:
Create a new folder structure: ./src/extensions/user-permissions if it does not exist.
Create a new file ./src/extensions/user-permissions/strapi-server.js if it does not exist.
Add the following to the file:
module.exports = (plugin) => {
plugin.controllers.<controller>['<new method>'] = async (ctx) => {
// custom logic here
}
plugin.routes['content-api'].routes.push({
method: '<method>',
path: '/your/path',
handler: '<controller>.<new method>',
config: {
policies: [],
prefix: '',
},
});
return plugin;
};
If you're unsure what controllers are available, you can always check the API documentation or console.log(plugin) or console.log(plugin.controllers).
After the admin server restarts, you should see your new route under the user-permissions section as you would expect, and you can assign rights to it as you see fit.
My full strapi-server.js file including the logic to validate JWT:
module.exports = (plugin) => {
plugin.controllers.auth['tokenDecrypt'] = async (ctx) => {
// get token from the POST request
const {token} = ctx.request.body;
// check token requirement
if (!token) {
return ctx.badRequest('`token` param is missing')
}
try {
// decrypt the jwt
const obj = await strapi.plugin('users-permissions').service('jwt').verify(token);
// send the decrypted object
return obj;
} catch (err) {
// if the token is not a valid token it will throw and error
return ctx.badRequest(err.toString());
}
}
plugin.routes['content-api'].routes.push({
method: 'POST',
path: '/token/validation',
handler: 'auth.tokenDecrypt',
config: {
policies: [],
prefix: '',
},
});
return plugin;
};
When exporting routes you need to export the type, either content-api or admin. Look at the Strapi email plugin in node_modules for example, change the folder and file structure in your routes folder to match that and then you will be able to set permissions in the admin panel.
If your Strapi server is using Typescript, make sure that you name your extension files accordingly. So instead of strapi-server.js, you would need to name your file strapi-server.ts.

Nuxt.js custom role middleware doesn't work when page refresh

I have a simple application with some pages that need to be protected if the connected user is not an administrator.
I use the nuxt/auth package to handle the authentication:
auth: {
strategies: {
local: {
scopeKey: 'roles',
token: {
property: 'access_token',
type: 'Bearer',
name: 'Authorization',
},
user: {
property: 'user',
},
endpoints: {
login: {url: '/api/auth/login', method: 'post'},
// logout: { url: '/api/auth/logout', method: 'post' },
user: {url: '/api/auth/me', method: 'get'}
}
},
},
redirect: {
login: '/',
logout: '/',
callback: '/housing',
home: '/home'
},
plugins: [
'~/plugins/auth.js',
]
},
This works well but I have trouble achieving my middleware.
So what I want is to redirect the users to the home page if they don't have the role ROLE_ADMIN
export default function ({app, $auth, $axios}) {
if (!$auth.user.roles.includes('ROLE_ADMIN')) {
console.log("unauthorized");
app.router.push(app.localePath('home'));
}
}
And I use the middleware on the page I want.
It works perfectly when for example the user is logged and goes to the administration page without refreshing the page.
But if they go and refresh the page or use the direct URL, instantly after being redirected to the home page by my middleware, nuxt/auth redirect again my user to the "unauthorized" page.
Why this behavior?
Sorry for the bad answer last time. Here is a new one.
In the case of a hard refresh or moving to an URL from the search bar (same thing), you lose all your state and your app is loaded from scratch once again. At this point, you will have all of your middlewares executed again.
Here is a quote from this documentation page
The middleware will be executed in series in this order:
nuxt.config.js (in the order within the file)
Matched layouts
Matched pages
So, you'll have your auth (#nuxt/auth) middleware executed once again, then you will have your own custom one executed. Now, if you do not persist the info of the user (the one successfully logged in before the hard refresh), the auth module will have no clue of who you are and hence prompt you for a login once again.
So, nothing abnormal here so far.
Here is a link to an answer on how to persist data through a hard refresh: https://stackoverflow.com/a/66872372/8816585
The simple answer is: disable the redirect for auth/nuxt login and handle it on your own
redirect: {
login: false,
logout: '/',
callback: '/housing',
home: '/home'
},
If you don't disable it, it always is going to redirect the page to home after login

nuxtjs/google-tag-manager only add google analytics when cookie consent has been given

I'm currently trying to make my Tracking Opt-In. Meaning that before Google Analytics tracks the user, the user has to give consent. My website uses Nuxtjs and the #nuxtjs/google-tag-manager. In the nuxt-config.js I set it up like this modules: [
'nuxt-leaflet',
'#nuxtjs/redirect-module',
['#nuxtjs/moment', { locales: ['de'], plugin: false }],
['#nuxtjs/sitemap', {
path: '/sitemap.xml',
generate: false,
cacheTime: (1000 * 60 * 60), // generate every hour
gzip: true,
hostname: 'https://kreuzwerker.de',
routes () {
return generateSitemap()
}
}],
['#nuxtjs/google-tag-manager',
{
id: '/*GTM-Code*/',
dev: true // to disable in dev mode
}]
],
and it works perfectly fine but now I want to connect it somehow to my Cookie Consent Form. How would I do that?
First of all, you're using a deprecated nuxtjs module; use the new GTM module, right here; https://github.com/nuxt-community/gtm-module.
In your config, make sure you've set the following:
gtm: {
autoInit: false
}
Once you've gotten consent, in your form, call a callback function which calls the GTM init function; $gtm.init('GTM-XXXXXXX').
Good luck, read the GitHub page it explains it all.

How to add Matomo tracking code in VueJS Single Page Apps?

I wanted to confirm whether I got my analytics tracking setup correctly in my single page application within the VueJS framework.
I am using the Vue plugin for Matomo which is found here:
https://github.com/AmazingDreams/vue-matomo
I imported the VueMatomo plugin in my main.js entry file like so:
import VueMatomo from 'vue-matomo';
Then, I assign the VueMatomo as a global method in my main.js file like so:
Vue.use(VueMatomo, {
// Configure your matomo server and site
host: 'https://matomo.example.com', <-- i configured this to match my real site
siteId: 5, <--- i configured this to match my real site
// Enables automatically registering pageviews on the router
router: router,
// Enables link tracking on regular links. Note that this won't
// work for routing links (ie. internal Vue router links)
// Default: true
enableLinkTracking: true,
// Require consent before sending tracking information to matomo
// Default: false
requireConsent: false,
// Whether to track the initial page view
// Default: true
trackInitialView: true,
// Changes the default .js and .php endpoint's filename
// Default: 'piwik'
trackerFileName: 'piwik',
// Whether or not to log debug information
// Default: false
debug: false
});
That gives me access to the Matomo API (_paq) in my components. However, this is where I am confused.
For example, I have a view called overview.vue which is the main page of the site. In this vue template, I have the following code in my created() hook. Since I am using a SPA, I need to somehow get the name of the page that the user is on and push it to the Matomo Reporting Tool. This is what I did:
<template>...snip...</template>
<script>
export default {
name: 'OverView',
created: function() {
window._paq.push(['setCustomUrl', '/' + window.location.hash.substr(1)]);
window._paq.push(['setDocumentTitle', 'Overview Page']);
window._paq.push(['trackPageView']);
}
};
</script>
Is the above adequate or is there a better lifecyle hook (mounted?) for the tracking code? Perhaps navigation guards are more appropriate?
Thank you
I got matomo working on my vue.js app (v 2.6.10).
I'm using a trial account from https://matomo.org/
In my main.js file:
// Analytics
import VueMatomo from "vue-matomo";
Vue.use(VueMatomo, {
host: "https://example.matomo.cloud", // switch this to your account
siteId: 1, // switch this as well you can find the site id after adding the website to the dashboard.
router: router,
enableLinkTracking: true,
requireConsent: false,
trackInitialView: true,
trackerFileName: "piwik",
debug: true
});
I can confirm that all of my nested routes are tracked. I can see what pages i viewed on my matomo dashboard.
To get custom events working just add the following:
this.$matomo.trackEvent("Event Category", "Event Name", "event action");
To give this some context, for my app i'm using it in a computed property:
computed: {
selectedMapDataType: {
get() {
return this.$store.state.mapDataType;
},
set(selected) {
this.$matomo.trackEvent("Dashboard Update", "Dashboard Data", selected);
this.$store.dispatch("updateMapDataType", selected);
}
},
...}