generator-angular-fullstack icon indicating copy to clipboard operation
generator-angular-fullstack copied to clipboard

Question : how to secure new route after yo angular-fullstack:route myroute

Open stevejvv opened this issue 10 years ago • 15 comments

Hi,

Not sure if I can ask this here, but I haven't found a way to secure a new route after route generator... I have added authenticate: 'admin' to my new routes' state provider, but not sure what else to do? any ideas? Thanks!

stevejvv avatar Dec 11 '15 09:12 stevejvv

You should also limit access to your REST endpoint for your entity: server/api/entityName/index.js

router.get('/', auth.isAuthenticated(), controller.index);

Also for your client part you can change your state resolver to allow only auth users by default: client/app/app.js

$rootScope.$on('$stateChangeStart', function(event, next) {
      if (next.authenticate !== false) {
        Auth.isLoggedIn(function(loggedIn) {
          if (!loggedIn) {
            event.preventDefault();
            $state.go('login');
          }
        });
      }
    });

donvadicastro avatar Dec 11 '15 10:12 donvadicastro

Hey, Thanks for your reply!

I'm hesitating as to where to put the later code in app.js, not inside config()? Could you perhaps show me an example of app.js? Thanks

stevejvv avatar Dec 11 '15 11:12 stevejvv

@stevejvv The later code is not in server side. It is on client side. It will be generated be default. All you need to do is give authenticate: true to that specific route in client side.

For example please check account.js file in account folder in client side

chinnichaitanya avatar Dec 11 '15 12:12 chinnichaitanya

You have this code on your 'run' method in app.js. Please find at the end of file. My "if" statement I've replaced as described above. This allow me to create pages which are auth protected by default.

donvadicastro avatar Dec 11 '15 12:12 donvadicastro

Thanks guys!

@chinnichaitanya, this was my first thought, but I got this error :

TypeError: Auth.isLoggedIn(...).then is not a function at router.decorator.js:18

@donvadicastro, I have no 'run' method in client/app/app.js, here's the complete code of app.js :

angular.module('auth10App', [
  'auth10App.auth',
  'auth10App.admin',
  'auth10App.constants',
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'btford.socket-io',
  'ui.router',
  'ui.bootstrap',
  'validation.match'
])
  .config(function($urlRouterProvider, $locationProvider) {
    $urlRouterProvider
      .otherwise('/');

    $locationProvider.html5Mode(true);
  });

You guys are getting me worried! What am I missing?

This is what I've done :

yo angular-fullstack

yo angular-fullstack:route rooms

yo angular-fullstack:endpoint rooms

added authenticate: true to rooms.js (I get the error mentioned above) added var auth = require('../../auth/auth.service'); to /api/rooms/index.js modified /api/rooms/index.js to router.get('/', auth.isAuthenticated(), controller.index);

Same error shows...

stevejvv avatar Dec 11 '15 13:12 stevejvv

@stevejvv Maybe that is where this is going wrong.

The client/app/app.js must have

'use strict';

angular.module(<app_name>, [
...
])
  .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
    $urlRouterProvider
      .otherwise('/');

    $locationProvider.html5Mode(true);
    $httpProvider.interceptors.push('authInterceptor');
  })

  .factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
    return {
      // Add authorization token to headers
      request: function (config) {
        config.headers = config.headers || {};
        if ($cookieStore.get('token')) {
          config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
        }
        return config;
      },

      // Intercept 401s and redirect you to login
      responseError: function(response) {
        if(response.status === 401) {
          $location.path('/login');
          // remove any stale tokens
          $cookieStore.remove('token');
          return $q.reject(response);
        }
        else {
          return $q.reject(response);
        }
      }
    };
  })

  .run(function ($rootScope, $location, Auth) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$stateChangeStart', function (event, next) {
      Auth.isLoggedInAsync(function(loggedIn) {
        if (next.authenticate && !loggedIn) {
          $location.path('/login');
        }
      });
    });
  });

May be you might have to update the generator and try once again if the above code isin't generated by default.

One doubt occurs to me. Can you tell me if you have checked yes for login and auth while scaffolding the app ?

chinnichaitanya avatar Dec 11 '15 14:12 chinnichaitanya

It seems that you forgot to include auth part on running generator when project scaffolds. Did you?

image

donvadicastro avatar Dec 11 '15 14:12 donvadicastro

I ran into the same issue late last night after generating a fresh app using generator version 3.2.0. I definitely made sure to select 'y' when asked whether I'd like to scaffold an authentication boilerplate. [Edit: More Specificity]

When creating a new route, if I set authenticate: true on the client-side route specification, and then attempt to access the route while NOT logged in, the route loads, and the following error bubbles up in console:

TypeError: Auth.isLoggedIn(...).then is not a function at router.decorator.js:18

strangetopology avatar Dec 11 '15 14:12 strangetopology

@dburns I am having the same issue in 3.0.2

I'm also getting the error on the ootb admin page as well.

TypeError: Auth.isLoggedIn(...).then is not a function
    at router.decorator.js:18

acacia314 avatar Dec 15 '15 20:12 acacia314

Look at the updated router.decorator.js from 3.1.0. I'm going to be changing some of the confusing bits of auth.service.js soon..

Awk34 avatar Dec 15 '15 21:12 Awk34

Updated my project to 3.1.0. This resolved this issue on routes with authenticate: true but the error still occurs for the default admin route which is role based authenticate: 'admin'

acacia314 avatar Dec 15 '15 21:12 acacia314

@acacia314 Aha! Fail! In router.decorator.js on this line change return Auth.isLoggedIn().then(is => { to return Auth.isLoggedIn(_.noop).then(is => {

Awk34 avatar Dec 15 '15 21:12 Awk34

@Awk34 yeah that does it! All good after updating to 3.1.0 and fixing the _.noop.

acacia314 avatar Dec 15 '15 21:12 acacia314

@acacia314 Thanks for the comments. That will be fixed in the next patch.

And then later I'm going to change some of the auth service stuff so we don't need to dance around these functions....

Awk34 avatar Dec 15 '15 21:12 Awk34

Thanks!

stevejvv avatar Dec 16 '15 21:12 stevejvv