我能够使用api在登录屏幕上对用户进行身份验证,但是当我尝试在第二个屏幕上调用另一个api并显示其内容时,我遇到401错误,我需要在我可以做的表格格式,但是第二次api调用失败。
我正在使用github代码中的angular-client-side-auth-master。我也在这里添加片段。
service.js
'use strict';
angular.module('angular-client-side-auth')
.factory('Auth', function ($http, $cookieStore) {
var accessLevels = routingConfig.accessLevels
, userRoles = routingConfig.userRoles
, currentUser = $cookieStore.get('user') || { username: '', role: userRoles.public };
$cookieStore.remove('user');
function changeUser(user) {
angular.extend(currentUser, user);
}
return {
authorize: function (accessLevel, role) {
if (role === undefined) {
role = currentUser.role;
}
return accessLevel.bitMask & role.bitMask;
},
isLoggedIn: function (user) {
if (user === undefined) {
user = currentUser;
}
return user.role.title === userRoles.user.title || user.role.title === userRoles.admin.title;
},
register: function (user, success, error) {
$http.post('/register', user).success(function (res) {
changeUser(res);
success();
}).error(error);
},
login: function (user, success, error) {
user = { email: user.username, password: user.password }
$http.post('https://workdaysync.io/api/auth/login', user).success(function (user) {
console.log(user);
user = {"username": user.email, "role":"user"};
changeUser(user);
success(user);
console.log(user);
user = { username: "admin", password: "123", rememberme: true };
$http.post('/login', user).success(function (user) {
user = { "role": { "bitMask": 4, "title": user.firstName }, "username": "admin" };
console.log(user);
changeUser(user);
success(user);
}).error(error);
}).error(error);
console.log(user);
},
logout: function (success, error) {
$http.post('/logout').success(function () {
// console.log(user);
changeUser({
username: '',
role: userRoles.public
});
success();
//console.log(user);
}).error(error);
},
accessLevels: accessLevels,
userRoles: userRoles,
user: currentUser
};
});
angular.module('angular-client-side-auth').service('HttpService', function ($http, user) {
return {
getPost: function () {
user = { email: user.username, password: user.password }
// $http returns a promise, which has a then function, which also returns a promise.
return $http.get('https://qa.workdaysync.io/getcadentapi/sync/2019-04-09', user)
.then(function (response) {
// In the response, resp.data contains the result. Check the console to see all of the data returned.
console.log('Get Post' +response);
return response.data;
});
},
getUsers: function () {
user = { email: user.username, password: user.password }
// $http returns a promise, which has a then function, which also returns a promise.
return $http.get('https://qa.workdaysync.io/getcadentapi/sync/2019-04-09', user)
.then(function (response) {
// In the response, resp.data contains the result. Check the console to see all of the data returned.
console.log('Get Users', response);
return response.data;
});
}
}
});
angular.module('angular-client-side-auth').controller('mainController', function ($scope, HttpService) {
HttpService.getPost()
.then(function (response) {
$scope.post = response;
});
HttpService.getUsers()
.then(function (response) {
$scope.user = response;
});
});
angular.module('angular-client-side-auth').filter('counterValue', function () {
return function (value) {
value = parseInt(value);
if (!isNaN(value) && value >= 0 && value < 10) {
return "0" + value;
//return "";
} else {
return value;
//return "";
}
}
})
angular.module('angular-client-side-auth')
.factory('Users', function ($http) {
return {
getAll: function (success, error,user) {
//user = { email: "mradul@mobile-di.com", password: "wds1990" }
console.log(user);
return $http.get('https://workdaysync.io/getcadentapi/sync/2019-04-09').console.log("response coming? "+response.data).success(success).error(error);
}
};
});
users.js
var User
, _ = require('underscore')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, TwitterStrategy = require('passport-twitter').Strategy
, FacebookStrategy = require('passport-facebook').Strategy
, GoogleStrategy = require('passport-google').Strategy
, LinkedInStrategy = require('passport-linkedin').Strategy
, check = require('validator').check
, userRoles = require('../../client/js/routingConfig').userRoles;
var users = [
{
id: 1,
username: "user",
password: "123",
role: userRoles.user
},
{
id: 2,
username: "admin",
password: "123",
role: userRoles.admin
}
];
module.exports = {
addUser: function(username, password, role, callback) {
if(this.findByUsername(username) !== undefined) return callback("UserAlreadyExists");
// Clean up when 500 users reached
if(users.length > 500) {
users = users.slice(0, 2);
}
var user = {
id: _.max(users, function(user) { return user.id; }).id + 1,
username: username,
password: password,
role: role
};
users.push(user);
callback(null, user);
},
findOrCreateOauthUser: function(provider, providerId) {
var user = module.exports.findByProviderId(provider, providerId);
if(!user) {
user = {
id: _.max(users, function(user) { return user.id; }).id + 1,
username: provider + '_user', // Should keep Oauth users anonymous on demo site
role: userRoles.user,
provider: provider
};
user[provider] = providerId;
users.push(user);
}
return user;
},
findAll: function() {
return _.map(users, function(user) { return _.clone(user); });
},
findById: function(id) {
return _.clone(_.find(users, function(user) { return user.id === id }));
},
findByUsername: function(username) {
return _.clone(_.find(users, function(user) { return user.username === username; }));
},
findByProviderId: function(provider, id) {
return _.find(users, function(user) { return user[provider] === id; });
},
validate: function(user) {
check(user.username, 'Username must be 1-20 characters long').len(1, 20);
check(user.password, 'Password must be 5-60 characters long').len(5, 60);
check(user.username, 'Invalid username').not(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/);
// TODO: Seems node-validator's isIn function doesn't handle Number arrays very well...
// Till this is rectified Number arrays must be converted to string arrays
// https://github.com/chriso/node-validator/issues/185
var stringArr = _.map(_.values(userRoles), function(val) { return val.toString() });
check(user.role, 'Invalid user role given').isIn(stringArr);
},
localStrategy: new LocalStrategy(
function(username, password, done) {
var user = module.exports.findByUsername(username);
if(!user) {
done(null, false, { message: 'Incorrect username.' });
}
else if(user.password != password) {
done(null, false, { message: 'Incorrect username.' });
}
else {
return done(null, user);
}
}
),
twitterStrategy: function() {
if(!process.env.TWITTER_CONSUMER_KEY) throw new Error('A Twitter Consumer Key is required if you want to enable login via Twitter.');
if(!process.env.TWITTER_CONSUMER_SECRET) throw new Error('A Twitter Consumer Secret is required if you want to enable login via Twitter.');
return new TwitterStrategy({
consumerKey: process.env.TWITTER_CONSUMER_KEY,
consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
callbackURL: process.env.TWITTER_CALLBACK_URL || 'http://localhost:8000/auth/twitter/callback'
},
function(token, tokenSecret, profile, done) {
var user = module.exports.findOrCreateOauthUser(profile.provider, profile.id);
done(null, user);
});
},
facebookStrategy: function() {
if(!process.env.FACEBOOK_APP_ID) throw new Error('A Facebook App ID is required if you want to enable login via Facebook.');
if(!process.env.FACEBOOK_APP_SECRET) throw new Error('A Facebook App Secret is required if you want to enable login via Facebook.');
return new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: process.env.FACEBOOK_CALLBACK_URL || "http://localhost:8000/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done) {
var user = module.exports.findOrCreateOauthUser(profile.provider, profile.id);
done(null, user);
});
},
googleStrategy: function() {
return new GoogleStrategy({
returnURL: process.env.GOOGLE_RETURN_URL || "http://localhost:8000/auth/google/return",
realm: process.env.GOOGLE_REALM || "http://localhost:8000/"
},
function(identifier, profile, done) {
var user = module.exports.findOrCreateOauthUser('google', identifier);
done(null, user);
});
},
linkedInStrategy: function() {
if(!process.env.LINKED_IN_KEY) throw new Error('A LinkedIn App Key is required if you want to enable login via LinkedIn.');
if(!process.env.LINKED_IN_SECRET) throw new Error('A LinkedIn App Secret is required if you want to enable login via LinkedIn.');
return new LinkedInStrategy({
consumerKey: process.env.LINKED_IN_KEY,
consumerSecret: process.env.LINKED_IN_SECRET,
callbackURL: process.env.LINKED_IN_CALLBACK_URL || "http://localhost:8000/auth/linkedin/callback"
},
function(token, tokenSecret, profile, done) {
var user = module.exports.findOrCreateOauthUser('linkedin', profile.id);
done(null,user);
}
);
},
serializeUser: function(user, done) {
done(null, user.id);
},
deserializeUser: function(id, done) {
var user = module.exports.findById(id);
if(user) { done(null, user); }
else { done(null, false); }
}
};
第二个api的api响应
[
{
"id": 171,
"name": "Betterleasing",
"customQuestion": "What did you get done today?",
"maxSyncItems": 1,
"orderIndex": 1,
"hidden": false,
"dones": [],
"unReported": 0,
"seenCount": 108,
"inProgressCount": 0,
"completedCount": 0
},
{
"id": 106,
"name": "Capitol Contact - support",
"customQuestion": "What did you get done today?",
"maxSyncItems": 1,
"orderIndex": 0,
"hidden": false,
"dones": [],
"unReported": 0,
"seenCount": 17,
"inProgressCount": 0,
"completedCount": 0
},
{
"id": 109,
"name": "DataTrendz-Android",
"customQuestion": "What did you get done today?",
"maxSyncItems": 1,
"orderIndex": 0,
"hidden": false,
"dones": [],
"unReported": 0,
"seenCount": 23,
"inProgressCount": 0,
"completedCount": 0
},
{
"id": 169,
"name": "Earnitapp",
"customQuestion": "What did you get done today?",
"maxSyncItems": 1,
"orderIndex": 2,
"hidden": false,
"dones": [],
"unReported": 0,
"seenCount": 9,
"inProgressCount": 0,
"completedCount": 0
},
{
"id": 121,
"name": "Self Improvement",
"customQuestion": "What did you learn or mentor?",
"maxSyncItems": 1,
"orderIndex": 0,
"hidden": false,
"dones": [],
"unReported": 0,
"seenCount": 19,
"inProgressCount": 37,
"completedCount": 0
},
{
"id": 111,
"name": "WorkdaySync",
"customQuestion": "What did you get done today?",
"maxSyncItems": 1,
"orderIndex": 0,
"hidden": false,
"dones": [],
"unReported": 0,
"seenCount": 12,
"inProgressCount": 0,
"completedCount": 0
}
]
登录api响应
{
"id": 144,
"firstName": "demo",
"lastName": "dummy",
"email": "dummy@dummy.com",
"handle": "demo",
"timezone": "Asia/Kolkata",
"account_id": 69,
"city": "hyderabad South",
"role": "USER",
"active": "true",
"updated": "2017-02-03T04:23:25.177Z",
"created": "2017-02-03T04:23:25.177Z",
"country": "India",
"passwordFlag": "true",
"tmp_hash": "24269c531d960a68385f313f99e6b8f28dd10c28f07c2d0f9da7982e60b0af51",
"avatar": "",
"remindMe": "true",
"sendReminderAt": "21:55:00",
"optInEmail": "false",
"firstLaunchFlag": "true",
"chromeSignup": "false",
"checkDefaultTimeZone": "",
"typeNotify": "true",
"weekendNotify": "false",
"phoneNumber": null,
"trialends": true,
"subscription": {
"id": "sub_AQhS3jLfXjKU2v",
"object": "subscription",
"application_fee_percent": null,
"billing": "charge_automatically",
"billing_cycle_anchor": 1494136467,
"billing_thresholds": null,
"cancel_at": null,
"cancel_at_period_end": false,
"canceled_at": null,
"created": 1491544467,
"current_period_end": 1557208467,
"current_period_start": 1554616467,
"customer": "cus_AQhSnFr0WYaC4M",
"days_until_due": null,
"default_payment_method": null,
"default_source": null,
"discount": null,
"ended_at": null,
"items": {
"object": "list",
"data": [
{
"id": "si_1A5q3DBV3j7XRCWQQQZA7bgj",
"object": "subscription_item",
"billing_thresholds": null,
"created": 1491544467,
"metadata": {},
"plan": {
"id": "PRO",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 399,
"billing_scheme": "per_unit",
"created": 1478217746,
"currency": "usd",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {},
"name": "Small team",
"nickname": null,
"product": "prod_BToLLhDPhqdFuL",
"statement_descriptor": null,
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": 30,
"usage_type": "licensed"
},
"quantity": 5,
"subscription": "sub_AQhS3jLfXjKU2v"
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/subscription_items?subscription=sub_AQhS3jLfXjKU2v"
},
"latest_invoice": "in_1EMTxdBV3j7XRCWQRWY7siT1",
"livemode": false,
"metadata": {},
"plan": {
"id": "PRO",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 399,
"billing_scheme": "per_unit",
"created": 1478217746,
"currency": "usd",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {},
"name": "Small team",
"nickname": null,
"product": "prod_BToLLhDPhqdFuL",
"statement_descriptor": null,
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": 30,
"usage_type": "licensed"
},
"quantity": 5,
"schedule": null,
"start": 1554442934,
"status": "active",
"tax_percent": null,
"trial_end": null,
"trial_start": null
},
"stripeCustomerId": null,
"stripePlanId": null,
"stripeCardId": null,
"status": "active",
"company": "mobile-di",
"couponcode": "WDSEA",
"couponActiveAt": "2018-06-24T06:00:21.669Z"
}