Refresh token feature - spartacus-storefront

how can i make refresh token feature work?
I don't see refresh token in local storage, and it is because core doesn't have it in storemodule config
export function authStoreConfigFactory(): StateConfig {
// if we want to reuse AUTH_FEATURE const in config, we have to use factory instead of plain object
const config: StateConfig = {
state: {
storageSync: {
keys: {
'auth.userToken.token.access_token': StorageSyncType.LOCAL_STORAGE,
'auth.userToken.token.token_type': StorageSyncType.LOCAL_STORAGE,
'auth.userToken.token.expires_in': StorageSyncType.LOCAL_STORAGE,
'auth.userToken.token.expiration_time': StorageSyncType.LOCAL_STORAGE,
'auth.userToken.token.scope': StorageSyncType.LOCAL_STORAGE,
'auth.userToken.token.userId': StorageSyncType.LOCAL_STORAGE,
},
},
},
};
return config;
}
What is the correct way to use it?

Refresh token was deliberately omitted in default storage synchronization configuration for security reasons.
However, if you need that you can always provide your own storage synchronization configuration like in the example below. It will not override default configuration, but it will be combined with it. To exclude something from default configuration you can use excludeKeys similarly to keys property in storageSync configuration.
import { NgModule } from "#angular/core";
import { BrowserModule } from "#angular/platform-browser";
import { translationChunksConfig, translations } from "#spartacus/assets";
import { ConfigModule, StateConfig, StorageSyncType } from "#spartacus/core";
import { B2cStorefrontModule } from "#spartacus/storefront";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
export function refreshTokenConfigFactory(): StateConfig {
const config: StateConfig = {
state: {
storageSync: {
keys: {
"auth.userToken.token.refresh_token": StorageSyncType.LOCAL_STORAGE
}
}
}
};
return config;
}
#NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
B2cStorefrontModule.withConfig({
backend: {
occ: {
baseUrl: "http://localhost:9002",
prefix: "/rest/v2/"
}
},
context: {
baseSite: ["electronics-spa"]
},
i18n: {
resources: translations,
chunks: translationChunksConfig,
fallbackLang: "en"
},
features: {
level: "1.5",
anonymousConsents: true
}
}),
ConfigModule.withConfigFactory(refreshTokenConfigFactory),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}

Related

ngx-toastr.js?4996:264 Uncaught TypeError: Object(...) is not a function at eval (ngx-toastr.js?4996:264)

I am using ngx-toastr in angular 6 for http error notification, as injected ToastrService in httpInterceptor
export class MyInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
tap((evt: any) => {
if (evt instanceof HttpResponse) {
if (evt.body)
this.toasterService.success('success', '!!', { positionClass: 'toast-bottom-center' });
//alert(`success`);
}
}),
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
try {
this.toasterService.error(err.error.message, err.error.title, { positionClass: 'toast-bottom-center' });
} catch (e) {
this.toasterService.error('An error occurred', '', { positionClass: 'toast-bottom-center' });
}
//log error
}
return of(err);
})
)
}
}
and imported ToastrModule in app.module.ts like
imports:[
ToastrModule.forRoot()
]
I am getting below error, any idea whats going wrong here..............
ngx-toastr.js?4996:264 Uncaught TypeError: Object(...) is not a
function
at eval (ngx-toastr.js?4996:264) .................................
I found the actual issue regarding this. It's happening because of the mismatch of the version of an angular and the package. To overcome this problem perform the following steps
STEP1: Check for angular CLI version: ng --version
Now check this image
If your angular version is 7.3.10 then you need to install 10.1.0 version of ngx-toastr
STEP2: Install a specific version of ngx-toastr according to your angular CLI version: npm i ngx-toastr#10.1.0 --save
STEP3: import it into app.module.ts
app.module.ts
import { CommonModule } from '#angular/common';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
#NgModule({
imports: [
CommonModule,
BrowserAnimationsModule, // required animations module
ToastrModule.forRoot() // ToastrModule added
],
bootstrap: [App],
declarations: [App]
})
export class AppModule {}
STEP4: add css path in styles array in angular.json file
angular.json
"styles": [
"node_modules/font-awesome/css/font-awesome.css",
"src/styles/app.scss",
"node_modules/sweetalert2/dist/sweetalert2.min.css",
"node_modules/ngx-toastr/toastr.css"
]
Don't forget to restart your server after making changes in angular.json file
STEP5: make helper service to show toasters
helper.service.ts
import { Injectable } from '#angular/core';
import { ToastrService } from 'ngx-toastr';
#Injectable({
providedIn: 'root'
})
export class HelperService {
constructor(private toastr: ToastrService) { };
showSuccessToast(msg) {
this.toastr.success(msg);
}
showErrorToast(msg) {
this.toastr.error(msg);
}
showInfoToast(msg) {
this.toastr.info(msg);
}
}
STEP6: Now you are done you just need to use these functions in your component.ts file
user.component.ts
import { Component, OnInit } from '#angular/core';
import { routerTransition } from '../../router.animations';
import { UserService } from './user.service';
import { HelperService } from 'src/app/helpers/helper.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss'],
animations: [routerTransition()]
})
export class UserComponent implements OnInit {
constructor(
private userService: UserService,
private helperService: HelperService,
) {
}
ngOnInit() {
this.getUsers();
}
async getUsers() {
try {
const res: any = await this.userService.getUsers();
this.helperService.showSuccessToast(res.message);
} catch (err) {
this.helperService.showErrorToast(err.error || 'Something went wrong');
}
}
}

