【问题标题】:Laravel 4 + Angular authentication routingLaravel 4 + Angular 身份验证路由
【发布时间】:2016-02-05 20:50:54
【问题描述】:

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

来自 app/views/albums/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/controllers/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');
    }

}

【问题讨论】:

    标签: angularjs laravel authentication laravel-4


    【解决方案1】:

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

    $http.get('route/to/logout').success(
      window.location.href = "/login ";
    });
    

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 2013-12-11
      • 1970-01-01
      • 2013-09-09
      • 2021-12-16
      • 2018-03-14
      • 2013-05-16
      • 2016-04-06
      • 1970-01-01
      相关资源
      最近更新 更多