angular-meteor.auth resolve to a blank page - angularjs

I'm trying to authenticate the user before the view, in this case dashboard, gets rendered.
If the user is logged in, then your good to go, but if not, redirect to login state.
This is my controller:
import angular from 'angular';
import angularMeteor from 'angular-meteor';
import uiRouter from 'angular-ui-router';
import angularMeteorAuth from 'angular-meteor-auth';
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { name as navBar } from '../navBar/navBar';
import './dashboard.html';
class dashboardCtrl {
constructor($scope) {
'ngInject';
if (Meteor.user()) {
console.log('logged in ', Meteor.user());
} else {
console.log('not logged in or error');
}
}
}
const name = 'dashboard';
export default angular.module(name, [
angularMeteor,
uiRouter,
navBar,
angularMeteorAuth
])
.component(name, {
templateUrl: `imports/ui/components/${name}/${name}.html`,
controller: dashboardCtrl,
})
.config(function($stateProvider, $urlRouterProvider) {
'ngInject';
$stateProvider
.state('dashboard', {
url: '/dashboard',
template: '<dashboard></dashboard>',
resolve: {
user: function($auth, $state){
return $auth.requireUser().then(function(){
return true;
}, function(err){
$state.go('login');
});
}
}
})
})
This works fine if the user is not logged in, it will redirect to login normally, but when the user is indeed logged in and you try to refresh in dashboard it returns a blank screen/page with no console logs or errors or anything.
How can I solve this?
Thanks!

Related

redirect user if the already logged in ionic

I want to redirect logged in user if the comeback to my app the will redirected to home not to log in page.
in my login function like this
login(){
this.googlePlus.login({
'webClientId' : '927898787134-spvfdmvm9apq0e1fo2efvvura8vqpid8.apps.googleusercontent.com',
'offile' : true
}).then(res=>{
firebase.auth().signInWithCredential(firebase.auth.GoogleAuthProvider.credential(res.idToken))
.then(suc=>{
// console.log('users', JSON.stringify(suc));
localStorage.setItem('user', JSON.stringify(suc));
this.router.navigate(["/tabs/home"]);
}).catch(ns=>{
alert('Unsucessful');
})
})
}
i have user data in my localStorage, i think i can check whether the user token is exist on localStorage or not. but when i try this in my login page
ionViewWillEnter() {
firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
console.log("user is not logged in");
} else {
console.log("user is logged in");
this.router.navigateByUrl('/tabs/home');
return;
}
});
}
it doesn't redirected to home, did anyone know exactly how to do that?
after trying to insert to app.component.ts my code like this
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.overlaysWebView(true);
this.statusBar.show();
firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
console.log("user is not logged in");
} else {
console.log("user is logged in");
this.router.navigateByUrl('/home');
return;
}
});
});
}
above code give me this error
heres my app-routing.module
const routes: Routes = [
{
path: '',
loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
},
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{ path: 'welcome', loadChildren: './welcome/welcome.module#WelcomePageModule' },
{ path: 'settings', loadChildren: './settings/settings.module#SettingsPageModule' }
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule {}
try to put it in app.component.ts after constractor() { here your code }

integrated angularjs service

hello every one I had a problem, I create my Ticketservice. this file and I try to add it to the home.ts file but it gives me an error
tickerServices.ts
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root',
})
export class TicketService{
result:any;
constructor(public http: HttpClient) { }
getTicket(){
var CronJob = require('cron').CronJob;
var id=this.formulaire.id;
new CronJob('* * * * * *', function(){
const http = require('http');
console.log('You will see this message every second');
/* this.url+'/'*/
http.get('http://localhost:8888/'+id+'/notif', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
this.resulta=data;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}, null, true, 'America/Los_Angeles');
}
}
home.ts
import {Component} from "#angular/core";
import {NavController, PopoverController,NavParams} from "ionic-angular";
import { HttpClient } from '#angular/common/http';
import { TicketService } from '../services/ticketservice'
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public search = {
date: new Date().toISOString()
}
constructor(public nav: NavController,public http: HttpClient,public popoverCtrl: PopoverController ,public tikSer:TicketService) {
}}
when I test it, he gives me undefined ".. /services/ticketservice"
Add it like this
import { TicketService } from '../../services/ticketservice'

ionic error while getting data from woocommerece api

