This repository has been archived by the owner on Dec 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
authentication.rb
54 lines (47 loc) · 1.51 KB
/
authentication.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# This module is included in your application controller which makes
# several methods available to all controllers and views. Here's a
# common example you might add to your application layout file.
#
# <% if logged_in? %>
# Welcome <%=h current_user.username %>! Not you?
# <%= link_to "Log out", logout_path %>
# <% else %>
# <%= link_to "Sign up", signup_path %> or
# <%= link_to "log in", login_path %>.
# <% end %>
#
# You can also restrict unregistered users from accessing a controller using
# a before filter. For example.
#
# before_filter :login_required, :except => [:index, :show]
module Authentication
def self.included(controller)
controller.send :helper_method, :current_user, :logged_in?, :redirect_to_target_or_default
end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
def logged_in?
current_user
end
def login_required
unless logged_in?
flash[:error] = "You must first log in or sign up before accessing this page."
store_target_location
redirect_to login_url
end
end
def redirect_to_target_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
private
def store_target_location
session[:return_to] = request.url
end
end