Authentication/Authorization INFO 2310: Topics in Web Design and Programming.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

PRESENTED BY MATTHEW GRAF AND LEE MIROWITZ Linked Lists.
The Librarian Web Page Carol Wolf CS396X. Create new controller  To create a new controller that can manage more than just books, type ruby script/generate.
Ruby on Rails Model of MVC. Model-View-Controller Paradigm A way of organizing a software system Benefits: Isolation of business logic from the user interface.
Chapter User authorization & safety Maciej Mensfeld Presented by: Maciej Mensfeld User authorization & safety dev.mensfeld.pl.
JavaScript and Ajax INFO 2310: Topics in Web Design and Programming.
Creating a wiki blog. Run apps that come with instant rails distribution select I /rails applications/open ruby console window Cd to cookbook or typo.
1 Spidering the Web in Python CSC 161: The Art of Programming Prof. Henry Kautz 11/23/2009.
28/08/2015SJF L31 F21SF Software Engineering Foundations ASSUMPTIONS AND TESTING Monica Farrow EM G30 Material available on Vision.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
Welcome to My Tabor Groupwise & My Tabor (LMS) training Student Orientation Fall 2008.
Databases with PHP A quick introduction. Y’all know SQL and Databases  You put data in  You get data out  You can do processing on it very easily 
1 Dr Alexiei Dingli Web Science Stream Models, Views and Controllers.
Securing Ruby on Rails CIS 6939 Web Engineering with Ruby on Rails University of North Florida Stephen Jones 8 July 2007.
By Daniel Siassi.  XHTML  For Structure  CSS  For Stylization of Structure  SQL Database  Store Customer, Calendar, and Order Data  PHP  Server-side.
Server-side Scripting Powering the webs favourite services.
Lecture 14 – Web Security SFDV3011 – Advanced Web Development 1.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Ajax and Ruby on Rails Session 9 INFM 603.
Nachos Phase 1 Code -Hints and Comments
Bill's Amazing Content Rotator jQuery Content Rotator.
1 Dr Alexiei Dingli Web Science Stream Helpers, Forms and Layouts.
FUNCTIONS AND STORED PROCEDURES & FUNCTIONS AND PROTECTING A DB AND PHP (Chapters 9, 15, 18)
PHP meets MySQL.
Sayed Ahmed Computer Engineering, BUET, Bangladesh MSc., Computer Science, Canada
Ruby on Rails Your first app. Rails files app/ Contains the controllers, models, views and assets for your application. You’ll focus on this folder for.
Programming using C# Joins SQL Injection Stored Procedures
Feedback #2 (under assignments) Lecture Code:
CAKEPHP Blog tutorial. what you’ll need examples/blog/blog.html 2  A running web server  A database server.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
Associations INFO 2310: Topics in Web Design and Programming.
Analysis of SQL injection prevention using a filtering proxy server By: David Rowe Supervisor: Barry Irwin.
Photo Gallery INFO 2310: Topics in Web Design and Programming.
Diagnostic Pathfinder for Instructors. Diagnostic Pathfinder Local File vs. Database Normal operations Expert operations Admin operations.
1 Dr Alexiei Dingli Web Science Stream A ROR Twitter.
InfoBox A Personal Information Manager Built with Ruby on Rails Dustin Martin.
RateMyService: Lessons SANS group Milestone 2. Status Report Currently, users to our site can: Search on our site, either by browsing or by using the.
Routes & REST & URL-helpers & validations & filters
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
Grade Book Database Presentation Jeanne Winstead CINS 137.
Creating Programs on UNIX This term you can create programs on UNIX or you can create programs using a C++ compiler on your PC. This set of slides steps.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Implementing The Middle Tier These slides.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
Create, Update and Delete Carol Wolf Computer Science.
PHP Secure Communications Web Technologies Computing Science Thompson Rivers University.
Database Access Control IST2101. Why Implementing User Authentication? Remove a lot of redundancies in duplicate inputs of database information – Your.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
Introduction to Ruby&Rails Yuri Veremeyenko Monica Verma.
Testing External Survey Automatic Credit Granting Shepherd University Department of Psychology.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 1: Introduction to IS2803 Rob Gleasure
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Rails and routing INFO 2310: Topics in Web Design and Programming.
ASSIGNMENT 2 Salim Malakouti. Ticketing Website  User submits tickets  Admins answer tickets or take appropriate actions.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
CS 160 and CMPE/SE 131 Software Engineering February 9 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
CS 160 and CMPE/SE 131 Software Engineering February 11 Class Meeting Department of Computer Science Department of Computer Engineering San José State.
Ruby on Rails. Web Framework for Ruby Designed to make it easier to develop, deploy, and maintain web applications Design with Model-View-Controller –almost.
Introduction to Exceptions in Java CS201, SW Development Methods.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
M M Waseem Iqbal.  Cause: Unverified/unsanitized user input  Effect: the application runs unintended SQL code.  Attack is particularly effective if.
MVC Framework, in general.
Agile Web Development with Ruby and Rails
PHP: Security issues FdSc Module 109 Server side scripting and
In Class Program: Today in History
Queries.
Technical Integration Guide
MVC Controllers.
CMPE/SE 131 Software Engineering February 7 Class Meeting
Presentation transcript:

