Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMPE 280 Web UI Design and Development October 26 Class Meeting

Similar presentations


Presentation on theme: "CMPE 280 Web UI Design and Development October 26 Class Meeting"— Presentation transcript:

1 CMPE 280 Web UI Design and Development October 26 Class Meeting
Department of Computer Engineering San Jose State University Fall 2017 Instructor: Ron Mak

2 Sessions Each time a user requests a web page from your application is a separate and isolated request and response. To provide a good user experience, your server must maintain a “conversation” by remembering information from one request to another. Otherwise, your application has severe amnesia. For example, your application needs to remember that a user has already logged in.

3 Sessions, cont’d Many applications require new users to register.
You can store registered users in a database. Registered user then must log in each time to use the application. The application can keep track of a logged-in user in a session. Only logged-in users can visit certain pages. The application remembers that a user is logged in so that each request doesn’t require a log in. Each logged-in user is in a separate session.

4 Example: User Authentication
A very simple example of user authentication. User registration and log in We will use the express-session module: ...   "dependencies": {     "body-parser": "~1.18.2",     "debug": "~2.6.9",     "express": "~4.15.5",     "express-session": "^1.15.6",     "jade": "~1.11.0",     "mongodb": "^2.2.25",     "monk": "^4.0.0",     "morgan": "~1.9.0",     "serve-favicon": "~2.4.5"   } package.json

5 User Authentication, cont’d
var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var session = require('express-session'); var index = require('./routes/index'); var app = express(); //View engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));  app.use(express.static(path.join(__dirname, 'public'))); app.use(session( {secret: "String for encrypting cookies." } )); app.use('/', index); module.exports = app; app.listen(3000); app.js

