Skip to content

Commit

Permalink
added authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
rnielsen committed Feb 24, 2009
1 parent 65bbf0b commit 3b48c0d
Show file tree
Hide file tree
Showing 149 changed files with 11,887 additions and 187 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -1,5 +1,6 @@
public/.DS_Store
log/*
tmp/*
db/*sqlite3
db/development.sqlite3
.DS_Store
32 changes: 25 additions & 7 deletions app/controllers/account_controller.rb
@@ -1,20 +1,17 @@
class AccountController < ApplicationController
before_filter :authenticate
before_filter :authenticate, :except=>[:front, :login, :end_session]

def index
@tweets = @user.public_tweets.find(:all,:include => :user,:limit => 20 )
end

def end_session
reset_session
redirect_to :action=>'front'
end

def update_profile_image
upload_image = "#{RAILS_ROOT}/tmp/upload/#{@user.id}"
File.open(upload_image, "wb") { |f| f.write(params[:image].read) }
cmd = "convert -size 100x100 #{upload_image} #{RAILS_ROOT}/public/images/profile/#{@user.username}.png"
puts cmd
puts `#{cmd}`
upload_image(params[:image])
redirect_to :action=>'index'
end

Expand All @@ -32,11 +29,32 @@ def rate_limit_status
format.json { render :json => rate_limit }
end
end

def settings
if (request.post?)
if (@user.update_attributes(params[:user]))
flash[:notice] = 'User attributes updated'
end
end
end

def picture
if (request.post?)
upload_image(params[:profile_image][:uploaded_data])
end
end

private

def date_formatted(date)
date.gmtime.strftime("%a %b %d %H:%M:%S +0000 %Y")
end


def upload_image(image)
upload_image = "#{RAILS_ROOT}/tmp/upload/#{@user.id}"
File.open(upload_image, "wb") { |f| f.write(image.read) }
cmd = "convert -size 100x100 #{upload_image} #{RAILS_ROOT}/public/images/profile/#{@user.username}.png"
puts cmd
puts `#{cmd}`
end
end
14 changes: 7 additions & 7 deletions app/controllers/application.rb
Expand Up @@ -2,6 +2,8 @@
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
include AuthenticatedSystem

helper :all # include all helpers, all the time

# See ActionController::RequestForgeryProtection for details
Expand All @@ -16,15 +18,13 @@ class ApplicationController < ActionController::Base
def verify_authenticity_token
return true
end

def authenticate
if user = authenticate_with_http_basic { |u, p| u if !u.to_s.strip.blank? }
logger.debug user
@user = User.find_or_create_by_username(user)
else
request_http_basic_authentication
end
x = login_required
@user = current_user
x
end

private

def render_tweets(root="statuses")
Expand Down
2 changes: 2 additions & 0 deletions app/controllers/friendships_controller.rb
@@ -1,4 +1,6 @@
class FriendshipsController < ApplicationController
before_filter :authenticate

def exists
respond_to do |format|
format.xml { render :xml=>"<friends>true</friends>"}
Expand Down
40 changes: 40 additions & 0 deletions app/controllers/sessions_controller.rb
@@ -0,0 +1,40 @@
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
# render new.rhtml
def new
end

def create
logout_keeping_session!
user = User.authenticate(params[:login], params[:password])
if user
# Protects against session fixation attacks, causes request forgery
# protection if user resubmits an earlier form using back
# button. Uncomment if you understand the tradeoffs.
# reset_session
self.current_user = user
new_cookie_flag = (params[:remember_me] == "1")
handle_remember_cookie! new_cookie_flag
redirect_back_or_default('/home')
flash[:notice] = "Logged in successfully"
else
note_failed_signin
@login = params[:login]
@remember_me = params[:remember_me]
render :action => 'new'
end
end

def destroy
logout_killing_session!
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end

protected
# Track failed login attempts
def note_failed_signin
flash[:error] = "Couldn't log you in as '#{params[:login]}'"
logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}"
end
end
14 changes: 11 additions & 3 deletions app/controllers/statuses_controller.rb
@@ -1,11 +1,13 @@
class StatusesController < ApplicationController
before_filter :authenticate, :except => [:show]

def replies
@tweets = @user.replies.find(:all, :include => :user,:limit => 25)
render_tweets
end

def friends_timeline
puts "request=#{@user}"
limit = params[:all] ? 100000000000 : 25
@tweets = Tweet.find(:all,:order => "tweets.created_at DESC",:conditions => "tweets.tweet_type!='direct'",:include => :user,:limit => limit)
render_tweets
Expand Down Expand Up @@ -45,8 +47,14 @@ def update
recipient = User.find_or_create_by_username(recipient_name)
end

@tweet = Tweet.create({:tweet => tweet, :user => @user, :recipient => recipient, :tweet_type => type, :source => params[:source]})
render_tweet

@tweet = Tweet.create({:tweet => tweet, :user => @user, :recipient => recipient, :tweet_type => type, :source => params[:source] || 'web'})
if (params['twttr'])
latest_status = render_to_string :partial => "latest", :object=> @tweet
ret = {"status_count"=>@user.public_tweets.count, "latest_status"=> latest_status,"text"=>tweet}
ret["status_tr"] = render_to_string :partial => "tweet", :object=> @tweet, :locals=>{:type=>'friends_update'}
render :json => ret
else
render_tweet
end
end
end
5 changes: 0 additions & 5 deletions app/controllers/upload_controller.rb

This file was deleted.

7 changes: 2 additions & 5 deletions app/controllers/user_controller.rb
@@ -1,10 +1,7 @@
class UserController < ApplicationController

def index
@duser = User.find_or_create_by_username(params[:username])
if (@duser == @user)
redirect_to :controller=>'account'
else
@tweets = @duser.public_tweets.find(:all,:include => :user,:limit => 20 )
end
@tweets = @duser.public_tweets.find(:all,:include => :user,:limit => 20 )
end
end
28 changes: 28 additions & 0 deletions app/controllers/users_controller.rb
@@ -0,0 +1,28 @@
class UsersController < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem


# render new.rhtml
def new
@user = User.new
end

def create
logout_keeping_session!
@user = User.new(params[:user])
success = @user && @user.save
if success && @user.errors.empty?
# Protects against session fixation attacks, causes request forgery
# protection if visitor resubmits an earlier form using back
# button. Uncomment if you understand the tradeoffs.
# reset session
self.current_user = @user # !! now logged in
redirect_back_or_default('/')
flash[:notice] = "Thanks for signing up! We're sending you an email with your activation code."
else
flash[:error] = "We couldn't set up that account, sorry. Please try again, or contact an admin (link is above)."
render :action => 'new'
end
end
end
11 changes: 11 additions & 0 deletions app/helpers/account_helper.rb
@@ -1,2 +1,13 @@
module AccountHelper
def settings_list_entry(page)
"<li id=\"tab_#{page}\">#{settings_link(page)}</li>"
end

def settings_link(page)
if (params[:action]==page)
page.capitalize
else
"<a href=\"#{page}\" id=\"#{page}_tab\">#{page.capitalize}</a>"
end
end
end
6 changes: 6 additions & 0 deletions app/helpers/application_helper.rb
@@ -1,3 +1,9 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def setup(options)
@title = "Twetter / #{options[:title]}" || "Twetter"
@body_id = options[:body_id] || "body"
@body_classes = options[:body_classes] || "account"
@css = options[:css] || []
end
end
2 changes: 2 additions & 0 deletions app/helpers/sessions_helper.rb
@@ -0,0 +1,2 @@
module SessionsHelper
end
3 changes: 3 additions & 0 deletions app/helpers/statuses_helper.rb
@@ -1,2 +1,5 @@
module StatusesHelper
def link_users(tweet)
html_escape(tweet).gsub(/@(\S+)/, '@<a href="/\1"/>\1</a>')
end
end
93 changes: 93 additions & 0 deletions app/helpers/users_helper.rb
@@ -0,0 +1,93 @@
module UsersHelper

#
# Use this to wrap view elements that the user can't access.
# !! Note: this is an *interface*, not *security* feature !!
# You need to do all access control at the controller level.
#
# Example:
# <%= if_authorized?(:index, User) do link_to('List all users', users_path) end %> |
# <%= if_authorized?(:edit, @user) do link_to('Edit this user', edit_user_path) end %> |
# <%= if_authorized?(:destroy, @user) do link_to 'Destroy', @user, :confirm => 'Are you sure?', :method => :delete end %>
#
#
def if_authorized?(action, resource, &block)
if authorized?(action, resource)
yield action, resource
end
end

#
# Link to user's page ('users/1')
#
# By default, their login is used as link text and link title (tooltip)
#
# Takes options
# * :content_text => 'Content text in place of user.login', escaped with
# the standard h() function.
# * :content_method => :user_instance_method_to_call_for_content_text
# * :title_method => :user_instance_method_to_call_for_title_attribute
# * as well as link_to()'s standard options
#
# Examples:
# link_to_user @user
# # => <a href="/users/3" title="barmy">barmy</a>
#
# # if you've added a .name attribute:
# content_tag :span, :class => :vcard do
# (link_to_user user, :class => 'fn n', :title_method => :login, :content_method => :name) +
# ': ' + (content_tag :span, user.email, :class => 'email')
# end
# # => <span class="vcard"><a href="/users/3" title="barmy" class="fn n">Cyril Fotheringay-Phipps</a>: <span class="email">barmy@blandings.com</span></span>
#
# link_to_user @user, :content_text => 'Your user page'
# # => <a href="/users/3" title="barmy" class="nickname">Your user page</a>
#
def link_to_user(user, options={})
raise "Invalid user" unless user
options.reverse_merge! :content_method => :login, :title_method => :login, :class => :nickname
content_text = options.delete(:content_text)
content_text ||= user.send(options.delete(:content_method))
options[:title] ||= user.send(options.delete(:title_method))
link_to h(content_text), user_path(user), options
end

#
# Link to login page using remote ip address as link content
#
# The :title (and thus, tooltip) is set to the IP address
#
# Examples:
# link_to_login_with_IP
# # => <a href="/login" title="169.69.69.69">169.69.69.69</a>
#
# link_to_login_with_IP :content_text => 'not signed in'
# # => <a href="/login" title="169.69.69.69">not signed in</a>
#
def link_to_login_with_IP content_text=nil, options={}
ip_addr = request.remote_ip
content_text ||= ip_addr
options.reverse_merge! :title => ip_addr
if tag = options.delete(:tag)
content_tag tag, h(content_text), options
else
link_to h(content_text), login_path, options
end
end

#
# Link to the current user's page (using link_to_user) or to the login page
# (using link_to_login_with_IP).
#
def link_to_current_user(options={})
if current_user
link_to_user current_user, options
else
content_text = options.delete(:content_text) || 'not signed in'
# kill ignored options from link_to_user
[:content_method, :title_method].each{|opt| options.delete(opt)}
link_to_login_with_IP content_text, options
end
end

end

0 comments on commit 3b48c0d

Please sign in to comment.