gpt4 book ai didi

javascript - AngularJS - 检查用户是否经过身份验证,然后将其路由到正确的页面

转载 作者:行者123 更新时间:2023-12-03 21:46:30 25 4
gpt4 key购买 nike

当用户访问index.html页面时,我想要做什么,我需要登录模块做两件事:

  1. 我需要这个来检查用户是否已通过身份验证(我认为我已经从“function authService”开始)如果用户具有有效的 token ,则将 ui-view 更改为dashboard/dashboard.html 并如果 key 无效或根本没有 key ,则将 login/login.html 加载到 ui-view 中。

  2. 他们成功登录后,我希望他们被路由到“dashboard/dashboard.html”

这是我的登录脚本:

function authInterceptor(API) {
return {
request: function(config) {
if(config.url.indexOf(API) === 0) {
request.headers = request.headers || {};
request.headers['X-PCC-API-TOKEN'] = localStorage.getItem('token');
}
return config;
}
}
}

function authService(auth) {
var self = this;
self.isAuthed = function() {
localStorage.getItem('token');
}
}

function userService($http, API) {

$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;';
$http.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];

var self = this;

self.login = function(username, pwd, ctrl) {
ctrl.requestdata = API + '/winauth' + '; with ' + username;
return $http.post(API + '/winauth', {
username: username,
pwd: pwd
})
};

var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

for(name in obj) {
value = obj[name];

if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}

return query.length ? query.substr(0, query.length - 1) : query;
};

}

function LoginCtrl(user) {
var self = this;

function handleRequest(res) {
self.responsedata = res;
self.message = res.data.message;

var authToken = res.data.auth_token;
localStorage.setItem('token', authToken);
}

self.login = function() {
this.requestdata = 'Starting request...';
user.login(self.username, self.pwd, self)
.then(handleRequest, handleRequest)
}
}

// Login Module
var login = angular.module('login', ["ui.router"])

login.factory('authInterceptor', authInterceptor)
login.service('user', userService)
login.service('auth', authService)
login.constant('API', 'http://myserver.com/api')

编辑-我将其添加到我的登录 Controller 中以提供登录路由

login.config(function($httpProvider, $stateProvider, $urlRouterProvider) {

$httpProvider.interceptors.push('authInterceptor');

$urlRouterProvider.otherwise('/login');

$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('login', {
url: '/login',
templateUrl: 'login/login.html',
controller: "mainLogin",
controllerAs: "log"
})
// nested list with just some random string data
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/dashboard.html',
})

})

login.controller('mainLogin', LoginCtrl)

这是我的index.html:

编辑-我删除了“ng-include”并添加了“ng-view”来控制路线。

<body ng-app="login" ng-controller="mainLogin as log" class="loginPage">

<div class="main" ui-view></div>

</body>

如您所见,我有一个函数正在检查用户本地存储中的 token :

function authService(auth) {
var self = this;
self.isAuthed = function() {
localStorage.getItem('token');
}
}

我将其作为服务加载到模块中:

login.service('auth', authService)

这就是我被困住的地方。我不知道从这里该去哪里。我什至不知道我是否正确使用了 authService 功能。我仍在学习很多关于 AngularJS 的知识,所以我很容易陷入困境。 :)

您会注意到的另一件事是在我的index.html 文件中,我只是默认加载“login/login.html”部分。我需要它来加载login.html 或dashboard.html,具体取决于它们是否登录。然后在成功登录后将它们路由到dashboard.html。

该脚本在访问身份验证 API、验证用户身份,然后在本地存储上存储有效的身份验证 key 方面效果很好。

有人知道我怎样才能做到这一点吗?

最佳答案

您正在处理两个不同的问题。首先,是能够确定您是否已登录。假设用户需要在除登录状态之外的任何状态下登录,您可以通过监听 $stateChangeState 事件并验证用户是否已登录来实现它在:

login.run(function($state, authService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
var authToken = authService.isAuthed();
if (!authToken && toState !== 'login') {
//not logged in, so redirect to the login view instead of the view
//the user was attempting to load
event.preventDefault();
$state.go('login');

}
})
});

如果他们尚未登录,这会将他们置于登录状态。

第二部分是在登录后重定向到正确的 View ,您可以在登录 Controller 中执行此操作:

function LoginCtrl(user, $state) {
var self = this;

function handleRequest(res) {
self.responsedata = res;
self.message = res.data.message;

var authToken = res.data.auth_token;
localStorage.setItem('token', authToken);

//after successful login, redirect to dashboard
$state.go('dashboard');
}

self.login = function() {
this.requestdata = 'Starting request...';
user.login(self.username, self.pwd, self)
.then(handleRequest, handleRequest)
}
}

关于javascript - AngularJS - 检查用户是否经过身份验证,然后将其路由到正确的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38647544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com