6 User Authentication, cont’d
routes/index.js var express = require('express'); var router = express.Router(); var registeredUsers = []; /*  * GET home page.  */ router.get('/', function(req, res, next)  {     res.render('index', { title: 'Authentication Demo' }); });  * GET registration page. router.get('/register', function(req, res)     res.render('register',               { message: "Please register!" });

7 User Authentication, cont’d
routes/index.js /*  * POST registration page.  */ router.post('/register', function(req, res) {     if(!req.body.username || !req.body.password)     {         res.status("400");         res.send("Invalid details!");     }      else          // Create an array of users with matching usernames.         var matches = registeredUsers.filter(function(user)                       {                           return user.username === req.body.username;                       });         

8 User Authentication, cont’d
routes/index.js         // If there is a match, the user has already registered.         if (matches.length > 0)         {             res.render('register', {message: "User already registered!"});         }                  // Register a new user.         else             var newUser = { username: req.body.username,                              password: req.body.password };             registeredUsers.push(newUser);             console.log("New user:"); console.log(newUser);             console.log("Registered users:"); console.log(registeredUsers);             res.redirect('/login');     } });

9 User Authentication, cont’d
views/register.jade html    head       title Registration    body       if(message)          h4 #{message}          form(action = "/register" method = "POST")              input(name = "username" type = "text" required                     placeholder = "username")              input(name = "password" type = "password" required                     placeholder = "password")              button(type = "Submit") Register me!

10 User Authentication, cont’d
routes/index.js /*  * GET login page.  */ router.get('/login', function(req, res) {    res.render('login', { message: "Please log in!" }); });  * POST login page. router.post('/login', function(req, res)     console.log("Registered users:"); console.log(registeredUsers);     console.log("Logging in: " + req.body.username + "/" + req.body.password);          // Create an array of users with matching credentials.     var matches = registeredUsers.filter(function(user)                   {                       return    (user.username === req.body.username)                               && (user.password === req.body.password);                   });

11 User Authentication, cont’d
routes/index.js     console.log("Matching credentials: "); console.log(matches);          if (matches.length === 0)     {         res.render('login', {message: "Invalid credentials!"});     }     else         // The user is logged in for this session.         req.session.user = matches[0];         console.log("Sucessfully logged in:"); console.log(req.session.user.username);         res.render('protected_page', { name: req.session.user.username }); }); Record the logged-in user in a session.

12 User Authentication, cont’d
views/login.jade html    head       title Login    body       if(message)          h4 #{message}          form(action = "/login" method = "POST")              input(name = "username" type = "text" required                     placeholder = "username")              input(name = "password" type = "password" required                     placeholder = "password")              button(type = "Submit") Log in

13 User Authentication, cont’d
/*  * GET logout page.  */ router.get('/logout', function(req, res) {     console.log("Logging out:");          if (req.session.user)     {         var name = req.session.user.username;         console.log(name);                  req.session.destroy(function()         {             console.log(name + " logged out.");         });         res.send(name + " is now logged out.");     }     else         console.log("Nobody is currently logged in!");         res.send("Nobody is currently logged in!"); }); routes/index.js Kill the session.

14 User Authentication, cont’d
routes/index.js function loggedIn(req, res, next) {     console.log("Checking if logged in:");     if (req.session.user)     {         // Proceed if the user is logged in.         console.log("Logged in: "); console.log(req.session.user);         next();       }      else          console.log("Not logged in");         res.send("You must first log in.")     } } /*  * GET protected page.  */ router.get('/protected_page', loggedIn, function(req, res)     res.render('protected_page', { name: req.session.user.username }); });

15 User Authentication, cont’d
views/protected_page.jade html    head       title Protected page    body       p Hi, #{name}!       p Welcome to the protected page. Demo

16 Cookies A cookie is a small file that the server application writes to the client’s file system. The cookie contents are sent back to the server application each time the client makes a request. Purpose: To keep some information about the user that can be retrieved for a future session. It’s up to the application how to use cookies and what information to keep in them.

17 Simple Cookie Example A very simple demo of cookies.
We will use the Express cookie-parser module. package.json   "dependencies": {     "express": "3.2.6",     "express-session": "^1.15.6",     "cookie-parser": "^1.4.3",     "jade": "*"   }

18 Simple Cookie Example, cont’d
app.js var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var app = express(); app.use(cookieParser()); app.use(session( {secret: "String for encrypting cookies." } ));

19 Simple Cookie Example, cont’d
app.js app.get('/', function(req, res) {     if(req.session.page_views)     {         req.session.page_views++;         res.send("You visited this page " +                   req.session.page_views + " times");         console.log('Cookies: ', req.cookies);     }      else          req.session.page_views = 1;         res.send("Welcome to this page for the first time!");     } }); app.listen(3000); A cookie keeps track of session information. Demo

20 Simple Cookie Example, cont’d
In this example, Express keeps each session’s page count in server memory. Each cookie contains a key value that accesses the session page count. When the server restarts, the counts are lost. More persistent solutions? Write the counts into a database. Write the counts into the cookies.

21 Assignment #4 Add a MongoDB database to your project.
Create web pages to: display documents add and delete documents update documents You must use Express and either Monk or Mongoose to talk to the database. Monk: Mongoose:

22 Assignment #4, cont’d Create a RESTful API to perform operations on your MongoDB database. Add user authentication (registration and log in) with session management. Due Friday, November 3.

23 Review for the Midterm Similar to the first midterm.
Emphasis on material covered since then. Advanced JavaScript regular expressions string formatting DOM modification JavaScript objects instantiation prototypes

24 Review for the Midterm, cont’d
AJAX web browser – node.js cycle XMLHttpRequest object

25 Review for the Midterm, cont’d
jQuery simple AJAX jQuery objects initialization element selection setting style events changing classes dynamically jQuery/AJAX templates automatic looping object effects object animation

26 Review for the Midterm, cont’d
jQuery UI themes icons dragging objects resize an object classes for CSS drag and drop objects widgets

27 Review for the Midterm, cont’d
UI design patterns organization navigation page layout list design

28 Review for the Midterm, cont’d
Data visualization data analysis tables vs. graphs what is data visualization traits of meaningful data visual perception abstract data pre-attentive attributes successful data analyst

29 Review for the Midterm, cont’d
Dashboard design presenting useful information design do’s and don’ts data-ink ratio situational awareness performance monitoring decision making

30 Review for the Midterm, cont’d
NoSQL benefits and disadvantages types semi-structured data document model scalability auto-sharding CAP theorem

31 Review for the Midterm, cont’d
MongoDB documents and collections cursor eventually consistent data query language Express project scaffolding project dependencies MongoDB interface routes and views

32 Review for the Midterm, cont’d
Model-view-controller (MVC) REST HTTP verbs default RESTful actions RESTful web services User authentication sessions user registration and login cookies


Download ppt "CMPE 280 Web UI Design and Development October 26 Class Meeting"

Similar presentations


Ads by Google