javascript AngularJs + php 认证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20539019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:44:17  来源:igfitidea点击:

AngularJs + php authentication

javascriptphpangularjs

提问by Georgi Stefanov

Hi i started learning AngularJs and now im trying to do my Login module using angular and php, but i have some issues. I have watched alot tutorials but none of them was helpful in my case, so here is what i have: controllers.js:

嗨,我开始学习 AngularJs,现在我尝试使用 angular 和 php 来做我的登录模块,但我有一些问题。我看过很多教程,但没有一个对我的情况有帮助,所以这是我所拥有的:controllers.js:

var controllers = angular.module('controllers', []);     

controllers.controller('loginController', ['$scope', '$http', 'UserService', function(scope, $http, User) {
scope.main = [
    {username: '', password: ''}
]

scope.login = function(){
    var config = {
        url: '../auth/login.php',
        method: 'POST',
        data: {
            username: scope.main.username,
            password: scope.main.password
        },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }

    $http(config)
    .success(function(data,status,headers,config){
        if(data.status){
            //succefull login
            User.isLogged = true;
            User.username = data.username;
        }
        else{
            User.isLogged = false;
            User.username = '';
        }
    })
    .error(function(data,status,headers,config){
        User.isLogged = false;
        User.username = '';
    });
}
}])

auth.js:

auth.js:

var services = angular.module('services', []);

services.factory('UserService', [function(){
    var sdo = {
        isLogged: false,
        username: ''
    };
    return sdo;
}]);

login.php:

登录.php:

$username = $_POST['username'];
if($username){
    return "Logged";
}else{
    return false;
}

and the html:

和 html:

<div class="col-xs-12" id="loginCol" ng-controller="loginController">
   <form ng-submit='login()' name="form" novalidate>
      <div class="form-group">
         <label for="username" class="sr-only">Username</label>
         <input type="text" ng-model="scope.main.username" class="form-control" id="username" placeholder="Име..." />
         <label for="password" class="sr-only">Password</label>
         <input type="password" ng-model="scope.main.password" class="form-control" id="password" placeholder="Парола..." />
      </div>

      <div class="form-group pull-right">
         <button type="button" class="btn btn-primary">Login</button>
         <button type="button" class="btn btn-default">Register</button>
      </div>
   </form>
</div>

In this case i want just if user type something in the username input and hit the login button and on successful call of login.php to return some message. The problem is that code written like that got error "'loginController' is not a function, got undefined" how to fix it?

在这种情况下,我只希望用户在用户名输入中输入一些内容并点击登录按钮并成功调用 login.php 以返回一些消息。问题是这样编写的代码出现错误“'loginController' 不是函数,未定义”如何解决?

回答by Timothy E. Johansson

(Disclosure: I'm one of the developers of UserApp)

(披露:我是UserApp的开发者之一)

You could try the third-party service UserApp, together with the AngularJS module.

您可以尝试使用第三方服务UserApp以及AngularJS 模块

Check out the getting started guide, or take the course on Codecademy. Here's some examples of how it works:

查看入门指南,或参加Codecademy 上课程。以下是它如何工作的一些示例:

  • Login form with error handling:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • Signup form with error handling:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    

    ua-is-emailmeans that the username is the same as the email.

  • How to specify which routes that should be public, and which route that is the login form:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    

    The .otherwise()route should be set to where you want your users to be redirected after login. Example:

    $routeProvider.otherwise({redirectTo: '/home'});

  • Log out link:

    <a href="#" ua-logout>Log Out</a>

  • Access user properties:

    User info is accessed using the userservice, e.g: user.current.email

    Or in the template: <span>{{ user.email }}</span>

  • Hide elements that should only be visible when logged in:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • Show an element based on permissions:

    <div ua-has-permission="admin">You are an admin</div>

  • 带有错误处理的登录表单:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • 带有错误处理的注册表单:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    

    ua-is-email表示用户名与电子邮件相同。

  • 如何指定哪些路由应该是公开的,哪些路由是登录表单:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    

    .otherwise()路由应设置为您希望用户在登录后重定向到的位置。例子:

    $routeProvider.otherwise({redirectTo: '/home'});

  • 登出链接:

    <a href="#" ua-logout>Log Out</a>

  • 访问用户属性:

    使用该user服务访问用户信息,例如:user.current.email

    或者在模板中: <span>{{ user.email }}</span>

  • 隐藏应该只在登录时可见的元素:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • 根据权限显示元素:

    <div ua-has-permission="admin">You are an admin</div>

And to authenticate to your back-end services, just use user.token()to get the session token and send it with the AJAX request. At the back-end, use the UserApp APIwith the PHP libraryto check if the token is valid or not.

并且要对您的后端服务进行身份验证,只需使用user.token()获取会话令牌并将其与 AJAX 请求一起发送。在后端,使用带有PHP 库UserApp API来检查令牌是否有效。

If you need any help, just let me know :)

如果您需要任何帮助,请告诉我:)

回答by IgorCh

You have created the application

您已创建应用程序

var controllers = angular.module('controllers', []);   

but didn't use it in the html code, add ng-app attribute to the wrapper div

但没有在html代码中使用它,将ng-app属性添加到包装器div

<div class="col-xs-12" ng-app="controllers" id="loginCol" ng-controller="loginController">

the second issue, that you try to catch submit event, but don't submit the form, use submittype instead button

第二个问题,您尝试捕获提交事件,但不提交表单,submit而是使用类型button

<button type="submit" class="btn btn-primary">Login</button>

or add ng-click="login()"attribute to the button and remove ng-submit='login()'from the form

ng-click="login()"向按钮添加属性并ng-submit='login()'从表单中删除