Failed connection handshake and 500 error when refreshing page - Abp Zero with Angular and .Net Core

When I log into the application, angular changes the ulr to https://baseurl/app/home and the home page renders correctly. If I refresh the page I get a server (500) error. if I remove the /app/home part in the address bar and refresh, the page reloads without issues.
In the logs on the server side I find this:
Fail: Microsoft.AspNetCore.SignalR.HubConnectionContext[5]
Failed connection handshake.
I am running the angular client and the .net core application on two different servers, and CORS is set up correctly and the client app is able to connect to the api. The app works fine except when i refresh a page with an angular route.
The problem does not occur when I run the application locally on my development machine.
I have not changed any routing or signalr related code in the original Abp Zero template.
On server:
.NetCore 2.2
Abp Zero v 4.8
services.AddSignalR() is called in the startup.cs file and
app.UseSignalR(routes =>
{
routes.MapHub("/signalr");
});
is also called in the startup.cs file from the Configuration method. All this is standard tempate code.
In Angular client:
#aspnet/signalr v 1.1.4
The unchanged SignalRAspNetCoreHelper of which the initSignalR() is called in OnInit in the app.component.ts file:
import { AppConsts } from '#shared/AppConsts';
import { UtilsService } from '#abp/utils/utils.service';
export class SignalRAspNetCoreHelper {
static initSignalR(): void {
const encryptedAuthToken = new UtilsService().getCookieValue(AppConsts.authorization.encrptedAuthTokenName);
abp.signalr = {
autoConnect: true,
connect: undefined,
hubs: undefined,
qs: AppConsts.authorization.encrptedAuthTokenName + '=' + encodeURIComponent(encryptedAuthToken),
remoteServiceBaseUrl: AppConsts.remoteServiceBaseUrl,
startConnection: undefined,
url: '/signalr'
};
jQuery.getScript(AppConsts.appBaseUrl + '/assets/abp/abp.signalr-client.js');
}
}
The app-routing.module.ts is also unchanged:
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { AppRouteGuard } from '#shared/auth/auth-route-guard';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { UsersComponent } from './users/users.component';
import { TenantsComponent } from './tenants/tenants.component';
import { RolesComponent } from 'app/roles/roles.component';
import { ChangePasswordComponent } from './users/change-password/change-password.component';
#NgModule({
imports: [
RouterModule.forChild([
{
path: '',
component: AppComponent,
children: [
{ path: 'home', component: HomeComponent, canActivate: [AppRouteGuard] },
{ path: 'users', component: UsersComponent, data: { permission: 'Pages.Users' }, canActivate: [AppRouteGuard] },
{ path: 'roles', component: RolesComponent, data: { permission: 'Pages.Roles' }, canActivate: [AppRouteGuard] },
{ path: 'tenants', component: TenantsComponent, data: { permission: 'Pages.Tenants' }, canActivate: [AppRouteGuard] },
{ path: 'about', component: AboutComponent },
{ path: 'update-password', component: ChangePasswordComponent }
]
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule { }
root-routing.module.ts (also unchanged):
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/app/home', pathMatch: 'full' },
{
path: 'account',
loadChildren: 'account/account.module#AccountModule', // Lazy load account module
data: { preload: true }
},
{
path: 'app',
loadChildren: 'app/app.module#AppModule', // Lazy load account module
data: { preload: true }
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class RootRoutingModule { }
Any ideas as to what is wrong? As I haven't changed anything, I wonder if the issue is with the environments/configurations?
in case anyone stumbled upon this question:
The problem does not occur when I run the application locally on my development machine.
The problem is related to the production server, the request is not being forwarded into your angular application properly
IIS
basically you need to install the url-rewrite and then configure a web.config file for the front-end site web.config configuration link 1 link 2
Apachi
link 1 link 2

Nativescript angular - module that contains dataform exits in ios without error! lazy loading module

I am developing nativescript-angular app that contains dataform in a module and calling this module using in lazy loading technique. Life is beautiful in Android, but the application exits immediately when I open this module in ios wihtout any error log!
The code is very simple and forward, I can't see where is the problem!
test.component.ts
import { Component, OnInit } from "#angular/core";
import { ActivatedRoute } from "#angular/router";
import { RadDataForm, DataFormEventData } from "nativescript-ui-dataform";
import { UserAddress } from "../../shared/data-services/address";
#Component({
selector: "test",
moduleId: module.id,
templateUrl: "./test.component.html",
styleUrls:["./test.component.css"]
})
export class TestComponent implements OnInit {
private _userAddress: UserAddress;
constructor() {
}
ngOnInit() {
this._userAddress = new UserAddress();
}
get userAddress(): UserAddress {
return this._userAddress;
}
}
test.component.html
<ActionBar class="action-bar">
<NavigationButton [nsRouterLink]="['../../home']" android.systemIcon="ic_menu_back"></NavigationButton>
<Label class="action-bar-title" text="Test"></Label>
</ActionBar>
<ScrollView tkExampleTitle tkToggleNavButton>
<StackLayout>
<RadDataForm tkExampleTitle tkToggleNavButton [source]="userAddress">
</RadDataForm>
</StackLayout>
</ScrollView>
Routing of this module
signup-routing.module.ts
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { ItemsComponent } from "./test/test.component";
export const COMPONENTS = [ItemsComponent ];
const routes: Routes = [
{ path: "", redirectTo: "testInfo" },
{ path: "testInfo", component: testComponent }
];
#NgModule({
imports: [NativeScriptRouterModule.forChild(routes)], // set the lazy loaded routes using forChild
exports: [NativeScriptRouterModule]
})
export class SignupRoutingModule {}
Then we have
signup.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { COMPONENTS, SignupRoutingModule } from "./signup-routing.module";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { NativeScriptUIDataFormModule } from "nativescript-ui-dataform/angular";
#NgModule({
imports: [
NativeScriptCommonModule, // for rednering actionbar with lazy laoding
NativeScriptFormsModule,
SignupRoutingModule,
NativeScriptUIDataFormModule
],
declarations: [
...COMPONENTS
],
// providers: [SignupService],
schemas: [
NO_ERRORS_SCHEMA
]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class SignupModule { }
And the module is called using lazy loading in the basic routing file like this:
{ path: "signup", loadChildren: "~/app/signup/signup.module#SignupModule", outlet: "homeTab" }
Help is appreciated!
CODE ON GitHub
https://github.com/lighttiger/lazy

Error: StaticInjectorError(DynamicTestModule) Angular 5 Karma Jasmine 2.8.0

My app is working fine but while i am trying to perform unit testing i am getting below mentioned error :
Error: StaticInjectorError(DynamicTestModule)[AppComponent ->
FinanceserviceService]: StaticInjectorError(Platform:
core)[AppComponent -> FinanceserviceService]:
NullInjectorError: No provider for FinanceserviceService!
My codes are given below :
financeservice.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import 'rxjs/add/operator/map';
#Injectable()
export class FinanceserviceService {
constructor(private _http: HttpClient) { }
finData() {
return this._http.get("./assets/data.json")
.map(result => result);
}
}
test.spec.ts
import { TestBed, inject,async,ComponentFixture } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { FinanceserviceService } from './financeservice.service';
import { AppComponent } from './XXXX.component';
import { SliderModule } from 'angular-image-slider';
import { CUSTOM_ELEMENTS_SCHEMA,NO_ERRORS_SCHEMA } from '#angular/core';
import 'rxjs/add/operator/map';
describe('FinanceserviceService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [FinanceserviceService],
schemas: [
CUSTOM_ELEMENTS_SCHEMA,
NO_ERRORS_SCHEMA
]
});
});
it(`should create`, async(inject([HttpTestingController, FinanceserviceService],
(httpClient: HttpTestingController, financeservice: FinanceserviceService) => {
expect(financeservice).toBeTruthy();
})));
});
*.component.ts
import { Component } from '#angular/core';
import { FinanceserviceService } from './financeservice.service';
import { Chart } from 'chart.js';
constructor(private _fin: FinanceserviceService){
}
ngOnInit() {
this._fin.finData()
.subscribe(res => {
let Fmax = res['list'].map(res => res.main.temp_max);
let Fmin = res['list'].map(res => res.main.temp_min);
let alldates = res['list'].map(res => res.dt)
let FDates = []
alldates.forEach((res) => {
let jsdate = new Date(res * 1000)
FDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
})
this.chart=new Chart('canvas',{
type: 'line',
data: {
labels: FDates,
datasets: [
{
data: Fmax,
borderColor: "#3cba9f",
fill: false
},
{
data: Fmin,
borderColor: "#ffcc00",
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}],
}
}
})
})
}
*.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
import { FinanceserviceService } from './financeservice.service';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { AppComponent } from './XXX.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { SliderModule } from 'angular-image-slider';
import { CommonModule } from '#angular/common';
import { NO_ERRORS_SCHEMA } from '#angular/core';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
SliderModule,
],
schemas: [NO_ERRORS_SCHEMA],
providers: [FinanceserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
Kindly help

Angular 2 error after authentication - Cannot find primary outlet to load

I have an error in console after authentication. After reload page CreateChartComponent page start working. Error just happen in authentication process.
Uncaught (in promise): Error: Cannot find primary outlet to load 'CreateChartComponent'
This is the login function.
login(event, username, password): void {
event.preventDefault();
this.authService.login(username, password).subscribe(
res => {
this.router.navigate(['drawing']);
},
err => {
// todo: handle error with a lable
console.log(err);
if (err.ok === false) {
this.errorMessage = 'Error logging in.';
}
});
}
}
Aditional information:
I send clear mode of code where I get same issue.
It's Router code:
// Import our dependencies
import { Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './home/login/login.component';
import { CreateChartComponent } from './home/drawing/create-chart.component';
import { AuthGuard } from './auth.guard';
// Define which component should be loaded based on the current URL
export const routes: Routes = [
{ path: '', component: CreateChartComponent, pathMatch: 'full', canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: 'drawing', component: CreateChartComponent, canActivate: [AuthGuard] },
];
and its create-chart.component.ts
import {
Component,
OnInit,
} from '#angular/core';
#Component({
selector: 'np-chart-create',
templateUrl: './create-chart.component.html',
styleUrls: ['./create-chart.component.css']
})
export class CreateChartComponent implements OnInit {
ngOnInit() {
}
}