Angular2 - Nebular theme API endpoints - api

I am developing application under Angular2 and I choose Nebular frontend - https://akveo.github.io/nebular/#/home
Documentation is not really detailed for me and I am not expert in Angular2.
I am struggling in part - API endpoints https://akveo.github.io/nebular/#/docs/auth/configuring-a-provider
Where I can save the API basepoint? In which file or part of file?
Affected code:
{
baseEndpoint: 'http://...
...
My code (core.module.js):
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '#angular/core';
import { CommonModule } from '#angular/common';
import { NbEmailPassAuthProvider, NbAuthModule } from '#nebular/auth';
import { throwIfAlreadyLoaded } from './module-import-guard';
import { DataModule } from './data/data.module';
import { AnalyticsService } from './utils/analytics.service';
import { environment } from './../../environments/environment';
const NB_CORE_PROVIDERS = [
...DataModule.forRoot().providers,
...NbAuthModule.forRoot({
providers: {
email: {
service: NbEmailPassAuthProvider,
config: {
delay: 3000,
login: {
rememberMe: true,
},
},
},
},
forms: {
validation: {
password: {
required: true,
minLength: 6,
maxLength: 255,
},
email: {
required: true,
}
}
}
}).providers,
AnalyticsService
];
#NgModule({
imports: [
CommonModule,
],
exports: [
NbAuthModule,
],
declarations: [],
})
export class CoreModule {
constructor(#Optional() #SkipSelf() parentModule: CoreModule) {
throwIfAlreadyLoaded(parentModule, 'CoreModule');
}
static forRoot(): ModuleWithProviders {
return <ModuleWithProviders>{
ngModule: CoreModule,
providers: [
...NB_CORE_PROVIDERS,
],
};
}
}

I'm trying to put it to work and i'm at the same part of the manual.
As i could understand, the baseEndpoint: 'http://... thing and others configuration goes on the authentication provider config variable. Looks like it's of the type NgEmailPassAuthProviderConfig (defined on #nebular/auth/providers/email-pass-auth.options).
#NgModule({
imports: [
// ...
NbAuthModule.forRoot({
providers: {
email: {
service: NbEmailPassAuthProvider,
config: {
baseEndpoint: 'http://localhost:8080', // <-- here
login: {
rememberMe: true,
},
},
},
},
}),
],
});
I already managed to put it to call a api method on a Spring rest API. I can see the HttpResponse on browser with status: 200 but still getting "Oh snap!
Something went wrong." message on the NbLoginComponent.

In order to create the api correctly follow these steps
1) implement this on your localhost :
2) add this code to core.module.ts
strategies: [
NbPasswordAuthStrategy.setup({
name: 'email',
login: {
requireValidToken: false,
},
baseEndpoint: 'http://localhost:4400/api/auth/',
logout: {
redirect: {
success: '/auth/login',
failure: '/auth/login',
},
},
requestPass: {
redirect: {
success: '/auth/reset-password',
},
},
resetPass: {
redirect: {
success: '/auth/login',
},
},
errors: {
key: 'data.errors',
},
}),
],

I propose to create a proxy proxy.conf.json in the root of the project with content
{
   "/api/*": {
     "target": "http://localhost",
     "secure": false,
     "logLevel": "debug"
   }
}
then start the angular application with the command
$ ng serve --port 8097 --proxy-config proxy.conf.json
remember the * 8097 * port you mentioned in the ng serve command
to finish adding your base url as follows:
{
baseEndpoint: '/api/',
...
for more information about proxy config refer you to https://morioh.com/p/07bddb33e3ab
I hope this help

Related

PWA (Workbox) When User get Online, network error (failed) apis not getting call on iphones

I'm building web app which is pwa which is cached the data to serve offline as well as it also cached the network error api requests and whenever user get online it run those apis to up to date the DB.
Application is Progressive Web App (PWA), Its built with Javascript framework Vuejs. Additional we used the workbox for recall the network failed apis functionality, these workbox functionality working on all devices except on iPhone.
I've attached the vue.config.js file which has the config of workbox, Please let me know what I can do to fix the error on iPhone.
Your help will be very appreciated!
Filename: Vue.config.js
configureWebpack: {
entry: ['babel-polyfill', './src/main.js'],
},
pwa: {
workboxPluginMode: 'GenerateSW',
workboxOptions: {
navigateFallback: '/index.html',
skipWaiting: true,
runtimeCaching: [
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
handler: 'networkOnly',
options: {
cacheName: 'api',
},
},
{
^https:\/\/api\.dev\.firststep\.zinpro\.cn\/apiPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'POST',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'new-tasks-queue-0',
options: {
maxRetentionTime: 24 * 60, // 24 hr
},
},
},
},
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'DELETE',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'delete-tasks-queue-1',
options: {
maxRetentionTime: 24 * 60, // minutes
},
},
},
},
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'GET',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'new-tasks-queue-2',
options: {
maxRetentionTime: 24 * 60, // minutes
},
},
},
},
],
},
themeColor: '#000000',
iconPaths: {
favicon32: 'icons/ZinproFavicon32x32.png',
favicon16: 'icons/ZinproFavicon32x32.png',
appleTouchIcon: 'icons/Zinpro_App_Icon_192x192.png',
maskIcon: 'icons/safari-pinned-tab.svg',
msTileImage: 'icons/Zinpro_App_Icon_192x192.png',
},
},
}

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!

