Skip to content

Instantly share code, notes, and snippets.

@kudchikarsk kudchikarsk/addToken.js
Last active Apr 23, 2019

Embed
What would you like to do?
AngularJs service interceptor to inject tokens in every request
(function(module) {
var addToken = function(currentUser, $q) {
return {
request: function(config) {
if (currentUser.profile.token) {
config.headers.Authorization = "Bearer " + currentUser.profile.token;
}
return $q.when(config);
}
};
};
module.factory("addToken", addToken);
module.config(function($httpProvider) {
$httpProvider.interceptors.push("addToken");
});
})(angular.module("common"));
//CurrentUserService.js Service to manage users
(function(module) {
var USERKEY = "utoken";
var currentUser = function (localStorage) {
var saveUser = function () {
localStorage.add(USERKEY, profile);
};
var removeUser = function () {
localStorage.remove(USERKEY);
};
var initialize = function() {
var user = {
username: "",
token: "",
get loggedIn() {
return this.token ? true : false;
}
};
var localUser = localStorage.get(USERKEY);
if (localUser) {
user.username = localUser.username;
user.token = localUser.token;
}
return user;
}
var profile = initialize();
return {
save: saveUser,
remove: removeUser,
profile: profile
};
};
module.factory("currentUser", currentUser);
}(angular.module("common")));
//localStorage.js service to store data
(function(module) {
var localStorage = function($window) {
var store = $window.localStorage;
var add = function (key, value) {
value = angular.toJson(value);
store.setItem(key, value);
};
var get = function(key) {
var value = store.getItem(key);
if (value) {
value = angular.fromJson(value);
}
return value;
};
var remove = function(key) {
store.removeItem(key);
};
return {
add: add,
get: get,
remove: remove
};
};
module.factory("localStorage", localStorage);
}(angular.module("common")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.