Authentication/Authorization INFO 2310: Topics in Web Design and Programming

Want to get a job or internship in Information Science? Is your resume ready for companies to see, or would you like it to help you get that job? The ISSA will be having a Resume Workshop specifically tailored to Information Science with Craig Jones from Cornell Career Services Monday, October 6 th, 4:30 in Upson 205 We’ll have food and prizes!

Announcement Last class for INFO 2310 will be November 7, not October 31.

In our last episode… Last time, we defined two new models for users and comments. We also started connecting the models, and starting modifying the associated views to start working more like a blog. Still need to modify routes and controllers (and views) to be more blog-like.

Nested resources

It really doesn’t make sense for comments to be separate from posts; we shouldn’t be able to create a separate comment #4 via a URL comments/4. We really want every comment connected to a post; the URLs for comments should be posts/2/comments/4.

We can do this by updating our routing table to declare that comments are a resource nested inside posts.

Get config/routes.rb. Remove the line map.resources :comments Modify the line map.resources :posts to map.resources :posts, :has_many => :comments

We can see what the new routes are by typing ‘ rake routes ’.

We’d like someone to be able to add a comment to a post. In app/views/posts/show.html.erb, we can add the line | before the links to Edit and Back.

This breaks when we actually try to enter a new comment. A few things to fix: The view The comments controller

new.html.erb Edit app/views/comments/new.html.erb to: New comment {:action => :create} do |f| %>

Comments controller For almost everything we want to do in the comments controller, we’re going to want the post associated with the comment. We can set up a call to make sure we get it each time.

before_filter At the top of the comments controller (app/controllers/comments_controller.rb) we add before_filter :grab_post This gets called before each action. At the bottom we define this method private def = Post.find(params[:post_id]) end Of course, there’s an “after_filter” as well, if we ever needed it.

Comments controller In fact, we then should redefine all the actions in the comments controller in (app/controllers/comments.rb). See code snippets for the entire file.

class CommentsController < ApplicationController before_filter :grab_post def = Comment.find(:all) end def = Comment.find(params[:id]) end def = Comment.new end def end def =Comment.new(params[:comment]) if redirect_to else render :action => :new end def redirect_to else render :action => :edit end def destroy redirect_to end private def = Post.find(params[:post_id]) end

To dos.. There’s still plenty of work to do in fixing up the views and controllers to get them to do what you want… But let’s go on to our next topic…

Authentication/Authorization

We will want to be able to: Allow users to log in (and keep their password secure) Limit actions to users who have been authorized to do them (e.g. maybe only the author of a post can edit it).

We were bad We created a user model with a password, but we did something bad. What was it?

Passwords in the clear Right now our user password is in the database in cleartext. This is a bad idea. create_table :users do |t| t.string :name t.string : t.string :password t.timestamps end

Let’s change it so that we have a encrypted password and a salt in our DB; while we’re at it, let’s make sure the string is not null. Create a migration ( ruby script/generate migration crypt_password ).

class CryptPassword < ActiveRecord::Migration def self.up remove_column :users, :password add_column :users, :crypted_password, :string, :limit => 256 add_column :users, :salt, :string change_column :users, : , :string, :null => false end def self.down remove_column :users, :crypted_password remove_column :users, :salt add_column :users, :password, :string end This is in the code snippets file.

Adding an accessor Since ‘password’ isn’t part of the User model given by the DB anymore, we need to allow for a way to get/set the unencrypted password for a User instance (which won’t get saved to the DB). In the User model (app/models/user), add the line attr_accessor :password (Remember from Lecture 1 on Ruby, this adds a standard getter/setter to an object).

Model callbacks So what do we do with a password to make sure it is saved in encrypted form? We can ask a model to call a function before_validation, before_save, or after_create. In this case, we want the password to be encrypted before saving it.

Encryption In app/models/users, add the line before_save :encrypt_password, :unless => lambda {|u| u.password.blank?} This will call a function ‘encrypt_password’. What does the rest do? It passes in an ‘anonymous function’ that takes as input a user and checks if its password is blank, so we only do encryption on a save in case we are saving the plaintext password.

Doing the encryption We’re going to use a standard library, so at the very top of the User model (before the Class statement), add the line require ‘digest/sha2’. Then inside the model add protected def encrypt_password self.salt ||= Digest:SHA256.hexdigest("--#{Time.now.to_s}- -#{ }--") self.crypted_password = encrypt(password) self.password = nil end def encrypt(password) Digest::SHA256.hexdigest("--#{salt}--#{password}--") end

