当前位置: 首页 > 知识库问答 >
问题:

Laravel 4角认证路由

司空高义
2023-03-14

我有一个使用Laravel 4和AngularJS构建的应用程序。除了注销之外,一切都很好。如果我直接访问路由(/user/logout),用户将成功注销并重定向回 /login页面。但是,当我尝试链接到视图中的laravel注销路由时,它不起作用。我认为角是阻塞。我试着玩了一些东西,但总是,网址在地址栏中出现一瞬间,什么也没发生。

从应用程序/视图/相册/index.blade.php

<ul>
    @if(Auth::check())
        <li><a href="#0">My Account</a></li>
        <li><a href="{{ URL::route('getLogout') }}">Logout</a></li>
    @endif
</ul>

public/js/app。js

(function() {
    var app = angular.module('chp', ['ngRoute', 'projectControllers']);

    app.config(['$routeProvider', '$locationProvider',
      function($routeProvider, $locationProvider) {
        $routeProvider.
          when('/albums', {
            templateUrl: '/partials/directory.html',
            controller: 'ProjectsCtrl'
          }).
          when('/albums/:slug', {
            templateUrl: '/partials/album.html',
            controller: 'ProjectDetailCtrl'
          }).
          otherwise({
            redirectTo: '/login'
          });

          $locationProvider.html5Mode(true);
      }]);  

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

    projectControllers.controller('ProjectsCtrl', ['$scope', '$http',
      function ($scope, $http) {
        $http.get('/get_albums', {cache: true}).success(function(albums) {
            $scope.projects = albums;
            $scope.filters = { };
        });
      }]);

    projectControllers.controller('ProjectDetailCtrl', ['$scope', '$http', '$routeParams', '$sce',
      function($scope, $http, $routeParams, $sce) {


        $http.get('/get_albums', {cache: true}).success(function(albums) {
            $scope.projects = albums;
            $scope.filters = { };

            for(var i = 0; i < $scope.projects.length; i++) {
                if($scope.projects[i].slug === $routeParams.slug) {
                    $scope.album = $scope.projects[i];
                    $scope.albumIdx = i;
                    break;
                }
            }    

            $scope.project = albums[$scope.albumIdx];

            $scope.showVideo = function(id) {
                var videoCode = $(this)[0].song.video;
                var listItem = $('li[data-songid="'+id+'"]');

                $('li.video').remove();
                $(listItem).after('<li class="video"><img src="/img/progress.gif" alt="Loading..."><div class="flex-video">'+videoCode+'</div></li>');
                $('li.video').slideDown();

                setTimeout(function() { 
                    $('li.video img').hide(); 
                    $('li.video .flex-video').fadeIn(); 
                }, 500);
            }

            $scope.addLyrics = function(id) { 
                $('#lyricsModal .track-number').html('Add Lyrics - <span style="color: #ccc">' + $(this)[0].song.title + '</span>')
                $('#lyricsModal').foundation('reveal', 'open');
                $('#add-lyrics-form').prop('action', '/albums/add-lyrics/' + id + '/save');         
            }

        });

    }]);

})();

App/routes.php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', array('uses' => 'HomeController@hello', 'as' => 'home'));

Route::get('/login', array('uses' => 'LoginController@index', 'as' => 'login'));

Route::get('get_albums', function() {
    return Album::with('songs.lyric', 'artworks', 'series')->get();  
});

Route::group(array('before' => 'admin'), function() {
    Route::get('/edit-albums', array('uses' => 'AlbumsController@editAlbums', 'as' => 'edit-albums'));
});

Route::group(array('before' => 'auth'), function() {
    Route::group(array('prefix' => 'albums'), function() {
        Route::get('/', array('uses' => 'AlbumsController@index', 'as' => 'albums-home'));
        Route::get('/{slug}', array('uses' => 'AlbumsController@index', 'as' => 'albums-details'));

        Route::group(array('before' => 'auth'), function() {
            Route::post('/add-lyrics/{id}/save', array('uses' => 'AlbumsController@addLyrics', 'as' => 'add-lyrics'));
        });

        Route::group(array('before' => 'admin'), function() {   
            Route::get('/album/{id}/delete', array('uses' => 'AlbumsController@deleteAlbum', 'as' => 'delete-album'));
            Route::get('/song/{id}/delete', array('uses' => 'AlbumsController@deleteSong', 'as' => 'delete-song'));

            Route::group(array('before' => 'csrf'), function() {
                Route::post('/newalbum', array('uses' => 'AlbumsController@saveAlbum', 'as' => 'save-album'));
                Route::post('/add-song/{id}/new', array('uses' => 'AlbumsController@saveSong', 'as' => 'save-song'));
                Route::post('/update-song/{id}/save', array('uses' => 'AlbumsController@editSong', 'as' => 'update-song'));
                Route::post('/update-album/{id}/save', array('uses' => 'AlbumsController@editAlbum', 'as' => 'update-album'));

            });
        });
    });
});

