Difference between revisions of "Module 5"

From CSE330 Wiki
Jump to navigationJump to search
 
(132 intermediate revisions by 13 users not shown)
Line 1: Line 1:
THIS PAGE UNDER CONSTRUCTION
+
__NOTOC__
 +
In Module 5, you will learn JavaScript, the dominant client-side web language.  JavaScript is the third and final programming language you will learn in CSE 330.
  
 +
This article contains your assignments for Module 5.
  
In Module 6, you will learn about python, a scripting language, and Django, a web framework.
+
'''Warning:'''
  
This article contains your assignments for Module 6.
+
''This module takes students a while. It is strongly recommended that you start early and ask questions as they come up.''
 +
 
 +
 
 +
== Reading ==
 +
 
 +
The following articles on the online class wiki textbook contain information that will help you complete the assignments.
 +
 
 +
* [[JavaScript]]
 +
* [[AJAX and JSON]]
 +
* [[jQuery]]
 +
* [[Web Application Security, Part 3]]
 +
* [[FAQ - Mod 5]]
  
 
== Individual Assignments ==
 
== Individual Assignments ==
  
Python tutorial
+
'''''IMPORTANT:'' Both of the individual assignments must be completed ''without'' using a JavaScript library like jQuery.'''  However, you may use jQuery for the group portion.
Django tutorial
+
 
 +
=== JavaScript Calculator ===
  
=== Python Tutorial ===
+
In Module 2, you made a calculator using PHP.  Now you will be making one using JavaScript.
  