Logs

A good thing Lots of details of the various events occurring in your Rails application get stored in a log; open up blog/log/development.log and take a look around.

A bad thing Search for the SQL INSERT INTO “users”. What do you see?

Passwords in the clear Processing UsersController#create (for at :34:12) [POST] Session ID: BAh7BzoMY3NyZl9pZCIlNjg5MzEzOGQ2ZWE5YmI5YjJmNGYwMDU2ODg0NWZh ZGUiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhh c2h7AAY6CkB1c2VkewA=--7670d43a2c040709b6ab697f171cf ce Parameters: {"user"=>{"name"=>"David", "password"=>"MyPassword", "commit"=>"Create", "authenticity_token"=>"d92550adeea871720c84356fe3d26ffb54d62236", "action"=>"create", "controller"=>"users"} [4;36;1mUser Create ( )[0m [0;1mINSERT INTO "users" ("name", "updated_at", "password", " ", "created_at") VALUES('David', ' :34:12', 'MyPassword', ' :34:12')[0m Redirected to Completed in (2 reqs/sec) | DB: (0%) | 302 Found [ Not good for our users’ security…

A fix We can fix this by adding a line to app/controllers/application.rb; whatever is in this file applies/is available to all controllers. In this case we add filter_parameter_logging :password This removes from the log the value of any parameter hash whose key has a substring of ‘password’ in it.

More caution

What happens if someone does an HTTP PUT to /users/1 with params[:user][:salt] set to ‘haxx0r!1’. Yes, your salt gets reset and saved to the new value.

Some protection In the user model, add the line attr_accessible : , :name, :password Then when a hash passed in to the user model, only these attributes are set; e.g. User.new(params[:user]) only sets the : , :name, :password from the params[:user] hash.

Logging in

We could create logging in/out actions in our Users Controller, but instead we take the perspective that Logging in = Creating a new session Logging out = Destroying a session So let’s make a Sessions Controller (note that there’s no corresponding Sessions model!)

Making a sessions controller We can create a sessions controller via ‘ ruby script/generate controller sessions ’.

sessions_controller.rb def new unless User.count > 0 flash[:notice] = "Please create the first user" redirect_to new_user_path end def create self.current_user = User.authenticate(params[: ], params[:password]) unless logged_in? flash[:notice] = "Incorrect login/password" render :action => 'new' and return end redirect_to(root_path) end def destroy reset_session flash[:notice] = "You've been logged out" redirect_to(root_path) end

We’re using some methods we didn’t define in this controller (User.authenticate, logged_in?). We’ll come back to these.

In particular, we aren’t actually trying to find the user and set the session variable in the controller; e.g. we didn’t try to write: def create user = User.find_by_ (params[: ]) unless user && user.crypted_password == user.encrypt(params[:password]) flash[:notice] = "Incorrect login/password“ render :action => 'new' and return end session[:user_id] = user.id redirect_to(root_path) end Why not?

Skinny controllers, Fat models More Rails philosophy: This kind of code doesn’t belong in our controller. Let the model figure out whether a user meets the conditions of being logged in. The controller is only supposed to figure out what view to show you in that case.

Implementing the methods In the User model, add these methods: def self.authenticate( , password) user = find_by_ ( ) user && user.authenticated_by?(password) ? user : nil end def authenticated_by?(password) encrypt(password) == crypted_password end

To app/controllers/application.rb we add def logged_in? current_user != :false end

But wait… Where is the current user coming from? We used this in the sessions controller too. self.current_user = User.authenticate(params[: ], params[:password]) There’s no current_user instance variable.

Getting/setting the current user To do this, we fake it by adding methods to the app/controllers/application.rb. def current_user=(user) session[:user_id] = user.nil? ? nil : = user || :false end def ||= (login_from_session || :false) end protected def login_from_session self.current_user = User.find(session[:user_id]) if session[:user_id] end

Adding helpers to views If we want to be able to use the logged_in? and current_user methods in our views, we can do this by declaring helper_method :current_user, :logged_in? in app/controller/application.rb.

Allowing for logins

Routing logins Let’s set up routes in config/routes.rb to allow for logins: map.resources :sessions map.login 'login', :controller => 'sessions', :action => 'new‘ map.logout 'logout', :controller => 'sessions', :action => 'destroy‘ We create named routes; these will match the URLs /login and /logout, but will also let us refer to login_path in our views.

An application view Now we create an application layout in app/views/layouts/application.html.erb (and deleting the other layouts).

application.html.erb <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " Sample Blog You are:. | |

Now give this all a try…

Want to get a job or internship in Information Science? Is your resume ready for companies to see, or would you like it to help you get that job? The ISSA will be having a Resume Workshop specifically tailored to Information Science with Craig Jones from Cornell Career Services Monday, October 6 th, 4:30 in Upson 205 We’ll have food and prizes!

Announcement Last class for INFO 2310 will be November 7, not October 31.