Route::group(array('prefix' => 'forum'), function() {
    Route::get('/', array('uses' => 'ForumController@index', 'as' => 'forum-home'));
    Route::get('/category/{id}', array('uses' => 'ForumController@category', 'as' => 'forum-category'));
    Route::get('/thread/{id}', array('uses' => 'ForumController@thread', 'as' => 'forum-thread'));

    Route::group(array('before' => 'admin'), function() {
        Route::get('/group/{id}/delete', array('uses' => 'ForumController@deleteGroup', 'as' => 'forum-delete-group'));
        Route::get('/category/{id}/delete', array('uses' => 'ForumController@deleteCategory', 'as' => 'forum-delete-category'));
        Route::get('/thread/{id}/delete', array('uses' => 'ForumController@deleteThread', 'as' => 'forum-delete-thread'));

        Route::group(array('before' => 'csrf'), function() {
            Route::post('/category/{id}/new', array('uses' => 'ForumController@storeCategory', 'as' => 'forum-store-category'));
            Route::post('/group', array('uses' => 'ForumController@storeGroup', 'as' => 'forum-store-group'));
        });
    });

    Route::group(array('before' => 'auth'), function() {
        Route::get('/thread/{id}/new', array('uses' => 'ForumController@newThread', 'as' => 'forum-get-new-thread'));

        Route::group(array('before' => 'csrf'), function() {
            Route::post('/thread/{id}/new', array('uses' => 'ForumController@storeThread', 'as' => 'forum-store-thread'));
        });
    });
});

Route::group(array('before' => 'guest'), function() {
    Route::get('/user/create', array('uses' => 'UserController@getCreate', 'as' => 'getCreate'));
    Route::get('/user/login', array('uses' => 'UserController@getLogin', 'as' => 'getLogin'));

    Route::group(array('before' => 'csrf'), function() {
        Route::post('/user/create', array('uses' => 'UserController@postCreate', 'as' => 'postCreate'));
        Route::post('/user/login', array('uses' => 'UserController@postLogin', 'as' => 'postLogin'));
    });
});

Route::group(array('before' => 'auth'), function() {
    Route::get('/user/logout', array('uses' => 'UserController@getLogout', 'as' => 'getLogout'));
});

App/控制器/UserController.php

class UserController extends BaseController
{
    //gets the view for the register page
    public function getCreate()
    {
        return View::make('user.register');
    }

    //gets the view for the login page
    public function getLogin()
    {
        return View::make('user.login');
    }

    public function postCreate()
    {
        $validate = Validator::make(Input::all(), array(
            'username' => 'required|unique:users|min:4',
            'pass1' => 'required|min:6',
            'pass2' => 'required|same:pass1',
        ));

        if ($validate->fails())
        {
            return Redirect::route('getCreate')->withErrors($validate)->withInput();
        }
        else
        {
            $user = new User();
            $user->username = Input::get('username');
            $user->password = Hash::make(Input::get('pass1'));

            if ($user->save())
            {
                return Redirect::route('home')->with('success', 'You registed successfully. You can now login.');
            }
            else
            {
                return Redirect::route('home')->with('fail', 'An error occured while creating the user. Please try again.');
            }
        }
    }

    public function postLogin()
    {
        $validator = Validator::make(Input::all(), array(
        'username' => 'required',
        'pass1' => 'required'
        ));

        if($validator->fails())
        {
            return Redirect::route('login')->withErrors($validator)->withInput();
        }
        else
        {
            $remember = (Input::has('remember')) ? true : false;

            $auth = Auth::attempt(array(
                'username' => Input::get('username'),
                'password' => Input::get('pass1')
                ), $remember);

            if($auth)
            {
                return Redirect::route('albums-home');
            }
            else
            {
                return Redirect::route('login')->with('fail', 'You entered the wrong login credentials, please try again!');
            }
        }
    }

    public function getLogout()
    {
        Auth::logout();
        return Redirect::route('login');
    }

}

共有1个答案

洪俊拔
2023-03-14

只需创建用于注销的json路由,并在成功登录时更改浏览器url。为此,请定义全局函数logout()

$http.get('route/to/logout').success(
  window.location.href = "/login ";
});
 类似资料:
  • 问题内容: 角度ui路由器的示例演示在起始页面具有以下链接: “ ui-router”的完整网址为或 “关于”的完整网址为或 当我使用durandalJS时,存在一个限制,即默认URL只是“ /”,不能有“ / ui-router”。 Angular ui路由器插件有相同的限制吗? 问题答案: 请参阅此处,默认路由有一个“其他”选项。

  • 问题内容: 我正在开发一个Angular应用程序。在此,我将在进入仪表板之前对用户进行身份验证。为了达到这个目的,我写了as 登录功能 我还想限制用户访问路由(如果尚未登录)。为此,我想到了this 。 路线 我说上面的代码 DIRTY 的原因是,如果我要保护10条未授权用户使用的路由,则必须在所有路由中复制相同的resolve函数。 所以我的问题是,我应该怎么做才能摆脱多重解析功能并能够编写DR

  • 我有这个博客资源,它有通常的CRUD方法。(索引,创建,存储,显示,编辑,更新,销毁)。 我的路线中有以下路线。php: 这是很好的索引,但我不知道如何路由显示方法?还是有别的办法?我不应该路由资源,而是应该单独路由每个URI,并将我想要限制的URI放在我的限制访问路由中? 干杯

  • 就像在本主题中一样,我的Spring Security应用程序也有问题。单击“身份验证”按钮时,即使输入了正确的数据,也会在控制台中看到: 访问位于“”的XMLHttpRequesthttp://localhost:8080/api/v1/basicauth“起源”http://localhost:4200'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态。 而

  • 我无法找到一种REST webservice方式来身份验证(登录)并知道他的角色(授权)。虽然,Openbravo维基说有一种登录的方法,但没有提供任何其他关于其网址等细节。有人能在这方面提供帮助吗?谢啦 编辑 我也在Openbravo论坛上发布了这个问题。希望这将有利于其他人。

  • 和 Web 应用不同,RESTful APIs 通常是无状态的, 也就意味着不应使用 sessions 或 cookies, 因此每个请求应附带某种授权凭证,因为用户授权状态可能没通过 sessions 或 cookies 维护, 常用的做法是每个请求都发送一个秘密的 access token 来认证用户, 由于 access token 可以唯一识别和认证用户, API 请求应通过 HTTPS