質問編集履歴
1
追記
test
CHANGED
File without changes
|
test
CHANGED
@@ -77,3 +77,117 @@
|
|
77
77
|
+nil
|
78
78
|
|
79
79
|
```
|
80
|
+
|
81
|
+
sessins_helper.rb
|
82
|
+
|
83
|
+
```ruby
|
84
|
+
|
85
|
+
module SessionsHelper
|
86
|
+
|
87
|
+
# 渡されたユーザーでログインする
|
88
|
+
|
89
|
+
def log_in(user)
|
90
|
+
|
91
|
+
session[:user_id] = user.id
|
92
|
+
|
93
|
+
end
|
94
|
+
|
95
|
+
# ユーザーを永続的セッションに記憶する
|
96
|
+
|
97
|
+
def remember(user)
|
98
|
+
|
99
|
+
user.remember
|
100
|
+
|
101
|
+
cookies.permanent.signed[:user_id] = user.id
|
102
|
+
|
103
|
+
cookies.permanent[:remember_token] = user.remember_token
|
104
|
+
|
105
|
+
end
|
106
|
+
|
107
|
+
# 渡されたユーザーがログイン済みユーザーであればtrueを返す
|
108
|
+
|
109
|
+
def current_user?(user)
|
110
|
+
|
111
|
+
user == current_user
|
112
|
+
|
113
|
+
end
|
114
|
+
|
115
|
+
# 記憶トークンcookieに対応するユーザーを返す
|
116
|
+
|
117
|
+
def current_user
|
118
|
+
|
119
|
+
if (user_id = session[:user_id])
|
120
|
+
|
121
|
+
@current_user ||= User.find_by(id: user_id)
|
122
|
+
|
123
|
+
elsif (user_id = cookies.signed[:user_id])
|
124
|
+
|
125
|
+
user = User.find_by(id: user_id)
|
126
|
+
|
127
|
+
if user && user.authenticated?(:remember,cookies[:remember_token])
|
128
|
+
|
129
|
+
log_in user
|
130
|
+
|
131
|
+
@current_user = user
|
132
|
+
|
133
|
+
end
|
134
|
+
|
135
|
+
end
|
136
|
+
|
137
|
+
end
|
138
|
+
|
139
|
+
# ユーザーがログインしていればtrue、その他ならfalseを返す
|
140
|
+
|
141
|
+
def logged_in?
|
142
|
+
|
143
|
+
!current_user.nil?
|
144
|
+
|
145
|
+
end
|
146
|
+
|
147
|
+
# 永続的セッションを破棄する
|
148
|
+
|
149
|
+
def forget(user)
|
150
|
+
|
151
|
+
user.forget
|
152
|
+
|
153
|
+
cookies.delete(:user_id)
|
154
|
+
|
155
|
+
cookies.delete(:remember_token)
|
156
|
+
|
157
|
+
end
|
158
|
+
|
159
|
+
# 現在のユーザーをログアウトする
|
160
|
+
|
161
|
+
def log_out
|
162
|
+
|
163
|
+
forget(current_user)
|
164
|
+
|
165
|
+
session.delete(:user_id)
|
166
|
+
|
167
|
+
@current_user = nil
|
168
|
+
|
169
|
+
end
|
170
|
+
|
171
|
+
# 記憶したURL (もしくはデフォルト値) にリダイレクト
|
172
|
+
|
173
|
+
def redirect_back_or(default)
|
174
|
+
|
175
|
+
redirect_to(session[:forwarding_url] || default)
|
176
|
+
|
177
|
+
session.delete(:forwarding_url)
|
178
|
+
|
179
|
+
end
|
180
|
+
|
181
|
+
# アクセスしようとしたURLを覚えておく
|
182
|
+
|
183
|
+
def store_location
|
184
|
+
|
185
|
+
session[:forwarding_url] = request.original_url if request.get?
|
186
|
+
|
187
|
+
end
|
188
|
+
|
189
|
+
|
190
|
+
|
191
|
+
end
|
192
|
+
|
193
|
+
```
|