Friday 21 April 2017

Retrieving the name from the database provided the username

By this method, I can get the username from the database which is provided in the login form. The username is registered with first name, last name, email. How to get all the details from the server. I'm using JWT for session implementation and storing the token in the cookie. I wanna use,

<div ng-show="currentUser">Hello,  </div>

server.js

  var express = require('express');
    var bodyParser = require('body-parser');
    var bcrypt = require('bcryptjs');
    var jwt = require('jwt-simple');
    var MongoClient = require('mongodb').MongoClient;
    var ObjectId = require('mongodb').ObjectId;

    var app = express();
    var JWT_SECRET = '***';

    var url = 'mongodb://localhost:27017/**';

    var db = null;
    MongoClient.connect(url, function(err, dbconn) {
        if(!err){
            console.log("Connected correctly to server.");
            db = dbconn;
        }
    });

    app.use(bodyParser.json());
    app.use(express.static('client'));


    app.post('/register', function (req, res, next) {

      db.collection('users',function (err, usersCollection) {

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(req.body.password, salt, function(err, hash) {


              var newUser = {
                  firstName : req.body.firstName,
                  lastName : req.body.lastName,
                  userName : req.body.userName,
                  email : req.body.email,
                  password : hash
              }

              usersCollection.insert(newUser, {w:1}, function (err) {
                  return res.send();
              });
          });
       });
    });
});

app.put('/login', function (req, res, next) {

    db.collection('users',function (err, usersCollection) {

        usersCollection.findOne({userName: req.body.userName}, function (err,user) {

            bcrypt.compare(req.body.password, user.password,function (err,result) {
                if(result) {
                    var mytoken = jwt.encode(user, JWT_SECRET);
                    return res.json({token : mytoken});
                } else {
                    return res.status(400).send();
                }
            });
        });
    });
});


app.listen(3000, function () {
    console.log('app running on port 3000!')
});

My controller.js

.controller('RegisterController',function ($scope, $http) {

    $scope.signup = function() {

        var newUser = {
            firstName : $scope.firstName,
            lastName : $scope.lastName,
            userName : $scope.userName,
            email : $scope.email,
            password : $scope.password,
        };
            $http.post('/register', newUser).then(function () {
            alert('success');
            document.getElementById("registerForm").reset();
            });

    }
})

.controller('LoginController',function ($rootScope, $scope, $http, $cookies) {

    $scope.signin = function () {

        var user = {
            userName : $scope.userName,
            password: $scope.password
        };

        $http.put('/login', user)
            .then(function(res) {
                $cookies.put('token', res.data.token);
                $cookies.put('currentUser', $scope.userName);
                $rootScope.token = res.data.token;
                $rootScope.currentUser = $scope.userName;
                document.getElementById("loginForm").reset();
            },
            function (err) {
                alert('check username and password');
            });
    }

    $scope.logout = function () {
        $cookies.remove('token');
        $cookies.remove('currentUser');
        $rootScope.token = null;
        $rootScope.currentUser = null;
    }

})

.run(function ($cookies, $rootScope, $state, $stateParams, $anchorScroll) {

    $rootScope.$on('$stateChangeStart', function () {
        $anchorScroll();
    });

    if ($cookies.get('token') && $cookies.get('currentUser')) {
        $rootScope.token = $cookies.get('token');
        $rootScope.currentUser = $cookies.get('currentUser');
    }

});

Also, how to store the token in a cookie even though the browser is closed. How and where to set the cookie expiration ?



via 9094US

No comments:

Post a Comment