====Install Python Tools====
+
* The web page should have two input fields and a radio button group for the operation, with the 4 basic math operations represented (add, subtract, multiply, divide).
*<code>sudo yum install python-setuptools</code><br>
+
* JavaScript should monitor all three fields and display the current result whenever the user changes any value in any field, without refreshing the page.
*<code>sudo yum install python-devel</code>
+
*: '''Tip 1:''' Consider using either the ''change'' or the ''keyup'' event on the text fields, and either the ''change'' or the ''click'' event on the radio buttons.
====Assignment====
+
*: '''Tip 2:''' Re-read [[JavaScript|the JavaScript guide]] if you need help figuring our how to bind callback functions to events, or how to determine which radio button is currently selected.  (There are examples for both of these!)
*You will write a python script that reads a set of student grades in from a file and does some basic parsing and processing. [http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files here] is the section of the python tutorial on reading and writing files.
+
* The calculator should be completely self-contained; i.e., you should not be making any requests to any other server-side or client-side scripts or web pages after the initial page load.
*An example grades file is [http://research.engineering.wustl.edu/~todd/cse330/grades.txt here]. For the sake of simplicity you can assume that the file name is always going to be grades.txt.
 
*The first line of the file is of the form: NUM_LABS,NUM_EXAMS,LAB_WEIGHT
 
*All of the other lines in the file are of the form: FIRSTNAME LASTNAME|GRADE|TYPE
 
*The FIRSTNAME and LASTNAME fields are the student's full name (always only a first and last name), the GRADE is one grade for the student, and the TYPE describes what kind of assignment the grade was for, in this case either a 'lab' or an 'exam'.
 
*Your script should read in a grades file with the above format and perform the following:
 
*# Compute the final grade for every student, given that there were a total of NUM_LABS labs, NUM_EXAMS exams, and that the labs account for a total of LAB_WEIGHT percent of the grade.
 
*# Compute the final letter grade based on the final numeric grade (A = 90 or above, B = 80 - 90, C = 70 - 80, D = 60 - 70, F = below 60). 
 
*# Ignore any blank lines.
 
*# Sort the students by last name, and print out final grades in that sorted order.
 
*# No names should be hard coded into the script (you will run your script on another file with different student names when we grade your assignment).
 
*# Finally, the script should take one optional command line argument, which is a string to match against student names.  Only names that match the string in full or in part, should be printed out with their final grades.
 
***For example, with the argument 'John' grades for both John Smith and John Locke should be printed (if those are the only two Johns in the grades.txt file)
 
  
=== Set Up a Database ===
+
'''Tip:''' You can embed JavaScript code into an HTML document like this:
  
You may find the following article to be very helpful: [[Introduction to MySQL]]
+
<source lang="html4strict">
 +
<script>
 +
// your code here
 +
</script>
 +
</source>
  
# Create a database named '''wustl'''  
+
'''Tip:''' If your code isn't working the way you expect, use a JavaScript error console.  In Chrome, for example, press Ctrl-Shift-I (or Cmd-Option-I) to open the WebKit inspector.
# Create a user named '''wustl_inst''' and give them the password '''wustl_pass'''
 
  
=== Create Tables ===
+
'''Important:''' It is best practice to fully separate the content, appearance, and behavior.  In previous modules, you may have lost points for using HTML tags that change the appearance of things <nowiki>(like <center> and <font>).</nowiki>  In this module, make sure that you define your event listeners in JavaScript as in <code>document.getElementById("xyz").addEventListener(...)</code> and '''''not''''' in the HTML like <code><button onclick="badExample();">Bad Example</button></code>.
  
You may find the following article to be very helpful: [[MySQL Schema and State]]
+
=== Weather Widget ===
  
When creating tables, keep the following items in mind:
+
In this section, you will make a web page that displays the weather forecast using AJAX requests to a weather server.
  
* You should create all tables such that they use the InnoDB storage engine, since we wish to make use of its support of foreign keys. In other database engines, foreign key constraints are not enforced(If you mess up, you can use ALTER TABLE to change the storage engine.)
+
# Make an empty HTML document; name it '''weather.html'''
* Where it is appropriate, you should take advantage of the ability to define fields NOT NULL so that you do not inadvertently insert incomplete data for a row.
+
#: Refer to the [[HTML and CSS]] guide for the skeleton of an HTML document
 +
# Define a function in JavaScript; call it '''fetchWeather()'''.  You may write your JavaScript in an embedded script in your HTML document.
 +
# Inside your '''fetchWeather()''' function, make an AJAX request to the weather server.
 +
#: We have a server that outputs the current weather in JSON format.  The format is documented in the [[#JSON Structure]] section below.
 +
#: '''URL:''' https://classes.engineering.wustl.edu/cse330/content/weather_json.php
 +
#* '''IMPORTANT:''' Under normal circumstances, AJAX requests ''cannot'' be performed cross-domain for security reasons.  We have set the <code>Access-Control-Allow-Origin</code> header on our server to allow requests from your EC2 instances, or from localhost. '''You will therefore need to upload your code to your EC2, or access it via localhost, in order for the AJAX requests to work.''' This means that you cannot, for example, complete this part of the individual portion in JSFiddle.
 +
# In your callback, process the JSON and use JavaScript to manipulate the HTML DOM to display the following information on your page:
 +
#* Location
 +
#** City, in a <nowiki><strong></nowiki> tag
 +
#** State, not in any tag
 +
#* Humidity
 +
#* Current Temperature
 +
#* Image for Tomorrow's Forecast (see [[#Weather Condition Images]] below for more information)
 +
#* Image for the Day After Tomorrow's Forecast
 +
# Finally, bind '''fetchWeather()''' to the DOMContentLoaded event so that your weather widget is automatically initialized when the page is loaded:
 +
#: <source lang="javascript">document.addEventListener("DOMContentLoaded", fetchWeather, false);</source>
 +
# In addition, add a button that runs your ''fetchWeather'' function when clicked.  This should update your widget with the current weather conditions.
  
Create the following tables:
+
Use the following HTML:
  
# Create a table named '''students''' with the following fields:
+
<source lang="html4strict">
#* '''id''' of an appropriately-sized unsigned integer type (we will never need to process more than a million students)
+
<div class="weather" id="weatherWidget">
#* '''first_name''' of type '''VARCHAR(50)'''
+
<div class="weather-loc"></div>
#* '''last_name''' of type '''VARCHAR(50)'''
+
<div class="weather-humidity"></div>
#* '''email_address''' of type '''VARCHAR(50)'''
+
<div class="weather-temp"></div>
#: The primary key should be on the '''id''' field.
+
<img class="weather-tomorrow" />
# Create a table named '''departments''' with the following fields:
+
<img class="weather-dayaftertomorrow" />
#* '''school_code''' of type '''ENUM''' (e.g. "L" for ArtSci and "E" for Engineering).  The options are as follows:
+
</div>
#*: 'L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M'
+
</source>
#* '''dept_id''' of an appropriately-sized unsigned integer type (in the foreseeable future there will never be more than 200 departments in a school)
 
#* '''abbreviation''' of type '''VARCHAR(9)''' (e.g. CSE, ChemE, etc)
 
#* '''dept_name''' of type '''VARCHAR(200)''' (e.g. Computer Science and Engineering)
 
#: The primary key should be on two fields: '''school_code''' and '''dept_id'''
 
#: '''Note:''' Why not just use the department ID? The ID numbers are sometimes reused across schools. For instance, department 33 in The School of Arts and Sciences is Psychology while department 33 in The School of Engineering and Applied Sciences is Energy, Environmental and Chemical Engineering. Thus we must also include the school code to differentiate them  such that the record for  E33 is distinct from that of L33.
 
# Create a table named '''courses''' with the following fields:
 
#* '''school_code''' of type '''ENUM'''
 
#*: This should have the same letters in the same order as the '''school_code''' '''ENUM''' field in the '''departments''' table.
 
#* '''dept_id''' of the same size of integer as in the '''departments''' table
 
#* '''course_code''' of type '''CHAR(5)''' (this will hold course codes; e.g., '330S', '131', '2960')
 
#* '''name''' of type '''VARCHAR(150)'''
 
#: The appropriate fields in this table should make a foreign key reference to the corresponding fields in '''department'''.
 
#: In addition, it is up to you to determine the field(s) for the primary key.
 
#: '''Note:''' If you are unsure which fields to make the foreign keys and feel the need to beg your friends or the TAs to give you the answer, bang your head on your desk whilst repeating "I WILL EXERCISE REASON AND COMMON SENSE AND I WILL CURTAIL MY DESIRE TO BLINDLY FOLLOW DIRECTIONS"
 
#: ''Disclaimer: don't actually bang your head on your desk, the resulting head trauma may in fact make it harder for you to determine which fields should have associated foreign keys.''
 
# Create a table named '''grades''' with the following fields:
 
#* '''pk_grade_ID''' of an appropriately-sized unsigned integer type (should be larger than the one you chose for the '''students''' table)
 
#*: You should declare this field to be '''auto_increment''' and make it the primary key.
 
#*: This is called a ''surrogate key'' as opposed to a ''natural key'' because it doesn't arise "naturally" from the data; that is to say that it is not derived from application data. The use of surrogate keys vs. natural keys is a polemic issue amongst database designers.  For a decently unbiased take on the issue, see this page: http://www.agiledata.org/essays/keys.html#Comparison
 
#*: '''Food for thought:''' Aside from simply exposing you to the concept, can you think of any reasons why a surrogate key might be preferable for this table?  Alternatively, what attributes, if any, could you use as a natural key, and what might be the drawbacks of doing so?
 
#* '''student_id''' of the same integer (unsigned) type that you chose in the '''students''' table
 
#* '''grade''' of type '''decimal'''
 
#* '''school_code''' of type '''ENUM'''
 
#*: Can you guess what entries to use for the enum?
 
#* '''dept_id''' of the same integer type that you've used for this field in other tables
 
#* '''course_code''' of the same type you chose for the course code in the '''courses''' table
 
#: The '''grades''' table should have foreign keys to both the '''students''' table and the '''courses''' table.
 
  
=== Populate Tables ===
+
Include the CSS file from here: https://classes.engineering.wustl.edu/cse330/content/weather.css
  
Now, populate the tables by downloading the text files given below and loading them into the appropriate tables.
+
When everything is working, the weather widget should look something like this:
  
'''Note:''' Do not insert all the values manually; instead, use the MySQL's ability to load in data from text files.
+
[[File:WeatherWidget.png]]
  
You may find the following article to be very helpful: [[MySQL Schema and State]]
+
'''Important:''' The widget in this section needs to work in only Firefox and Chrome.  It does '''''not''''' need to work Internet Explorer.
  
The files containing the data are:
+
==== Tips ====
* students: http://research.engineering.wustl.edu/~todd/cse330/students_data.txt
 
* courses: http://research.engineering.wustl.edu/~todd/cse330/course_data.txt
 
* departments: http://research.engineering.wustl.edu/~todd/cse330/departments_data.txt
 
* grades: http://research.engineering.wustl.edu/~todd/cse330/grade_data.txt
 
  
=== Insert More Data ===
+
===== JSON Structure =====
  
Insert the following data into the tables that you have created and populated:
+
The JSON from our server looks like this:
  
# Insert an entry for CSE 330
+
<source lang="javascript">
#: ''If you don't know CSE's department code, how can you find out using the tables in the database?''
+
{
# Insert the grades given for the students named below. You may choose to make the entries for whichever classes you like, with the one condition that all of the students must have a grade for CSE 330 (who wouldn't want to take that class: I hear the professor and TAs are amazing!)
+
  "updated": "Thu, 11 Oct 2012 5:54 pm CDT",
#* '''Ben Harper'''
+
  "location": {
#** E-mail: '''bharper@ffym.com'''
+
      "city": "St. Louis",
#** Student ID: '''88'''
+
      "state": "MO"
#** Grades:
+
  },
#*** 5.5
+
  "wind": {
#*** 0
+
      "chill": "62",
#*** 20
+
      "direction": "150",
#* '''Matt Freeman'''
+
      "speed": "3 mph"
#** E-mail: '''mfreeman@kickinbassist.net'''
+
  },
#** Student ID: '''202'''
+
  "atmosphere": {
#** Grades:
+
      "humidity": "50",
#*** 100
+
      "visibility": "10",
#*** 90.5
+
      "pressure": "30.12 in"
#*** 94.8
+
  },
#* '''Marc Roberge'''
+
  "current": {
#** E-mail: '''mroberge@ofarevolution.us'''
+
      "code": "28",
#** Student ID: '''115'''
+
      "text": "Mostly Cloudy",
#** Grades:
+
      "temp": "62°F",
#*** 15
+
      "date": "Thu, 11 Oct 2012 5:54 pm CDT"
#*** 37
+
  },
#*** 45.5
+
  "tomorrow": {
#: You may choose any 3 classes you'd like for them to be enrolled in, with at least one class, "CSE 330S", in which they are all enrolled.
+
      "code": "29",
 +
      "text": "Clouds Early/Clearing Late",
 +
      "low": "45°F",
 +
      "high": "61°F"
 +
  },
 +
  "dayafter": {
 +
      "code": "30",
 +
      "text": "Partly Cloudy",
 +
      "low": "53°F",
 +
      "high": "65°F"
 +
  },
 +
  "credit": "http://us.rd.yahoo.com/dailynews/rss/weather/St._Louis__MO/*http://weather.yahoo.com/forecast/USMO0170_f.html"
 +
}
 +
</source>
  
=== Querying Your Database ===
+
===== Weather Condition Images =====
  
Now that you have a fully-functional, populated database, let's do some queries on it!
+
Each day's forecast has a code.  There are images associated with these codes.
  
Please take a screenshot of running the following '''select''' queries and show them to a TA (be sure to include your query command and the response:
+
One place to get the images is from here: <nowiki>http://us.yimg.com/i/us/nws/weather/gr/</nowiki>'''##'''<nowiki>ds.png</nowiki>
  
# Select the entire grades table.
+
Replace the '''##''' with the forecast code. For example, for code 32, the URL would be: http://us.yimg.com/i/us/nws/weather/gr/32ds.png
# Select all fields describing the courses offered in the school of arts and sciences (school code L).
 
# The names, student IDs, and grades of the students who are in CSE330.
 
# The names and e-mails of any student with an average below 50 so that the dean can send them an email notification that they are now on academic probation.
 
#: ''You should be able to do this in only one query, without making any temporary tables.  You will need to use aggregation functions and the '''having''' keyword.''
 
# An individual report card for Jack Johnson, consisting of two tables (these can be done using separate queries):
 
## His student ID, e-mail address, and average grade.
 
##: ''Again, you should be able to do this in just one query, using the correct combination of aggregation functions and joins.''
 
## The classes he is in and his grades for those classes. To give you an idea, one row in the table should look like this:
 
##: <code>E 81 400 Independent Study 98.5</code>
 
  
 
== Group Project ==
 
== Group Project ==
  
You will work in pairs on this projectYou may work with the same partner from Module 2, or change to someone else.
+
I forgot if I already mentioned this, but '''start early on this project!''' It will take longer than you think, I promise!
 +
 
 +
You are encouraged to use the advanced version control practices you learned in Module 5 when completing this assignment.
 +
 
 +
=== Calendar ===
  
'''Important Reminder:''' frequently commit your work to your subversion repository as a backup!
+
Build a simple calendar that allows users to add and remove events dynamically.
  
=== Simple News Web Site ===
+
You will use JavaScript to process user interactions at the web browser, without ever refreshing the browser after the initial web page load.  You may use a JavaScript library of your choice, including Ext JS, so long as that JavaScript library does not defeat the purpose of the assignment. If you have questions about this, ask. In particular, libraries like FullCalendar are unacceptable.
  
'''Examples:'''
+
Your application should utilize AJAX to run server-side scripts that query your database to save and retrieve information, including user accounts and events.
* http://digg.com/
 
* http://slashdot.org/
 
  
You should use '''PHP''' unless you get permission to use another web technology from the instructor.  You may also use phpMyAdmin to help set up databases.
+
We have also written some functions to help you get started: [[JavaScript Calendar Library]]
  
You may find this wiki article helpful: [[PHP and MySQL]]
+
==== Examples ====
 +
 
 +
* https://calendar.google.com/
 +
* http://www.zoho.com/calendar/
 +
 
 +
==== Server Side Language ====
 +
 
 +
 
 +
Additionally, you may use a database of your choice.  MySQL is probably the logical choice since you have been using it since Module 2, but you are free to explore other databases if you like.
  
 
==== Requirements ====
 
==== Requirements ====
  
* Users can register for accounts and then log in to the website.
+
* Support a month-by-month view of the calendar.
* Accounts should have both a username and a ''secure'' password. '''NEVER store plaintext passwords in a database!'''
+
*: Show one month at a time, with buttons to move forward or backward.
*: For more information on password security, refer to [[Web Application Security, Part 2#Password Security|the Web Application Security guide]].
+
*: There should be no limit to how far forward or backward the user can go.
* Registered users can submit stories: either a link with summary or news text.
+
* Users can register and log in to the website.
*: You do not have to make a distinction between the two types of stories, although if you want to, you could do something with this for the creative portion of your project.
+
*: You may leverage your MySQL project code and database from module 3 to get started.
* Registered users can comment on any story.
+
* Unregistered users should see no events on the calendar.
* Administrator users can delete stories and comments.
+
* Registered users can add events.
* Unregistered users can only view stories and comments.
+
*: All events should have a date and time, but do not need to have a duration.
* Registered users can edit their stories and can delete their comments.
+
*: You do ''not'' need to support recurring events (where you add an event that repeats, for example, every monday).
* All data must be kept in a MySQL database (user information, stories, comments, and categories).
+
* Registered users see only events that they have added.
* As before, please check with a TA to see if your creative portion is okay or not before you proceed.
+
*: Your AJAX should not ask the server for events from a certain username.  Instead, your AJAX should ask the server for events, and the server should respond with the events for only the currently-logged-in user (from the session). Can you think of why?
 +
* Registered users can edit and delete their own events, but not the events of others.
 +
*: Again, the server should edit and delete events based on the username present in the session, not based on a username or event ID provided by the user.  (If it deletes only based on an Event ID, an attacker could feed any arbitrary Event ID to your server, even if he/she didn't own that event.)
 +
* All user and event data should be kept in a database.
 +
* At no time should the main page need to be reloaded.
 +
*: User registration, user authentication, event addition, and event deletion should all be handled by JavaScript and AJAX requests to your server.
 +
* Your page needs to work in the versions of Firefox and Chrome installed on the lab computers.
 +
 
 +
'''Tip:''' Run your database schema by a TA before implementing it.
  
 
=== Web Security and Validation ===
 
=== Web Security and Validation ===
  
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 2]]
+
Your project needs to demonstrate that thought was put into web security and best practice.  For more information, see this week's Web Application Security guide: [[Web Application Security, Part 3]]
  
 
In particular:
 
In particular:
  
* '''Your application needs to be secure from SQL injection attacks'''. If you are using prepared queries, you should already be safe on this front.
+
* '''Your application needs to prevent XSS attacks.''' Be careful when transmitting data over JSON that will be reflected in an event title!  (Note: JSON data should be sanitized on the client side, not the server side.)
* '''All of your output needs to be sanitized using htmlentities()'''.
+
* '''Perform precautionary measures to prevent session hijacking attacks.'''
 +
*: You should specify your session cookie to be HTTP-Only.  However, for the means of this module, you need not test for user agent consistency.
  
You shouldn't forget the practices you learned last week:
+
You should continue the practices that you have learned in past weeks:
  
* '''You should pass tokens in forms''' to prevent CSRF attacks.
+
* Pass tokens in forms to prevent CSRF attacks.
* '''Your page should validate''' with no errors through the W3C validator.
+
*: '''Hint:''' You will need to send your CSRF tokens in your AJAX requests.  Remember that AJAX still submits forms and runs server-side scripts, just like the vanilla forms you've been using in Modules 2 and 3.
 +
* Use prepared queries to prevent SQL Injection attacks.
 +
* If storing passwords in a database, always store them salted and encrypted.
 +
* Your page should validate with no errors or warnings through the W3C validator.
  
 
== Grading ==
 
== Grading ==
  
<span style="font-size:2em; line-height:2em;">'''Due Date: Wednesday October 10th, by 1pm (both individual and group)'''</span>
 
  
{|
+
We will be grading the following aspects of your work.  There are 100 points in total.
!Assignment
+
 
!Points
+
'''Assignments (including code) must be committed to Github by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0. '''
|-
+
 
|Tables Correct
+
If you do not include a link to your individual and group portion running on your instance in the respective README.md, you will receive a 0 for the missing portion
|2
+
 
|-
+
_________
|Data Queries Correct
 
|2
 
|-
 
!colspan="2"|Group Portion:
 
|-
 
|User Authentication
 
|1
 
|-
 
|User Registration
 
|1
 
|-
 
|Salted One-Way Encryption
 
|1
 
|-
 
|Main page displays all stories (or most recent stories)
 
|1
 
|-
 
|Page with individual story and comments
 
|1
 
|-
 
|Story Submission
 
|1
 
|-
 
|Comment System
 
|1
 
|-
 
|Administrator Deletion of Stories/Comments
 
|1
 
|-
 
|User Edit/Delete of Story (1 pt) and Delete of Comment (1 pt)
 
|2
 
|-
 
|Protect Against SQL Injection Attack
 
|1
 
|-
 
|Sanitize Output
 
|1
 
|-
 
|CSRF Safe and Validation
 
|1
 
|-
 
|Creative Portion
 
|2
 
|-
 
|}
 
  
 +
# '''JavaScript Calculator (10 Points):'''
 +
#* Calculator successfully adds, subtracts, multiplies, and divides numbers (3 points)
 +
#* The result is automatically computed when a value in either field is changed (3 points)
 +
#* Calculator is written entirely in pure, conventional JavaScript with no external libraries (4 points)*
 +
#*: ''Note: be sure to fully separate content, appearance, and behavior.  This means that you should '''not''' use the event attributes on the HTML elements like onclick, onchange, and onkeyup.''
 +
# '''Weather Widget (15 Points):'''
 +
#* Widget performs an AJAX request to fetch the current weather (4 points)
 +
#* The HTML template is filled with the correct information, including an image (4 points)
 +
#* Button to reload the weather widget (2 points)
 +
#* Widget is written entirely in pure, conventional JavaScript with no external libraries (5 points)*
 +
# '''AJAX Calendar (60 Points):'''
 +
#* '''''Calendar View (10 Points):'''''
 +
#** The calendar is displayed as a table grid with days as the columns and weeks as the rows, one month at a time (5 points)
 +
#** The user can view different months as far in the past or future as desired (5 points)
 +
#* '''''User and Event Management (25 Points):'''''
 +
#** Events can be added, modified, and deleted (5 points)
 +
#** Events have a title, date, and time (2 points)
 +
#** Users can log into the site, and they cannot view or manipulate events associated with other users (8 points)
 +
#**: ''Don't fall into the Abuse of Functionality trap!  Check user credentials on the server side as well as on the client side.''
 +
#** All actions are performed over AJAX, without ever needing to reload the page (7 points)
 +
#** Refreshing the page does not log a user out (3 points)
 +
#* '''''Best Practices (20 Points):'''''
 +
#** Code is well formatted and easy to read, with proper commenting (2 points)
 +
#** If storing passwords, they are stored salted and hashed (2 points)
 +
#** All AJAX requests that either contain sensitive information or modify something on the server are performed via POST, not GET (3 points)
 +
#** Safe from XSS attacks; that is, all content is escaped on output (3 points)
 +
#** Safe from SQL Injection attacks (2 points)
 +
#** CSRF tokens are passed when adding/editing/deleting events (3 points)
 +
#** Session cookie is HTTP-Only (3 points)
 +
#** Page passes the W3C validator (2 points)
 +
#* '''''Usability (5 Points):'''''
 +
#** Site is intuitive to use and navigate (4 points)
 +
#** Site is visually appealing (1 point)
 +
# '''Creative Portion (15 Points)'''
 +
#* '''Additional Calendars Features (worth 15 points):''' Develop some additional features for the calendar, a few examples are provided below.
 +
#**  Users can tag an event with a particular category and enable/disable those tags in the calendar view. (5 points)
 +
#**  Users can share their calendar with additional users. (5 points)
 +
#**  Users can create group events that display on multiple users calendars (5 points)
 +
#*  '''Make sure to save a description of your creative portion, and a link to your server in your README.md file.'''
 +
''* These points can be earned only if at least 3 other points have been earned in that category.  This is to prevent these points from being "free."''
  
Total Points = 19
+
[[Category:Module 5]]
[[Category:Module 3]]
 
 
[[Category:Modules]]
 
[[Category:Modules]]

Latest revision as of 20:23, 11 March 2021

In Module 5, you will learn JavaScript, the dominant client-side web language. JavaScript is the third and final programming language you will learn in CSE 330.

This article contains your assignments for Module 5.

Warning:

This module takes students a while. It is strongly recommended that you start early and ask questions as they come up.


Reading

The following articles on the online class wiki textbook contain information that will help you complete the assignments.

Individual Assignments

IMPORTANT: Both of the individual assignments must be completed without using a JavaScript library like jQuery. However, you may use jQuery for the group portion.

JavaScript Calculator

In Module 2, you made a calculator using PHP. Now you will be making one using JavaScript.

  • The web page should have two input fields and a radio button group for the operation, with the 4 basic math operations represented (add, subtract, multiply, divide).
  • JavaScript should monitor all three fields and display the current result whenever the user changes any value in any field, without refreshing the page.
    Tip 1: Consider using either the change or the keyup event on the text fields, and either the change or the click event on the radio buttons.
    Tip 2: Re-read the JavaScript guide if you need help figuring our how to bind callback functions to events, or how to determine which radio button is currently selected. (There are examples for both of these!)
  • The calculator should be completely self-contained; i.e., you should not be making any requests to any other server-side or client-side scripts or web pages after the initial page load.

Tip: You can embed JavaScript code into an HTML document like this:

<script>
// your code here
</script>

Tip: If your code isn't working the way you expect, use a JavaScript error console. In Chrome, for example, press Ctrl-Shift-I (or Cmd-Option-I) to open the WebKit inspector.

Important: It is best practice to fully separate the content, appearance, and behavior. In previous modules, you may have lost points for using HTML tags that change the appearance of things (like <center> and <font>). In this module, make sure that you define your event listeners in JavaScript as in document.getElementById("xyz").addEventListener(...) and not in the HTML like <button onclick="badExample();">Bad Example</button>.

Weather Widget

In this section, you will make a web page that displays the weather forecast using AJAX requests to a weather server.

  1. Make an empty HTML document; name it weather.html
    Refer to the HTML and CSS guide for the skeleton of an HTML document
  2. Define a function in JavaScript; call it fetchWeather(). You may write your JavaScript in an embedded script in your HTML document.
  3. Inside your fetchWeather() function, make an AJAX request to the weather server.
    We have a server that outputs the current weather in JSON format. The format is documented in the #JSON Structure section below.
    URL: https://classes.engineering.wustl.edu/cse330/content/weather_json.php
    • IMPORTANT: Under normal circumstances, AJAX requests cannot be performed cross-domain for security reasons. We have set the Access-Control-Allow-Origin header on our server to allow requests from your EC2 instances, or from localhost. You will therefore need to upload your code to your EC2, or access it via localhost, in order for the AJAX requests to work. This means that you cannot, for example, complete this part of the individual portion in JSFiddle.
  4. In your callback, process the JSON and use JavaScript to manipulate the HTML DOM to display the following information on your page:
    • Location
      • City, in a <strong> tag
      • State, not in any tag
    • Humidity
    • Current Temperature
    • Image for Tomorrow's Forecast (see #Weather Condition Images below for more information)
    • Image for the Day After Tomorrow's Forecast
  5. Finally, bind fetchWeather() to the DOMContentLoaded event so that your weather widget is automatically initialized when the page is loaded:
    document.addEventListener("DOMContentLoaded", fetchWeather, false);
    
  6. In addition, add a button that runs your fetchWeather function when clicked. This should update your widget with the current weather conditions.

Use the following HTML:

<div class="weather" id="weatherWidget">
	<div class="weather-loc"></div>
	<div class="weather-humidity"></div>
	<div class="weather-temp"></div>
	<img class="weather-tomorrow" />
	<img class="weather-dayaftertomorrow" />
</div>

Include the CSS file from here: https://classes.engineering.wustl.edu/cse330/content/weather.css

When everything is working, the weather widget should look something like this:

WeatherWidget.png

Important: The widget in this section needs to work in only Firefox and Chrome. It does not need to work Internet Explorer.

Tips

JSON Structure

The JSON from our server looks like this:

{
   "updated": "Thu, 11 Oct 2012 5:54 pm CDT",
   "location": {
      "city": "St. Louis",
      "state": "MO"
   },
   "wind": {
      "chill": "62",
      "direction": "150",
      "speed": "3 mph"
   },
   "atmosphere": {
      "humidity": "50",
      "visibility": "10",
      "pressure": "30.12 in"
   },
   "current": {
      "code": "28",
      "text": "Mostly Cloudy",
      "temp": "62°F",
      "date": "Thu, 11 Oct 2012 5:54 pm CDT"
   },
   "tomorrow": {
      "code": "29",
      "text": "Clouds Early/Clearing Late",
      "low": "45°F",
      "high": "61°F"
   },
   "dayafter": {
      "code": "30",
      "text": "Partly Cloudy",
      "low": "53°F",
      "high": "65°F"
   },
   "credit": "http://us.rd.yahoo.com/dailynews/rss/weather/St._Louis__MO/*http://weather.yahoo.com/forecast/USMO0170_f.html"
}
Weather Condition Images

Each day's forecast has a code. There are images associated with these codes.

One place to get the images is from here: http://us.yimg.com/i/us/nws/weather/gr/##ds.png

Replace the ## with the forecast code. For example, for code 32, the URL would be: http://us.yimg.com/i/us/nws/weather/gr/32ds.png

Group Project

I forgot if I already mentioned this, but start early on this project! It will take longer than you think, I promise!

You are encouraged to use the advanced version control practices you learned in Module 5 when completing this assignment.

Calendar

Build a simple calendar that allows users to add and remove events dynamically.

You will use JavaScript to process user interactions at the web browser, without ever refreshing the browser after the initial web page load. You may use a JavaScript library of your choice, including Ext JS, so long as that JavaScript library does not defeat the purpose of the assignment. If you have questions about this, ask. In particular, libraries like FullCalendar are unacceptable.

Your application should utilize AJAX to run server-side scripts that query your database to save and retrieve information, including user accounts and events.

We have also written some functions to help you get started: JavaScript Calendar Library

Examples

Server Side Language

Additionally, you may use a database of your choice. MySQL is probably the logical choice since you have been using it since Module 2, but you are free to explore other databases if you like.

Requirements

  • Support a month-by-month view of the calendar.
    Show one month at a time, with buttons to move forward or backward.
    There should be no limit to how far forward or backward the user can go.
  • Users can register and log in to the website.
    You may leverage your MySQL project code and database from module 3 to get started.
  • Unregistered users should see no events on the calendar.
  • Registered users can add events.
    All events should have a date and time, but do not need to have a duration.
    You do not need to support recurring events (where you add an event that repeats, for example, every monday).
  • Registered users see only events that they have added.
    Your AJAX should not ask the server for events from a certain username. Instead, your AJAX should ask the server for events, and the server should respond with the events for only the currently-logged-in user (from the session). Can you think of why?
  • Registered users can edit and delete their own events, but not the events of others.
    Again, the server should edit and delete events based on the username present in the session, not based on a username or event ID provided by the user. (If it deletes only based on an Event ID, an attacker could feed any arbitrary Event ID to your server, even if he/she didn't own that event.)
  • All user and event data should be kept in a database.
  • At no time should the main page need to be reloaded.
    User registration, user authentication, event addition, and event deletion should all be handled by JavaScript and AJAX requests to your server.
  • Your page needs to work in the versions of Firefox and Chrome installed on the lab computers.

Tip: Run your database schema by a TA before implementing it.

Web Security and Validation

Your project needs to demonstrate that thought was put into web security and best practice. For more information, see this week's Web Application Security guide: Web Application Security, Part 3

In particular:

  • Your application needs to prevent XSS attacks. Be careful when transmitting data over JSON that will be reflected in an event title! (Note: JSON data should be sanitized on the client side, not the server side.)
  • Perform precautionary measures to prevent session hijacking attacks.
    You should specify your session cookie to be HTTP-Only. However, for the means of this module, you need not test for user agent consistency.

You should continue the practices that you have learned in past weeks:

  • Pass tokens in forms to prevent CSRF attacks.
    Hint: You will need to send your CSRF tokens in your AJAX requests. Remember that AJAX still submits forms and runs server-side scripts, just like the vanilla forms you've been using in Modules 2 and 3.
  • Use prepared queries to prevent SQL Injection attacks.
  • If storing passwords in a database, always store them salted and encrypted.
  • Your page should validate with no errors or warnings through the W3C validator.

Grading

We will be grading the following aspects of your work. There are 100 points in total.

Assignments (including code) must be committed to Github by the end of class on the due date (commit early and often). Failing to commit by the end of class on the due date will result in a 0.

If you do not include a link to your individual and group portion running on your instance in the respective README.md, you will receive a 0 for the missing portion

_________

  1. JavaScript Calculator (10 Points):
    • Calculator successfully adds, subtracts, multiplies, and divides numbers (3 points)
    • The result is automatically computed when a value in either field is changed (3 points)
    • Calculator is written entirely in pure, conventional JavaScript with no external libraries (4 points)*
      Note: be sure to fully separate content, appearance, and behavior. This means that you should not use the event attributes on the HTML elements like onclick, onchange, and onkeyup.
  2. Weather Widget (15 Points):
    • Widget performs an AJAX request to fetch the current weather (4 points)
    • The HTML template is filled with the correct information, including an image (4 points)
    • Button to reload the weather widget (2 points)
    • Widget is written entirely in pure, conventional JavaScript with no external libraries (5 points)*
  3. AJAX Calendar (60 Points):
    • Calendar View (10 Points):
      • The calendar is displayed as a table grid with days as the columns and weeks as the rows, one month at a time (5 points)
      • The user can view different months as far in the past or future as desired (5 points)
    • User and Event Management (25 Points):
      • Events can be added, modified, and deleted (5 points)
      • Events have a title, date, and time (2 points)
      • Users can log into the site, and they cannot view or manipulate events associated with other users (8 points)
        Don't fall into the Abuse of Functionality trap! Check user credentials on the server side as well as on the client side.
      • All actions are performed over AJAX, without ever needing to reload the page (7 points)
      • Refreshing the page does not log a user out (3 points)
    • Best Practices (20 Points):
      • Code is well formatted and easy to read, with proper commenting (2 points)
      • If storing passwords, they are stored salted and hashed (2 points)
      • All AJAX requests that either contain sensitive information or modify something on the server are performed via POST, not GET (3 points)
      • Safe from XSS attacks; that is, all content is escaped on output (3 points)
      • Safe from SQL Injection attacks (2 points)
      • CSRF tokens are passed when adding/editing/deleting events (3 points)
      • Session cookie is HTTP-Only (3 points)
      • Page passes the W3C validator (2 points)
    • Usability (5 Points):
      • Site is intuitive to use and navigate (4 points)
      • Site is visually appealing (1 point)
  4. Creative Portion (15 Points)
    • Additional Calendars Features (worth 15 points): Develop some additional features for the calendar, a few examples are provided below.
      • Users can tag an event with a particular category and enable/disable those tags in the calendar view. (5 points)
      • Users can share their calendar with additional users. (5 points)
      • Users can create group events that display on multiple users calendars (5 points)
    • Make sure to save a description of your creative portion, and a link to your server in your README.md file.

* These points can be earned only if at least 3 other points have been earned in that category. This is to prevent these points from being "free."