angularjscontrollerpage-refreshautologincookiestore

AngularJS - Call Login Controller when cookieStore found


I have the following code:

angular.module('myApp', ['ngRoute', 'ngCookies', ... , 'myApp.controllers'])
    .run(function($cookieStore) {
        console.log("Checking user credentials");
        if ($cookieStore.get('credentials') != null) {
            console.log("User credentials found in cookies");
            //LoginCtrl.login($cookieStore.get('credentials'));
        }
    })

The goal of this code is that when the app runs it checks the cookiestore for saved credentials. If it finds credentials I want it to call the function login() from the Login Controller defined below:

angular.module('myApp.controllers')
    .controller('LoginCtrl', function($scope, $log, $cookieStore, $location, $http, AuthenticationService, User) {

        $scope.login = function(credentials) {
            $log.debug("/POST to /api/login");
            AuthenticationService.login(credentials).success(function(user) {
                ...
            }).error(function(err) {
                ...
            });
        };

It is currently complaining that LoginCtrl doesn't exist and I've tried various ways to try to define the LoginCtrl (myApp.controllers.LoginCtrl, myApp.LoginCtrl, etc) but none seem to work.

Any advice on this please? I don't want to save a user object in the cookie, I'd rather save the credentials with a hashed password.

Thank you for any help and advice you can provide!


Solution

  • The pattern for share code between controllers is services, you need create a generic service to authenticate and use this service between controllers