I am not able to spot what I am doing wrong. I have installed the woocommerce node package, and i have checked the rest api with the help postman app.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
WooCommerce: any;
constructor(public navCtrl: NavController) {
this.WooCommerce = WC({
url: "http://localhost/wordpress",
consumerKey: ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
consumerSecret: cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
});
this.WooCommerce.getAsync("products").then((data)=>{
console.log(data);
}, (err)=>{
console.log(err)
})
}
}
Screenshot of the error:
Change
this.WooCommerce = WC({
url: "http://localhost/wordpress",
consumerKey: ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
consumerSecret: cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
});
to
this.WooCommerce = WC({
url: "http://localhost/wordpress",
consumerKey: "ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
consumerSecret: "cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
Notice the quotes.

history.replace not working from 'history/createBrowserHistory' with Auth0

I am trying to redirect a user using history.replace('/user') in my application, but when I do it does nothing. I am using Auth0 and following their guide:
https://auth0.com/docs/quickstart/spa/react/01-login
When I redirect after login it shows /user in the url but nothing happens, I stack on the callback component. Even more than that if I hit logout which should redirect to the user component it does not work either. It just shows the /user in the browser and does not actually take them to the page.
import auth0 from 'auth0-js';
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
export default class Auth {
constructor() {
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.handleAuth = this.handleAuth.bind(this);
this.isAuth = this.isAuth.bind(this);
}
auth0 = new auth0.WebAuth({
domain: 'taustin.auth0.com',
clientID: 'IL1cmtElngJNYF3Ncjpt3pCRA5NFIDZw',
redirectUri: 'http://localhost:3000/callback',
audience: 'https://taustin.auth0.com/userinfo',
responseType: 'token id_token',
scope: 'openid'
});
handleAuth() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
// redirect user to home page
history.replace('/user');
} else if (err) {
// redirect user to home page with error
history.replace('/user');
}
});
}
setSession(authResult) {
// Set how long the access token will last
let expiresAt = JSON.stringify(
authResult.expiresIn * 1000 + new Date().getTime()
);
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('expires_at', expiresAt);
// redirect user to home page or desired page
history.replace('/user');
}
logout() {
// Clear Access Token and ID Token from local storage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
// navigate to the home route
history.replace('/user');
}
isAuth() {
// Check whether the current time is past the
// Access Token's expiry time
// If not expires at exist should automatically return false
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
login() {
this.auth0.authorize();
}
}
I think this should solve your problem.
import React, {Component} from 'react';
import { Router } from 'react-router';
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
class App extends Component {
render(){
return (
<Router history={history}> //pass in your custom history object
// your routes come here
<Router />
)
}
}

Angular UI Router Transition HookMatchCriteria not working

My run block is as follows:
angular.module('app', [...]).run(['$transitions', '$state', 'EmployeeService', ($transitions, $state, EmployeeService) => {
$transitions.onBefore(
{ to: 'app.*' },
() => EmployeeService.checkAuth().then(() => {
console.log("run success");
},
() => {
console.log("run caught");
return $state.target('login');
}),
{priority: 10}
);
}])
And for some reason it executes for states 'app' and 'login' though they don't match 'app.*' match criteria, and thus it brings me to infinite loop when performing the logout. What is the right syntax to specify the match criteria ? I've already looked here:
https://ui-router.github.io/ng1/docs/latest/interfaces/transition.hookmatchcriteria.html
Edit: Posting routes configurations as requested
Routes for the main module (includes 'app' state which shouldn't fire the auth check):
export default mainPageRoutesConfig;
function mainPageRoutesConfig($stateProvider, $urlRouterProvider, $locationProvider) {
"ngInject";
$locationProvider.html5Mode(true).hashPrefix('!');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('app', {
url: '/',
component: 'main'
})
.state('app.timesheet', {
url: 'timesheet',
component: 'timesheet'
})
.state('app.saveHours', {
url: 'saveTaskHours',
component: 'saveTaskHours',
params: {
timesheet:null
}
})
}
Routes for the employee module (includes 'login' state which shouldn't fire the auth check as well):
export default employeesRoutesConfig;
function employeesRoutesConfig($stateProvider, $urlRouterProvider, $locationProvider) {
"ngInject";
$locationProvider.html5Mode(true).hashPrefix('!');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login', {
url: 'login',
component: 'login'
})
.state('app.employeesList', {
url: 'employees',
component: 'employeesList'
})
.state('app.saveEmployee', {
url: 'employee/?Id',
component: 'saveEmployee'
})
.state('app.deleteEmployee', {
url: 'employee/:Id',
component: 'deleteEmployee'
})
.state('app.employeePage', {
url: 'profile/:Id',
component: 'employeePage'
})
}
The solution (though not really an answer) was to specify match criteria as a function:
{
to: function(state) {
return state.name !== 'app.login' && state.name !== 'app.error';
}
}
And the full code (after moving to separate file):
export default ($transitions, $state, EmployeeService) => {
$transitions.onBefore(
{
to: function(state) {
return state.name !== 'app.login' && state.name !== 'app.error';
}
},
() => EmployeeService.checkAuth().then(() => {
console.log("run block. Authorization check succeeded");
},
() => {
console.log("run block. Authorization check failed");
return $state.target('app.login');
}),
{priority: 10}
);
}])

Resources