Im fairly new to Angular 2 and i have got a question.
In my "older" Angular 1 Webapps i had a "Api-Service" and a "Http-Service" every time.
They looked like this:
"ApiService":
angular.module('ionicApp.apiServices', [])
.service('apiService', function(httpService) {
return {
getProfile: function(){
return httpService.async('get', 'profile', {}, {}, {});
},
addSkills: function(skillList) {
var url = 'profile/skills';
return httpService.async('post', url, {}, {}, skillList);
}
}
HTTP-Service:
angular.module('ionicApp.httpService', [])
.service('httpService', function ($http, $rootScope, $state, $ionicLoading, $ionicHistory) {
var httpCall = {
async : function (method, url, header, params, data) {
// Setze den X-AUTH-TOKEN in den Header, welcher für die Authentifizierung des Users verantwortlich ist
if (url != 'login' || url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
header['X-AUTH-TOKEN'] = $rootScope.userToken;
}
header['Access-Control-Allow-Origin'] = '*';
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http({
method : method,
url : ipurl + url,
headers : header,
params : params,
data : data,
timeout: 10000,
withCredentials : true
}).then(function successCallback(response) {
if (url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
$rootScope.userToken = response.headers('X-AUTH-TOKEN');
}
return response;
}, function errorCallback(response) {
if (response.status === 401) {
$rootScope.isFailure = true;
$rootScope.failure = "Sie haben keine gültige Session mehr. Bitte loggen Sie sich erneut ein.";
doLogout();
} else {
return response;
}
});
// Return the promise to the controller
return promise;
},
doLogout : doLogout
};
return httpCall;
});
Ok, now my question is, how can i do this with angular 2?
I already did an Api-Service and an HTTP-Service (both are Injectables), and injected them in each component.
But what´s the trick to get them functional?
Thanks so much!
Related
I have a loader function called getBlogData which is like this:
import { getFromCacheOrApi } from 'Base'
const getBlogData = async () => {
const { pathname } = { pathname: "" }
var url = '/blog/data?'
let matches = /\/blog(\/\d+)?\/?$/.exec(pathname)
if (matches != null) {
const pageNumber = matches[1]
if (pageNumber !== undefined) {
url += `&pageNumber=${pageNumber.replace('/', '')}`
}
}
else {
const secondSegments = ['category', 'tag', 'author', 'search']
if (pathname.split('/').length >= 2 && !secondSegments.includes(pathname.split('/')[2])) {
response.status = 404
return
}
for (let i = 0; i < secondSegments.length; i++) {
const segment = secondSegments[i]
if (pathname.startsWith(`/blog/${segment}`)) {
matches = new RegExp(`(?<=\\/blog\\/${segment}\\/)[^/]+\\/?(\\d+)?\\/?$`).exec(pathname)
if (matches == null) {
response.status = 404
return
}
else {
url += `&${segment}=${encodeURI(matches[0].split('/')[0])}`
const pageNumber = matches[1]
if (pageNumber !== undefined) {
url += `&pageNumber=${pageNumber}`
}
break
}
}
}
}
url = url.replace('?&', '?')
const data = await getFromCacheOrApi(url)
// console.log(params, response.status)
// if (pageNumber && isNaN(pageNumber)) {
// console.log(pageNumber, isNaN(pageNumber))
// response.status = 400
// return
// }
const { seoParameters } = data
return data
}
export default getBlogData
This function is only used in my page which is inside app directory in Next 13, which means that it's a server component, and I don't want to change it to a client component.
However, I need to access request data, in this particular case, the path of the URL.
How can I get that?
ok so im having issues with axios, im getting 401 unauthorized for something that worked perfectly fine.
for some reason my token is added to the Authorization header but i cant access a page i could just yesterday.
as you can see here -
also the token is saved in the localstorage -
encryption-util -
function issueJWT(user) {
const { _id } = user;
const expiresIn = 24 * 60 * 60 * 1000; // 1 day
const payload = {
sub: _id,
iat: Date.now(),
};
const signedToken = jsonwebtoken.sign(payload, PRIV_KEY, {
expiresIn,
algorithm: "RS256",
});
return {
token: `Bearer ${signedToken}`,
expires: expiresIn,
};
}
function authMiddleware(req, res, next) {
let tokenParts = " ";
if (typeof req.headers.authorization === "string") {
tokenParts = req.headers.authorization.split(" ");
}
if (
tokenParts[0] === "Bearer" &&
tokenParts[1].match(/\S+\.\S+\.\S+/) !== null
) {
try {
const verification = jsonwebtoken.verify(tokenParts[1], PUB_KEY, {
algorithms: ["RS256"],
});
req.jwt = verification;
next();
} catch (err) {
res.status(401).json({
success: false,
msg: "You are not authorized to visit this route",
});
}
} else {
res.status(401).json({
success: false,
msg: "You are not authorized to visit this route",
});
}
}
does anyone have an idea what could cause it?
Code to generate keys : Ps validPublicKey is a firebase code p256dh.
I don´t know where is the problem. If is in the generate code, or the send notification.
I need to put it in php code yet.
navigator.serviceWorker.ready
.then(function(swreg) {
reg = swreg;
console.log(swreg.pushManager.getSubscription());
console.log(JSON.stringify(swreg.pushManager.getSubscription()));
return swreg.pushManager.getSubscription();
})
.then(function(sub) {
if (sub === null) {
console.log('criando a chave');
var validPublicKey = 'BIG2EEduGTIoAYMFC3zpq2lksUw-OLRUrq_abhLs1Y2Zbo_xDUGwlozyezbSKqNkYylNN2yWKV5adB0819nQ1y0';
var convertValidPublicKey = urlBase64ToUint8Array(validPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly:true,
applicationServerKey:convertValidPublicKey
});
} else {
//we have
}
}).then(function(newSub) {
return fetch('https://???????.firebaseio.com/subscriptions.json', {
method:'POST',
headers: {
'Content-Type':'application/json',
'Accept':'application/json'
},
body:JSON.stringify(newSub)
})
}).then(function(res) {
if (res.ok) {
displayConfirmNotification();
}
}).catch(function(err) {
console.log(err);
});
}
Yesterday my app was launched, Ionic v1, and a few users entered the wrong password and can't log into the app.
The app uses firebase authentication. I have a __refs file that points to the database and have tried numerous things trying to get the reset to work.
I've tried referencing $firebaseAuth, of course my __refs, $firebase then use $firebase.auth()...
I didn't write the authentication of this app so I'm not real sure how it works. I'm hoping that someone can help me.
My reset controller
angular.module('formulaWizard').controller('ResetPasswordCtrl',
function($scope, $ionicLoading, $firebaseAuth, __Refs) {
$scope.user = {
email: ''
};
$scope.errorMessage = null;
var fbAuth = $firebaseAuth(__Refs.rootRef);
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
fbAuth.sendPasswordResetEmail($scope.user.email)
.then(showConfirmation)
.catch(handleError);
};
function showConfirmation() {
$scope.emailSent = true;
$ionicLoading.hide();
}
function handleError(error) {
switch (error.code) {
case 'INVALID_EMAIL':
case 'INVALID_USER':
$scope.errorMessage = 'Invalid email';
break;
default:
$scope.errorMessage = 'Error: [' + error.code + ']';
}
$ionicLoading.hide();
}
});
My Refs file
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
customers: ref.child('customers'),
}
});
I can't take credit for the answer it was provide by Abimbola Idowu on HackHands.
Since I paid for the answer I thought I would share it with anyone else that might also be stumped by this.
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
__Refs.rootRef.resetPassword({ email: $scope.user.email }, function(error) {
if (error === null) {
showConfirmation();
} else {
handleError()
}
});
};
This is the __refs service
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
}
});
In previous versions of angularFire, it was possible to secure selected routes by using "authRequired" and "pathTo" with Angular's $routeProvider. These no longer appear to work with AngularFire 0.6.0. What is the equivalent parameter/technique in Angular 0.6.0?
Routing was moved out of angularFire for the same reasons it was moved out of the core of Angular--to be less opinionated in how routing is conducted and which lib you should use.
You can still include routing by grabbing the module from angularFire-seed, which is plug-and-play ready.
The steps are:
add ngRoute and routeSecurity to your app dependencies
declare the loginRedirectPath constant
add authRequired where appropriate
Example:
// add routeSecurity to your dependency libs
angular.module('myApp', [..., 'ngRoute', 'firebase', 'routeSecurity']);
// declare the loginRedirectPath variable
angular.module('myApp').constant('loginRedirectPath', '/login')
// put authRequired in your routes
$routeProvider.when('/account', {
authRequired: true, // must authenticate before viewing this page
templateUrl: 'partials/account.html',
controller: 'AccountCtrl'
});
// live long and prosper
Here's a hard copy of the module as of 0.6.0 for compliance with SO policy; refer directly to the source for a current version:
(function(angular) {
angular.module('routeSecurity', [])
.run(['$injector', '$location', '$rootScope', 'loginRedirectPath', function($injector, $location, $rootScope, loginRedirectPath) {
if( $injector.has('$route') ) {
new RouteSecurityManager($location, $rootScope, $injector.get('$route'), loginRedirectPath);
}
}]);
function RouteSecurityManager($location, $rootScope, $route, path) {
this._route = $route;
this._location = $location;
this._rootScope = $rootScope;
this._loginPath = path;
this._redirectTo = null;
this._authenticated = !!($rootScope.auth && $rootScope.auth.user);
this._init();
}
RouteSecurityManager.prototype = {
_init: function() {
var self = this;
this._checkCurrent();
// Set up a handler for all future route changes, so we can check
// if authentication is required.
self._rootScope.$on("$routeChangeStart", function(e, next) {
self._authRequiredRedirect(next, self._loginPath);
});
self._rootScope.$on('$firebaseSimpleLogin:login', angular.bind(this, this._login));
self._rootScope.$on('$firebaseSimpleLogin:logout', angular.bind(this, this._logout));
self._rootScope.$on('$firebaseSimpleLogin:error', angular.bind(this, this._error));
},
_checkCurrent: function() {
// Check if the current page requires authentication.
if (this._route.current) {
this._authRequiredRedirect(this._route.current, this._loginPath);
}
},
_login: function() {
this._authenticated = true;
if( this._redirectTo ) {
this._redirect(this._redirectTo);
this._redirectTo = null;
}
else if( this._location.path() === this._loginPath ) {
this._location.replace();
this._location.path('/');
}
},
_logout: function() {
this._authenticated = false;
this._checkCurrent();
},
_error: function() {
if( !this._rootScope.auth || !this._rootScope.auth.user ) {
this._authenticated = false;
}
this._checkCurrent();
},
_redirect: function(path) {
this._location.replace();
this._location.path(path);
},
// A function to check whether the current path requires authentication,
// and if so, whether a redirect to a login page is needed.
_authRequiredRedirect: function(route, path) {
if (route.authRequired && !this._authenticated){
if (route.pathTo === undefined) {
this._redirectTo = this._location.path();
} else {
this._redirectTo = route.pathTo === path ? "/" : route.pathTo;
}
this._redirect(path);
}
else if( this._authenticated && this._location.path() === this._loginPath ) {
this._redirect('/');
}
}
};
})(angular);