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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
# File 'lib/sinatra-authentication.rb', line 11
def self.registered(app)
set :lil_authentication_view_path, Pathname(__FILE__).dirname.expand_path + "views/"
get '/users' do
@users = User.all
if @users != []
haml get_view_as_string("index.haml"), :layout => use_layout?
else
redirect '/signup'
end
end
get '/users/:id' do
login_required
@user = User.get(:id => params[:id])
haml get_view_as_string("show.haml"), :layout => use_layout?
end
get '/logged_in' do
if session[:user]
"true"
else
"false"
end
end
get '/login' do
haml get_view_as_string("login.haml"), :layout => use_layout?
end
post '/login' do
if user = User.authenticate(params[:email], params[:password])
session[:user] = user.id
redirect '/'
else
redirect '/login'
end
end
get '/logout' do
session[:user] = nil
@message = "in case it weren't obvious, you've logged out"
redirect '/'
end
get '/signup' do
haml get_view_as_string("signup.haml"), :layout => use_layout?
end
post '/signup' do
@user = User.set(params[:user])
if @user
session[:user] = @user.id
redirect '/'
else
session[:flash] = "failure!"
redirect '/'
end
end
get '/users/:id/edit' do
login_required
redirect "/users" unless current_user.admin? || current_user == params[:id]
@user = User.get(:id => params[:id])
haml get_view_as_string("edit.haml"), :layout => use_layout?
end
post '/users/:id/edit' do
login_required
redirect "/users" unless current_user.admin? || current_user == params[:id]
user = User.get(:id => params[:id])
user_attributes = params[:user]
if params[:user][:password] == ""
user_attributes.delete("password")
user_attributes.delete("password_confirmation")
end
if user.update(user_attributes)
redirect "/users/#{user.id}"
else
throw user.errors
end
end
get '/users/:id/delete' do
login_required
redirect "/users" unless current_user.admin? || current_user == params[:id]
if User.delete(params[:id])
session[:flash] = "way to go, you deleted a user"
else
session[:flash] = "deletion failed, for whatever reason"
end
redirect '/'
end
end
|