-
Notifications
You must be signed in to change notification settings - Fork 3
/
chapter12.html
1537 lines (1342 loc) · 144 KB
/
chapter12.html
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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<title>Ruby on Rails 教程 - 第 12 章 重设密码</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content="最好的 Ruby on Rails 入门教程"/>
<meta name="keywords" content="ruby, rails, tutorial"/>
<meta name="author" content="Michael Hartl"/>
<meta name="translator" content="安道"/>
<meta name="generator" content="persie 0.0.5.1"/>
<link rel="stylesheet" type="text/css" href="//railstutorial-china.org/assets/css/main.css"/>
<link rel="stylesheet" type="text/css" href="book.css"/>
<script type="text/javascript" src="//railstutorial-china.org/assets/js/global.js"></script>
</head>
<body class="book-page">
<nav class="navbar">
<div class="container">
<div class="clearfix">
<a class="navbar-brand hidden-sm-up" href="//railstutorial-china.org/" title="Ruby on Rails 教程">Ruby on Rails 教程</a>
<button class="navbar-toggler hidden-sm-up pull-xs-right" type="button" data-toggle="collapse" data-target="#main-nav">☰</button>
</div>
<a class="navbar-brand hidden-xs-down" href="//railstutorial-china.org/" title="Ruby on Rails 教程">Ruby on Rails 教程</a>
<div class="collapse navbar-toggleable-xs pull-sm-right" id="main-nav">
<ul class="nav navbar-nav">
<li class="nav-item"><a class="nav-link" href="//railstutorial-china.org/" title="首页">首页</a></li>
<li class="nav-item"><a class="nav-link" href="//railstutorial-china.org/blog/" title="博客">博客</a></li>
<li class="nav-item active"><a class="nav-link" href="//railstutorial-china.org/book/" title="阅读">阅读</a></li>
<li class="nav-item"><a class="nav-link" href="//railstutorial-china.org/#ebook" title="电子书">电子书</a></li>
</ul>
</div>
</div>
</nav>
<div class="content">
<div class="container">
<div class="row">
<div class="col-lg-offset-2 col-lg-8">
<div class="book-versions">
选择版本:
<a class="btn btn-primary" href="//railstutorial-china.org/book/" title="Ruby on Rails 教程(原书第 4 版,针对 Rails 5)">Rails 5</a>
<a class="btn btn-secondary" href="//railstutorial-china.org/rails42/" title="Ruby on Rails 教程(原书第 3 版,针对 Rails 4.2)">Rails 4.2</a>
<a class="btn btn-secondary" href="//railstutorial-china.org/rails4/" title="Ruby on Rails 教程(原书第 3 版,针对 Rails 4.0)">Rails 4.0</a>
<a class="btn btn-secondary" href="//railstutorial-china.org/rails3/" title="Ruby on Rails 教程(原书第 2 版,针对 Rails 3.2)">Rails 3.2</a>
</div>
<div class="alert alert-warning">
<p>在线版的内容可能落后于电子书,如果想及时获得更新,请<a href="//railstutorial-china.org/#ebook" title="购买电子书">购买电子书</a>。</p>
</div>
<article class="article">
<section data-type="chapter" id="password-reset">
<h1><span class="title-label">第 12 章</span> 重设密码</h1>
<p>完成账户激活功能后(从而确认了用户的电子邮件地址可用),我们可以实现密码重设功能了,以防用户忘记密码。我们将看到,密码重设的很多步骤和账户激活类似,所以这里会用到<a class="xref-link" href="chapter11.html#account-activation">第 11 章</a>学到的知识。不过,开头不一样,与账户激活功能不同的是,密码重设要修改一个视图,还要创建两个新表单(用于提交电子邮件地址和设定新密码)。</p>
<p>编写代码之前,我们先构思要实现的重设密码步骤。首先,我们要在演示应用的登录表单中添加“forgot password”(忘记密码)链接,如<a class="xref-link" href="#fig-login-forgot-password-mockup">图 12.1</a> 所示。</p>
<div id="fig-login-forgot-password-mockup" class="figure"><img src="images/chapter12/login_forgot_password_mockup.png" alt="login forgot password mockup" /><div class="figcaption"><span class="title-label">图 12.1</span>:“forgot password”链接的构思图</div></div>
<p>点击“forgot password”链接后打开一个页面,这个页面中有一个表单,要求输入电子邮件地址,用户提交之后,应用向这个地址发送一封包含密码重设链接的邮件,如<a class="xref-link" href="#fig-forgot-password-form-mockup">图 12.2</a> 所示。</p>
<div id="fig-forgot-password-form-mockup" class="figure"><img src="images/chapter12/forgot_password_form_mockup.png" alt="forgot password form mockup" /><div class="figcaption"><span class="title-label">图 12.2</span>:“Forgot password”表单的构思图</div></div>
<p>点击密码重设链接会打开一个表单,用户在这个表单中重设密码(还要填写密码确认),如<a class="xref-link" href="#fig-reset-password-form-mockup">图 12.3</a> 所示。</p>
<div id="fig-reset-password-form-mockup" class="figure"><img src="images/chapter12/reset_password_form_mockup.png" alt="reset password form mockup" /><div class="figcaption"><span class="title-label">图 12.3</span>:“Reset password”表单的构思图</div></div>
<p>如果你读完了<a class="xref-link" href="chapter11.html#account-activation">第 11 章</a>,已经有了密码重设邮件程序(<a class="xref-link" href="chapter11.html#listing-generate-user-mailer">代码清单 11.6</a>)。本节将完成剩下的工作,为密码重设功能添加资源和数据模型。重设密码功能在 <a class="xref-link" href="#resetting-the-password">12.3 节</a>实现。</p>
<p>与账户激活功能一样,我们要把“密码重设”看做一个资源,每个重设密码操作都有一个重设令牌和对应的摘要。主要的步骤如下:</p>
<ol class="arabic">
<li>
<p>用户请求重设密码时,使用提交的电子邮件地址查找用户;</p>
</li>
<li>
<p>如果数据库中有这个电子邮件地址,生成一个重设令牌和对应的摘要;</p>
</li>
<li>
<p>把重设摘要保存在数据库中,然后给用户发送一封邮件,其中有一个包含重设令牌和用户电子邮件地址的链接;</p>
</li>
<li>
<p>用户点击链接后,使用电子邮件地址查找用户,然后对比令牌和摘要;</p>
</li>
<li>
<p>如果通过身份验证,显示重设密码表单。</p>
</li>
</ol>
<section data-type="sect1" id="password-resets-resource">
<h1><span class="title-label">12.1</span> <code>PasswordResets</code> 资源</h1>
<p>与会话(<a class="xref-link" href="chapter8.html#sessions">8.1 节</a>)和账户激活(<a class="xref-link" href="chapter11.html#account-activation">第 11 章</a>)一样,我们要把“密码重设”看做一个资源(<code>PasswordResets</code>),不过这个资源不对应 Active Record 模型,相关的数据(包括重设令牌)存储在 <code>User</code> 模型中。</p>
<p>我们将把“密码重设”看做一个资源,因此要使用标准的 REST URL 与之交互。处理激活链接只需 <code>edit</code> 一个动作,而这里要渲染 <code>new</code> 和 <code>edit</code> 表单,处理密码重设请求,还要创建和更新密码,因此最终共计要使用四个 REST 式路由。</p>
<p>与之前一样,我们要在主题分支中实现这个新功能:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>git checkout <span class="nt">-b</span> password-reset
</code></pre></div>
</div>
<section data-type="sect2" id="password-resets-controller">
<h2><span class="title-label">12.1.1</span> <code>PasswordResets</code> 控制器</h2>
<p>首先,生成 <code>PasswordResets</code> 控制器,并且根据上述讨论,指定 <code>new</code> 和 <code>edit</code> 两个动作:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails generate controller PasswordResets new edit <span class="nt">--no-test-framework</span>
</code></pre></div>
</div>
<p>注意,我们指定了一个旗标,不让 Rails 生成测试。这是因为我们不需要控制器测试,而将继续使用 <a class="xref-link" href="chapter11.html#activation-test-and-refactoring">11.3.3 节</a>编写的集成测试。</p>
<p>我们需要两个表单,一个请求重设密码(<a class="xref-link" href="#fig-forgot-password-form-mockup">图 12.2</a>),一个修改 <code>User</code> 模型中的密码(<a class="xref-link" href="#fig-reset-password-form-mockup">图 12.3</a>),所以需要为 <code>new</code>、<code>create</code>、<code>edit</code> 和 <code>update</code> 四个动作定义路由——通过<a class="xref-link" href="#listing-password-resets-resource">代码清单 12.1</a> 中高亮显示的那条 <code>resources</code> 规则实现。</p>
<div id="listing-password-resets-resource" data-type="listing">
<h5><span class="title-label">代码清单 12.1</span>:添加 <code>PasswordResets</code> 资源的路由</h5>
<div class="source-file">config/routes.rb</div>
<div class="highlight language-ruby"><pre><code><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">routes</span><span class="p">.</span><span class="nf">draw</span> <span class="k">do</span>
<span class="n">root</span> <span class="s1">'static_pages#home'</span>
<span class="n">get</span> <span class="s1">'/help'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'static_pages#help'</span>
<span class="n">get</span> <span class="s1">'/about'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'static_pages#about'</span>
<span class="n">get</span> <span class="s1">'/contact'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'static_pages#contact'</span>
<span class="n">get</span> <span class="s1">'/signup'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'users#new'</span>
<span class="n">get</span> <span class="s1">'/login'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'sessions#new'</span>
<span class="n">post</span> <span class="s1">'/login'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'sessions#create'</span>
<span class="n">delete</span> <span class="s1">'/logout'</span><span class="p">,</span> <span class="ss">to: </span><span class="s1">'sessions#destroy'</span>
<span class="n">resources</span> <span class="ss">:users</span>
<span class="n">resources</span> <span class="ss">:account_activations</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">]</span>
<span class="hll"> <span class="n">resources</span> <span class="ss">:password_resets</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:new</span><span class="p">,</span> <span class="ss">:create</span><span class="p">,</span> <span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span></span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>添加这个规则后,得到了<a class="xref-link" href="#table-restful-password-resets">表 12.1</a> 中的 REST 式路由。</p>
<table id="table-restful-password-resets" class="tableblock frame-all grid-all" style="width: 100%;">
<caption><span class="title-label">表 12.1</span>:在<a class="xref-link" href="#listing-password-resets-resource">代码清单 12.1</a> 中添加那条规则后得到的 REST 式路由</caption>
<colgroup>
<col style="width: 15%;" />
<col style="width: 35%;" />
<col style="width: 15%;" />
<col style="width: 35%;" />
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP 请求</th>
<th class="tableblock halign-left valign-top">URL</th>
<th class="tableblock halign-left valign-top">动作</th>
<th class="tableblock halign-left valign-top">具名路由</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>GET</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/password_resets/new</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>new</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>new_password_reset_path</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>POST</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/password_resets</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>create</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>password_resets_path</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>GET</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/password_resets/<token>/edit</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>edit</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>edit_password_reset_url(token)</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>PATCH</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/password_resets/<token></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>update</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>password_reset_path(token)</code></p></td>
</tr>
</tbody>
</table>
<p>通过表中第一个路由可以得到指向“Forgot password”表单的链接:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="n">new_password_reset_path</span>
</code></pre></div>
</div>
<p>把这个链接添加到登录表单,如<a class="xref-link" href="#listing-log-in-password-reset">代码清单 12.2</a> 所示。添加后的效果如<a class="xref-link" href="#fig-forgot-password-link">图 12.4</a> 所示。</p>
<div id="listing-log-in-password-reset" data-type="listing">
<h5><span class="title-label">代码清单 12.2</span>:添加打开忘记密码表单的链接</h5>
<div class="source-file">app/views/sessions/new.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:title</span><span class="p">,</span> <span class="s2">"Log in"</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><h1></span>Log in<span class="nt"></h1></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"row"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"col-md-6 col-md-offset-3"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">form_for</span><span class="p">(</span><span class="ss">:session</span><span class="p">,</span> <span class="ss">url: </span><span class="n">login_path</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:email</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">email_field</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password</span> <span class="cp">%></span>
<span class="hll"> <span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"(forgot password)"</span><span class="p">,</span> <span class="n">new_password_reset_path</span> <span class="cp">%></span></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:remember_me</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"checkbox inline"</span> <span class="k">do</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">check_box</span> <span class="ss">:remember_me</span> <span class="cp">%></span>
<span class="nt"><span></span>Remember me on this computer<span class="nt"></span></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">submit</span> <span class="s2">"Log in"</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"btn btn-primary"</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="nt"><p></span>New user? <span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Sign up now!"</span><span class="p">,</span> <span class="n">signup_path</span> <span class="cp">%></span><span class="nt"></p></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div>
</div>
<div id="fig-forgot-password-link" class="figure"><img src="images/chapter12/forgot_password_link.png" alt="forgot password link" /><div class="figcaption"><span class="title-label">图 12.4</span>:添加“Forgot Password”链接后的登录页面</div></div>
<h5 id="exercises-password-resets-controller" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>确认测试组件仍能通过。</p>
</li>
<li>
<p><a class="xref-link" href="#table-restful-password-resets">表 12.1</a> 为什么列出具名路由的 <code>_url</code> 形式,而不是 <code>_path</code> 形式?提示:我们将在电子邮件中使用链接。</p>
</li>
</ol>
</section>
<section data-type="sect2" id="new-password-resets">
<h2><span class="title-label">12.1.2</span> 请求重设密码</h2>
<p>请求重设密码之前,我们要定义数据模型。密码重设所需的数据模型与账户激活的类似(<a class="xref-link" href="chapter11.html#fig-user-model-account-activation">图 11.1</a>)。参照“记住我”功能(<a class="xref-link" href="chapter9.html#remember-me">9.1 节</a>)和账户激活功能(<a class="xref-link" href="chapter11.html#account-activation">第 11 章</a>),密码重设需要一个虚拟的重设令牌属性,在重设密码的邮件中使用,以及对应的重设摘要,用于检索用户。如果存储未哈希的令牌,能访问数据库的攻击者就能发送一封重设密码邮件给用户,然后使用令牌和邮件地址访问对应的密码重设链接,从而获得账户控制权。因此,必须存储令牌的摘要。为了进一步保障安全,我们还计划过几个小时后让重设链接失效,所以要记录重设邮件发送的时间。据此,我们要添加两个属性:<code>reset_digest</code> 和 <code>reset_sent_at</code>,如<a class="xref-link" href="#fig-user-model-password-reset">图 12.5</a> 所示。</p>
<div id="fig-user-model-password-reset" class="figure"><img src="images/chapter12/user_model_password_reset.png" alt="user model password reset" /><div class="figcaption"><span class="title-label">图 12.5</span>:添加密码重设相关属性后的 <code>User</code> 模型</div></div>
<p>执行下面的命令,创建添加这两个属性的迁移:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails generate migration add_reset_to_users reset_digest:string <span class="se">\</span>
<span class="o">></span> reset_sent_at:datetime
</code></pre></div>
</div>
<p>(前面说过,第二行开头的 <code>></code> 是“行接续”符号,是 shell 自动插入的,无需输入。)</p>
<p>然后像之前一样执行迁移:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails db:migrate
</code></pre></div>
</div>
<p>我们要参照前面为没有模型的资源编写表单的方式,即创建新会话的登录表单(<a class="xref-link" href="chapter8.html#listing-login-form">代码清单 8.4</a>),编写请求重设密码的表单。为了便于参考,我们再把那个表单列出来,如<a class="xref-link" href="#listing-login-form-redux">代码清单 12.3</a> 所示。</p>
<div id="listing-login-form-redux" data-type="listing">
<h5><span class="title-label">代码清单 12.3</span>:登录表单的代码</h5>
<div class="source-file">app/views/sessions/new.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:title</span><span class="p">,</span> <span class="s2">"Log in"</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><h1></span>Log in<span class="nt"></h1></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"row"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"col-md-6 col-md-offset-3"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">form_for</span><span class="p">(</span><span class="ss">:session</span><span class="p">,</span> <span class="ss">url: </span><span class="n">login_path</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:email</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">email_field</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:remember_me</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"checkbox inline"</span> <span class="k">do</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">check_box</span> <span class="ss">:remember_me</span> <span class="cp">%></span>
<span class="nt"><span></span>Remember me on this computer<span class="nt"></span></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">submit</span> <span class="s2">"Log in"</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"btn btn-primary"</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="nt"><p></span>New user? <span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Sign up now!"</span><span class="p">,</span> <span class="n">signup_path</span> <span class="cp">%></span><span class="nt"></p></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div>
</div>
<p>请求重设密码的表单和<a class="xref-link" href="#listing-login-form-redux">代码清单 12.3</a> 有很多共通之处,二者之间最大的区别是,<code>form_for</code> 中的资源和地址不一样,而且也没有密码字段。请求重设密码的表单如<a class="xref-link" href="#listing-new-password-reset">代码清单 12.4</a> 所示,渲染的结果如<a class="xref-link" href="#fig-forgot-password-form">图 12.6</a> 所示。</p>
<div id="listing-new-password-reset" data-type="listing">
<h5><span class="title-label">代码清单 12.4</span>:请求重设密码页面的视图</h5>
<div class="source-file">app/views/password_resets/new.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:title</span><span class="p">,</span> <span class="s2">"Forgot password"</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><h1></span>Forgot password<span class="nt"></h1></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"row"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"col-md-6 col-md-offset-3"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">form_for</span><span class="p">(</span><span class="ss">:password_reset</span><span class="p">,</span> <span class="ss">url: </span><span class="n">password_resets_path</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:email</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">email_field</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">submit</span> <span class="s2">"Submit"</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"btn btn-primary"</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div>
</div>
<div id="fig-forgot-password-form" class="figure"><img src="images/chapter12/forgot_password_form.png" alt="forgot password form" /><div class="figcaption"><span class="title-label">图 12.6</span>:“Forgot Password”表单</div></div>
<h5 id="exercises-new-password-resets" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>在<a class="xref-link" href="#listing-new-password-reset">代码清单 12.4</a> 中,传给 <code>form_for</code> 的为什么是 <code>:password_reset</code>,而不是 <code>@password_reset</code>?</p>
</li>
</ol>
</section>
<section data-type="sect2" id="password-reset-create-action">
<h2><span class="title-label">12.1.3</span> <code>PasswordResets</code> 控制器的 <code>create</code> 动作</h2>
<p>提交<a class="xref-link" href="#fig-forgot-password-form">图 12.6</a> 中的表单后,我们要通过电子邮件地址查找用户,更新这个用户的 <code>reset_token</code>、<code>reset_digest</code> 和 <code>reset_sent_at</code> 属性,然后重定向到根地址,并显示一个闪现消息。与登录一样(<a class="xref-link" href="chapter8.html#listing-correct-login-failure">代码清单 8.11</a>),如果提交的数据无效,我们要重新渲染页面,并且使用 <code>flash.now</code> 显示一个闪现消息。<sup>[<a id="fn-ref-1" href="#fn-1">1</a>]</sup>据此写出的 <code>create</code> 动作如<a class="xref-link" href="#listing-create-password-reset">代码清单 12.5</a> 所示。</p>
<div id="listing-create-password-reset" data-type="listing">
<h5><span class="title-label">代码清单 12.5</span>:<code>PasswordResets</code> 控制器的 <code>create</code> 动作</h5>
<div class="source-file">app/controllers/password_resets_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">PasswordResetsController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="k">def</span> <span class="nf">new</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">create</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">email: </span><span class="n">params</span><span class="p">[</span><span class="ss">:password_reset</span><span class="p">][</span><span class="ss">:email</span><span class="p">].</span><span class="nf">downcase</span><span class="p">)</span>
<span class="k">if</span> <span class="vi">@user</span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">create_reset_digest</span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">send_password_reset_email</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:info</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Email sent with password reset instructions"</span>
<span class="n">redirect_to</span> <span class="n">root_url</span>
<span class="k">else</span>
<span class="n">flash</span><span class="p">.</span><span class="nf">now</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Email address not found"</span>
<span class="n">render</span> <span class="s1">'new'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">edit</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p><code>User</code> 模型中的代码与 <code>before_create</code> 回调中使用的 <code>create_activation_digest</code> 方法(<a class="xref-link" href="chapter11.html#listing-user-model-activation-code">代码清单 11.3</a>)类似,如<a class="xref-link" href="#listing-user-model-password-reset">代码清单 12.6</a> 所示。</p>
<div id="listing-user-model-password-reset" data-type="listing">
<h5><span class="title-label">代码清单 12.6</span>:在 <code>User</code> 模型中添加重设密码所需的方法</h5>
<div class="source-file">app/models/user.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span>
<span class="hll"> <span class="nb">attr_accessor</span> <span class="ss">:remember_token</span><span class="p">,</span> <span class="ss">:activation_token</span><span class="p">,</span> <span class="ss">:reset_token</span></span>
<span class="n">before_save</span> <span class="ss">:downcase_email</span>
<span class="n">before_create</span> <span class="ss">:create_activation_digest</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="o">.</span>
<span class="c1"># 激活账户</span>
<span class="k">def</span> <span class="nf">activate</span>
<span class="n">update_attribute</span><span class="p">(</span><span class="ss">:activated</span><span class="p">,</span> <span class="kp">true</span><span class="p">)</span>
<span class="n">update_attribute</span><span class="p">(</span><span class="ss">:activated_at</span><span class="p">,</span> <span class="no">Time</span><span class="p">.</span><span class="nf">zone</span><span class="p">.</span><span class="nf">now</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># 发送激活邮件</span>
<span class="k">def</span> <span class="nf">send_activation_email</span>
<span class="no">UserMailer</span><span class="p">.</span><span class="nf">account_activation</span><span class="p">(</span><span class="nb">self</span><span class="p">).</span><span class="nf">deliver_now</span>
<span class="k">end</span>
<span class="c1"># 设置密码重设相关的属性</span>
<span class="k">def</span> <span class="nf">create_reset_digest</span>
<span class="hll"> <span class="nb">self</span><span class="p">.</span><span class="nf">reset_token</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new_token</span></span>
<span class="hll"> <span class="n">update_attribute</span><span class="p">(</span><span class="ss">:reset_digest</span><span class="p">,</span> <span class="no">User</span><span class="p">.</span><span class="nf">digest</span><span class="p">(</span><span class="n">reset_token</span><span class="p">))</span></span>
<span class="hll"> <span class="n">update_attribute</span><span class="p">(</span><span class="ss">:reset_sent_at</span><span class="p">,</span> <span class="no">Time</span><span class="p">.</span><span class="nf">zone</span><span class="p">.</span><span class="nf">now</span><span class="p">)</span></span>
<span class="k">end</span>
<span class="c1"># 发送密码重设邮件</span>
<span class="k">def</span> <span class="nf">send_password_reset_email</span>
<span class="hll"> <span class="no">UserMailer</span><span class="p">.</span><span class="nf">password_reset</span><span class="p">(</span><span class="nb">self</span><span class="p">).</span><span class="nf">deliver_now</span></span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
</code></pre></div>
</div>
<p>如<a class="xref-link" href="#fig-invalid-email-password-reset">图 12.7</a> 所示,提交无效的电子邮件地址时,应用的表现正常。为了让提交有效地址时应用也能正常运行,我们要定义发送密码重设邮件的方法。</p>
<div id="fig-invalid-email-password-reset" class="figure"><img src="images/chapter12/invalid_email_password_reset.png" alt="invalid email password reset" /><div class="figcaption"><span class="title-label">图 12.7</span>:提交无效电子邮件地址后显示的“Forgot Password”表单</div></div>
<h5 id="exercises-password-reset-create-action" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>在<a class="xref-link" href="#fig-forgot-password-form">图 12.6</a> 所示的表单中提交有效的电子邮件地址,会看到什么错误消息?</p>
</li>
<li>
<p>在 Rails 控制台中确认,虽然前一题有错误,但是 <code>reset_digest</code> 和 <code>reset_sent_at</code> 属性有值了。这两个属性的值是什么?</p>
</li>
</ol>
</section>
</section>
<section data-type="sect1" id="password-reset-emails">
<h1><span class="title-label">12.2</span> 密码重设邮件</h1>
<p>前一节在 <code>PasswordResets</code> 控制器中定义的 <code>create</code> 动作基本可用,但是发送密码重设邮件的方法还没有。</p>
<p>如果你跟着 <a class="xref-link" href="chapter11.html#account-activations-resource">11.1 节</a>做了,<code>app/mailers/user_mailer.rb</code> 文件中应该有一个默认生成的 <code>password_reset</code> 方法,这是<a class="xref-link" href="chapter11.html#listing-generate-user-mailer">代码清单 11.6</a> 生成 <code>User</code> 邮件程序时生成的。如果你跳过了<a class="xref-link" href="chapter11.html#account-activation">第 11 章</a>,可以直接复制下面的代码(不含 <code>account_activation</code> 及相关的方法),并且创建缺少的文件。</p>
<section data-type="sect2" id="password-reset-mailer">
<h2><span class="title-label">12.2.1</span> 密码重设邮件程序和模板</h2>
<p>在<a class="xref-link" href="#listing-user-model-password-reset">代码清单 12.6</a> 中我们用到了 <a class="xref-link" href="chapter11.html#activation-test-and-refactoring">11.3.3 节</a>重构的成果,直接在 <code>User</code> 模型中使用 <code>User</code> 邮件程序:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="no">UserMailer</span><span class="p">.</span><span class="nf">password_reset</span><span class="p">(</span><span class="nb">self</span><span class="p">).</span><span class="nf">deliver_now</span>
</code></pre></div>
</div>
<p>让这个邮件程序运作起来所需的代码几乎与 <a class="xref-link" href="chapter11.html#account-activation-emails">11.2 节</a>的账户激活邮件程序一样。我们首先在 <code>UserMailer</code> 中定义 <code>password_reset</code> 方法(<a class="xref-link" href="#listing-mail-password-reset">代码清单 12.7</a>),然后编写邮件的纯文本视图(<a class="xref-link" href="#listing-password-reset-text">代码清单 12.8</a>)和 HTML 视图(<a class="xref-link" href="#listing-password-reset-html">代码清单 12.9</a>)。</p>
<div id="listing-mail-password-reset" data-type="listing">
<h5><span class="title-label">代码清单 12.7</span>:发送密码重设链接</h5>
<div class="source-file">app/mailers/user_mailer.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">UserMailer</span> <span class="o"><</span> <span class="no">ApplicationMailer</span>
<span class="k">def</span> <span class="nf">account_activation</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">user</span>
<span class="n">mail</span> <span class="ss">to: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">,</span> <span class="ss">subject: </span><span class="s2">"Account activation"</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">password_reset</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="hll"> <span class="vi">@user</span> <span class="o">=</span> <span class="n">user</span></span>
<span class="hll"> <span class="n">mail</span> <span class="ss">to: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">,</span> <span class="ss">subject: </span><span class="s2">"Password reset"</span></span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<div id="listing-password-reset-text" data-type="listing">
<h5><span class="title-label">代码清单 12.8</span>:密码重设邮件的纯文本视图</h5>
<div class="source-file">app/views/user_mailer/password_reset.text.erb</div>
<div class="highlight language-erb"><pre><code>To reset your password click the link below:
<span class="cp"><%=</span> <span class="n">edit_password_reset_url</span><span class="p">(</span><span class="vi">@user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">,</span> <span class="ss">email: </span><span class="vi">@user</span><span class="p">.</span><span class="nf">email</span><span class="p">)</span> <span class="cp">%></span>
This link will expire in two hours.
If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
</code></pre></div>
</div>
<div id="listing-password-reset-html" data-type="listing">
<h5><span class="title-label">代码清单 12.9</span>:密码重设邮件的 HTML 视图</h5>
<div class="source-file">app/views/user_mailer/password_reset.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="nt"><h1></span>Password reset<span class="nt"></h1></span>
<span class="nt"><p></span>To reset your password click the link below:<span class="nt"></p></span>
<span class="cp"><%=</span> <span class="n">link_to</span> <span class="s2">"Reset password"</span><span class="p">,</span> <span class="n">edit_password_reset_url</span><span class="p">(</span><span class="vi">@user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">,</span>
<span class="ss">email: </span><span class="vi">@user</span><span class="p">.</span><span class="nf">email</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><p></span>This link will expire in two hours.<span class="nt"></p></span>
<span class="nt"><p></span>
If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
<span class="nt"></p></span>
</code></pre></div>
</div>
<p>与账户激活邮件一样(<a class="xref-link" href="chapter11.html#account-activation-emails">11.2 节</a>),我们可以使用 Rails 提供的邮件预览程序预览密码重设邮件。参照<a class="xref-link" href="chapter11.html#listing-account-activation-preview">代码清单 11.18</a>,密码重设邮件的预览程序如<a class="xref-link" href="#listing-password-reset-preview">代码清单 12.10</a> 所示。</p>
<div id="listing-password-reset-preview" data-type="listing">
<h5><span class="title-label">代码清单 12.10</span>:预览密码重设邮件所需的方法</h5>
<div class="source-file">test/mailers/previews/user_mailer_preview.rb</div>
<div class="highlight language-ruby"><pre><code><span class="c1"># Preview all emails at http://localhost:3000/rails/mailers/user_mailer</span>
<span class="k">class</span> <span class="nc">UserMailerPreview</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Preview</span>
<span class="c1"># Preview this email at</span>
<span class="c1"># http://localhost:3000/rails/mailers/user_mailer/account_activation</span>
<span class="k">def</span> <span class="nf">account_activation</span>
<span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">first</span>
<span class="n">user</span><span class="p">.</span><span class="nf">activation_token</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new_token</span>
<span class="no">UserMailer</span><span class="p">.</span><span class="nf">account_activation</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="k">end</span>
<span class="c1"># Preview this email at</span>
<span class="c1"># http://localhost:3000/rails/mailers/user_mailer/password_reset</span>
<span class="k">def</span> <span class="nf">password_reset</span>
<span class="hll"> <span class="n">user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">first</span></span>
<span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new_token</span>
<span class="no">UserMailer</span><span class="p">.</span><span class="nf">password_reset</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>然后就可以预览密码重设邮件了,HTML 格式和纯文本格式分别如<a class="xref-link" href="#fig-password-reset-html-preview">图 12.8</a> 和<a class="xref-link" href="#fig-password-reset-text-preview">图 12.9</a> 所示。</p>
<div id="fig-password-reset-html-preview" class="figure"><img src="images/chapter12/password_reset_html_preview_4th_ed.png" alt="password reset html preview 4th ed" /><div class="figcaption"><span class="title-label">图 12.8</span>:预览 HTML 格式的密码重设邮件</div></div>
<p>现在,提交有效的电子邮件地址后会看到如<a class="xref-link" href="#fig-valid-email-password-reset">图 12.10</a> 所示的页面。服务器日志中会显示相应的邮件,如<a class="xref-link" href="#listing-password-reset-email">代码清单 12.11</a> 所示。</p>
<div id="fig-password-reset-text-preview" class="figure"><img src="images/chapter12/password_reset_text_preview_4th_ed.png" alt="password reset text preview 4th ed" /><div class="figcaption"><span class="title-label">图 12.9</span>:预览纯文本格式的密码重设邮件</div></div>
<div id="fig-valid-email-password-reset" class="figure"><img src="images/chapter12/valid_email_password_reset.png" alt="valid email password reset" /><div class="figcaption"><span class="title-label">图 12.10</span>:提交有效电子邮件地址后看到的页面</div></div>
<div id="listing-password-reset-email" data-type="listing">
<h5><span class="title-label">代码清单 12.11</span>:服务器日志中看到的密码重设邮件</h5>
<div class="highlight language-text"><pre><code>Sent mail to [email protected] (66.8ms)
Date: Mon, 06 Jun 2016 22:00:41 +0000
From: [email protected]
Message-ID: <[email protected]>
Subject: Password reset
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_5407babbe3505_8722b257d045617";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_5407babbe3505_8722b257d045617
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
To reset your password click the link below:
https://rails-tutorial-mhartl.c9users.io/password_resets/3BdBrXeQZSWqFIDRN8cxHA/
edit?email=michael%40michaelhartl.com
This link will expire in two hours.
If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
----==_mimepart_5407babbe3505_8722b257d045617
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<h1>Password reset</h1>
<p>To reset your password click the link below:</p>
<a href="https://rails-tutorial-mhartl.c9users.io/
password_resets/3BdBrXeQZSWqFIDRN8cxHA/
edit?email=michael%40michaelhartl.com">Reset password</a>
<p>This link will expire in two hours.</p>
<p>
If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
</p>
----==_mimepart_5407babbe3505_8722b257d045617--
</code></pre></div>
</div>
<h5 id="exercises-password-reset-mailer" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>在浏览器中预览电子邮件模板。你看到的发送日期是什么?</p>
</li>
<li>
<p>在请求重设密码表单中提交有效的电子邮件地址,在服务器日志中会看到什么?</p>
</li>
<li>
<p>在 Rails 控制台中查找前一题中那个电子邮件地址对应的用户对象,确认它有 <code>reset_digest</code> 和 <code>reset_sent_at</code> 属性。</p>
</li>
</ol>
</section>
<section data-type="sect2" id="reset-email-tests">
<h2><span class="title-label">12.2.2</span> 测试电子邮件</h2>
<p>参照账户激活邮件程序的测试(<a class="xref-link" href="chapter11.html#listing-real-account-activation-test">代码清单 11.20</a>),下面为密码重设邮件程序编写一个测试,如<a class="xref-link" href="#listing-password-reset-mailer-test">代码清单 12.12</a> 所示。</p>
<div id="listing-password-reset-mailer-test" data-type="listing">
<h5><span class="title-label">代码清单 12.12</span>:添加密码重设邮件程序的测试 <span class="green">GREEN</span></h5>
<div class="source-file">test/mailers/user_mailer_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">UserMailerTest</span> <span class="o"><</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">TestCase</span>
<span class="nb">test</span> <span class="s2">"account_activation"</span> <span class="k">do</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="n">user</span><span class="p">.</span><span class="nf">activation_token</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new_token</span>
<span class="n">mail</span> <span class="o">=</span> <span class="no">UserMailer</span><span class="p">.</span><span class="nf">account_activation</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="n">assert_equal</span> <span class="s2">"Account activation"</span><span class="p">,</span> <span class="n">mail</span><span class="p">.</span><span class="nf">subject</span>
<span class="n">assert_equal</span> <span class="p">[</span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">],</span> <span class="n">mail</span><span class="p">.</span><span class="nf">to</span>
<span class="n">assert_equal</span> <span class="p">[</span><span class="s2">"[email protected]"</span><span class="p">],</span> <span class="n">mail</span><span class="p">.</span><span class="nf">from</span>
<span class="n">assert_match</span> <span class="n">user</span><span class="p">.</span><span class="nf">name</span><span class="p">,</span> <span class="n">mail</span><span class="p">.</span><span class="nf">body</span><span class="p">.</span><span class="nf">encoded</span>
<span class="n">assert_match</span> <span class="n">user</span><span class="p">.</span><span class="nf">activation_token</span><span class="p">,</span> <span class="n">mail</span><span class="p">.</span><span class="nf">body</span><span class="p">.</span><span class="nf">encoded</span>
<span class="n">assert_match</span> <span class="no">CGI</span><span class="p">.</span><span class="nf">escape</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">),</span> <span class="n">mail</span><span class="p">.</span><span class="nf">body</span><span class="p">.</span><span class="nf">encoded</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"password_reset"</span> <span class="k">do</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="hll"> <span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new_token</span></span>
<span class="n">mail</span> <span class="o">=</span> <span class="no">UserMailer</span><span class="p">.</span><span class="nf">password_reset</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
<span class="n">assert_equal</span> <span class="s2">"Password reset"</span><span class="p">,</span> <span class="n">mail</span><span class="p">.</span><span class="nf">subject</span>
<span class="n">assert_equal</span> <span class="p">[</span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">],</span> <span class="n">mail</span><span class="p">.</span><span class="nf">to</span>
<span class="n">assert_equal</span> <span class="p">[</span><span class="s2">"[email protected]"</span><span class="p">],</span> <span class="n">mail</span><span class="p">.</span><span class="nf">from</span>
<span class="n">assert_match</span> <span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">,</span> <span class="n">mail</span><span class="p">.</span><span class="nf">body</span><span class="p">.</span><span class="nf">encoded</span>
<span class="n">assert_match</span> <span class="no">CGI</span><span class="p">.</span><span class="nf">escape</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">),</span> <span class="n">mail</span><span class="p">.</span><span class="nf">body</span><span class="p">.</span><span class="nf">encoded</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>现在,测试组件应该能通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 12.13</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<h5 id="exercises-reset-email-tests" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>只运行邮件程序的测试,能通过吗?</p>
</li>
<li>
<p>把<a class="xref-link" href="#listing-password-reset-mailer-test">代码清单 12.12</a> 中第二个测试里的 <code>CGI.escape</code> 去掉,确认测试会失败。</p>
</li>
</ol>
</section>
</section>
<section data-type="sect1" id="resetting-the-password">
<h1><span class="title-label">12.3</span> 重设密码</h1>
<p>现在能正确生成邮件了(<a class="xref-link" href="#listing-password-reset-email">代码清单 12.11</a>),接下来我们要编写 <code>PasswordResets</code> 控制器的 <code>edit</code> 动作,重设用户的密码。与 <a class="xref-link" href="chapter11.html#activation-test-and-refactoring">11.3.3 节</a>一样,我们将编写完整的集成测试。</p>
<section data-type="sect2" id="reset-edit-action">
<h2><span class="title-label">12.3.1</span> <code>PasswordResets</code> 控制器的 <code>edit</code> 动作</h2>
<p>密码重设邮件中有类似下面这种形式的链接:</p>
<div data-type="listing">
<div class="highlight language-text"><pre><code>https://example.com/password_resets/3BdBrXeQZSWqFIDRN8cxHA/edit?email=foo%40bar.com
</code></pre></div>
</div>
<p>为了让这种形式的链接生效,我们要编写一个表单,重设密码。这个表单的目的与编辑用户资料的表单(<a class="xref-link" href="chapter10.html#listing-user-edit-view">代码清单 10.2</a>)类似,不过现在只需更新密码和密码确认两个字段。</p>
<p>不过,这一次处理起来有点复杂,因为我们希望通过电子邮件地址查找用户。也就是说,在 <code>edit</code> 动作和 <code>update</code> 动作中都需要使用邮件地址。在 <code>edit</code> 动作中可以轻易地获取邮件地址,因为链接中有。可是提交表单后,邮件地址就没有了。为了解决这个问题,我们可以使用一个隐藏字段,把它的值设为邮件地址(不会显示),和表单中的其他数据一起提交给 <code>update</code> 动作,如<a class="xref-link" href="#listing-password-reset-form">代码清单 12.14</a> 所示。</p>
<div id="listing-password-reset-form" data-type="listing">
<h5><span class="title-label">代码清单 12.14</span>:重设密码的表单</h5>
<div class="source-file">app/views/password_resets/edit.html.erb</div>
<div class="highlight language-erb"><pre><code><span class="cp"><%</span> <span class="n">provide</span><span class="p">(</span><span class="ss">:title</span><span class="p">,</span> <span class="s1">'Reset password'</span><span class="p">)</span> <span class="cp">%></span>
<span class="nt"><h1></span>Reset password<span class="nt"></h1></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"row"</span><span class="nt">></span>
<span class="nt"><div</span> <span class="na">class=</span><span class="s">"col-md-6 col-md-offset-3"</span><span class="nt">></span>
<span class="cp"><%=</span> <span class="n">form_for</span><span class="p">(</span><span class="vi">@user</span><span class="p">,</span> <span class="ss">url: </span><span class="n">password_reset_path</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">]))</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">render</span> <span class="s1">'shared/error_messages'</span> <span class="cp">%></span>
<span class="hll"> <span class="cp"><%=</span> <span class="n">hidden_field_tag</span> <span class="ss">:email</span><span class="p">,</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">email</span> <span class="cp">%></span></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">label</span> <span class="ss">:password_confirmation</span><span class="p">,</span> <span class="s2">"Confirmation"</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">password_field</span> <span class="ss">:password_confirmation</span><span class="p">,</span> <span class="ss">class: </span><span class="s1">'form-control'</span> <span class="cp">%></span>
<span class="cp"><%=</span> <span class="n">f</span><span class="p">.</span><span class="nf">submit</span> <span class="s2">"Update password"</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"btn btn-primary"</span> <span class="cp">%></span>
<span class="cp"><%</span> <span class="k">end</span> <span class="cp">%></span>
<span class="nt"></div></span>
<span class="nt"></div></span>
</code></pre></div>
</div>
<p>注意,在<a class="xref-link" href="#listing-password-reset-form">代码清单 12.14</a> 中,使用的表单标签辅助方法是</p>
<div data-type="listing">
<div class="highlight language-erb"><pre><code>hidden_field_tag :email, @user.email
</code></pre></div>
</div>
<p>而不是</p>
<div data-type="listing">
<pre class="highlight language-erb"><code>f.hidden_field :email, @user.email</code></pre>
</div>
<p>因为在重设密码的链接中,邮件地址在 <code>params[:email]</code> 中,如果使用后者,会把邮件地址放入 <code>params[:user][:email]</code> 中。</p>
<p>为了正确渲染这个表单,我们要在 <code>PasswordResets</code> 控制器的 <code>edit</code> 动作中定义 <code>@user</code> 变量。与账户激活一样(<a class="xref-link" href="chapter11.html#listing-account-activation-edit-action">代码清单 11.31</a>),我们要找到 <code>params[:email]</code> 中电子邮件地址对应的用户,确认这个用户已经激活,然后使用<a class="xref-link" href="chapter11.html#listing-generalized-authenticated-p">代码清单 11.26</a> 中定义的通用版 <code>authenticated?</code> 方法验证 <code>params[:id]</code> 中的重设令牌。因为在 <code>edit</code> 和 <code>update</code> 动作中都要使用 <code>@user</code>,所以我们要把查找用户和验证令牌的代码写入一个前置过滤器中,如<a class="xref-link" href="#listing-password-reset-edit-action">代码清单 12.15</a> 所示。</p>
<div id="listing-password-reset-edit-action" data-type="listing">
<h5><span class="title-label">代码清单 12.15</span>:<code>PasswordResets</code> 控制器的 <code>edit</code> 动作</h5>
<div class="source-file">app/controllers/password_resets_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">PasswordResetsController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="hll"> <span class="n">before_action</span> <span class="ss">:get_user</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span></span>
<span class="hll"> <span class="n">before_action</span> <span class="ss">:valid_user</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span></span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">def</span> <span class="n">edit</span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">get_user</span>
<span class="hll"> <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">email: </span><span class="n">params</span><span class="p">[</span><span class="ss">:email</span><span class="p">])</span></span>
<span class="k">end</span>
<span class="c1"># 确保是有效用户</span>
<span class="k">def</span> <span class="nf">valid_user</span>
<span class="hll"> <span class="k">unless</span> <span class="p">(</span><span class="vi">@user</span> <span class="o">&&</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">activated?</span> <span class="o">&&</span></span>
<span class="hll"> <span class="vi">@user</span><span class="p">.</span><span class="nf">authenticated?</span><span class="p">(</span><span class="ss">:reset</span><span class="p">,</span> <span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">]))</span></span>
<span class="hll"> <span class="n">redirect_to</span> <span class="n">root_url</span></span>
<span class="hll"> <span class="k">end</span></span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p><a class="xref-link" href="#listing-password-reset-edit-action">代码清单 12.15</a> 中的 <code>authenticated?(:reset, params[:id])</code>,<a class="xref-link" href="chapter11.html#listing-generalized-current-user">代码清单 11.28</a> 中的 <code>authenticated?(:remember, cookies[:remember_token])</code>,以及<a class="xref-link" href="chapter11.html#listing-account-activation-edit-action">代码清单 11.31</a> 中的 <code>authenticated?(:activation, params[:id])</code>,就是<a class="xref-link" href="chapter11.html#table-password-token-digest">表 11.1</a> 中 <code>authenticated?</code> 方法的三个用例。</p>
<p>现在,点击<a class="xref-link" href="#listing-password-reset-email">代码清单 12.11</a> 中的链接后,会显示密码重设表单,如<a class="xref-link" href="#fig-password-reset-form">图 12.11</a> 所示。</p>
<div id="fig-password-reset-form" class="figure"><img src="images/chapter12/password_reset_form.png" alt="password reset form" /><div class="figcaption"><span class="title-label">图 12.11</span>:密码重设表单</div></div>
<h5 id="exercises-reset-edit-action" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>点击服务器日志中的密码重设链接,看能不能正确渲染如<a class="xref-link" href="#fig-password-reset-form">图 12.11</a> 所示的表单。</p>
</li>
<li>
<p>提交前一题看到的表单会发生什么?</p>
</li>
</ol>
</section>
<section data-type="sect2" id="updating-the-reset">
<h2><span class="title-label">12.3.2</span> 更新密码</h2>
<p><code>AccountActivations</code> 控制器的 <code>edit</code> 动作只需把用户的状态由“未激活”改成“激活”,而 <code>PasswordResets</code> 控制器的 <code>edit</code> 动作处理的是表单,因此提交后要交给 <code>update</code> 动作处理。为了定义 <code>update</code> 动作,我们要考虑四种情况:</p>
<ol class="arabic">
<li>
<p>密码重设请求已过期</p>
</li>
<li>
<p>填写的新密码无效,更新失败</p>
</li>
<li>
<p>没有填写密码和密码确认,更新失败(看起来像是成功了)</p>
</li>
<li>
<p>成功更新密码</p>
</li>
</ol>
<p>第一第二和第四种情况非常简单,第三种情况不是那么直观,下面会详述。</p>
<p>第一种情况在 <code>edit</code> 和 <code>update</code> 动作中都要考虑,因此可以使用前置过滤器:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="n">before_action</span> <span class="ss">:check_expiration</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span> <span class="c1"># 第一种情况</span>
</code></pre></div>
</div>
<p>为此,我们要定义私有的 <code>check_expiration</code> 方法:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="c1"># 检查重设令牌是否过期</span>
<span class="k">def</span> <span class="nf">check_expiration</span>
<span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">password_reset_expired?</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Password reset has expired."</span>
<span class="n">redirect_to</span> <span class="n">new_password_reset_url</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>在 <code>check_expiration</code> 方法中,我们把过期检查交给实例方法 <code>password_reset_expired?</code> 去做。这个方法有点难定义,稍后再讲。</p>
<p><a class="xref-link" href="#listing-password-reset-update-action">代码清单 12.16</a> 给出了这两个过滤器的实现,还给出了涵盖第二第三和第四种情况的 <code>update</code> 动作。第二种情况会导致更新失败,然后重新渲染 <code>edit</code> 视图,显示错误消息(使用<a class="xref-link" href="#listing-password-reset-form">代码清单 12.14</a> 中共用的局部视图)。第四种情况是成功更新密码,处理方式与成功登录类似(<a class="xref-link" href="chapter8.html#listing-login-upon-signup">代码清单 8.25</a>)。</p>
<p>第二种情况没有处理密码为空(即第三种情况),而现在 <code>User</code> 模型允许密码为空(<a class="xref-link" href="chapter10.html#listing-allow-blank-password">代码清单 10.13</a>),所以我们要捕获这个问题,然后单独处理。<sup>[<a id="fn-ref-2" href="#fn-2">2</a>]</sup>为了处理这种情况,我们使用 <code>errors.add</code> 方法直接为 <code>@user</code> 对象添加错误消息:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="vi">@user</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="ss">:password</span><span class="p">,</span> <span class="ss">:blank</span><span class="p">)</span>
</code></pre></div>
</div>
<p>密码为空时,上述代码使用没有内容时的默认消息。<sup>[<a id="fn-ref-3" href="#fn-3">3</a>]</sup></p>
<p>综上,处理四种情况的 <code>update</code> 动作如<a class="xref-link" href="#listing-password-reset-update-action">代码清单 12.16</a> 所示。</p>
<div id="listing-password-reset-update-action" data-type="listing">
<h5><span class="title-label">代码清单 12.16</span>:重设密码的 <code>update</code> 动作</h5>
<div class="source-file">app/controllers/password_resets_controller.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">PasswordResetsController</span> <span class="o"><</span> <span class="no">ApplicationController</span>
<span class="n">before_action</span> <span class="ss">:get_user</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span>
<span class="n">before_action</span> <span class="ss">:valid_user</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span>
<span class="hll"> <span class="n">before_action</span> <span class="ss">:check_expiration</span><span class="p">,</span> <span class="ss">only: </span><span class="p">[</span><span class="ss">:edit</span><span class="p">,</span> <span class="ss">:update</span><span class="p">]</span> <span class="c1"># 第一种情况</span></span>
<span class="k">def</span> <span class="nf">new</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">create</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">email: </span><span class="n">params</span><span class="p">[</span><span class="ss">:password_reset</span><span class="p">][</span><span class="ss">:email</span><span class="p">].</span><span class="nf">downcase</span><span class="p">)</span>
<span class="k">if</span> <span class="vi">@user</span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">create_reset_digest</span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">send_password_reset_email</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:info</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Email sent with password reset instructions"</span>
<span class="n">redirect_to</span> <span class="n">root_url</span>
<span class="k">else</span>
<span class="n">flash</span><span class="p">.</span><span class="nf">now</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Email address not found"</span>
<span class="n">render</span> <span class="s1">'new'</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">edit</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">update</span>
<span class="hll"> <span class="k">if</span> <span class="n">params</span><span class="p">[</span><span class="ss">:user</span><span class="p">][</span><span class="ss">:password</span><span class="p">].</span><span class="nf">empty?</span> <span class="c1"># 第三种情况</span></span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="ss">:password</span><span class="p">,</span> <span class="s2">"can't be empty"</span><span class="p">)</span>
<span class="n">render</span> <span class="s1">'edit'</span>
<span class="hll"> <span class="k">elsif</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">update_attributes</span><span class="p">(</span><span class="n">user_params</span><span class="p">)</span> <span class="c1"># 第四种情况</span></span>
<span class="n">log_in</span> <span class="vi">@user</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:success</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Password has been reset."</span>
<span class="n">redirect_to</span> <span class="vi">@user</span>
<span class="k">else</span>
<span class="hll"> <span class="n">render</span> <span class="s1">'edit'</span> <span class="c1"># 第二种情况</span></span>
<span class="k">end</span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="hll"> <span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:password</span><span class="p">,</span> <span class="ss">:password_confirmation</span><span class="p">)</span></span>
<span class="k">end</span>
<span class="c1"># 前置过滤器</span>
<span class="k">def</span> <span class="nf">get_user</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">email: </span><span class="n">params</span><span class="p">[</span><span class="ss">:email</span><span class="p">])</span>
<span class="k">end</span>
<span class="c1"># 确保是有效用户</span>
<span class="k">def</span> <span class="nf">valid_user</span>
<span class="k">unless</span> <span class="p">(</span><span class="vi">@user</span> <span class="o">&&</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">activated?</span> <span class="o">&&</span>
<span class="vi">@user</span><span class="p">.</span><span class="nf">authenticated?</span><span class="p">(</span><span class="ss">:reset</span><span class="p">,</span> <span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">]))</span>
<span class="n">redirect_to</span> <span class="n">root_url</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="c1"># 检查重设令牌是否过期</span>
<span class="hll"> <span class="k">def</span> <span class="nf">check_expiration</span></span>
<span class="k">if</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">password_reset_expired?</span>
<span class="n">flash</span><span class="p">[</span><span class="ss">:danger</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Password reset has expired."</span>
<span class="n">redirect_to</span> <span class="n">new_password_reset_url</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p>注意,我们在 <code>user_params</code> 方法中指定允许修改 <code>password</code> 和 <code>password_confirmation</code> 两个属性。</p>
<p>前面说过,我们把密码重设超时检查交给 <code>User</code> 模型去做:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="vi">@user</span><span class="p">.</span><span class="nf">password_reset_expired?</span>
</code></pre></div>
</div>
<p>所以,我们要定义 <code>password_reset_expired?</code> 方法。如 <a class="xref-link" href="#password-reset-mailer">12.2.1 节</a>的邮件模板所示,如果邮件发出后两个小时内没重设密码,就认为此次请求超时了。这个限制可以通过下面的 Ruby 代码实现:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="n">reset_sent_at</span> <span class="o"><</span> <span class="mi">2</span><span class="p">.</span><span class="nf">hours</span><span class="p">.</span><span class="nf">ago</span>
</code></pre></div>
</div>
<p>如果你把 <code><</code> 当成小于号,读成“密码重设邮件发出少于两小时”就错了,这和想表达的意思正好相反。这里,最好把 <code><</code> 理解成“超过”,读成“密码重设邮件已经发出超过两小时”,这才是我们想表达的意思。<code>password_reset_expired?</code> 方法的定义如<a class="xref-link" href="#listing-user-model-password-reset-expired">代码清单 12.17</a> 所示。(对这个比较算式的证明参见 <a class="xref-link" href="#proof-of-expiration-comparison">12.6 节</a>。)</p>
<div id="listing-user-model-password-reset-expired" data-type="listing">
<h5><span class="title-label">代码清单 12.17</span>:在 <code>User</code> 模型中定义 <code>password_reset_expired?</code> 方法</h5>
<div class="source-file">app/models/user.rb</div>
<div class="highlight language-ruby"><pre><code><span class="k">class</span> <span class="nc">User</span> <span class="o"><</span> <span class="no">ApplicationRecord</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="o">.</span>
<span class="c1"># 如果密码重设请求超时了,返回 true</span>
<span class="k">def</span> <span class="nf">password_reset_expired?</span>
<span class="hll"> <span class="n">reset_sent_at</span> <span class="o"><</span> <span class="mi">2</span><span class="p">.</span><span class="nf">hours</span><span class="p">.</span><span class="nf">ago</span></span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="p">.</span>
<span class="nf">.</span>
<span class="p">.</span>
<span class="nf">end</span>
</code></pre></div>
</div>
<p>现在,<a class="xref-link" href="#listing-password-reset-update-action">代码清单 12.16</a> 中的 <code>update</code> 动作可以使用了。密码重设失败和成功后显示的页面分别如<a class="xref-link" href="#fig-password-reset-failure">图 12.12</a> 和<a class="xref-link" href="#fig-password-reset-success">图 12.13</a> 所示。(你可能不想等两个小时再确认效果,<a class="xref-link" href="#exercises-updating-the-reset">本节的练习</a>中有一题,为第三个分支编写测试。)</p>
<h5 id="exercises-updating-the-reset" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>打开邮件中的链接,在页面中填写不一致的密码,会看到什么错误消息?</p>
</li>
<li>
<p>在 Rails 控制台中找到邮件中链接对应的用户,获取 <code>password_digest</code> 属性的值。然后在如<a class="xref-link" href="#fig-password-reset-failure">图 12.12</a> 所示的表单中填写匹配的密码,提交后有什么效果?对 <code>password_digest</code> 属性的值有什么影响?提示:使用 <code>user.reload</code> 方法加载新值。</p>
</li>
</ol>
<div id="fig-password-reset-failure" class="figure"><img src="images/chapter12/password_reset_failure_4th_ed.png" alt="password reset failure 4th ed" /><div class="figcaption"><span class="title-label">图 12.12</span>:密码重设失败</div></div>
<div id="fig-password-reset-success" class="figure"><img src="images/chapter12/password_reset_success_4th_ed.png" alt="password reset success 4th ed" /><div class="figcaption"><span class="title-label">图 12.13</span>:密码重设成功</div></div>
</section>
<section data-type="sect2" id="password-reset-test">
<h2><span class="title-label">12.3.3</span> 测试密码重设功能</h2>
<p>本节,我们要编写一个集成测试,覆盖<a class="xref-link" href="#listing-password-reset-update-action">代码清单 12.16</a> 中的两个分支:重设失败和重设成功。(前面说过,第三个分支的测试留作练习。)首先,为重设密码功能生成一个测试文件:</p>
<div data-type="listing">
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails generate integration_test password_resets
invoke test_unit
create <span class="nb">test</span>/integration/password_resets_test.rb
</code></pre></div>
</div>
<p>这个测试的步骤大致与<a class="xref-link" href="chapter11.html#listing-signup-with-account-activation-test">代码清单 11.33</a> 中的账户激活测试差不多,不过开头有点不同。首先访问“Forgot password”表单,分别提交有效和无效的电子邮件地址,电子邮件地址有效时要创建密码重设令牌,并且发送重设邮件。然后,访问邮件中的链接,分别提交无效和有效的密码,验证各自的行为是否正确。最终写出的测试如<a class="xref-link" href="#listing-password-reset-integration-test">代码清单 12.18</a> 所示。这是一个不错的练习,可以锻炼阅读代码的能力。</p>
<div id="listing-password-reset-integration-test" data-type="listing">
<h5><span class="title-label">代码清单 12.18</span>:密码重设功能的集成测试</h5>
<div class="source-file">test/integration/password_resets_test.rb</div>
<div class="highlight language-ruby"><pre><code><span class="nb">require</span> <span class="s1">'test_helper'</span>
<span class="k">class</span> <span class="nc">PasswordResetsTest</span> <span class="o"><</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">IntegrationTest</span>
<span class="k">def</span> <span class="nf">setup</span>
<span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span><span class="p">.</span><span class="nf">deliveries</span><span class="p">.</span><span class="nf">clear</span>
<span class="vi">@user</span> <span class="o">=</span> <span class="n">users</span><span class="p">(</span><span class="ss">:michael</span><span class="p">)</span>
<span class="k">end</span>
<span class="nb">test</span> <span class="s2">"password resets"</span> <span class="k">do</span>
<span class="n">get</span> <span class="n">new_password_reset_path</span>
<span class="n">assert_template</span> <span class="s1">'password_resets/new'</span>
<span class="c1"># 电子邮件地址无效</span>
<span class="n">post</span> <span class="n">password_resets_path</span><span class="p">,</span> <span class="ss">params: </span><span class="p">{</span> <span class="ss">password_reset: </span><span class="p">{</span> <span class="ss">email: </span><span class="s2">""</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_template</span> <span class="s1">'password_resets/new'</span>
<span class="c1"># 电子邮件地址有效</span>
<span class="n">post</span> <span class="n">password_resets_path</span><span class="p">,</span>
<span class="ss">params: </span><span class="p">{</span> <span class="ss">password_reset: </span><span class="p">{</span> <span class="ss">email: </span><span class="vi">@user</span><span class="p">.</span><span class="nf">email</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_not_equal</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">reset_digest</span><span class="p">,</span> <span class="vi">@user</span><span class="p">.</span><span class="nf">reload</span><span class="p">.</span><span class="nf">reset_digest</span>
<span class="n">assert_equal</span> <span class="mi">1</span><span class="p">,</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span><span class="p">.</span><span class="nf">deliveries</span><span class="p">.</span><span class="nf">size</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="n">root_url</span>
<span class="c1"># 密码重设表单</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">assigns</span><span class="p">(</span><span class="ss">:user</span><span class="p">)</span>
<span class="c1"># 电子邮件地址错误</span>
<span class="n">get</span> <span class="n">edit_password_reset_path</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">,</span> <span class="ss">email: </span><span class="s2">""</span><span class="p">)</span>
<span class="n">assert_redirected_to</span> <span class="n">root_url</span>
<span class="c1"># 用户未激活</span>
<span class="n">user</span><span class="p">.</span><span class="nf">toggle!</span><span class="p">(</span><span class="ss">:activated</span><span class="p">)</span>
<span class="n">get</span> <span class="n">edit_password_reset_path</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">,</span> <span class="ss">email: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">)</span>
<span class="n">assert_redirected_to</span> <span class="n">root_url</span>
<span class="n">user</span><span class="p">.</span><span class="nf">toggle!</span><span class="p">(</span><span class="ss">:activated</span><span class="p">)</span>
<span class="c1"># 电子邮件地址正确,令牌不对</span>
<span class="n">get</span> <span class="n">edit_password_reset_path</span><span class="p">(</span><span class="s1">'wrong token'</span><span class="p">,</span> <span class="ss">email: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">)</span>
<span class="n">assert_redirected_to</span> <span class="n">root_url</span>
<span class="c1"># 电子邮件地址正确,令牌也对</span>
<span class="n">get</span> <span class="n">edit_password_reset_path</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">,</span> <span class="ss">email: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">)</span>
<span class="n">assert_template</span> <span class="s1">'password_resets/edit'</span>
<span class="n">assert_select</span> <span class="s2">"input[name=email][type=hidden][value=?]"</span><span class="p">,</span> <span class="n">user</span><span class="p">.</span><span class="nf">email</span>
<span class="c1"># 密码和密码确认不匹配</span>
<span class="n">patch</span> <span class="n">password_reset_path</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">),</span>
<span class="ss">params: </span><span class="p">{</span> <span class="ss">email: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">,</span>
<span class="ss">user: </span><span class="p">{</span> <span class="ss">password: </span><span class="s2">"foobaz"</span><span class="p">,</span>
<span class="ss">password_confirmation: </span><span class="s2">"barquux"</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_select</span> <span class="s1">'div#error_explanation'</span>
<span class="c1"># 密码为空值</span>
<span class="n">patch</span> <span class="n">password_reset_path</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">),</span>
<span class="ss">params: </span><span class="p">{</span> <span class="ss">email: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">,</span>
<span class="ss">user: </span><span class="p">{</span> <span class="ss">password: </span><span class="s2">""</span><span class="p">,</span>
<span class="ss">password_confirmation: </span><span class="s2">""</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert_select</span> <span class="s1">'div#error_explanation'</span>
<span class="c1"># 密码和密码确认有效</span>
<span class="n">patch</span> <span class="n">password_reset_path</span><span class="p">(</span><span class="n">user</span><span class="p">.</span><span class="nf">reset_token</span><span class="p">),</span>
<span class="ss">params: </span><span class="p">{</span> <span class="ss">email: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">,</span>
<span class="ss">user: </span><span class="p">{</span> <span class="ss">password: </span><span class="s2">"foobaz"</span><span class="p">,</span>
<span class="ss">password_confirmation: </span><span class="s2">"foobaz"</span> <span class="p">}</span> <span class="p">}</span>
<span class="n">assert</span> <span class="n">is_logged_in?</span>
<span class="n">assert_not</span> <span class="n">flash</span><span class="p">.</span><span class="nf">empty?</span>
<span class="n">assert_redirected_to</span> <span class="n">user</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div>
</div>
<p><a class="xref-link" href="#listing-password-reset-integration-test">代码清单 12.18</a> 中的大多数用法前面都见过,但是针对 <code>input</code> 标签的测试有点陌生:</p>
<div data-type="listing">
<div class="highlight language-ruby"><pre><code><span class="n">assert_select</span> <span class="s2">"input[name=email][type=hidden][value=?]"</span><span class="p">,</span> <span class="n">user</span><span class="p">.</span><span class="nf">email</span>
</code></pre></div>
</div>
<p>这行代码的意思是,页面中有 <code>name</code> 属性、类型(隐藏)和电子邮件地址都正确的 <code>input</code> 标签:</p>
<div data-type="listing">
<div class="highlight language-html"><pre><code><span class="nt"><input</span> <span class="na">id=</span><span class="s">"email"</span> <span class="na">name=</span><span class="s">"email"</span> <span class="na">type=</span><span class="s">"hidden"</span> <span class="na">value=</span><span class="s">"[email protected]"</span> <span class="nt">/></span>
</code></pre></div>
</div>
<p>现在,测试组件应该能通过:</p>
<div data-type="listing">
<h5><span class="title-label">代码清单 12.19</span>:<strong class="green">GREEN</strong></h5>
<div class="highlight language-sh"><pre><code><span class="nv">$ </span>rails <span class="nb">test</span>
</code></pre></div>
</div>
<h5 id="exercises-password-reset-test" class="discrete">练习</h5>
<ol class="arabic">
<li>
<p>在<a class="xref-link" href="#listing-user-model-password-reset">代码清单 12.6</a> 中,<code>create_reset_digest</code> 方法调用了两次 <code>update_attribute</code> 方法,每一次调用都要单独执行一个数据库事务。填写<a class="xref-link" href="#listing-update-columns-redux">代码清单 12.20</a> 中缺少的代码,把两个 <code>update_attribute</code> 调用换成一个 <code>update_columns</code> 调用,这样修改后只会与数据库交互一次。改完后运行测试组件,确保仍能通过。(<a class="xref-link" href="#listing-update-columns-redux">代码清单 12.20</a> 中包含<a class="xref-link" href="chapter11.html#listing-update-columns">代码清单 11.39</a> 的解答。)</p>
</li>
<li>
<p>填写<a class="xref-link" href="#listing-password-reset-expire-test">代码清单 12.21</a> 中缺少的代码,为<a class="xref-link" href="#listing-password-reset-update-action">代码清单 12.16</a> 中的密码重设请求超时分支编写集成测试。(这里使用的 <code>response.body</code> 用于获取返回页面中的 HTML。)检查是否过期有很多方法,这里使用的方法是,检查响应主体中是否包含单词“expired”(不区分大小写)。</p>
</li>
<li>
<p>几小时后让密码重设请求过期是个不错的安全防护措施,可是对使用公共电脑的用户来说,安全隐患更大。这是因为密码重设链接的有效期是 2 小时,而在这段时间内,即便用户已经退出,重设链接仍能使用。如果用户在公共电脑上重设密码,任何人都能点击后退按钮,然后再次重设密码(从而使用新密码登录)。为了避免这个问题,添加<a class="xref-link" href="#listing-update-clear-reset">代码清单 12.22</a> 中的代码,在用户成功修改密码后清除重设摘要。<sup>[<a id="fn-ref-4" href="#fn-4">4</a>]</sup></p>
</li>
<li>
<p>在<a class="xref-link" href="#listing-password-reset-integration-test">代码清单 12.18</a> 中添加一行代码,测试前一题实现的重设摘要清除功能。提示:使用 <code>assert_nil</code> 和 <code>user.reload</code> 直接测试 <code>reset_digest</code> 属性。</p>
</li>