Problem implementing nuxtjs/auth using local strategy

I'm following a nuxtjs tutorial and I'm having issues implementing nuxtjs/auth loginWith. It is pretty straightforward but I don't know why it doesn't work for me. tested with postman and the API responds with a token;
Everything looks okay, saves the token to cookies and local storage. Signup also works but it doesn't login. When I inspect with Vue dev tools, it shows login false and the user undefined when I'm expecting a user object. What could be wrong?
As it is, here's the method for Login.vue
async onLogin() {
try {
this.$auth.loginWith("local", {
data: {
email: this.email,
password: this.password
}
});
this.$router.push("/");
} catch (err) {
console.log(err);
}
}
here's also my nuxt.config.js
const URL = 'http://localhost:3000'
export default {
/*
** Nuxt rendering mode
** See https://nuxtjs.org/api/configuration-mode
*/
mode: 'universal',
/*
** Nuxt target
** See https://nuxtjs.org/api/configuration-target
*/
target: 'server',
/*
** Headers of the page
** See https://nuxtjs.org/api/configuration-head
*/
head: {
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: '/css/font-awesome/css/all.css' },
{ rel: 'stylesheet', href: '/css/default.css' }
]
},
/*
** Global CSS
*/
css: [],
/*
** Plugins to load before mounting the App
** https://nuxtjs.org/guide/plugins
*/
plugins: [],
/*
** Auto import components
** See https://nuxtjs.org/api/configuration-components
*/
components: true,
/*
** Nuxt.js dev-modules
*/
buildModules: [],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://bootstrap-vue.js.org
'bootstrap-vue/nuxt',
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
'#nuxtjs/pwa',
'#nuxtjs/auth',
// Doc: https://github.com/nuxt/content
// '#nuxt/content',
],
/*
**Axios Module config
** See https://axios.nuxtjs.org/options
*/
axios: {
proxy: true,
baseURL: URL
},
proxy: {
"/api": URL
},
/*
** Build configuration
** See https://nuxtjs.org/api/configuration-build/
*/
build: {
extend(config, ctx) {}
},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: "/api/auth/login",
method: "post",
propertyName: "token"
},
user: {
url: "/api/auth/user",
method: "get",
propertyName: "token"
},
logout: true
}
}
}
}
};
Try this:
auth: {
strategies: {
local: {
endpoints: {
login: {
url: "/api/auth/login",
method: "post",
propertyName: "data.token"
},
user: {
url: "/api/auth/user",
method: "get",
propertyName: "data.user"
},
logout: true
}
}
}
}
As the response from the api is received inside data, when axios is used.
Okay Somehow, it only updates the after I refresh the entire browser. I thought the Hot reloading would suffice but it works. this is my auth strategies setup
auth: {
strategies: {
local: {
endpoints: {
login: {
url: "/api/auth/login",
method: "post",
propertyName: "data.token"
},
user: {
url: "/api/auth/user",
method: "get",
propertyName: "data.user"
},
logout: true
}
}
}
}
Thanks to all that commented. It has helped my confidence and problem solving ability.

How do I configure the Core module without using the store module?

Below are our current configurations. How would we configure, backend, authentication, context without going through storeConfig?
B2cStorefrontModule.withConfig(environment.storeConfig), ConfigModule.withConfigFactory(defaultCmsContentConfig),
storeConfig: {
backend: {
occ: {
baseUrl: 'https://localhost:9002',
prefix: '/mywebservices/v2/'
}
},
authentication: {
client_id: 'myid',
client_secret: 'mysecret'
},
context: {
baseSite: ['mysite'],
currency: ['USD'],
},
i18n: {
resources: translations,
chunks: translationChunksConfig,
fallbackLang: 'en'
}
},
You can import provideConfig from #spartacus/core and use it like this:
#NgModule({
...
imports: [
...
provideConfig({
// your config goes here
backend: {
occ: {
baseUrl: 'https://localhost:9002',
prefix: '/mywebservices/v2/'
}
},
authentication: {
client_id: 'myid',
client_secret: 'mysecret'
},
}),
]
...
})
You can have as many provideConfig() as you want.

How to resolve Apollo error 401 accessing DatoCMS

I followed this guide:
https://medium.com/#marcmintel/quickly-develop-static-websites-with-vuejs-a-headless-cms-and-graphql-bf64e75910d6
but when I run npm run dev I get error 401 on my localhost:3000
this is my nuxt.config.js
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'hello-world',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
modules: [
'#nuxtjs/apollo',
],
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.datocms.com',
getAuth: () => 'Bearer XXXXXXXXXXXXX' //my apikey
}
}
}
}
And this is the vue file performing the query. I'm currently displaying nothing in the page but I still get the error.
<template>
<div>
All blog posts
</div>
</template>
<script>
import gql from 'graphql-tag'
export default {
apollo: {
allPosts: gql`{
allPosts{
title,
text,
slug
}
}`
}
}
</script>
The post data type is correctly defined in DatoCMS, I tested it with the API Explorer
Found the solution in the comments of the article.
You need to put your auth in a separate file like this and format it as follows:
~/apollo/config.js
export default function(context){
return {
httpEndpoint: ‘https://graphql.datocms.com',
getAuth:() => ‘my-token’ //Bearer is added by default
}
}
Then in nuxt.config.js
apollo:
apollo: {
clientConfigs: {
default: ‘~/apollo/config.js’
}
}