HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Creating a simple login with AngularJS

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
angularjssimplecreatingwithlogin

Problem

I'm brand new to AngularJS. I would like advice as to whether I'm approaching the design of a simple login section of an app built with Angular correctly.

The app consists of two view partials: login.html and user-admin.html. Of what I have so far, the user types their username into the login page. A controller checks if that username is listed in users.json file, if so then login is successful and the user-admin.html partial replaces login.html.

I feel that the controller which checks the typed username against the usernames in users.json could be written better. Is there a more efficient way than using the 'for' statement?

To develop this further I will want to add some way of preventing a logged in user seeing the login page and a non-logged in user seeing the admin page. My initial thought is to use cookies. But would the 'Angular' way be to create a service that perpetuates the logged in status between views? If that is the best way to implement it, what would that service look like?

app.js

angular.module('userApp', ["ngResource"]).

config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/login', {templateUrl: 'partials/login.html',   controller: LoginCtrl}).
        when('/loggedin', {templateUrl: 'partials/user-admin.html', controller: UserCtrl}).
        otherwise({redirectTo: '/login'});
}],[ '$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode = true;
}]).

factory("User", function($resource) {
    return $resource("users/:userId.json", {}, {
        query: {method: "GET", params: {userId: "users"}, isArray: true}
    });
});


controllers.js

```
function LoginCtrl($scope, $route, $routeParams, $location, User) {
$scope.users = User.query();
$scope.loginUser = function() {
var loggedin = false;
var totalUsers = $scope.users.length;
var usernameTyped = $scope.userUsername;

for( i=0; i < totalUsers; i++ ) {
if( $scope.users[i].name

Solution

There is much wrong with your code..

  • You are iterating over every record to find a username, what happens if you have lots of users ?



  • You are not verifying the password !?



  • It seems like you are exposing the REST services with all the user id's and passwords !?



  • It seems that if the user knows the /loggedin URL, then the user can skip logging in since you do not validate loggedIn anywhere. Even worse, loggedIn is a variable local to LoginCtrl.



It is good to try and write everything yourself, it brings valuable experience. But please, use this only for throwaway websites.

Context

StackExchange Code Review Q#21245, answer score: 6

Revisions (0)

No revisions yet.