Route after authentication in Ember - authentication

According to the docs, I should put routeAfterAuthentication in my config/environment.js file.
My environment.js contains the following:
module.exports = function(environment) {
var ENV = {
modulePrefix: 'client',
environment: environment,
baseURL: '',
locationType: 'auto',
routeAfterAuthentication: 'dashboard',
...
However, it's still not getting redirected to the dashboard route and showing that the index route is not defined.
Am I missing something here?

You will need to include ember-simple-auth key like this
var ENV = {
};
...
ENV['ember-simple-auth'] = {
authenticationRoute: 'sign-in',
routeAfterAuthentication: 'YOUR ROUTE GOES HERE'
}
...
You can also define them by environment inside if (environment === 'development'), but for all environments you can put them after var ENV declaration. It is also important to import application route mixin so that redirect works (app / routes / application.js)
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin, {});

Related

Nuxt.js env Property, understanding and how to use it?

following https://nuxtjs.org/api/configuration-env
I have been trying to set up my apiUrl in nuxt.config.js once for the whole project, like:
export default {
env: {
apiUrl: process.env.MY_REMOTE_CMS_API_URL || 'http://localhost:1337'
}
}
adding this in nuxt.config.js, I'd expect (and would like) to have apiUrl accessible everywhere in the project.
In particular, it is needed for the 3 following cases:
with axios, to generate static pages from dynamic urls (in nuxt.config.js)
generate: {
routes: function () {
return axios.get(apiUrl + '/posts')
.then((res) => {
return res.data.filter(page => {
return page.publish === true;
}).map(page => {
return {
route: '/news/' + page.slug
}
})
})
}
},
with apollo, to get data via graphql (in nuxt.config.js)
apollo: {
clientConfigs: {
default: {
httpEndpoint: apiUrl + '/graphql'
}
}
},
in every layout, page and components, as the base url of media:
<img :src="apiUrl + item.image.url" />
As you might see, only thing I need is to 'print' the actual base url of the cms.
I have also tried to access it with process.env.apiUrl, with no success.
The only way I was able to make it has been to create an extra plugin/apiUrl.js file, which injects the api url, and seems wrong to me as I am now setting the apiUrl twice in my project.
I asked this question in the past, but in a way less clear way. I was suggested to use dotenv, but from the docs it looks like adding an additional layer of complication that might not be necessary for a simpler setup.
Thanks.
I think dotenv module really is what you need.
This is my setup:
Project root has a .env file that contains
BASE_URL=https://www.myapi.com
require('dotenv').config() at top of nuxt.config.js
#nuxtjs/dotenv installed and added to buildModules of nuxt.config.js
env: { BASE_URL: process.env.BASE_URL} added to nuxt.config.js
axios: { baseURL: process.env.BASE_URL } added to nuxt.config.js (optional)
You should have access to your .env throughout the project. (process.env.BASE_URL)
I haven't used apollo, but you should be able to set the apollo endpoint with process.env.BASE_URL + '/graphql'
As of Nuxt 2.13, #nuxtjs/dotenv is not required anymore. Read here
The concept that I was missing is that you set up the same named variable in your server / pipeline, so that you have your (always local / never pushed) .env file and a same name variable remotely, not added to your repo (where the value can be the same or different)

How to reuse i18next instance in an express app

I have an express backend that I want to internationalise. I want to:
init my i18next instance at one place
reuse that instance on multiple places in code
I want to use them also in model code, not only in routes
This might sound like a primitive question, but even after reading through the i18next docs, I still don't know how I should reuse the initialised i18next instance. If I use i18next-express-middleware, I can use the t() method in routes. Fine, but what do I do if I want to use it in the models or some other file, let's say in model?
I dislike the idea of passing it down to every model method via a parameter. I cannot simply do import i18next from 'i18next' in each file, because it would return a new instance. I can't make js-file where I would init the instance in an async function and then return it, because I can't call an async function via await in the app.js (root file of my express app). Am I trying to force it on a use case for which it wasn't built?
Thank you for any tips.
In app.js:
const express = require('express');
const i18next = require('i18next');
const i18nextMiddleware = require('i18next-express-middleware');
const app = express();
First configure i18next
i18next
.use(i18nextMiddleware.LanguageDetector)
.init({
preload: ['de', 'en'],
fallbackLng: 'en',
resources: {
en: {
translation: {
key: 'hello world'
}
}, // ...
},
detection: {
// order and from where user language should be detected
order: [/*'path', 'session', */ 'querystring', 'cookie', 'header'],
// keys or params to lookup language from
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupHeader: 'accept-language',
lookupSession: 'lng',
lookupPath: 'lng',
lookupFromPathIndex: 0,
// cache user language
caches: false, // ['cookie']
// optional expire and domain for set cookie
cookieExpirationDate: new Date(),
cookieDomain: `${config.Host.hostname.replace(/^https?:\/\//, '')}`,
cookieSecure: true // if need secure cookie
}
});
Then register the middleware:
app.use(
i18nextMiddleware.handle(i18next, {
// options
})
);
And add a custom middleware for setting i18next instance:
app.use((req, res, next) => {
i18next.changeLanguage(req.language);
});
Gathered from documentation at
expressjs.com/en/guide/using-middleware.html
github.com/i18next/i18next
github.com/i18next/i18next-express-middleware

Nuxt - define a const once and which can use across all pages

I'm trying to implement Shopify JS SDK in Nuxt
So this is what I did, a plugin
// plugins/shopify.js
import Vue from 'vue'
import 'isomorphic-fetch'
import Shopify from 'shopify-buy'
export default ({ app }, inject) => {
app.shopify = Shopify.buildClient({
domain: 'aaa.myshopify.com',
storefrontAccessToken: 'aaa'
});
}
nuxt config
//nuxt.config.js
plugins : [{ src : '~/plugins/shopify', ssr: false}]
vendor : ['shopify-buy']
index
asyncData ({ app }) {
return app.shopify.product.fetchAll().then((products) => {
// Do something with the products
console.log(products);
return { products : products }
});
}
The result is
TypeError Cannot read property 'product' of undefined
But it works if I removed the asyncData, refresh my page, and add the code back without refreshing.
I believe this has something to do with the lifecycle.
Can anyone please tell me if I'm doing it the right way, or there's other proper way to define such const which can be use across pages, components etc
And if this is the right way, what I did wrong?
Thanks in advance.
My reference are Nuxt guides as well as examples.
I tried google around but can't locate what I need, or maybe I just didn't get the right keywords.
FROM DOCUMENTATION
Nuxt.js lets you create environment variables that will be shared for
the client and server-side.
To do this, you can use the env property:
nuxt.config.js:
module.exports = {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
}
Then to access it from anywhere, just use it like so:
process.env.baseEnv
For example, in an axios plugin:
import axios from 'axios'
export default axios.create({
baseURL: process.env.baseUrl
})

How to set root/base url for a laravel-vujs project?

I've deployed a VueJS project to a domain like www.example.com/demos/app,
But when I send a request to api from axios it is pointing to www.example.com/login instead of www.example.com/demos/app/login
Here is my request code using axios
export const login = ({ dispatch }, { payload, context }) => {
return axios.post('/login', payload).then((response) => {
// do something
}).catch((error) => {
// handle erros
})
}
One way you could go about this is to add a meta tag to the head of your page (like you may do with the csrf) and then reference it in your bootstrap.js file:
head
<meta name="api-base-url" content="{{ url('demos/app') }}" />
bootstrap.js (underneath window.axios = require('axios');)
window.axios.defaults.baseURL = document.head.querySelector('meta[name="api-base-url"]').content;
Hope this helps!
In config.js:
const CONFIG = {
API_URL_ROOT: 'http://localhost:8000/api/v1/',
}
export default CONFIG;
You can set axios default like this:
import config from '../config.js';
axios.create({
baseURL: config.API_BASE_URL
});
Or you can just set path by importing API_BASE_URL from config and then point it each time you make a get/post/put/delete call using axios
Laravel ships with axios and its imported in bootstrap.js, so simply go to bootstrap.js and add this:
window.axios.defaults.baseURL = 'http://example.test';
You can add this after window.axios.defaults.headers.common line
-Additional information:
axios.create will make an instance that has its own global url and configurations. use this if you have multiple urls or configuration and you want to use it in different components.
Create vue.config.js in Project root directory( if not exist ) -
In vue.config.js -
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/demos/app/'
: '/'
}
Then, Add the line in resources/js/bootstrap.js -
const {publicPath} = require("../../vue.config");
window.axios.defaults.baseURL = publicPath
.env
MIX_APP_URL="${APP_URL}"
resources/js/bootstrap.js
window.axios = require('axios');
window.axios.defaults.baseURL = process.env.MIX_APP_URL;
Update your APP_URL in .env file and add the above code on respective files.

how to write global router-function in nuxt.js

I am using Vue.js with Nuxt.js, but I got a problem in router's functions.
In the pure Vue, i can write in main.js like this:
val route = new Router({
routes:{
[...]
}
})
route.beforeEach(to,from,next){
//do something to validate
}
And how to do the same in nuxt.js ? I can not find any file like main.js.
Also, all i know is to deal with the pages folder to achieve router, I can not set the redirect path
please help, thx :)
You can create a plugin for Nuxt
create a plugins/route.js file:
export default ({ app }) => {
// Every time the route changes (fired on initialization too)
app.router.afterEach((to, from) => {
//do something to validate
})
}
and update your nuxt.config.js file:
plugins: ['~/plugins/route']
More details about Nuxt plugins: https://nuxtjs.org/guide/plugins
If anybody might be still interested, it's possible to setup global middleware in nuxt.config.js like this:
router: { middleware: ['foo'] },
then in your middleware/foo.js you do whatever...
export default function({ route, from, store, redirect }) {}
Beware: You can't use this for static sites (nuxt generate), because middleware is not executed on page load, but only on subsequent route changes. Thanks #ProblemsOfSumit for pointing that out.