summaryrefslogtreecommitdiff
path: root/spec/requests/api/users_spec.rb
blob: 3ecd012be129fc74086fa396cf8b5c45ad78c8d0 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe API::Users, :aggregate_failures, feature_category: :user_profile do
  include WorkhorseHelpers

  let_it_be(:admin) { create(:admin) }
  let_it_be(:user, reload: true) { create(:user, username: 'user.withdot') }
  let_it_be(:key) { create(:key, user: user) }
  let_it_be(:gpg_key) { create(:gpg_key, user: user) }
  let_it_be(:email) { create(:email, user: user) }

  let(:blocked_user) { create(:user, :blocked) }
  let(:omniauth_user) { create(:omniauth_user) }
  let(:ldap_user) { create(:omniauth_user, provider: 'ldapmain') }
  let(:ldap_blocked_user) { create(:omniauth_user, provider: 'ldapmain', state: 'ldap_blocked') }
  let(:private_user) { create(:user, private_profile: true) }
  let(:deactivated_user) { create(:user, state: 'deactivated') }
  let(:banned_user) { create(:user, :banned) }
  let(:internal_user) { create(:user, :bot) }
  let(:user_with_2fa) { create(:user, :two_factor_via_otp) }
  let(:admin_with_2fa) { create(:admin, :two_factor_via_otp) }

  context 'admin notes' do
    let_it_be(:admin) { create(:admin, note: '2019-10-06 | 2FA added | user requested | www.gitlab.com') }
    let_it_be(:user, reload: true) { create(:user, note: '2018-11-05 | 2FA removed | user requested | www.gitlab.com') }

    describe 'POST /users' do
      let(:path) { '/users' }

      it_behaves_like 'POST request permissions for admin mode' do
        let(:params) { attributes_for(:user).merge({ note: 'Awesome Note' }) }
      end

      context 'when unauthenticated' do
        it 'return authentication error' do
          post api(path)

          expect(response).to have_gitlab_http_status(:unauthorized)
        end
      end

      context 'when authenticated' do
        context 'as an admin' do
          it 'contains the note of the user' do
            optional_attributes = { note: 'Awesome Note' }
            attributes = attributes_for(:user).merge(optional_attributes)

            post api(path, admin, admin_mode: true), params: attributes

            expect(response).to have_gitlab_http_status(:created)
            expect(json_response['note']).to eq(optional_attributes[:note])
          end
        end

        context 'as a regular user' do
          it 'does not allow creating new user' do
            post api(path, user), params: attributes_for(:user)

            expect(response).to have_gitlab_http_status(:forbidden)
          end
        end
      end
    end

    describe "PUT /users/:id" do
      let(:path) { "/users/#{user.id}" }

      it_behaves_like 'PUT request permissions for admin mode' do
        let(:params) { { note: 'new note' } }
      end

      context 'when user is an admin' do
        it "updates note of the user" do
          new_note = '2019-07-07 | Email changed | user requested | www.gitlab.com'

          expect do
            put api(path, admin, admin_mode: true), params: { note: new_note }
          end.to change { user.reload.note }
                   .from('2018-11-05 | 2FA removed | user requested | www.gitlab.com')
                   .to(new_note)

          expect(response).to have_gitlab_http_status(:success)
          expect(json_response['note']).to eq(new_note)
        end
      end

      context 'when user is not an admin' do
        it "cannot update their own note" do
          expect do
            put api(path, user), params: { note: 'new note' }
          end.not_to change { user.reload.note }

          expect(response).to have_gitlab_http_status(:forbidden)
        end
      end
    end

    describe "PATCH /users/:id/disable_two_factor" do
      context "when current user is an admin" do
        it "returns a 204 when 2FA is disabled for the target user" do
          expect do
            patch api("/users/#{user_with_2fa.id}/disable_two_factor", admin, admin_mode: true)
          end.to change { user_with_2fa.reload.two_factor_enabled? }
                  .from(true)
                  .to(false)
          expect(response).to have_gitlab_http_status(:no_content)
        end

        it "uses TwoFactor Destroy Service" do
          destroy_service = instance_double(TwoFactor::DestroyService, execute: nil)
          expect(TwoFactor::DestroyService).to receive(:new)
            .with(admin, user: user_with_2fa)
            .and_return(destroy_service)
          expect(destroy_service).to receive(:execute)

          patch api("/users/#{user_with_2fa.id}/disable_two_factor", admin, admin_mode: true)
        end

        it "returns a 400 if 2FA is not enabled for the target user" do
          expect(TwoFactor::DestroyService).to receive(:new).and_call_original

          expect do
            patch api("/users/#{user.id}/disable_two_factor", admin, admin_mode: true)
          end.not_to change { user.reload.two_factor_enabled? }

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(json_response['message']).to eq("400 Bad request - Two-factor authentication is not enabled for this user")
        end

        it "returns a 403 if the target user is an admin" do
          expect(TwoFactor::DestroyService).not_to receive(:new)

          expect do
            patch api("/users/#{admin_with_2fa.id}/disable_two_factor", admin, admin_mode: true)
          end.not_to change { admin_with_2fa.reload.two_factor_enabled? }

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq("403 Forbidden - Two-factor authentication for admins cannot be disabled via the API. Use the Rails console")
        end

        it "returns a 404 if the target user cannot be found" do
          expect(TwoFactor::DestroyService).not_to receive(:new)

          patch api("/users/#{non_existing_record_id}/disable_two_factor", admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:not_found)
          expect(json_response['message']).to eq("404 User Not Found")
        end
      end

      context "when current user is not an admin" do
        it "returns a 403" do
          expect do
            patch api("/users/#{user_with_2fa.id}/disable_two_factor", user)
          end.not_to change { user_with_2fa.reload.two_factor_enabled? }

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq("403 Forbidden")
        end
      end

      context "when unauthenticated" do
        it "returns a 401" do
          patch api("/users/#{user_with_2fa.id}/disable_two_factor")

          expect(response).to have_gitlab_http_status(:unauthorized)
        end
      end
    end

    describe 'GET /users/' do
      let(:path) { '/users' }

      context 'when unauthenticated' do
        it "does not contain certain fields" do
          get api(path), params: { username: user.username }

          expect(json_response.first).not_to have_key('note')
          expect(json_response.first).not_to have_key('namespace_id')
          expect(json_response.first).not_to have_key('created_by')
        end
      end

      context 'when authenticated' do
        context 'as a regular user' do
          it 'does not contain certain fields' do
            get api(path, user), params: { username: user.username }

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response.first).not_to have_key('note')
            expect(json_response.first).not_to have_key('namespace_id')
            expect(json_response.first).not_to have_key('created_by')
          end
        end

        context 'as an admin' do
          it 'contains the note of users' do
            get api(path, admin, admin_mode: true), params: { username: user.username }

            expect(response).to have_gitlab_http_status(:success)
            expect(json_response.first).to have_key('note')
            expect(json_response.first['note']).to eq '2018-11-05 | 2FA removed | user requested | www.gitlab.com'
          end

          context 'with `created_by` details' do
            it 'has created_by as nil with a self-registered account' do
              get api(path, admin, admin_mode: true), params: { username: user.username }

              expect(response).to have_gitlab_http_status(:success)
              expect(json_response.first).to have_key('created_by')
              expect(json_response.first['created_by']).to eq(nil)
            end

            it 'is created_by a user and has those details' do
              created = create(:user, created_by_id: user.id)

              get api(path, admin, admin_mode: true), params: { username: created.username }

              expect(response).to have_gitlab_http_status(:success)
              expect(json_response.first['created_by'].symbolize_keys)
                .to eq(API::Entities::UserBasic.new(user).as_json)
            end
          end
        end

        context 'N+1 queries' do
          before do
            create_list(:user, 2)
          end

          it 'avoids N+1 queries when requested by admin' do
            control_count = ActiveRecord::QueryRecorder.new(skip_cached: false) do
              get api(path, admin)
            end.count

            create_list(:user, 3)

            # There is a still a pending N+1 query related to fetching
            # project count for each user.
            # Refer issue https://gitlab.com/gitlab-org/gitlab/-/issues/367080

            expect do
              get api(path, admin)
            end.not_to exceed_all_query_limit(control_count + 3)
          end

          it 'avoids N+1 queries when requested by a regular user' do
            control_count = ActiveRecord::QueryRecorder.new(skip_cached: false) do
              get api(path, user)
            end.count

            create_list(:user, 3)

            expect do
              get api(path, user)
            end.not_to exceed_all_query_limit(control_count)
          end
        end
      end
    end

    describe 'GET /user' do
      let(:path) { '/user' }

      context 'when authenticated' do
        context 'as an admin' do
          context 'accesses their own profile' do
            it 'contains the note of the user' do
              get api(path, admin, admin_mode: true)

              expect(json_response).to have_key('note')
              expect(json_response['note']).to eq(admin.note)
            end
          end

          context 'sudo' do
            let(:admin_personal_access_token) { create(:personal_access_token, :admin_mode, user: admin, scopes: %w[api sudo]).token }

            context 'accesses the profile of another regular user' do
              it 'does not contain the note of the user' do
                get api("/user?private_token=#{admin_personal_access_token}&sudo=#{user.id}")

                expect(json_response['id']).to eq(user.id)
                expect(json_response).not_to have_key('note')
              end
            end

            context 'accesses the profile of another admin' do
              let(:admin_2) { create(:admin, note: '2010-10-10 | 2FA added | admin requested | www.gitlab.com') }

              it 'contains the note of the user' do
                get api("/user?private_token=#{admin_personal_access_token}&sudo=#{admin_2.id}")

                expect(json_response['id']).to eq(admin_2.id)
                expect(json_response).to have_key('note')
                expect(json_response['note']).to eq(admin_2.note)
              end
            end
          end
        end

        context 'as a regular user' do
          it 'does not contain the note of the user' do
            get api(path, user)

            expect(json_response).not_to have_key('note')
            expect(json_response).not_to have_key('namespace_id')
          end
        end
      end
    end
  end

  shared_examples 'rendering user status' do
    it 'returns the status if there was one' do
      create(:user_status, user: user)

      get api(path, user)

      expect(response).to have_gitlab_http_status(:success)
      expect(json_response['message']).to be_present
      expect(json_response['message_html']).to be_present
      expect(json_response['emoji']).to be_present
    end

    it 'returns an empty response if there was no status' do
      get api(path, user)

      expect(response).to have_gitlab_http_status(:success)
      expect(json_response['message']).to be_nil
      expect(json_response['emoji']).to be_nil
    end
  end

  describe 'GET /users' do
    let(:path) { '/users' }

    context "when unauthenticated" do
      it "returns authorization error when the `username` parameter is not passed" do
        get api(path)

        expect(response).to have_gitlab_http_status(:forbidden)
      end

      it "returns the user when a valid `username` parameter is passed" do
        get api(path), params: { username: user.username }

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(json_response.size).to eq(1)
        expect(json_response[0]['id']).to eq(user.id)
        expect(json_response[0]['username']).to eq(user.username)
      end

      it "returns the user when a valid `username` parameter is passed (case insensitive)" do
        get api(path), params: { username: user.username.upcase }

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(json_response.size).to eq(1)
        expect(json_response[0]['id']).to eq(user.id)
        expect(json_response[0]['username']).to eq(user.username)
      end

      it "returns an empty response when an invalid `username` parameter is passed" do
        get api(path), params: { username: 'invalid' }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.size).to eq(0)
      end

      it "does not return the highest role" do
        get api(path), params: { username: user.username }

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(json_response.first.keys).not_to include 'highest_role'
      end

      it "does not return the current or last sign-in ip addresses" do
        get api(path), params: { username: user.username }

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(json_response.first.keys).not_to include 'current_sign_in_ip'
        expect(json_response.first.keys).not_to include 'last_sign_in_ip'
      end

      context "when public level is restricted" do
        before do
          stub_application_setting(restricted_visibility_levels: [Gitlab::VisibilityLevel::PUBLIC])
        end

        it "returns authorization error when the `username` parameter refers to an inaccessible user" do
          get api(path), params: { username: user.username }

          expect(response).to have_gitlab_http_status(:forbidden)
        end

        it "returns authorization error when the `username` parameter is not passed" do
          get api(path)

          expect(response).to have_gitlab_http_status(:forbidden)
        end
      end
    end

    context "when authenticated" do
      # These specs are written just in case API authentication is not required anymore
      context "when public level is restricted" do
        before do
          stub_application_setting(restricted_visibility_levels: [Gitlab::VisibilityLevel::PUBLIC])
        end

        context 'when authenticate as a regular user' do
          it "renders 200" do
            get api(path, user)

            expect(response).to match_response_schema('public_api/v4/user/basics')
          end
        end

        context 'when authenticate as an admin' do
          it "renders 200" do
            get api(path, admin)

            expect(response).to match_response_schema('public_api/v4/user/basics')
          end
        end
      end

      it "returns an array of users" do
        get api(path, user)

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(response).to include_pagination_headers
        username = user.username
        expect(json_response.detect do |user|
          user['username'] == username
        end['username']).to eq(username)
      end

      it "returns an array of blocked users" do
        ldap_blocked_user
        create(:user, state: 'blocked')

        get api("/users?blocked=true", user)

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(response).to include_pagination_headers
        expect(json_response).to all(include('state' => /(blocked|ldap_blocked)/))
      end

      it "returns an array of external users" do
        create(:user)
        external_user = create(:user, external: true)

        get api("/users?external=true", user)

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(response).to include_pagination_headers
        expect(json_response.size).to eq(1)
        expect(json_response[0]['id']).to eq(external_user.id)
      end

      it "returns one user" do
        get api("/users?username=#{omniauth_user.username}", user)

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(response).to include_pagination_headers
        expect(json_response.first['username']).to eq(omniauth_user.username)
      end

      it "returns one user (case insensitive)" do
        get api("/users?username=#{omniauth_user.username.upcase}", user)

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(response).to include_pagination_headers
        expect(json_response.first['username']).to eq(omniauth_user.username)
      end

      it "returns a 403 when non-admin user searches by external UID" do
        get api("/users?extern_uid=#{omniauth_user.identities.first.extern_uid}&provider=#{omniauth_user.identities.first.provider}", user)

        expect(response).to have_gitlab_http_status(:forbidden)
      end

      it 'does not reveal the `is_admin` flag of the user' do
        get api(path, user)

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(json_response.first.keys).not_to include 'is_admin'
      end
    end

    context "when admin" do
      context 'exclude_internal param' do
        let_it_be(:internal_user) { User.alert_bot }

        it 'returns all users when it is not set' do
          get api("/users?exclude_internal=false", admin)

          expect(response).to match_response_schema('public_api/v4/user/basics')
          expect(response).to include_pagination_headers
          expect(json_response.map { |u| u['id'] }).to include(internal_user.id)
        end

        it 'returns all non internal users when it is set' do
          get api("/users?exclude_internal=true", user)

          expect(response).to match_response_schema('public_api/v4/user/basics')
          expect(response).to include_pagination_headers
          expect(json_response.map { |u| u['id'] }).not_to include(internal_user.id)
        end
      end

      context 'without_project_bots param' do
        let_it_be(:project_bot) { create(:user, :project_bot) }

        it 'returns all users when it is not set' do
          get api("/users?without_project_bots=false", user)

          expect(response).to match_response_schema('public_api/v4/user/basics')
          expect(response).to include_pagination_headers
          expect(json_response.map { |u| u['id'] }).to include(project_bot.id)
        end

        it 'returns all non project_bot users when it is set' do
          get api("/users?without_project_bots=true", user)

          expect(response).to match_response_schema('public_api/v4/user/basics')
          expect(response).to include_pagination_headers
          expect(json_response.map { |u| u['id'] }).not_to include(project_bot.id)
        end
      end

      context 'admins param' do
        it 'returns all users' do
          get api("/users?admins=true", user)

          expect(response).to match_response_schema('public_api/v4/user/basics')
          expect(json_response.size).to eq(2)
          expect(json_response.map { |u| u['id'] }).to include(user.id, admin.id)
        end
      end
    end

    context "when admin" do
      context 'when sudo is defined' do
        it 'does not return 500' do
          admin_personal_access_token = create(:personal_access_token, :admin_mode, user: admin, scopes: [:sudo])
          get api("/users?sudo=#{user.id}", admin, personal_access_token: admin_personal_access_token)

          expect(response).to have_gitlab_http_status(:success)
        end
      end

      it "returns an array of users" do
        get api(path, admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(response).to include_pagination_headers
      end

      it "users contain the `namespace_id` field" do
        get api(path, admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:success)
        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(2)
        expect(json_response.map { |u| u['namespace_id'] }).to include(user.namespace_id, admin.namespace_id)
      end

      it "returns an array of external users" do
        create(:user, external: true)

        get api("/users?external=true", admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(response).to include_pagination_headers
        expect(json_response).to all(include('external' => true))
      end

      it "returns one user by external UID" do
        get api("/users?extern_uid=#{omniauth_user.identities.first.extern_uid}&provider=#{omniauth_user.identities.first.provider}", admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(1)
        expect(json_response.first['username']).to eq(omniauth_user.username)
      end

      it "returns 400 error if provider with no extern_uid" do
        get api("/users?extern_uid=#{omniauth_user.identities.first.extern_uid}", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it "returns 400 error if provider with no extern_uid" do
        get api("/users?provider=#{omniauth_user.identities.first.provider}", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it "returns a user created before a specific date" do
        user = create(:user, created_at: Date.new(2000, 1, 1))

        get api("/users?created_before=2000-01-02T00:00:00.060Z", admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(1)
        expect(json_response.first['username']).to eq(user.username)
      end

      it "returns no users created before a specific date" do
        create(:user, created_at: Date.new(2001, 1, 1))

        get api("/users?created_before=2000-01-02T00:00:00.060Z", admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(0)
      end

      it "returns users created before and after a specific date" do
        user = create(:user, created_at: Date.new(2001, 1, 1))

        get api("/users?created_before=2001-01-02T00:00:00.060Z&created_after=1999-01-02T00:00:00.060", admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(1)
        expect(json_response.first['username']).to eq(user.username)
      end

      it 'returns the correct order when sorted by id' do
        # order of let_it_be definitions:
        # - admin
        # - user

        get api(path, admin, admin_mode: true), params: { order_by: 'id', sort: 'asc' }

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(2)
        expect(json_response.first['id']).to eq(admin.id)
        expect(json_response.last['id']).to eq(user.id)
      end

      it 'returns users with 2fa enabled' do
        user_with_2fa = create(:user, :two_factor_via_otp)

        get api(path, admin, admin_mode: true), params: { two_factor: 'enabled' }

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(1)
        expect(json_response.first['id']).to eq(user_with_2fa.id)
      end

      it "returns users without projects" do
        user_without_projects = create(:user)
        create(:project, namespace: user.namespace)
        create(:project, namespace: admin.namespace)

        get api(path, admin, admin_mode: true), params: { without_projects: true }

        expect(response).to match_response_schema('public_api/v4/user/admins')
        expect(json_response.size).to eq(1)
        expect(json_response.first['id']).to eq(user_without_projects.id)
      end

      it 'returns 400 when provided incorrect sort params' do
        get api(path, admin, admin_mode: true), params: { order_by: 'magic', sort: 'asc' }

        expect(response).to have_gitlab_http_status(:bad_request)
      end
    end

    context 'admins param' do
      it 'returns only admins' do
        get api("/users?admins=true", admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/basics')
        expect(json_response.size).to eq(1)
        expect(json_response.first['id']).to eq(admin.id)
      end
    end
  end

  describe "GET /users/:id" do
    let_it_be(:user2, reload: true) { create(:user, username: 'another_user') }

    let(:path) { "/users/#{user.id}" }

    before do
      allow(Gitlab::ApplicationRateLimiter).to receive(:throttled?)
        .with(:users_get_by_id, scope: user, users_allowlist: []).and_return(false)
    end

    it "returns a user by id" do
      get api(path, user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response['username']).to eq(user.username)
    end

    it "does not return the user's `is_admin` flag" do
      get api(path, user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).not_to include 'is_admin'
    end

    it "does not return the user's `highest_role`" do
      get api(path, user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).not_to include 'highest_role'
    end

    it "does not return the user's sign in IPs" do
      get api(path, user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).not_to include 'current_sign_in_ip'
      expect(json_response.keys).not_to include 'last_sign_in_ip'
    end

    it "does not contain plan or trial data" do
      get api(path, user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).not_to include 'plan'
      expect(json_response.keys).not_to include 'trial'
    end

    it 'returns a 404 if the target user is present but inaccessible' do
      allow(Ability).to receive(:allowed?).and_call_original
      allow(Ability).to receive(:allowed?).with(user, :read_user, user2).and_return(false)

      get api("/users/#{user2.id}", user)

      expect(response).to have_gitlab_http_status(:not_found)
    end

    it 'returns the `created_at` field for public users' do
      get api("/users/#{user2.id}", user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).to include('created_at')
    end

    it 'does not return the `created_at` field for private users' do
      get api("/users/#{private_user.id}", user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).not_to include('created_at')
    end

    it 'returns the `followers` field for public users' do
      get api("/users/#{user2.id}", user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).to include('followers')
    end

    it 'does not return the `followers` field for private users' do
      get api("/users/#{private_user.id}", user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).not_to include('followers')
    end

    it 'returns the `following` field for public users' do
      get api("/users/#{user2.id}", user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).to include('following')
    end

    it 'does not return the `following` field for private users' do
      get api("/users/#{private_user.id}", user)

      expect(response).to match_response_schema('public_api/v4/user/basic')
      expect(json_response.keys).not_to include('following')
    end

    it 'does not contain the note of the user' do
      get api(path, user)

      expect(json_response).not_to have_key('note')
      expect(json_response).not_to have_key('sign_in_count')
    end

    context 'when the rate limit is not exceeded' do
      it 'returns a success status' do
        expect(Gitlab::ApplicationRateLimiter)
          .to receive(:throttled?).with(:users_get_by_id, scope: user, users_allowlist: [])
          .and_return(false)

        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
      end
    end

    context 'when the rate limit is exceeded' do
      context 'when feature flag is enabled' do
        it 'returns "too many requests" status' do
          expect(Gitlab::ApplicationRateLimiter)
            .to receive(:throttled?).with(:users_get_by_id, scope: user, users_allowlist: [])
            .and_return(true)

          get api(path, user)

          expect(response).to have_gitlab_http_status(:too_many_requests)
        end

        it 'still allows admin users' do
          expect(Gitlab::ApplicationRateLimiter)
            .not_to receive(:throttled?)

          get api(path, admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:ok)
        end

        it 'allows users whose username is in the allowlist' do
          allowlist = [user.username]
          current_settings = Gitlab::CurrentSettings.current_application_settings

          # Necessary to ensure the same object is returned on each call
          allow(Gitlab::CurrentSettings).to receive(:current_application_settings).and_return current_settings

          allow(current_settings).to receive(:users_get_by_id_limit_allowlist).and_return(allowlist)

          expect(Gitlab::ApplicationRateLimiter)
            .to receive(:throttled?).with(:users_get_by_id, scope: user, users_allowlist: allowlist)
            .and_call_original

          get api(path, user)

          expect(response).to have_gitlab_http_status(:ok)
        end
      end
    end

    context 'when job title is present' do
      let(:job_title) { 'Fullstack Engineer' }

      before do
        create(:user_detail, user: user, job_title: job_title)
      end

      it 'returns job title of a user' do
        get api(path, user)

        expect(response).to match_response_schema('public_api/v4/user/basic')
        expect(json_response['job_title']).to eq(job_title)
      end
    end

    context 'when authenticated as admin' do
      it 'contains the note of the user' do
        get api(path, admin, admin_mode: true)

        expect(json_response).to have_key('note')
        expect(json_response['note']).to eq(user.note)
        expect(json_response).to have_key('sign_in_count')
      end

      it 'includes the `is_admin` field' do
        get api(path, admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admin')
        expect(json_response['is_admin']).to be(false)
      end

      it "includes the `created_at` field for private users" do
        get api("/users/#{private_user.id}", admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admin')
        expect(json_response.keys).to include 'created_at'
      end

      it 'includes the `highest_role` field' do
        get api(path, admin, admin_mode: true)

        expect(response).to match_response_schema('public_api/v4/user/admin')
        expect(json_response['highest_role']).to be(0)
      end

      it 'includes the `namespace_id` field' do
        get api(path, admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:success)
        expect(response).to match_response_schema('public_api/v4/user/admin')
        expect(json_response['namespace_id']).to eq(user.namespace_id)
      end

      if Gitlab.ee?
        it 'does not include values for plan or trial' do
          get api(path, admin, admin_mode: true)

          expect(response).to match_response_schema('public_api/v4/user/basic')
        end
      else
        it 'does not include plan or trial data' do
          get api(path, admin, admin_mode: true)

          expect(response).to match_response_schema('public_api/v4/user/basic')
          expect(json_response.keys).not_to include 'plan'
          expect(json_response.keys).not_to include 'trial'
        end
      end

      context 'when user has not logged in' do
        it 'does not include the sign in IPs' do
          get api(path, admin, admin_mode: true)

          expect(response).to match_response_schema('public_api/v4/user/admin')
          expect(json_response).to include('current_sign_in_ip' => nil, 'last_sign_in_ip' => nil)
        end
      end

      context 'when user has logged in' do
        let_it_be(:signed_in_user) { create(:user, :with_sign_ins) }

        it 'includes the sign in IPs' do
          get api("/users/#{signed_in_user.id}", admin, admin_mode: true)

          expect(response).to match_response_schema('public_api/v4/user/admin')
          expect(json_response['current_sign_in_ip']).to eq('127.0.0.1')
          expect(json_response['last_sign_in_ip']).to eq('127.0.0.1')
        end
      end
    end

    context 'for an anonymous user' do
      it 'returns 403' do
        get api(path)

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    it "returns a 404 error if user id not found" do
      get api("/users/#{non_existing_record_id}", user)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it "returns a 404 for invalid ID" do
      get api("/users/1ASDF", user)

      expect(response).to have_gitlab_http_status(:not_found)
    end
  end

  describe 'GET /users/:id_or_username/status' do
    context 'when finding the user by id' do
      it_behaves_like 'rendering user status' do
        let(:path) { "/users/#{user.id}/status" }
      end
    end

    context 'when finding the user by username' do
      it_behaves_like 'rendering user status' do
        let(:path) { "/users/#{user.username}/status" }
      end
    end

    context 'when finding the user by username (case insensitive)' do
      it_behaves_like 'rendering user status' do
        let(:path) { "/users/#{user.username.upcase}/status" }
      end
    end
  end

  describe 'POST /users/:id/follow' do
    let(:followee) { create(:user) }
    let(:path) { "/users/#{followee.id}/follow" }

    context 'on an unfollowed user' do
      it 'follows the user' do
        post api(path, user)

        expect(user.followees).to contain_exactly(followee)
        expect(response).to have_gitlab_http_status(:created)
      end

      it 'alerts and not follow when over followee limit' do
        stub_const('Users::UserFollowUser::MAX_FOLLOWEE_LIMIT', 2)
        Users::UserFollowUser::MAX_FOLLOWEE_LIMIT.times { user.follow(create(:user)) }

        post api(path, user)
        expect(response).to have_gitlab_http_status(:bad_request)
        expected_message = format(_("You can't follow more than %{limit} users. To follow more users, unfollow some others."), limit: Users::UserFollowUser::MAX_FOLLOWEE_LIMIT)
        expect(json_response['message']).to eq(expected_message)
        expect(user.following?(followee)).to be_falsey
      end
    end

    context 'on a followed user' do
      before do
        user.follow(followee)
      end

      it 'does not change following' do
        post api(path, user)

        expect(user.followees).to contain_exactly(followee)
        expect(response).to have_gitlab_http_status(:not_modified)
      end
    end

    context 'on a user with disabled following' do
      before do
        user.enabled_following = false
        user.save!
      end

      it 'does not change following' do
        post api("/users/#{followee.id}/follow", user)

        expect(user.followees).to be_empty
        expect(response).to have_gitlab_http_status(:not_modified)
      end
    end
  end

  describe 'POST /users/:id/unfollow' do
    let(:followee) { create(:user) }
    let(:path) { "/users/#{followee.id}/unfollow" }

    context 'on a followed user' do
      before do
        user.follow(followee)
      end

      it 'unfollow the user' do
        post api(path, user)

        expect(user.followees).to be_empty
        expect(response).to have_gitlab_http_status(:created)
      end
    end

    context 'on an unfollowed user' do
      it 'does not change following' do
        post api(path, user)

        expect(user.followees).to be_empty
        expect(response).to have_gitlab_http_status(:not_modified)
      end
    end
  end

  describe 'GET /users/:id/followers' do
    let(:follower) { create(:user) }
    let(:path) { "/users/#{user.id}/followers" }

    context 'for an anonymous user' do
      it 'returns 403' do
        get api("/users/#{user.id}")

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    context 'user has followers' do
      it 'lists followers' do
        follower.follow(user)

        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
      end

      it 'do not lists followers if profile is private' do
        follower.follow(private_user)

        get api("/users/#{private_user.id}/followers", user)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end
    end

    context 'user does not have any follower' do
      it 'does list nothing' do
        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_empty
      end
    end
  end

  describe 'GET /users/:id/following' do
    let(:followee) { create(:user) }
    let(:path) { "/users/#{user.id}/followers" }

    context 'for an anonymous user' do
      it 'returns 403' do
        get api("/users/#{user.id}")

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    context 'user has followers' do
      it 'lists following user' do
        user.follow(followee)

        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
      end

      it 'do not lists following user if profile is private' do
        user.follow(private_user)

        get api("/users/#{private_user.id}/following", user)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end
    end

    context 'user does not have any follower' do
      it 'does list nothing' do
        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_empty
      end
    end
  end

  describe "POST /users" do
    let(:path) { '/users' }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:params) { attributes_for(:user, projects_limit: 3) }
    end

    it "creates user" do
      expect do
        post api(path, admin, admin_mode: true), params: attributes_for(:user, projects_limit: 3)
      end.to change { User.count }.by(1)
    end

    it "creates user with correct attributes" do
      post api(path, admin, admin_mode: true), params: attributes_for(:user, admin: true, can_create_group: true)
      expect(response).to have_gitlab_http_status(:created)
      user_id = json_response['id']
      new_user = User.find(user_id)
      expect(new_user.admin).to eq(true)
      expect(new_user.can_create_group).to eq(true)
    end

    it "creates user with optional attributes" do
      optional_attributes = { confirm: true, theme_id: 2, color_scheme_id: 4 }
      attributes = attributes_for(:user).merge(optional_attributes)

      post api(path, admin, admin_mode: true), params: attributes

      expect(response).to have_gitlab_http_status(:created)
    end

    it "creates non-admin user" do
      post api(path, admin, admin_mode: true), params: attributes_for(:user, admin: false, can_create_group: false)
      expect(response).to have_gitlab_http_status(:created)
      user_id = json_response['id']
      new_user = User.find(user_id)
      expect(new_user.admin).to eq(false)
      expect(new_user.can_create_group).to eq(false)
    end

    it "creates non-admin users by default" do
      post api(path, admin, admin_mode: true), params: attributes_for(:user)
      expect(response).to have_gitlab_http_status(:created)
      user_id = json_response['id']
      new_user = User.find(user_id)
      expect(new_user.admin).to eq(false)
    end

    it "returns 201 Created on success" do
      post api(path, admin, admin_mode: true), params: attributes_for(:user, projects_limit: 3)
      expect(response).to match_response_schema('public_api/v4/user/admin')
      expect(response).to have_gitlab_http_status(:created)
    end

    it 'creates non-external users by default' do
      post api(path, admin, admin_mode: true), params: attributes_for(:user)
      expect(response).to have_gitlab_http_status(:created)

      user_id = json_response['id']
      new_user = User.find(user_id)
      expect(new_user.external).to be_falsy
    end

    it 'allows an external user to be created' do
      post api(path, admin, admin_mode: true), params: attributes_for(:user, external: true)
      expect(response).to have_gitlab_http_status(:created)

      user_id = json_response['id']
      new_user = User.find(user_id)
      expect(new_user.external).to be_truthy
    end

    it "creates user with reset password" do
      post api(path, admin, admin_mode: true), params: attributes_for(:user, reset_password: true).except(:password)

      expect(response).to have_gitlab_http_status(:created)

      user_id = json_response['id']
      new_user = User.find(user_id)

      expect(new_user.recently_sent_password_reset?).to eq(true)
    end

    it "creates user with random password" do
      params = attributes_for(:user, force_random_password: true)
      params.delete(:password)
      post api(path, admin, admin_mode: true), params: params

      expect(response).to have_gitlab_http_status(:created)

      user_id = json_response['id']
      new_user = User.find(user_id)

      expect(new_user.encrypted_password).to be_present
    end

    it "creates user with private profile" do
      post api(path, admin, admin_mode: true), params: attributes_for(:user, private_profile: true)

      expect(response).to have_gitlab_http_status(:created)

      user_id = json_response['id']
      new_user = User.find(user_id)

      expect(new_user).not_to eq(nil)
      expect(new_user.private_profile?).to eq(true)
    end

    it "creates user with view_diffs_file_by_file" do
      post api(path, admin, admin_mode: true), params: attributes_for(:user, view_diffs_file_by_file: true)

      expect(response).to have_gitlab_http_status(:created)

      user_id = json_response['id']
      new_user = User.find(user_id)

      expect(new_user).not_to eq(nil)
      expect(new_user.user_preference.view_diffs_file_by_file?).to eq(true)
    end

    it "creates user with avatar" do
      workhorse_form_with_file(
        api(path, admin, admin_mode: true),
        method: :post,
        file_key: :avatar,
        params: attributes_for(:user, avatar: fixture_file_upload('spec/fixtures/banana_sample.gif', 'image/gif'))
      )

      expect(response).to have_gitlab_http_status(:created)

      new_user = User.find_by(id: json_response['id'])

      expect(new_user).not_to eq(nil)
      expect(json_response['avatar_url']).to include(new_user.avatar_path)
    end

    it "does not create user with invalid email" do
      post api(path, admin, admin_mode: true),
        params: {
          email: 'invalid email',
          password: User.random_password,
          name: 'test'
        }
      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it 'returns 400 error if name not given' do
      post api(path, admin, admin_mode: true), params: attributes_for(:user).except(:name)
      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it 'returns 400 error if password not given' do
      post api(path, admin, admin_mode: true), params: attributes_for(:user).except(:password)
      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it 'returns 400 error if email not given' do
      post api(path, admin, admin_mode: true), params: attributes_for(:user).except(:email)
      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it 'returns 400 error if username not given' do
      post api(path, admin, admin_mode: true), params: attributes_for(:user).except(:username)
      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it "doesn't create user with invalid optional attributes" do
      optional_attributes = { theme_id: 50, color_scheme_id: 50 }
      attributes = attributes_for(:user).merge(optional_attributes)

      post api(path, admin, admin_mode: true), params: attributes

      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it 'returns 400 error if user does not validate' do
      post api(path, admin, admin_mode: true),
        params: {
          password: 'pass',
          email: 'test@example.com',
          username: 'test!',
          name: 'test',
          bio: 'g' * 256,
          projects_limit: -1
        }
      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['message']['password'])
        .to eq(['is too short (minimum is 8 characters)'])
      expect(json_response['message']['bio'])
        .to eq(['is too long (maximum is 255 characters)'])
      expect(json_response['message']['projects_limit'])
        .to eq(['must be greater than or equal to 0'])
      expect(json_response['message']['username'])
        .to match_array([Gitlab::PathRegex.namespace_format_message, Gitlab::Regex.oci_repository_path_regex_message])
    end

    it 'tracks weak password errors' do
      attributes = attributes_for(:user).merge({ password: "password" })
      post api(path, admin, admin_mode: true), params: attributes

      expect(json_response['message']['password'])
        .to eq(['must not contain commonly used combinations of words and letters'])
      expect_snowplow_event(
        category: 'Gitlab::Tracking::Helpers::WeakPasswordErrorEvent',
        action: 'track_weak_password_error',
        controller: 'API::Users',
        method: 'create'
      )
    end

    it "is not available for non admin users" do
      post api(path, user), params: attributes_for(:user)
      expect(response).to have_gitlab_http_status(:forbidden)
    end

    context 'with existing user' do
      before do
        post api(path, admin, admin_mode: true),
          params: {
            email: 'test@example.com',
            password: User.random_password,
            username: 'test',
            name: 'foo'
          }
      end

      it 'returns 409 conflict error if user with same email exists' do
        expect do
          post api(path, admin, admin_mode: true),
            params: {
              name: 'foo',
              email: 'test@example.com',
              password: User.random_password,
              username: 'foo'
            }
        end.to change { User.count }.by(0)
        expect(response).to have_gitlab_http_status(:conflict)
        expect(json_response['message']).to eq('Email has already been taken')
      end

      it 'returns 409 conflict error if same username exists' do
        expect do
          post api(path, admin, admin_mode: true),
            params: {
              name: 'foo',
              email: 'foo@example.com',
              password: User.random_password,
              username: 'test'
            }
        end.to change { User.count }.by(0)
        expect(response).to have_gitlab_http_status(:conflict)
        expect(json_response['message']).to eq('Username has already been taken')
      end

      it 'returns 409 conflict error if same username exists (case insensitive)' do
        expect do
          post api(path, admin, admin_mode: true),
            params: {
              name: 'foo',
              email: 'foo@example.com',
              password: User.random_password,
              username: 'TEST'
            }
        end.to change { User.count }.by(0)
        expect(response).to have_gitlab_http_status(:conflict)
        expect(json_response['message']).to eq('Username has already been taken')
      end

      it 'creates user with new identity' do
        post api(path, admin, admin_mode: true), params: attributes_for(:user, provider: 'github', extern_uid: '67890')

        expect(response).to have_gitlab_http_status(:created)
        expect(json_response['identities'].first['extern_uid']).to eq('67890')
        expect(json_response['identities'].first['provider']).to eq('github')
      end
    end

    context 'when user with a primary email exists' do
      context 'when the primary email is confirmed' do
        let!(:confirmed_user) { create(:user, email: 'foo@example.com') }

        it 'returns 409 conflict error' do
          expect do
            post api(path, admin, admin_mode: true),
              params: {
                name: 'foo',
                email: confirmed_user.email,
                password: 'password',
                username: 'TEST'
              }
          end.to change { User.count }.by(0)
          expect(response).to have_gitlab_http_status(:conflict)
          expect(json_response['message']).to eq('Email has already been taken')
        end
      end

      context 'when the primary email is unconfirmed' do
        let!(:unconfirmed_user) { create(:user, :unconfirmed, email: 'foo@example.com') }

        it 'returns 409 conflict error' do
          expect do
            post api(path, admin, admin_mode: true),
              params: {
                name: 'foo',
                email: unconfirmed_user.email,
                password: 'password',
                username: 'TEST'
              }
          end.to change { User.count }.by(0)
          expect(response).to have_gitlab_http_status(:conflict)
          expect(json_response['message']).to eq('Email has already been taken')
        end
      end
    end

    context 'when user with a secondary email exists' do
      context 'when the secondary email is confirmed' do
        let!(:email) { create(:email, :confirmed, email: 'foo@example.com') }

        it 'returns 409 conflict error' do
          expect do
            post api(path, admin, admin_mode: true),
              params: {
                name: 'foo',
                email: email.email,
                password: 'password',
                username: 'TEST'
              }
          end.to change { User.count }.by(0)
          expect(response).to have_gitlab_http_status(:conflict)
          expect(json_response['message']).to eq('Email has already been taken')
        end
      end

      context 'when the secondary email is unconfirmed' do
        let!(:email) { create(:email, email: 'foo@example.com') }

        it 'does not create user' do
          expect do
            post api(path, admin, admin_mode: true),
              params: {
                name: 'foo',
                email: email.email,
                password: 'password',
                username: 'TEST'
              }
          end.to change { User.count }.by(0)
          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end
    end

    context "scopes" do
      let(:user) { admin }
      let(:path) { '/users' }
      let(:api_call) { method(:api) }

      include_examples 'does not allow the "read_user" scope'
    end

    context "`private_profile` attribute" do
      context "based on the application setting" do
        before do
          stub_application_setting(user_defaults_to_private_profile: true)
        end

        let(:params) { attributes_for(:user) }

        shared_examples_for 'creates the user with the value of `private_profile` based on the application setting' do
          specify do
            post api(path, admin, admin_mode: true), params: params

            expect(response).to have_gitlab_http_status(:created)
            user = User.find_by(id: json_response['id'], private_profile: true)
            expect(user).to be_present
          end
        end

        context 'when the attribute is not overridden in params' do
          it_behaves_like 'creates the user with the value of `private_profile` based on the application setting'
        end

        context 'when the attribute is overridden in params' do
          it 'creates the user with the value of `private_profile` same as the value of the overridden param' do
            post api(path, admin, admin_mode: true), params: params.merge(private_profile: false)

            expect(response).to have_gitlab_http_status(:created)
            user = User.find_by(id: json_response['id'], private_profile: false)
            expect(user).to be_present
          end

          context 'overridden as `nil`' do
            let(:params) { attributes_for(:user, private_profile: nil) }

            it_behaves_like 'creates the user with the value of `private_profile` based on the application setting'
          end
        end
      end
    end
  end

  describe "PUT /users/:id" do
    let(:path) { "/users/#{user.id}" }

    it_behaves_like 'PUT request permissions for admin mode' do
      let(:params) { { bio: 'new test bio' } }
    end

    it "returns 200 OK on success" do
      put api(path, admin, admin_mode: true), params: { bio: 'new test bio' }

      expect(response).to match_response_schema('public_api/v4/user/admin')
      expect(response).to have_gitlab_http_status(:ok)
    end

    context 'updating password' do
      def update_password(user, admin, password = User.random_password)
        put api("/users/#{user.id}", admin, admin_mode: true), params: { password: password }
      end

      context 'admin updates their own password' do
        it 'does not force reset on next login' do
          update_password(admin, admin)

          expect(response).to have_gitlab_http_status(:ok)
          expect(user.reload.password_expired?).to eq(false)
        end

        it 'does not enqueue the `admin changed your password` email' do
          expect { update_password(admin, admin) }
            .not_to have_enqueued_mail(DeviseMailer, :password_change_by_admin)
        end

        it 'enqueues the `password changed` email' do
          expect { update_password(admin, admin) }
            .to have_enqueued_mail(DeviseMailer, :password_change)
        end
      end

      context 'admin updates the password of another user' do
        it 'forces reset on next login' do
          update_password(user, admin)

          expect(response).to have_gitlab_http_status(:ok)
          expect(user.reload.password_expired?).to eq(true)
        end

        it 'enqueues the `admin changed your password` email' do
          expect { update_password(user, admin) }
            .to have_enqueued_mail(DeviseMailer, :password_change_by_admin)
        end

        it 'does not enqueue the `password changed` email' do
          expect { update_password(user, admin) }
            .not_to have_enqueued_mail(DeviseMailer, :password_change)
        end
      end

      context 'with a weak password' do
        it 'tracks weak password errors' do
          update_password(user, admin, "password")

          expect(json_response['message']['password'])
            .to eq(['must not contain commonly used combinations of words and letters'])
          expect_snowplow_event(
            category: 'Gitlab::Tracking::Helpers::WeakPasswordErrorEvent',
            action: 'track_weak_password_error',
            controller: 'API::Users',
            method: 'update'
          )
        end
      end
    end

    it "updates user with new bio" do
      put api(path, admin, admin_mode: true), params: { bio: 'new test bio' }

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['bio']).to eq('new test bio')
      expect(user.reload.bio).to eq('new test bio')
    end

    it "updates user with empty bio" do
      user.update!(bio: 'previous bio')

      put api(path, admin, admin_mode: true), params: { bio: '' }

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['bio']).to eq('')
      expect(user.reload.bio).to eq('')
    end

    it 'updates user with nil bio' do
      put api(path, admin, admin_mode: true), params: { bio: nil }

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['bio']).to eq('')
      expect(user.reload.bio).to eq('')
    end

    it "updates user with organization" do
      put api(path, admin, admin_mode: true), params: { organization: 'GitLab' }

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['organization']).to eq('GitLab')
      expect(user.reload.organization).to eq('GitLab')
    end

    it 'updates user with avatar' do
      workhorse_form_with_file(
        api(path, admin, admin_mode: true),
        method: :put,
        file_key: :avatar,
        params: { avatar: fixture_file_upload('spec/fixtures/banana_sample.gif', 'image/gif') }
      )

      user.reload

      expect(user.avatar).to be_present
      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['avatar_url']).to include(user.avatar_path)
    end

    it 'updates user with a new email' do
      old_email = user.email
      old_notification_email = user.notification_email_or_default
      put api(path, admin, admin_mode: true), params: { email: 'new@email.com' }

      user.reload

      expect(response).to have_gitlab_http_status(:ok)
      expect(user).to be_confirmed
      expect(user.email).to eq(old_email)
      expect(user.notification_email_or_default).to eq(old_notification_email)
      expect(user.unconfirmed_email).to eq('new@email.com')
    end

    it 'skips reconfirmation when requested' do
      put api(path, admin, admin_mode: true), params: { email: 'new@email.com', skip_reconfirmation: true }

      user.reload

      expect(response).to have_gitlab_http_status(:ok)
      expect(user).to be_confirmed
      expect(user.email).to eq('new@email.com')
    end

    it 'updates user with their own username' do
      put api(path, admin, admin_mode: true), params: { username: user.username }

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['username']).to eq(user.username)
      expect(user.reload.username).to eq(user.username)
    end

    it "updates user's existing identity" do
      put api("/users/#{ldap_user.id}", admin, admin_mode: true), params: { provider: 'ldapmain', extern_uid: '654321' }

      expect(response).to have_gitlab_http_status(:ok)
      expect(ldap_user.reload.identities.first.extern_uid).to eq('654321')
    end

    it 'updates user with new identity' do
      put api(path, admin, admin_mode: true), params: { provider: 'github', extern_uid: 'john' }

      expect(response).to have_gitlab_http_status(:ok)
      expect(user.reload.identities.first.extern_uid).to eq('john')
      expect(user.reload.identities.first.provider).to eq('github')
    end

    it "updates admin status" do
      put api(path, admin, admin_mode: true), params: { admin: true }

      expect(response).to have_gitlab_http_status(:ok)
      expect(user.reload.admin).to eq(true)
    end

    it "updates external status" do
      put api(path, admin, admin_mode: true), params: { external: true }

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['external']).to eq(true)
      expect(user.reload.external?).to be_truthy
    end

    it "does have default values for theme and color-scheme ID" do
      put api(path, admin, admin_mode: true), params: {}

      expect(user.reload.theme_id).to eq(Gitlab::Themes.default.id)
      expect(user.reload.color_scheme_id).to eq(Gitlab::ColorSchemes.default.id)
    end

    it "updates viewing diffs file by file" do
      put api(path, admin, admin_mode: true), params: { view_diffs_file_by_file: true }

      expect(response).to have_gitlab_http_status(:ok)
      expect(user.reload.user_preference.view_diffs_file_by_file?).to eq(true)
    end

    context 'updating `private_profile`' do
      it "updates private profile" do
        current_value = user.private_profile
        new_value = !current_value

        put api(path, admin, admin_mode: true), params: { private_profile: new_value }

        expect(response).to have_gitlab_http_status(:ok)
        expect(user.reload.private_profile).to eq(new_value)
      end

      context 'when `private_profile` is set to `nil`' do
        before do
          stub_application_setting(user_defaults_to_private_profile: true)
        end

        it "updates private_profile to value of the application setting" do
          user.update!(private_profile: false)

          put api(path, admin, admin_mode: true), params: { private_profile: nil }

          expect(response).to have_gitlab_http_status(:ok)
          expect(user.reload.private_profile).to eq(true)
        end
      end

      it "does not modify private profile when field is not provided" do
        user.update!(private_profile: true)

        put api(path, admin, admin_mode: true), params: {}

        expect(response).to have_gitlab_http_status(:ok)
        expect(user.reload.private_profile).to eq(true)
      end
    end

    it "does not modify theme or color-scheme ID when field is not provided" do
      theme = Gitlab::Themes.each.find { |t| t.id != Gitlab::Themes.default.id }
      scheme = Gitlab::ColorSchemes.each.find { |t| t.id != Gitlab::ColorSchemes.default.id }

      user.update!(theme_id: theme.id, color_scheme_id: scheme.id)

      put api(path, admin, admin_mode: true), params: {}

      expect(response).to have_gitlab_http_status(:ok)
      expect(user.reload.theme_id).to eq(theme.id)
      expect(user.reload.color_scheme_id).to eq(scheme.id)
    end

    it "does not update admin status" do
      admin_user = create(:admin)

      put api("/users/#{admin_user.id}", admin, admin_mode: true), params: { can_create_group: false }

      expect(response).to have_gitlab_http_status(:ok)
      expect(admin_user.reload.admin).to eq(true)
      expect(admin_user.can_create_group).to eq(false)
    end

    it "does not allow invalid update" do
      put api(path, admin, admin_mode: true), params: { email: 'invalid email' }

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(user.reload.email).not_to eq('invalid email')
    end

    it "updates theme id" do
      put api(path, admin, admin_mode: true), params: { theme_id: 5 }

      expect(response).to have_gitlab_http_status(:ok)
      expect(user.reload.theme_id).to eq(5)
    end

    it "does not update invalid theme id" do
      put api(path, admin, admin_mode: true), params: { theme_id: 50 }

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(user.reload.theme_id).not_to eq(50)
    end

    it "updates color scheme id" do
      put api(path, admin, admin_mode: true), params: { color_scheme_id: 5 }

      expect(response).to have_gitlab_http_status(:ok)
      expect(user.reload.color_scheme_id).to eq(5)
    end

    it "does not update invalid color scheme id" do
      put api(path, admin, admin_mode: true), params: { color_scheme_id: 50 }

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(user.reload.color_scheme_id).not_to eq(50)
    end

    context 'when the current user is not an admin' do
      it "is not available" do
        expect do
          put api(path, user), params: attributes_for(:user)
        end.not_to change { user.reload.attributes }

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    it "returns 404 for non-existing user" do
      put api("/users/#{non_existing_record_id}", admin, admin_mode: true), params: { bio: 'update should fail' }

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it "returns a 404 if invalid ID" do
      put api("/users/ASDF", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
    end

    it 'returns 400 error if user does not validate' do
      put api(path, admin, admin_mode: true),
        params: {
          password: 'pass',
          email: 'test@example.com',
          username: 'test!',
          name: 'test',
          bio: 'g' * 256,
          projects_limit: -1
        }
      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['message']['password'])
        .to eq(['is too short (minimum is 8 characters)'])
      expect(json_response['message']['bio'])
        .to eq(['is too long (maximum is 255 characters)'])
      expect(json_response['message']['projects_limit'])
        .to eq(['must be greater than or equal to 0'])
      expect(json_response['message']['username'])
        .to match_array([Gitlab::PathRegex.namespace_format_message, Gitlab::Regex.oci_repository_path_regex_message])
    end

    it 'returns 400 if provider is missing for identity update' do
      put api("/users/#{omniauth_user.id}", admin, admin_mode: true), params: { extern_uid: '654321' }

      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it 'returns 400 if external UID is missing for identity update' do
      put api("/users/#{omniauth_user.id}", admin, admin_mode: true), params: { provider: 'ldap' }

      expect(response).to have_gitlab_http_status(:bad_request)
    end

    context "with existing user" do
      before do
        post api("/users", admin, admin_mode: true), params: { email: 'test@example.com', password: User.random_password, username: 'test', name: 'test' }
        post api("/users", admin, admin_mode: true), params: { email: 'foo@bar.com', password: User.random_password, username: 'john', name: 'john' }
        @user = User.all.last
      end

      it 'returns 409 conflict error if email address exists' do
        put api("/users/#{@user.id}", admin, admin_mode: true), params: { email: 'test@example.com' }

        expect(response).to have_gitlab_http_status(:conflict)
        expect(@user.reload.email).to eq(@user.email)
      end

      it 'returns 409 conflict error if username taken' do
        @user_id = User.all.last.id
        put api("/users/#{@user.id}", admin, admin_mode: true), params: { username: 'test' }

        expect(response).to have_gitlab_http_status(:conflict)
        expect(@user.reload.username).to eq(@user.username)
      end

      it 'returns 409 conflict error if username taken (case insensitive)' do
        @user_id = User.all.last.id
        put api("/users/#{@user.id}", admin, admin_mode: true), params: { username: 'TEST' }

        expect(response).to have_gitlab_http_status(:conflict)
        expect(@user.reload.username).to eq(@user.username)
      end
    end

    context 'when user with a primary email exists' do
      context 'when the primary email is confirmed' do
        let!(:confirmed_user) { create(:user, email: 'foo@example.com') }

        it 'returns 409 conflict error' do
          put api(path, admin, admin_mode: true), params: { email: confirmed_user.email }

          expect(response).to have_gitlab_http_status(:conflict)
          expect(user.reload.email).not_to eq(confirmed_user.email)
        end
      end

      context 'when the primary email is unconfirmed' do
        let!(:unconfirmed_user) { create(:user, :unconfirmed, email: 'foo@example.com') }

        it 'returns 409 conflict error' do
          put api(path, admin, admin_mode: true), params: { email: unconfirmed_user.email }

          expect(response).to have_gitlab_http_status(:conflict)
          expect(user.reload.email).not_to eq(unconfirmed_user.email)
        end
      end
    end

    context 'when user with a secondary email exists' do
      context 'when the secondary email is confirmed' do
        let!(:email) { create(:email, :confirmed, email: 'foo@example.com') }

        it 'returns 409 conflict error' do
          put api(path, admin, admin_mode: true), params: { email: email.email }

          expect(response).to have_gitlab_http_status(:conflict)
          expect(user.reload.email).not_to eq(email.email)
        end
      end

      context 'when the secondary email is unconfirmed' do
        let!(:email) { create(:email, email: 'foo@example.com') }

        it 'does not update email' do
          put api(path, admin, admin_mode: true), params: { email: email.email }

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(user.reload.email).not_to eq(email.email)
        end
      end
    end
  end

  describe "PUT /user/:id/credit_card_validation" do
    let(:credit_card_validated_time) { Time.utc(2020, 1, 1) }
    let(:expiration_year) { Date.today.year + 10 }
    let(:path) { "/user/#{user.id}/credit_card_validation" }
    let(:params) do
      {
        credit_card_validated_at: credit_card_validated_time,
        credit_card_expiration_year: expiration_year,
        credit_card_expiration_month: 1,
        credit_card_holder_name: 'John Smith',
        credit_card_type: 'AmericanExpress',
        credit_card_mask_number: '1111'
      }
    end

    it_behaves_like 'PUT request permissions for admin mode'

    context 'when unauthenticated' do
      it 'returns authentication error' do
        put api(path), params: {}

        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated as non-admin' do
      it "does not allow updating user's credit card validation" do
        put api(path, user), params: params

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    context 'when authenticated as admin' do
      it "updates user's credit card validation" do
        put api(path, admin, admin_mode: true), params: params

        user.reload

        expect(response).to have_gitlab_http_status(:ok)
        expect(user.credit_card_validation).to have_attributes(
          credit_card_validated_at: credit_card_validated_time,
          expiration_date: Date.new(expiration_year, 1, 31),
          last_digits: 1111,
          network: 'AmericanExpress',
          holder_name: 'John Smith'
        )
      end

      it "returns 400 error if credit_card_validated_at is missing" do
        put api(path, admin, admin_mode: true), params: {}

        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it 'returns 404 error if user not found' do
        put api("/user/#{non_existing_record_id}/credit_card_validation", admin, admin_mode: true), params: params

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end
    end
  end

  describe "DELETE /users/:id/identities/:provider" do
    let(:test_user) { create(:omniauth_user, provider: 'ldapmain') }
    let(:path) { "/users/#{test_user.id}/identities/ldapmain" }

    it_behaves_like 'DELETE request permissions for admin mode'

    context 'when unauthenticated' do
      it 'returns authentication error' do
        delete api(path)

        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated' do
      it 'deletes identity of given provider' do
        expect do
          delete api(path, admin, admin_mode: true)
        end.to change { test_user.identities.count }.by(-1)
        expect(response).to have_gitlab_http_status(:no_content)
      end

      it_behaves_like '412 response' do
        let(:request) { api(path, admin, admin_mode: true) }
      end

      it 'returns 404 error if user not found' do
        delete api("/users/#{non_existing_record_id}/identities/ldapmain", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end

      it 'returns 404 error if identity not found' do
        delete api("/users/#{test_user.id}/identities/saml", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 Identity Not Found')
      end
    end
  end

  describe "POST /users/:id/keys" do
    let(:path) { "/users/#{user.id}/keys" }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:params) { attributes_for(:key, usage_type: :signing) }
    end

    it "does not create invalid ssh key" do
      post api(path, admin, admin_mode: true), params: { title: "invalid key" }

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('key is missing')
    end

    it 'does not create key without title' do
      post api(path, admin, admin_mode: true), params: { key: 'some key' }

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('title is missing')
    end

    it "creates ssh key" do
      key_attrs = attributes_for(:key, usage_type: :signing)

      expect do
        post api(path, admin, admin_mode: true), params: key_attrs
      end.to change { user.keys.count }.by(1)

      expect(response).to have_gitlab_http_status(:created)

      key = user.keys.last
      expect(key.title).to eq(key_attrs[:title])
      expect(key.key).to eq(key_attrs[:key])
      expect(key.usage_type).to eq(key_attrs[:usage_type].to_s)
    end

    it 'creates SSH key with `expires_at` attribute' do
      optional_attributes = { expires_at: 3.weeks.from_now }
      attributes = attributes_for(:key).merge(optional_attributes)

      post api(path, admin, admin_mode: true), params: attributes

      expect(response).to have_gitlab_http_status(:created)
      expect(json_response['expires_at'].to_date).to eq(optional_attributes[:expires_at].to_date)
    end

    it "returns 400 for invalid ID" do
      post api("/users/#{non_existing_record_id}/keys", admin, admin_mode: true)
      expect(response).to have_gitlab_http_status(:bad_request)
    end
  end

  describe 'GET /users/:id/project_deploy_keys' do
    let(:project) { create(:project) }
    let(:path) { "/users/#{user.id}/project_deploy_keys" }

    before do
      project.add_maintainer(user)

      deploy_key = create(:deploy_key, user: user)
      create(:deploy_keys_project, project: project, deploy_key_id: deploy_key.id)
    end

    it 'returns 404 for non-existing user' do
      get api("/users/#{non_existing_record_id}/project_deploy_keys")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns array of project deploy keys with pagination' do
      get api(path, user)

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to include_pagination_headers
      expect(json_response).to be_an Array
      expect(json_response.first['title']).to eq(user.deploy_keys.first.title)
    end

    it 'forbids when a developer fetches maintainer keys' do
      dev_user = create(:user)
      project.add_developer(dev_user)

      get api(path, dev_user)

      expect(response).to have_gitlab_http_status(:forbidden)
      expect(json_response['message']).to eq('403 Forbidden - No common authorized project found')
    end

    context 'with multiple projects' do
      let(:second_project) { create(:project) }
      let(:second_user) { create(:user) }

      before do
        second_project.add_maintainer(second_user)

        deploy_key = create(:deploy_key, user: second_user)
        create(:deploy_keys_project, project: second_project, deploy_key_id: deploy_key.id)
      end

      context 'when no common projects for user and current_user' do
        it 'forbids' do
          get api(path, second_user)

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('403 Forbidden - No common authorized project found')
        end
      end

      context 'when there are common projects for user and current_user' do
        before do
          project.add_maintainer(second_user)
        end

        let(:path) { "/users/#{second_user.id}/project_deploy_keys" }

        it 'lists only common project keys' do
          expect(second_user.project_deploy_keys).to contain_exactly(
            project.deploy_keys.first, second_project.deploy_keys.first)

          get api(path, user)

          expect(json_response.count).to eq(1)
          expect(json_response.first['key']).to eq(project.deploy_keys.first.key)
        end

        it 'lists only project_deploy_keys and not user deploy_keys' do
          third_user = create(:user)

          project.add_maintainer(third_user)
          second_project.add_maintainer(third_user)

          create(:deploy_key, user: second_user)
          create(:deploy_key, user: third_user)

          get api(path, third_user)

          expect(json_response.count).to eq(2)
          expect([json_response.first['key'], json_response.second['key']]).to contain_exactly(
            project.deploy_keys.first.key, second_project.deploy_keys.first.key)
        end

        it 'avoids N+1 queries' do
          second_project.add_maintainer(user)

          control_count = ActiveRecord::QueryRecorder.new do
            get api(path, user)
          end.count

          deploy_key = create(:deploy_key, user: second_user)
          create(:deploy_keys_project, project: second_project, deploy_key_id: deploy_key.id)

          expect do
            get api(path, user)
          end.not_to exceed_query_limit(control_count)
        end
      end
    end
  end

  describe 'GET /user/:id/keys' do
    subject(:request) { get api(path) }

    let(:path) { "/users/#{user.id}/keys" }

    it 'returns 404 for non-existing user' do
      get api("/users/#{non_existing_record_id}/keys")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns array of ssh keys' do
      user.keys << key

      request

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to include_pagination_headers
      expect(json_response).to be_an Array
      expect(json_response.first['title']).to eq(key.title)
    end

    it 'returns array of ssh keys with comments replaced with'\
      'a simple identifier of username + hostname' do
      request

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to include_pagination_headers
      expect(json_response).to be_an Array

      keys = json_response.map { |key_detail| key_detail['key'] }
      expect(keys).to all(include("#{user.name} (#{Gitlab.config.gitlab.host}"))
    end

    context 'N+1 queries' do
      before do
        request
      end

      it 'avoids N+1 queries', :request_store do
        control_count = ActiveRecord::QueryRecorder.new(skip_cached: false) do
          request
        end.count

        create_list(:key, 2, user: user)

        expect do
          request
        end.not_to exceed_all_query_limit(control_count)
      end
    end
  end

  describe 'GET /user/:user_id/keys' do
    let(:path) { "/users/#{user.username}/keys" }

    it 'returns 404 for non-existing user' do
      get api("/users/#{non_existing_record_id}/keys")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns array of ssh keys' do
      user.keys << key

      get api(path)

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to include_pagination_headers
      expect(json_response).to be_an Array
      expect(json_response.first['title']).to eq(key.title)
    end
  end

  describe 'GET /user/:id/keys/:key_id' do
    let(:path) { "/users/#{user.id}/keys/#{key.id}" }

    it 'gets existing key' do
      user.keys << key

      get api(path)

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['title']).to eq(key.title)
    end

    it 'returns 404 error if user not found' do
      user.keys << key

      get api("/users/#{non_existing_record_id}/keys/#{key.id}")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns 404 error if key not found' do
      get api("/users/#{user.id}/keys/#{non_existing_record_id}")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Key Not Found')
    end
  end

  describe 'DELETE /user/:id/keys/:key_id' do
    let(:path) { "/users/#{user.id}/keys/#{key.id}" }

    it_behaves_like 'DELETE request permissions for admin mode'

    context 'when unauthenticated' do
      it 'returns authentication error' do
        delete api("/users/#{user.id}/keys/#{non_existing_record_id}")
        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated' do
      it 'deletes existing key' do
        user.keys << key

        expect do
          delete api(path, admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:no_content)
        end.to change { user.keys.count }.by(-1)
      end

      it_behaves_like '412 response' do
        let(:request) { api(path, admin, admin_mode: true) }
      end

      it 'returns 404 error if user not found' do
        user.keys << key

        delete api("/users/#{non_existing_record_id}/keys/#{key.id}", admin, admin_mode: true)
        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end

      it 'returns 404 error if key not foud' do
        delete api("/users/#{user.id}/keys/#{non_existing_record_id}", admin, admin_mode: true)
        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 Key Not Found')
      end
    end
  end

  describe 'POST /users/:id/gpg_keys' do
    let(:path) { "/users/#{user.id}/gpg_keys" }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:params) { attributes_for :gpg_key, key: GpgHelpers::User2.public_key }
    end

    it 'does not create invalid GPG key' do
      post api(path, admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('key is missing')
    end

    it 'creates GPG key' do
      key_attrs = attributes_for :gpg_key, key: GpgHelpers::User2.public_key

      expect do
        post api(path, admin, admin_mode: true), params: key_attrs

        expect(response).to have_gitlab_http_status(:created)
      end.to change { user.gpg_keys.count }.by(1)
    end

    it 'returns 400 for invalid ID' do
      post api("/users/#{non_existing_record_id}/gpg_keys", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:bad_request)
    end
  end

  describe 'GET /user/:id/gpg_keys' do
    let(:path) { "/users/#{user.id}/gpg_keys" }

    it 'returns 404 for non-existing user' do
      get api("/users/#{non_existing_record_id}/gpg_keys")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns array of GPG keys' do
      user.gpg_keys << gpg_key

      get api(path)

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to include_pagination_headers
      expect(json_response).to be_an Array
      expect(json_response.first['key']).to eq(gpg_key.key)
    end
  end

  describe 'GET /user/:id/gpg_keys/:key_id' do
    let(:path) { "/users/#{user.id}/gpg_keys/#{gpg_key.id}" }

    it 'returns 404 for non-existing user' do
      get api("/users/#{non_existing_record_id}/gpg_keys/1")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns 404 for non-existing key' do
      get api("/users/#{user.id}/gpg_keys/#{non_existing_record_id}")

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 GPG Key Not Found')
    end

    it 'returns a single GPG key' do
      user.gpg_keys << gpg_key

      get api(path)

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['key']).to eq(gpg_key.key)
    end
  end

  describe 'DELETE /user/:id/gpg_keys/:key_id' do
    let(:path) { "/users/#{user.id}/gpg_keys/#{gpg_key.id}" }

    it_behaves_like 'DELETE request permissions for admin mode'

    context 'when unauthenticated' do
      it 'returns authentication error' do
        delete api("/users/#{user.id}/keys/#{non_existing_record_id}")

        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated' do
      it 'deletes existing key' do
        user.gpg_keys << gpg_key

        expect do
          delete api(path, admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:no_content)
        end.to change { user.gpg_keys.count }.by(-1)
      end

      it 'returns 404 error if user not found' do
        user.keys << key

        delete api("/users/#{non_existing_record_id}/gpg_keys/#{gpg_key.id}", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end

      it 'returns 404 error if key not foud' do
        delete api("/users/#{user.id}/gpg_keys/#{non_existing_record_id}", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 GPG Key Not Found')
      end
    end
  end

  describe 'POST /user/:id/gpg_keys/:key_id/revoke' do
    let(:path) { "/users/#{user.id}/gpg_keys/#{gpg_key.id}/revoke" }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:params) { {} }
      let(:success_status_code) { :accepted }
    end

    context 'when unauthenticated' do
      it 'returns authentication error' do
        post api("/users/#{user.id}/gpg_keys/#{non_existing_record_id}/revoke")

        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated' do
      it 'revokes existing key' do
        user.gpg_keys << gpg_key

        expect do
          post api(path, admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:accepted)
        end.to change { user.gpg_keys.count }.by(-1)
      end

      it 'returns 404 error if user not found' do
        user.gpg_keys << gpg_key

        post api("/users/#{non_existing_record_id}/gpg_keys/#{gpg_key.id}/revoke", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end

      it 'returns 404 error if key not foud' do
        post api("/users/#{user.id}/gpg_keys/#{non_existing_record_id}/revoke", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 GPG Key Not Found')
      end
    end
  end

  describe "POST /users/:id/emails", :mailer do
    let(:path) { "/users/#{user.id}/emails" }

    it_behaves_like 'POST request permissions for admin mode' do
      before do
        email_attrs[:skip_confirmation] = true
      end

      let(:email_attrs) { attributes_for :email }
      let(:params) { email_attrs }
    end

    it "does not create invalid email" do
      post api(path, admin, admin_mode: true), params: {}

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('email is missing')
    end

    it "creates unverified email" do
      email_attrs = attributes_for :email

      perform_enqueued_jobs do
        expect do
          post api(path, admin, admin_mode: true), params: email_attrs
        end.to change { user.emails.count }.by(1)
      end

      expect(json_response['confirmed_at']).to be_nil
      should_email(user)
    end

    it "returns a 400 for invalid ID" do
      post api("/users/#{non_existing_record_id}/emails", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:bad_request)
    end

    it "creates verified email" do
      email_attrs = attributes_for :email
      email_attrs[:skip_confirmation] = true

      post api(path, admin, admin_mode: true), params: email_attrs

      expect(response).to have_gitlab_http_status(:created)

      expect(json_response['confirmed_at']).not_to be_nil
    end

    context 'when user with a primary email exists' do
      context 'when the primary email is confirmed' do
        let!(:confirmed_user) { create(:user, email: 'foo@example.com') }

        it 'returns 400 error' do
          post api(path, admin, admin_mode: true), params: { email: confirmed_user.email }

          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end

      context 'when the primary email is unconfirmed' do
        let!(:unconfirmed_user) { create(:user, :unconfirmed, email: 'foo@example.com') }

        it 'returns 400 error' do
          post api(path, admin, admin_mode: true), params: { email: unconfirmed_user.email }

          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end
    end

    context 'when user with a secondary email exists' do
      context 'when the secondary email is confirmed' do
        let!(:email) { create(:email, :confirmed, email: 'foo@example.com') }

        it 'returns 400 error' do
          post api(path, admin, admin_mode: true), params: { email: email.email }

          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end

      context 'when the secondary email is unconfirmed' do
        let!(:email) { create(:email, email: 'foo@example.com') }

        it 'returns 400 error' do
          post api(path, admin, admin_mode: true), params: { email: email.email }

          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end
    end
  end

  describe 'GET /user/:id/emails' do
    let(:path) { "/users/#{user.id}/emails" }

    context 'when unauthenticated' do
      it 'returns authentication error' do
        get api(path)
        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated' do
      it 'returns 404 for non-existing user' do
        get api("/users/#{non_existing_record_id}/emails", admin, admin_mode: true)
        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end

      it 'returns array of emails' do
        user.emails << email

        get api(path, admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first['email']).to eq(user.email)
        expect(json_response.second['email']).to eq(email.email)
      end

      it "returns a 404 for invalid ID" do
        get api("/users/ASDF/emails", admin, admin_mode: true)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end
  end

  describe 'DELETE /user/:id/emails/:email_id' do
    let(:path) { "/users/#{user.id}/emails/#{email.id}" }

    it_behaves_like 'DELETE request permissions for admin mode'

    context 'when unauthenticated' do
      it 'returns authentication error' do
        delete api("/users/#{user.id}/emails/#{non_existing_record_id}")
        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated' do
      it 'deletes existing email' do
        user.emails << email

        expect do
          delete api(path, admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:no_content)
        end.to change { user.emails.count }.by(-1)
      end

      it_behaves_like '412 response' do
        subject(:request) { api(path, admin, admin_mode: true) }
      end

      it 'returns 404 error if user not found' do
        user.emails << email

        delete api("/users/#{non_existing_record_id}/emails/#{email.id}", admin, admin_mode: true)
        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end

      it 'returns 404 error if email not foud' do
        delete api("/users/#{user.id}/emails/#{non_existing_record_id}", admin, admin_mode: true)
        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 Email Not Found')
      end

      it "returns a 404 for invalid ID" do
        delete api("/users/ASDF/emails/bar", admin)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end
  end

  describe "DELETE /users/:id" do
    let_it_be(:issue) { create(:issue, author: user) }
    let(:path) { "/users/#{user.id}" }

    it_behaves_like 'DELETE request permissions for admin mode'

    it "deletes user", :sidekiq_inline do
      perform_enqueued_jobs { delete api(path, admin, admin_mode: true) }

      expect(response).to have_gitlab_http_status(:no_content)
      expect(Users::GhostUserMigration.where(user: user,
                                             initiator_user: admin)).to be_exists
    end

    context "sole owner of a group" do
      let!(:group) { create(:group).tap { |group| group.add_owner(user) } }

      context "hard delete disabled" do
        it "does not delete user" do
          perform_enqueued_jobs { delete api(path, admin, admin_mode: true) }
          expect(response).to have_gitlab_http_status(:conflict)
        end
      end

      context "hard delete enabled" do
        it "delete user and group", :sidekiq_inline do
          perform_enqueued_jobs { delete api("/users/#{user.id}?hard_delete=true", admin, admin_mode: true) }
          expect(response).to have_gitlab_http_status(:no_content)
          expect(Group.exists?(group.id)).to be_falsy
        end

        context "with subgroup owning" do
          let(:parent_group) { create(:group) }
          let(:subgroup) { create(:group, parent: parent_group) }

          before do
            parent_group.add_owner(create(:user))
            subgroup.add_owner(user)
          end

          it "delete only user", :sidekiq_inline do
            perform_enqueued_jobs { delete api("/users/#{user.id}?hard_delete=true", admin, admin_mode: true) }
            expect(response).to have_gitlab_http_status(:no_content)
            expect(Group.exists?(subgroup.id)).to be_truthy
          end
        end
      end
    end

    it_behaves_like '412 response' do
      let(:request) { api(path, admin, admin_mode: true) }
    end

    it "does not delete for unauthenticated user" do
      perform_enqueued_jobs { delete api(path) }
      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it "is not available for non admin users" do
      perform_enqueued_jobs { delete api(path, user) }
      expect(response).to have_gitlab_http_status(:forbidden)
    end

    it "returns 404 for non-existing user" do
      perform_enqueued_jobs { delete api("/users/#{non_existing_record_id}", admin, admin_mode: true) }
      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it "returns a 404 for invalid ID" do
      perform_enqueued_jobs { delete api("/users/ASDF", admin, admin_mode: true) }

      expect(response).to have_gitlab_http_status(:not_found)
    end

    context "hard delete disabled" do
      it "moves contributions to the ghost user", :sidekiq_might_not_need_inline do
        perform_enqueued_jobs { delete api(path, admin, admin_mode: true) }

        expect(response).to have_gitlab_http_status(:no_content)
        expect(issue.reload).to be_persisted
        expect(Users::GhostUserMigration.where(user: user,
                                               initiator_user: admin,
                                               hard_delete: false)).to be_exists
      end
    end

    context "hard delete enabled" do
      it "removes contributions", :sidekiq_might_not_need_inline do
        perform_enqueued_jobs { delete api("/users/#{user.id}?hard_delete=true", admin, admin_mode: true) }

        expect(response).to have_gitlab_http_status(:no_content)
        expect(Users::GhostUserMigration.where(user: user,
                                               initiator_user: admin,
                                               hard_delete: true)).to be_exists
      end
    end
  end

  describe "GET /user" do
    let(:path) { '/user' }

    shared_examples 'get user info' do |version|
      context 'with regular user' do
        context 'with personal access token' do
          let(:personal_access_token) { create(:personal_access_token, user: user).token }

          it 'returns 403 without private token when sudo is defined' do
            get api("/user?private_token=#{personal_access_token}&sudo=123", version: version)

            expect(response).to have_gitlab_http_status(:forbidden)
          end
        end

        it 'returns current user without private token when sudo not defined' do
          get api(path, user, version: version)

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to match_response_schema('public_api/v4/user/public')
          expect(json_response['id']).to eq(user.id)
        end

        context "scopes" do
          let(:api_call) { method(:api) }

          include_examples 'allows the "read_user" scope', version
        end
      end

      context 'with admin' do
        let(:admin_personal_access_token) { create(:personal_access_token, :admin_mode, user: admin).token }

        context 'with personal access token' do
          it 'returns 403 without private token when sudo defined' do
            get api("/user?private_token=#{admin_personal_access_token}&sudo=#{user.id}", version: version)

            expect(response).to have_gitlab_http_status(:forbidden)
          end

          it 'returns initial current user without private token but with is_admin when sudo not defined' do
            get api("/user?private_token=#{admin_personal_access_token}", version: version)

            expect(response).to have_gitlab_http_status(:ok)
            expect(response).to match_response_schema('public_api/v4/user/admin')
            expect(json_response['id']).to eq(admin.id)
          end
        end
      end

      context 'with unauthenticated user' do
        it "returns 401 error if user is unauthenticated" do
          get api(path, version: version)

          expect(response).to have_gitlab_http_status(:unauthorized)
        end
      end
    end

    it_behaves_like 'get user info', 'v3'
    it_behaves_like 'get user info', 'v4'
  end

  describe "GET /user/preferences" do
    let(:path) { '/user/preferences' }

    context "when unauthenticated" do
      it "returns authentication error" do
        get api(path)
        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context "when authenticated" do
      it "returns user preferences" do
        user.user_preference.view_diffs_file_by_file = false
        user.user_preference.show_whitespace_in_diffs = true
        user.save!

        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response["view_diffs_file_by_file"]).to eq(user.user_preference.view_diffs_file_by_file)
        expect(json_response["show_whitespace_in_diffs"]).to eq(user.user_preference.show_whitespace_in_diffs)
      end
    end
  end

  describe "GET /user/keys" do
    subject(:request) { get api(path, user) }

    let(:path) { "/user/keys" }

    context "when unauthenticated" do
      it "returns authentication error" do
        get api("/user/keys")
        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context "when authenticated" do
      it "returns array of ssh keys" do
        user.keys << key

        request

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first["title"]).to eq(key.title)
      end

      it 'returns array of ssh keys with comments replaced with'\
        'a simple identifier of username + hostname' do
        request

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array

        keys = json_response.map { |key_detail| key_detail['key'] }
        expect(keys).to all(include("#{user.name} (#{Gitlab.config.gitlab.host}"))
      end

      context 'N+1 queries' do
        before do
          request
        end

        it 'avoids N+1 queries', :request_store do
          control_count = ActiveRecord::QueryRecorder.new(skip_cached: false) do
            request
          end.count

          create_list(:key, 2, user: user)

          expect do
            request
          end.not_to exceed_all_query_limit(control_count)
        end
      end

      context "scopes" do
        let(:api_call) { method(:api) }

        include_examples 'allows the "read_user" scope'
      end
    end
  end

  describe "GET /user/keys/:key_id" do
    let(:path) { "/user/keys/#{key.id}" }

    it "returns single key" do
      user.keys << key

      get api(path, user)
      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response["title"]).to eq(key.title)
    end

    it 'exposes SSH key comment as a simple identifier of username + hostname' do
      get api(path, user)

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['key']).to include("#{key.user_name} (#{Gitlab.config.gitlab.host})")
    end

    it "returns 404 Not Found within invalid ID" do
      get api("/user/keys/#{non_existing_record_id}", user)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Key Not Found')
    end

    it "returns 404 error if admin accesses user's ssh key" do
      user.keys << key
      admin

      get api(path, admin, admin_mode: true)
      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Key Not Found')
    end

    it "returns 404 for invalid ID" do
      get api("/users/keys/ASDF", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
    end

    context "scopes" do
      let(:api_call) { method(:api) }

      include_examples 'allows the "read_user" scope'
    end
  end

  describe "POST /user/keys" do
    let(:path) { "/user/keys" }

    it "creates ssh key" do
      key_attrs = attributes_for(:key, usage_type: :signing)

      expect do
        post api(path, user), params: key_attrs
      end.to change { user.keys.count }.by(1)

      expect(response).to have_gitlab_http_status(:created)

      key = user.keys.last
      expect(key.title).to eq(key_attrs[:title])
      expect(key.key).to eq(key_attrs[:key])
      expect(key.usage_type).to eq(key_attrs[:usage_type].to_s)
    end

    it 'creates SSH key with `expires_at` attribute' do
      optional_attributes = { expires_at: 3.weeks.from_now }
      attributes = attributes_for(:key).merge(optional_attributes)

      post api(path, user), params: attributes

      expect(response).to have_gitlab_http_status(:created)
      expect(json_response['expires_at'].to_date).to eq(optional_attributes[:expires_at].to_date)
    end

    it "returns a 401 error if unauthorized" do
      post api(path), params: { title: 'some title', key: 'some key' }
      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it "does not create ssh key without key" do
      post api(path, user), params: { title: 'title' }

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('key is missing')
    end

    it 'does not create ssh key without title' do
      post api('/user/keys', user), params: { key: 'some key' }

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('title is missing')
    end

    it "does not create ssh key without title" do
      post api(path, user), params: { key: "somekey" }
      expect(response).to have_gitlab_http_status(:bad_request)
    end
  end

  describe "DELETE /user/keys/:key_id" do
    let(:path) { "/user/keys/#{key.id}" }

    it "deletes existed key" do
      user.keys << key

      expect do
        delete api(path, user)

        expect(response).to have_gitlab_http_status(:no_content)
      end.to change { user.keys.count }.by(-1)
    end

    it_behaves_like '412 response' do
      let(:request) { api(path, user) }
    end

    it "returns 404 if key ID not found" do
      delete api("/user/keys/#{non_existing_record_id}", user)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Key Not Found')
    end

    it "returns 401 error if unauthorized" do
      user.keys << key

      delete api(path)
      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it "returns a 404 for invalid ID" do
      delete api("/users/keys/ASDF", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
    end
  end

  describe 'GET /user/gpg_keys' do
    let(:path) { '/user/gpg_keys' }

    context 'when unauthenticated' do
      it 'returns authentication error' do
        get api(path)

        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'when authenticated' do
      it 'returns array of GPG keys' do
        user.gpg_keys << gpg_key

        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first['key']).to eq(gpg_key.key)
      end

      context 'scopes' do
        let(:api_call) { method(:api) }

        include_examples 'allows the "read_user" scope'
      end
    end
  end

  describe 'GET /user/gpg_keys/:key_id' do
    let(:path) { "/user/gpg_keys/#{gpg_key.id}" }

    it 'returns a single key' do
      user.gpg_keys << gpg_key

      get api(path, user)

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['key']).to eq(gpg_key.key)
    end

    it 'returns 404 Not Found within invalid ID' do
      get api("/user/gpg_keys/#{non_existing_record_id}", user)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 GPG Key Not Found')
    end

    it "returns 404 error if admin accesses user's GPG key" do
      user.gpg_keys << gpg_key

      get api(path, admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 GPG Key Not Found')
    end

    it 'returns 404 for invalid ID' do
      get api('/users/gpg_keys/ASDF', admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
    end

    context 'scopes' do
      let(:api_call) { method(:api) }

      include_examples 'allows the "read_user" scope'
    end
  end

  describe 'POST /user/gpg_keys' do
    let(:path) { '/user/gpg_keys' }

    it 'creates a GPG key' do
      key_attrs = attributes_for :gpg_key, key: GpgHelpers::User2.public_key

      expect do
        post api(path, user), params: key_attrs

        expect(response).to have_gitlab_http_status(:created)
      end.to change { user.gpg_keys.count }.by(1)
    end

    it 'returns a 401 error if unauthorized' do
      post api(path), params: { key: 'some key' }

      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it 'does not create GPG key without key' do
      post api(path, user)

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('key is missing')
    end
  end

  describe 'POST /user/gpg_keys/:key_id/revoke' do
    it 'revokes existing GPG key' do
      user.gpg_keys << gpg_key

      expect do
        post api("/user/gpg_keys/#{gpg_key.id}/revoke", user)

        expect(response).to have_gitlab_http_status(:accepted)
      end.to change { user.gpg_keys.count }.by(-1)
    end

    it 'returns 404 if key ID not found' do
      post api("/user/gpg_keys/#{non_existing_record_id}/revoke", user)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 GPG Key Not Found')
    end

    it 'returns 401 error if unauthorized' do
      user.gpg_keys << gpg_key

      post api("/user/gpg_keys/#{gpg_key.id}/revoke")

      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it 'returns a 404 for invalid ID' do
      post api('/users/gpg_keys/ASDF/revoke', admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
    end
  end

  describe 'DELETE /user/gpg_keys/:key_id' do
    let(:path) { "/user/gpg_keys/#{gpg_key.id}" }

    it 'deletes existing GPG key' do
      user.gpg_keys << gpg_key

      expect do
        delete api(path, user)

        expect(response).to have_gitlab_http_status(:no_content)
      end.to change { user.gpg_keys.count }.by(-1)
    end

    it 'returns 404 if key ID not found' do
      delete api("/user/gpg_keys/#{non_existing_record_id}", user)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 GPG Key Not Found')
    end

    it 'returns 401 error if unauthorized' do
      user.gpg_keys << gpg_key

      delete api(path)

      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it 'returns a 404 for invalid ID' do
      delete api('/users/gpg_keys/ASDF', admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
    end
  end

  describe "GET /user/emails" do
    let(:path) { '/user/emails' }

    context "when unauthenticated" do
      it "returns authentication error" do
        get api(path)
        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context "when authenticated" do
      it "returns array of emails" do
        user.emails << email

        get api(path, user)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first['email']).to eq(user.email)
        expect(json_response.second['email']).to eq(email.email)
      end

      context "scopes" do
        let(:api_call) { method(:api) }

        include_examples 'allows the "read_user" scope'
      end
    end
  end

  describe "GET /user/emails/:email_id" do
    let(:path) { "/user/emails/#{email.id}" }

    it "returns single email" do
      user.emails << email

      get api(path, user)
      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response["email"]).to eq(email.email)
    end

    it "returns 404 Not Found within invalid ID" do
      get api("/user/emails/#{non_existing_record_id}", user)
      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Email Not Found')
    end

    it "returns 404 error if admin accesses user's email" do
      user.emails << email
      admin

      get api(path, admin, admin_mode: true)
      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Email Not Found')
    end

    it "returns 404 for invalid ID" do
      get api("/users/emails/ASDF", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
    end

    context "scopes" do
      let(:api_call) { method(:api) }

      include_examples 'allows the "read_user" scope'
    end
  end

  describe "POST /user/emails" do
    let(:path) { '/user/emails' }

    it "creates email" do
      email_attrs = attributes_for :email
      expect do
        post api(path, user), params: email_attrs
      end.to change { user.emails.count }.by(1)
      expect(response).to have_gitlab_http_status(:created)
    end

    it "returns a 401 error if unauthorized" do
      post api(path), params: { email: 'some email' }
      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it "does not create email with invalid email" do
      post api(path, user), params: {}

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('email is missing')
    end
  end

  describe "DELETE /user/emails/:email_id" do
    let(:path) { "/user/emails/#{email.id}" }

    it "deletes existed email" do
      user.emails << email

      expect do
        delete api(path, user)

        expect(response).to have_gitlab_http_status(:no_content)
      end.to change { user.emails.count }.by(-1)
    end

    it_behaves_like '412 response' do
      let(:request) { api(path, user) }
    end

    it "returns 404 if email ID not found" do
      delete api("/user/emails/#{non_existing_record_id}", user)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Email Not Found')
    end

    it "returns 401 error if unauthorized" do
      user.emails << email

      delete api(path)
      expect(response).to have_gitlab_http_status(:unauthorized)
    end

    it "returns 400 for invalid ID" do
      delete api("/user/emails/ASDF", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:bad_request)
    end
  end

  context 'activate and deactivate' do
    shared_examples '404' do
      it 'returns 404' do
        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end
    end

    describe 'POST /users/:id/activate' do
      subject(:activate) { post api(path, api_user, **params) }

      let(:user_id) { user.id }
      let(:path) { "/users/#{user_id}/activate" }

      it_behaves_like 'POST request permissions for admin mode' do
        let(:params) { {} }
      end

      context 'performed by a non-admin user' do
        let(:api_user) { user }
        let(:params) { { admin_mode: false } }

        it 'is not authorized to perform the action' do
          activate

          expect(response).to have_gitlab_http_status(:forbidden)
        end
      end

      context 'performed by an admin user' do
        let(:api_user) { admin }
        let(:params) { { admin_mode: true } }

        context 'for a deactivated user' do
          let(:user_id) { deactivated_user.id }

          it 'activates a deactivated user' do
            activate

            expect(response).to have_gitlab_http_status(:created)
            expect(deactivated_user.reload.state).to eq('active')
          end
        end

        context 'for an active user' do
          before do
            user.activate
          end

          it 'returns 201' do
            activate

            expect(response).to have_gitlab_http_status(:created)
            expect(user.reload.state).to eq('active')
          end
        end

        context 'for a blocked user' do
          let(:user_id) { blocked_user.id }

          it 'returns 403' do
            activate

            expect(response).to have_gitlab_http_status(:forbidden)
            expect(json_response['message']).to eq('403 Forbidden - A blocked user must be unblocked to be activated')
            expect(blocked_user.reload.state).to eq('blocked')
          end
        end

        context 'for a ldap blocked user' do
          before do
            user.ldap_block
          end

          it 'returns 403' do
            activate

            expect(response).to have_gitlab_http_status(:forbidden)
            expect(json_response['message']).to eq('403 Forbidden - A blocked user must be unblocked to be activated')
            expect(user.reload.state).to eq('ldap_blocked')
          end
        end

        context 'for a user that does not exist' do
          let(:user_id) { non_existing_record_id }

          before do
            activate
          end

          it_behaves_like '404'
        end
      end
    end

    describe 'POST /users/:id/deactivate' do
      subject(:deactivate) { post api(path, api_user, **params) }

      let(:user_id) { user.id }
      let(:path) { "/users/#{user_id}/deactivate" }

      it_behaves_like 'POST request permissions for admin mode' do
        let(:params) { {} }
      end

      context 'performed by a non-admin user' do
        let(:api_user) { user }
        let(:params) { { admin_mode: false } }

        it 'is not authorized to perform the action' do
          deactivate

          expect(response).to have_gitlab_http_status(:forbidden)
        end
      end

      context 'performed by an admin user' do
        let(:api_user) { admin }
        let(:params) { { admin_mode: true } }

        context 'for an active user' do
          let(:activity) { {} }
          let(:user) { create(:user, **activity) }

          context 'with no recent activity' do
            let(:activity) { { last_activity_on: Gitlab::CurrentSettings.deactivate_dormant_users_period.next.days.ago } }

            it 'deactivates an active user' do
              deactivate

              expect(response).to have_gitlab_http_status(:created)
              expect(user.reload.state).to eq('deactivated')
            end
          end

          context 'with recent activity' do
            let(:activity) { { last_activity_on: Gitlab::CurrentSettings.deactivate_dormant_users_period.pred.days.ago } }

            it 'does not deactivate an active user' do
              deactivate

              expect(response).to have_gitlab_http_status(:forbidden)
              expect(json_response['message']).to eq("403 Forbidden - The user you are trying to deactivate has been active in the past #{Gitlab::CurrentSettings.deactivate_dormant_users_period} days and cannot be deactivated")
              expect(user.reload.state).to eq('active')
            end
          end
        end

        context 'for a deactivated user' do
          let(:user_id) { deactivated_user.id }

          it 'returns 201' do
            deactivate

            expect(response).to have_gitlab_http_status(:created)
            expect(deactivated_user.reload.state).to eq('deactivated')
          end
        end

        context 'for a blocked user' do
          let(:user_id) { blocked_user.id }

          it 'returns 403' do
            deactivate

            expect(response).to have_gitlab_http_status(:forbidden)
            expect(json_response['message']).to eq('403 Forbidden - A blocked user cannot be deactivated by the API')
            expect(blocked_user.reload.state).to eq('blocked')
          end
        end

        context 'for a ldap blocked user' do
          before do
            user.ldap_block
          end

          it 'returns 403' do
            deactivate

            expect(response).to have_gitlab_http_status(:forbidden)
            expect(json_response['message']).to eq('403 Forbidden - A blocked user cannot be deactivated by the API')
            expect(user.reload.state).to eq('ldap_blocked')
          end
        end

        context 'for an internal user' do
          let(:user) { User.alert_bot }

          it 'returns 403' do
            deactivate

            expect(response).to have_gitlab_http_status(:forbidden)
            expect(json_response['message']).to eq('403 Forbidden - An internal user cannot be deactivated by the API')
          end
        end

        context 'for a user that does not exist' do
          let(:user_id) { non_existing_record_id }

          before do
            deactivate
          end

          it_behaves_like '404'
        end
      end
    end
  end

  context 'approve and reject pending user' do
    let(:pending_user) { create(:user, :blocked_pending_approval) }

    shared_examples '404' do
      it 'returns 404' do
        expect(response).to have_gitlab_http_status(:not_found)
        expect(json_response['message']).to eq('404 User Not Found')
      end
    end

    describe 'POST /users/:id/approve' do
      subject(:approve) { post api(path, api_user, **params) }

      let(:path) { "/users/#{user_id}/approve" }

      it_behaves_like 'POST request permissions for admin mode' do
        let(:user_id) { pending_user.id }
        let(:params) { {} }
      end

      context 'performed by a non-admin user' do
        let(:api_user) { user }
        let(:user_id) { pending_user.id }
        let(:params) { { admin_mode: false } }

        it 'is not authorized to perform the action' do
          expect { approve }.not_to change { pending_user.reload.state }
          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You are not allowed to approve a user')
        end
      end

      context 'performed by an admin user' do
        let(:api_user) { admin }
        let(:params) { { admin_mode: true } }

        context 'for a deactivated user' do
          let(:user_id) { deactivated_user.id }

          it 'does not approve a deactivated user' do
            expect { approve }.not_to change { deactivated_user.reload.state }
            expect(response).to have_gitlab_http_status(:conflict)
            expect(json_response['message']).to eq('The user you are trying to approve is not pending approval')
          end
        end

        context 'for an pending approval user' do
          let(:user_id) { pending_user.id }

          it 'returns 201' do
            expect { approve }.to change { pending_user.reload.state }.to('active')
            expect(response).to have_gitlab_http_status(:created)
            expect(json_response['message']).to eq('Success')
          end
        end

        context 'for an active user' do
          let(:user_id) { user.id }

          it 'returns 201' do
            expect { approve }.not_to change { user.reload.state }
            expect(response).to have_gitlab_http_status(:conflict)
            expect(json_response['message']).to eq('The user you are trying to approve is not pending approval')
          end
        end

        context 'for a blocked user' do
          let(:user_id) { blocked_user.id }

          it 'returns 403' do
            expect { approve }.not_to change { blocked_user.reload.state }
            expect(response).to have_gitlab_http_status(:conflict)
            expect(json_response['message']).to eq('The user you are trying to approve is not pending approval')
          end
        end

        context 'for a ldap blocked user' do
          let(:user_id) { ldap_blocked_user.id }

          it 'returns 403' do
            expect { approve }.not_to change { ldap_blocked_user.reload.state }
            expect(response).to have_gitlab_http_status(:conflict)
            expect(json_response['message']).to eq('The user you are trying to approve is not pending approval')
          end
        end

        context 'for a user that does not exist' do
          let(:user_id) { non_existing_record_id }

          before do
            approve
          end

          it_behaves_like '404'
        end
      end
    end

    describe 'POST /users/:id/reject' do
      subject(:reject) { post api(path, api_user, **params) }

      let(:path) { "/users/#{user_id}/reject" }

      it_behaves_like 'POST request permissions for admin mode' do
        let(:user_id) { pending_user.id }
        let(:params) { {} }
        let(:success_status_code) { :success }
      end

      shared_examples 'returns 409' do
        it 'returns 409' do
          reject

          expect(response).to have_gitlab_http_status(:conflict)
          expect(json_response['message']).to eq('User does not have a pending request')
        end
      end

      context 'performed by a non-admin user' do
        let(:api_user) { user }
        let(:user_id) { pending_user.id }
        let(:params) { { admin_mode: false } }

        it 'returns 403' do
          expect { reject }.not_to change { pending_user.reload.state }
          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You are not allowed to reject a user')
        end
      end

      context 'performed by an admin user' do
        let(:api_user) { admin }
        let(:params) { { admin_mode: true } }

        context 'for an pending approval user' do
          let(:user_id) { pending_user.id }

          it 'returns 200' do
            reject

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response['message']).to eq('Success')
          end
        end

        context 'for a deactivated user' do
          let(:user_id) { deactivated_user.id }

          it 'does not reject a deactivated user' do
            expect { reject }.not_to change { deactivated_user.reload.state }
          end

          it_behaves_like 'returns 409'
        end

        context 'for an active user' do
          let(:user_id) { user.id }

          it 'does not reject an active user' do
            expect { reject }.not_to change { user.reload.state }
          end

          it_behaves_like 'returns 409'
        end

        context 'for a blocked user' do
          let(:user_id) { blocked_user.id }

          it 'does not reject a blocked user' do
            expect { reject }.not_to change { blocked_user.reload.state }
          end

          it_behaves_like 'returns 409'
        end

        context 'for a ldap blocked user' do
          let(:user_id) { ldap_blocked_user.id }

          it 'does not reject a ldap blocked user' do
            expect { reject }.not_to change { ldap_blocked_user.reload.state }
          end

          it_behaves_like 'returns 409'
        end

        context 'for a user that does not exist' do
          let(:user_id) { non_existing_record_id }

          before do
            reject
          end

          it_behaves_like '404'
        end
      end
    end
  end

  describe 'POST /users/:id/block' do
    subject(:block_user) { post api(path, api_user, **params) }

    let(:user_id) { user.id }
    let(:path) { "/users/#{user_id}/block" }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:params) { {} }
    end

    context 'when admin' do
      let(:api_user) { admin }
      let(:params) { { admin_mode: true } }

      context 'with an existing user' do
        it 'blocks existing user' do
          block_user

          expect(response).to have_gitlab_http_status(:created)
          expect(response.body).to eq('true')
          expect(user.reload.state).to eq('blocked')
        end

        it 'saves a custom attribute', :freeze_time, feature_category: :insider_threat do
          block_user

          custom_attribute = user.custom_attributes.last

          expect(custom_attribute.key).to eq(UserCustomAttribute::BLOCKED_BY)
          expect(custom_attribute.value).to eq("#{admin.username}/#{admin.id}+#{Time.current}")
        end
      end

      context 'with an ldap blocked user' do
        let(:user_id) { ldap_blocked_user.id }

        it 'does not re-block ldap blocked users' do
          block_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(ldap_blocked_user.reload.state).to eq('ldap_blocked')
        end
      end

      context 'with a non existent user' do
        let(:user_id) { non_existing_record_id }

        it 'does not block non existent user, returns 404' do
          block_user

          expect(response).to have_gitlab_http_status(:not_found)
          expect(json_response['message']).to eq('404 User Not Found')
        end
      end

      context 'with an internal user' do
        let(:user_id) { internal_user.id }

        it 'does not block internal user, returns 403' do
          block_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('An internal user cannot be blocked')
        end
      end

      context 'with a blocked user' do
        let(:user_id) { blocked_user.id }

        it 'returns a 201 if user is already blocked' do
          block_user

          expect(response).to have_gitlab_http_status(:created)
          expect(response.body).to eq('null')
        end
      end

      context 'with the API initiating user' do
        let(:user_id) { admin.id }

        it 'does not block the API initiating user, returns 403' do
          block_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('403 Forbidden - The API initiating user cannot be blocked by the API')
          expect(admin.reload.state).to eq('active')
        end
      end
    end

    context 'performed by a non-admin user' do
      let(:api_user) { user }
      let(:params) { { admin_mode: false } }

      it 'returns 403' do
        block_user

        expect(response).to have_gitlab_http_status(:forbidden)
        expect(user.reload.state).to eq('active')
      end
    end
  end

  describe 'POST /users/:id/unblock' do
    subject(:unblock_user) { post api(path, api_user, **params) }

    let(:path) { "/users/#{user_id}/unblock" }
    let(:user_id) { user.id }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:params) { {} }
    end

    context 'when admin' do
      let(:api_user) { admin }
      let(:params) { { admin_mode: true } }

      context 'with an existing user' do
        it 'unblocks existing user' do
          unblock_user

          expect(response).to have_gitlab_http_status(:created)
          expect(user.reload.state).to eq('active')
        end
      end

      context 'with a blocked user' do
        let(:user_id) { blocked_user.id }

        it 'unblocks a blocked user' do
          unblock_user

          expect(response).to have_gitlab_http_status(:created)
          expect(blocked_user.reload.state).to eq('active')
        end

        it 'saves a custom attribute', :freeze_time, feature_category: :insider_threat do
          unblock_user

          custom_attribute = blocked_user.custom_attributes.last

          expect(custom_attribute.key).to eq(UserCustomAttribute::UNBLOCKED_BY)
          expect(custom_attribute.value).to eq("#{admin.username}/#{admin.id}+#{Time.current}")
        end
      end

      context 'with a ldap blocked user' do
        let(:user_id) { ldap_blocked_user.id }

        it 'does not unblock ldap blocked users' do
          unblock_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(ldap_blocked_user.reload.state).to eq('ldap_blocked')
        end
      end

      context 'with a deactivated user' do
        let(:user_id) { deactivated_user.id }

        it 'does not unblock deactivated users' do
          unblock_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(deactivated_user.reload.state).to eq('deactivated')
        end
      end

      context 'with a non existent user' do
        let(:user_id) { non_existing_record_id }

        it 'returns a 404 error if user id not found' do
          unblock_user

          expect(response).to have_gitlab_http_status(:not_found)
          expect(json_response['message']).to eq('404 User Not Found')
        end
      end

      context 'with an invalid user id' do
        let(:user_id) { 'ASDF' }

        it 'returns a 404' do
          unblock_user

          expect(response).to have_gitlab_http_status(:not_found)
        end
      end
    end

    context 'performed by a non-admin user' do
      let(:api_user) { user }
      let(:params) { { admin_mode: false } }

      it 'returns 403' do
        unblock_user

        expect(response).to have_gitlab_http_status(:forbidden)
        expect(user.reload.state).to eq('active')
      end
    end
  end

  describe 'POST /users/:id/ban' do
    subject(:ban_user) { post api(path, api_user, **params) }

    let(:path) { "/users/#{user_id}/ban" }
    let(:user_id) { user.id }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:params) { {} }
    end

    context 'when admin' do
      let(:api_user) { admin }
      let(:params) { { admin_mode: true } }

      context 'with an active user' do
        it 'bans an active user' do
          ban_user

          expect(response).to have_gitlab_http_status(:created)
          expect(response.body).to eq('true')
          expect(user.reload.state).to eq('banned')
        end
      end

      context 'with an ldap blocked user' do
        let(:user_id) { ldap_blocked_user.id }

        it 'does not ban ldap blocked users' do
          ban_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You cannot ban ldap_blocked users.')
          expect(ldap_blocked_user.reload.state).to eq('ldap_blocked')
        end
      end

      context 'with a deactivated user' do
        let(:user_id) { deactivated_user.id }

        it 'does not ban deactivated users' do
          ban_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You cannot ban deactivated users.')
          expect(deactivated_user.reload.state).to eq('deactivated')
        end
      end

      context 'with a banned user' do
        let(:user_id) { banned_user.id }

        it 'does not ban banned users' do
          ban_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You cannot ban banned users.')
          expect(banned_user.reload.state).to eq('banned')
        end
      end

      context 'with a non existent user' do
        let(:user_id) { non_existing_record_id }

        it 'does not ban non existent users' do
          ban_user

          expect(response).to have_gitlab_http_status(:not_found)
          expect(json_response['message']).to eq('404 User Not Found')
        end
      end

      context 'with an invalid id' do
        let(:user_id) { 'ASDF' }

        it 'does not ban invalid id users' do
          ban_user

          expect(response).to have_gitlab_http_status(:not_found)
        end
      end
    end

    context 'performed by a non-admin user' do
      let(:api_user) { user }
      let(:params) { { admin_mode: false } }

      it 'returns 403' do
        ban_user

        expect(response).to have_gitlab_http_status(:forbidden)
        expect(user.reload.state).to eq('active')
      end
    end
  end

  describe 'POST /users/:id/unban' do
    subject(:unban_user) { post api(path, api_user, **params) }

    let(:path) { "/users/#{user_id}/unban" }

    it_behaves_like 'POST request permissions for admin mode' do
      let(:user_id) { banned_user.id }
      let(:params) { {} }
    end

    context 'when admin' do
      let(:api_user) { admin }
      let(:params) { { admin_mode: true } }

      context 'with a banned user' do
        let(:user_id) { banned_user.id }

        it 'activates a banned user' do
          unban_user

          expect(response).to have_gitlab_http_status(:created)
          expect(banned_user.reload.state).to eq('active')
        end
      end

      context 'with an ldap_blocked user' do
        let(:user_id) { ldap_blocked_user.id }

        it 'does not unban ldap_blocked users' do
          unban_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You cannot unban ldap_blocked users.')
          expect(ldap_blocked_user.reload.state).to eq('ldap_blocked')
        end
      end

      context 'with a deactivated user' do
        let(:user_id) { deactivated_user.id }

        it 'does not unban deactivated users' do
          unban_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You cannot unban deactivated users.')
          expect(deactivated_user.reload.state).to eq('deactivated')
        end
      end

      context 'with an active user' do
        let(:user_id) { user.id }

        it 'does not unban active users' do
          unban_user

          expect(response).to have_gitlab_http_status(:forbidden)
          expect(json_response['message']).to eq('You cannot unban active users.')
          expect(user.reload.state).to eq('active')
        end
      end

      context 'with a non existent user' do
        let(:user_id) { non_existing_record_id }

        it 'does not unban non existent users' do
          unban_user

          expect(response).to have_gitlab_http_status(:not_found)
          expect(json_response['message']).to eq('404 User Not Found')
        end
      end

      context 'with an invalid id user' do
        let(:user_id) { 'ASDF' }

        it 'does not unban invalid id users' do
          unban_user

          expect(response).to have_gitlab_http_status(:not_found)
        end
      end
    end

    context 'performed by a non-admin user' do
      let(:api_user) { user }
      let(:params) { { admin_mode: false } }
      let(:user_id) { banned_user.id }

      it 'returns 403' do
        unban_user

        expect(response).to have_gitlab_http_status(:forbidden)
        expect(user.reload.state).to eq('active')
      end
    end
  end

  describe "GET /users/:id/memberships" do
    subject(:request) { get api(path, requesting_user, admin_mode: true) }

    let_it_be(:user) { create(:user) }
    let_it_be(:project) { create(:project) }
    let_it_be(:group) { create(:group) }

    let(:requesting_user) { create(:user) }
    let(:path) { "/users/#{user.id}/memberships" }

    before_all do
      project.add_guest(user)
      group.add_guest(user)
    end

    it_behaves_like 'GET request permissions for admin mode'

    context 'requested by admin user' do
      let(:requesting_user) { create(:user, :admin) }

      it "responses successfully" do
        request

        aggregate_failures 'expect successful response including groups and projects' do
          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to match_response_schema('public_api/v4/memberships')
          expect(response).to include_pagination_headers
          expect(json_response).to contain_exactly(
            a_hash_including('source_type' => 'Project'),
            a_hash_including('source_type' => 'Namespace')
          )
        end
      end

      it 'does not submit N+1 DB queries' do
        # Avoid setup queries
        request
        expect(response).to have_gitlab_http_status(:ok)

        control = ActiveRecord::QueryRecorder.new do
          request
        end

        create_list(:project, 5).map { |project| project.add_guest(user) }

        expect do
          request
        end.not_to exceed_query_limit(control)
      end

      context 'with type filter' do
        it "only returns project memberships" do
          get api("/users/#{user.id}/memberships?type=Project", requesting_user, admin_mode: true)

          aggregate_failures do
            expect(json_response).to contain_exactly(a_hash_including('source_type' => 'Project'))
            expect(json_response).not_to include(a_hash_including('source_type' => 'Namespace'))
          end
        end

        it "only returns group memberships" do
          get api("/users/#{user.id}/memberships?type=Namespace", requesting_user, admin_mode: true)

          aggregate_failures do
            expect(json_response).to contain_exactly(a_hash_including('source_type' => 'Namespace'))
            expect(json_response).not_to include(a_hash_including('source_type' => 'Project'))
          end
        end

        it "recognizes unsupported types" do
          get api("/users/#{user.id}/memberships?type=foo", requesting_user, admin_mode: true)

          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end
    end
  end

  context "user activities", :clean_gitlab_redis_shared_state do
    let_it_be(:old_active_user) { create(:user, last_activity_on: Time.utc(2000, 1, 1)) }
    let_it_be(:newly_active_user) { create(:user, last_activity_on: 2.days.ago.midday) }
    let(:path) { '/user/activities' }

    it_behaves_like 'GET request permissions for admin mode'

    context 'last activity as normal user' do
      it 'has no permission' do
        get api(path, user)

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    context 'as admin' do
      it 'returns the activities from the last 6 months' do
        get api(path, admin, admin_mode: true)

        expect(response).to include_pagination_headers
        expect(json_response.size).to eq(1)

        activity = json_response.last

        expect(activity['username']).to eq(newly_active_user.username)
        expect(activity['last_activity_on']).to eq(2.days.ago.to_date.to_s)
        expect(activity['last_activity_at']).to eq(2.days.ago.to_date.to_s)
      end

      context 'passing a :from parameter' do
        it 'returns the activities from the given date' do
          get api("#{path}?from=2000-1-1", admin, admin_mode: true)

          expect(response).to include_pagination_headers
          expect(json_response.size).to eq(2)

          activity = json_response.first

          expect(activity['username']).to eq(old_active_user.username)
          expect(activity['last_activity_on']).to eq(Time.utc(2000, 1, 1).to_date.to_s)
          expect(activity['last_activity_at']).to eq(Time.utc(2000, 1, 1).to_date.to_s)
        end
      end
    end
  end

  describe '/user/status' do
    let(:user_status) { create(:user_status, clear_status_at: 8.hours.from_now) }
    let(:user_with_status) { user_status.user }
    let(:params) { {} }
    let(:request_user) { user }
    let(:path) { '/user/status' }

    shared_examples '/user/status successful response' do
      context 'when request is successful' do
        let(:params) { { emoji: 'smirk', message: 'hello world' } }

        it 'saves the status' do
          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(json_response['emoji']).to eq('smirk')
          expect(json_response['message']).to eq('hello world')
        end
      end
    end

    shared_examples '/user/status unsuccessful response' do
      context 'when request is unsuccessful' do
        let(:params) { { emoji: 'does not exist', message: 'hello world' } }

        it 'renders errors' do
          set_user_status

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(json_response['message']['emoji']).to be_present
        end
      end
    end

    shared_examples '/user/status passing nil for params' do
      context 'when passing nil for params' do
        let(:params) { { emoji: nil, message: nil, clear_status_after: nil } }
        let(:request_user) { user_with_status }

        it 'deletes the status' do
          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(user_with_status.reset.status).to be_nil
        end
      end
    end

    shared_examples '/user/status clear_status_after field' do
      context 'when clear_status_after is valid', :freeze_time do
        let(:params) { { emoji: 'smirk', message: 'hello world', clear_status_after: '3_hours' } }

        it 'sets the clear_status_at column' do
          expected_clear_status_at = 3.hours.from_now

          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(user.status.clear_status_at).to be_like_time(expected_clear_status_at)
          expect(Time.parse(json_response["clear_status_at"])).to be_like_time(expected_clear_status_at)
        end
      end

      context 'when clear_status_after is nil' do
        let(:params) { { emoji: 'smirk', message: 'hello world', clear_status_after: nil } }
        let(:request_user) { user_with_status }

        it 'unsets the clear_status_at column' do
          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(user_with_status.reset.status.clear_status_at).to be_nil
        end
      end

      context 'when clear_status_after is invalid' do
        let(:params) { { emoji: 'smirk', message: 'hello world', clear_status_after: 'invalid' } }

        it 'raises error when unknown status value is given' do
          set_user_status

          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end
    end

    describe 'GET' do
      it_behaves_like 'rendering user status'
    end

    describe 'PUT' do
      subject(:set_user_status) { put api(path, request_user), params: params }

      include_examples '/user/status successful response'

      include_examples '/user/status unsuccessful response'

      include_examples '/user/status passing nil for params'

      include_examples '/user/status clear_status_after field'

      context 'when passing empty params' do
        let(:request_user) { user_with_status }

        it 'deletes the status' do
          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(user_with_status.reset.status).to be_nil
        end
      end

      context 'when clear_status_after is not given' do
        let(:params) { { emoji: 'smirk', message: 'hello world' } }
        let(:request_user) { user_with_status }

        it 'unsets clear_status_at column' do
          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(user_with_status.reset.status.clear_status_at).to be_nil
        end
      end
    end

    describe 'PATCH' do
      subject(:set_user_status) { patch api(path, request_user), params: params }

      include_examples '/user/status successful response'

      include_examples '/user/status unsuccessful response'

      include_examples '/user/status passing nil for params'

      include_examples '/user/status clear_status_after field'

      context 'when passing empty params' do
        let(:request_user) { user_with_status }

        it 'does not update the status' do
          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(user_with_status.status).to eq(user_status)
        end
      end

      context 'when clear_status_after is not given' do
        let(:params) { { emoji: 'smirk', message: 'hello world' } }
        let(:request_user) { user_with_status }

        it 'does not unset clear_status_at column' do
          set_user_status

          expect(response).to have_gitlab_http_status(:success)
          expect(user_with_status.status.clear_status_at).not_to be_nil
        end
      end
    end
  end

  describe 'POST /users/:user_id/personal_access_tokens' do
    let(:name) { 'new pat' }
    let(:expires_at) { 3.days.from_now.to_date.to_s }
    let(:scopes) { %w(api read_user) }
    let(:path) { "/users/#{user.id}/personal_access_tokens" }
    let(:params) { { name: name, scopes: scopes, expires_at: expires_at } }

    it_behaves_like 'POST request permissions for admin mode'

    it 'returns error if required attributes are missing' do
      post api(path, admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('name is missing, scopes is missing, scopes does not have a valid value')
    end

    it 'returns a 404 error if user not found' do
      post api("/users/#{non_existing_record_id}/personal_access_tokens", admin, admin_mode: true), params: params

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns a 401 error when not authenticated' do
      post api(path), params: params

      expect(response).to have_gitlab_http_status(:unauthorized)
      expect(json_response['message']).to eq('401 Unauthorized')
    end

    it 'returns a 403 error when authenticated as normal user' do
      post api(path, user), params: params

      expect(response).to have_gitlab_http_status(:forbidden)
      expect(json_response['message']).to eq('403 Forbidden')
    end

    it 'creates a personal access token when authenticated as admin' do
      post api(path, admin, admin_mode: true), params: params

      expect(response).to have_gitlab_http_status(:created)
      expect(json_response['name']).to eq(name)
      expect(json_response['scopes']).to eq(scopes)
      expect(json_response['expires_at']).to eq(expires_at)
      expect(json_response['id']).to be_present
      expect(json_response['created_at']).to be_present
      expect(json_response['active']).to be_truthy
      expect(json_response['revoked']).to be_falsey
      expect(json_response['token']).to be_present
    end

    context 'when an error is thrown by the model' do
      let!(:admin_personal_access_token) { create(:personal_access_token, :admin_mode, user: admin) }
      let(:error_message) { 'error message' }

      before do
        allow_next_instance_of(PersonalAccessToken) do |personal_access_token|
          allow(personal_access_token).to receive_message_chain(:errors, :full_messages)
                                            .and_return([error_message])

          allow(personal_access_token).to receive(:save).and_return(false)
        end
      end

      it 'returns the error' do
        post api(path, personal_access_token: admin_personal_access_token), params: params

        expect(response).to have_gitlab_http_status(:unprocessable_entity)
        expect(json_response['message']).to eq(error_message)
      end
    end
  end

  describe 'GET /users/:user_id/impersonation_tokens' do
    let_it_be(:active_personal_access_token) { create(:personal_access_token, user: user) }
    let_it_be(:revoked_personal_access_token) { create(:personal_access_token, :revoked, user: user) }
    let_it_be(:expired_personal_access_token) { create(:personal_access_token, :expired, user: user) }
    let_it_be(:impersonation_token) { create(:personal_access_token, :impersonation, user: user) }
    let_it_be(:revoked_impersonation_token) { create(:personal_access_token, :impersonation, :revoked, user: user) }
    let(:path) { "/users/#{user.id}/impersonation_tokens" }

    it_behaves_like 'GET request permissions for admin mode'

    it 'returns a 404 error if user not found' do
      get api("/users/#{non_existing_record_id}/impersonation_tokens", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns a 403 error when authenticated as normal user' do
      get api("/users/#{non_existing_record_id}/impersonation_tokens", user)

      expect(response).to have_gitlab_http_status(:forbidden)
      expect(json_response['message']).to eq('403 Forbidden')
    end

    it 'returns an array of all impersonated tokens' do
      get api(path, admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to include_pagination_headers
      expect(json_response).to be_an Array
      expect(json_response.size).to eq(2)
    end

    it 'returns an array of active impersonation tokens if state active' do
      get api("#{path}?state=active", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to include_pagination_headers
      expect(json_response).to be_an Array
      expect(json_response.size).to eq(1)
      expect(json_response).to all(include('active' => true))
    end

    it 'returns an array of inactive personal access tokens if active is set to false' do
      get api("#{path}?state=inactive", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response).to be_an Array
      expect(json_response.size).to eq(1)
      expect(json_response).to all(include('active' => false))
    end
  end

  describe 'POST /users/:user_id/impersonation_tokens' do
    let(:name) { 'my new pat' }
    let(:expires_at) { '2016-12-28' }
    let(:scopes) { %w(api read_user) }
    let(:impersonation) { true }
    let(:path) { "/users/#{user.id}/impersonation_tokens" }
    let(:params) { { name: name, expires_at: expires_at, scopes: scopes, impersonation: impersonation } }

    it_behaves_like 'POST request permissions for admin mode'

    it 'returns validation error if impersonation token misses some attributes' do
      post api(path, admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:bad_request)
      expect(json_response['error']).to eq('name is missing')
    end

    it 'returns a 404 error if user not found' do
      post api("/users/#{non_existing_record_id}/impersonation_tokens", admin, admin_mode: true),
        params: {
          name: name,
          expires_at: expires_at
        }

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns a 403 error when authenticated as normal user' do
      post api(path, user),
        params: {
          name: name,
          expires_at: expires_at
        }

      expect(response).to have_gitlab_http_status(:forbidden)
      expect(json_response['message']).to eq('403 Forbidden')
    end

    it 'creates a impersonation token' do
      post api(path, admin, admin_mode: true), params: params

      expect(response).to have_gitlab_http_status(:created)
      expect(json_response['name']).to eq(name)
      expect(json_response['scopes']).to eq(scopes)
      expect(json_response['expires_at']).to eq(expires_at)
      expect(json_response['id']).to be_present
      expect(json_response['created_at']).to be_present
      expect(json_response['active']).to be_falsey
      expect(json_response['revoked']).to be_falsey
      expect(json_response['token']).to be_present
      expect(json_response['impersonation']).to eq(impersonation)
    end
  end

  describe 'GET /users/:user_id/impersonation_tokens/:impersonation_token_id' do
    let_it_be(:personal_access_token) { create(:personal_access_token, user: user) }
    let_it_be(:impersonation_token) { create(:personal_access_token, :impersonation, user: user) }
    let(:path) { "/users/#{user.id}/impersonation_tokens/#{impersonation_token.id}" }

    it_behaves_like 'GET request permissions for admin mode'

    it 'returns 404 error if user not found' do
      get api("/users/#{non_existing_record_id}/impersonation_tokens/1", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns a 404 error if impersonation token not found' do
      get api("/users/#{user.id}/impersonation_tokens/#{non_existing_record_id}", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Impersonation Token Not Found')
    end

    it 'returns a 404 error if token is not impersonation token' do
      get api("/users/#{user.id}/impersonation_tokens/#{personal_access_token.id}", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Impersonation Token Not Found')
    end

    it 'returns a 403 error when authenticated as normal user' do
      get api(path, user)

      expect(response).to have_gitlab_http_status(:forbidden)
      expect(json_response['message']).to eq('403 Forbidden')
    end

    it 'returns an impersonation token' do
      get api(path, admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['token']).not_to be_present
      expect(json_response['impersonation']).to be_truthy
    end
  end

  describe 'DELETE /users/:user_id/impersonation_tokens/:impersonation_token_id' do
    let_it_be(:personal_access_token) { create(:personal_access_token, user: user) }
    let_it_be(:impersonation_token) { create(:personal_access_token, :impersonation, user: user) }
    let(:path) { "/users/#{user.id}/impersonation_tokens/#{impersonation_token.id}" }

    it_behaves_like 'DELETE request permissions for admin mode'

    it 'returns a 404 error if user not found' do
      delete api("/users/#{non_existing_record_id}/impersonation_tokens/1", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 User Not Found')
    end

    it 'returns a 404 error if impersonation token not found' do
      delete api("/users/#{user.id}/impersonation_tokens/#{non_existing_record_id}", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Impersonation Token Not Found')
    end

    it 'returns a 404 error if token is not impersonation token' do
      delete api("/users/#{user.id}/impersonation_tokens/#{personal_access_token.id}", admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:not_found)
      expect(json_response['message']).to eq('404 Impersonation Token Not Found')
    end

    it 'returns a 403 error when authenticated as normal user' do
      delete api(path, user)

      expect(response).to have_gitlab_http_status(:forbidden)
      expect(json_response['message']).to eq('403 Forbidden')
    end

    it_behaves_like '412 response' do
      let(:request) { api(path, admin, admin_mode: true) }
    end

    it 'revokes a impersonation token' do
      delete api(path, admin, admin_mode: true)

      expect(response).to have_gitlab_http_status(:no_content)
      expect(impersonation_token.revoked).to be_falsey
      expect(impersonation_token.reload.revoked).to be_truthy
    end
  end

  describe 'GET /users/:id/associations_count' do
    let_it_be(:group) { create(:group) }
    let_it_be(:project) { create(:project, :public, group: group) }
    let(:path) { "/users/#{user.id}/associations_count" }
    let(:associations) do
      {
        groups_count: 1,
        projects_count: 1,
        issues_count: 2,
        merge_requests_count: 1
      }.as_json
    end

    before :all do
      group.add_member(user, Gitlab::Access::OWNER)
      project.add_member(user, Gitlab::Access::OWNER)
      create(:merge_request, source_project: project, source_branch: "my-personal-branch-1", author: user)
      create_list(:issue, 2, project: project, author: user)
    end

    it_behaves_like 'GET request permissions for admin mode'

    context 'as an unauthorized user' do
      it 'returns 401 unauthorized' do
        get api(path, nil)

        expect(response).to have_gitlab_http_status(:unauthorized)
      end
    end

    context 'as a non-admin user' do
      context 'with a different user id' do
        it 'returns 403 Forbidden' do
          get api("/users/#{omniauth_user.id}/associations_count", user)

          expect(response).to have_gitlab_http_status(:forbidden)
        end
      end

      context 'with the current user id' do
        it 'returns valid JSON response' do
          get api(path, user)

          expect(response).to have_gitlab_http_status(:ok)
          expect(json_response).to be_a Hash
          expect(json_response).to match(associations)
        end
      end
    end

    context 'as an admin user' do
      context 'with invalid user id' do
        it 'returns 404 User Not Found' do
          get api("/users/#{non_existing_record_id}/associations_count", admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:not_found)
        end
      end

      context 'with valid user id' do
        it 'returns valid JSON response' do
          get api(path, admin, admin_mode: true)

          expect(response).to have_gitlab_http_status(:ok)
          expect(json_response).to be_a Hash
          expect(json_response).to match(associations)
        end
      end
    end
  end

  it_behaves_like 'custom attributes endpoints', 'users' do
    let(:attributable) { user }
    let(:other_attributable) { admin }
  end

  describe 'POST /user/runners', feature_category: :runner_fleet do
    subject(:request) { post api(path, current_user, **post_args), params: runner_attrs }

    let_it_be(:group_owner) { create(:user) }
    let_it_be(:group) { create(:group) }
    let_it_be(:project) { create(:project, namespace: group) }

    let(:post_args) { { admin_mode: true } }
    let(:runner_attrs) { { runner_type: 'instance_type' } }
    let(:path) { '/user/runners' }

    before do
      group.add_owner(group_owner)
    end

    shared_context 'returns forbidden when user does not have sufficient permissions' do
      let(:current_user) { admin }
      let(:post_args) { { admin_mode: false } }

      it 'does not create a runner' do
        expect do
          request

          expect(response).to have_gitlab_http_status(:forbidden)
        end.not_to change { Ci::Runner.count }
      end
    end

    shared_examples 'creates a runner' do
      it 'creates a runner' do
        expect do
          request

          expect(response).to have_gitlab_http_status(:created)
        end.to change { Ci::Runner.count }.by(1)
      end
    end

    shared_examples 'fails to create runner with :bad_request' do
      it 'does not create runner' do
        expect do
          request

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(json_response['message']).to include(expected_error)
        end.not_to change { Ci::Runner.count }
      end
    end

    context 'when runner_type is :instance_type' do
      let(:runner_attrs) { { runner_type: 'instance_type' } }

      context 'when user has sufficient permissions' do
        let(:current_user) { admin }

        it_behaves_like 'creates a runner'
      end

      it_behaves_like 'returns forbidden when user does not have sufficient permissions'

      context 'when model validation fails' do
        let(:runner_attrs) { { runner_type: 'instance_type', run_untagged: false, tag_list: [] } }
        let(:current_user) { admin }

        it_behaves_like 'fails to create runner with :bad_request' do
          let(:expected_error) { 'Tags list can not be empty' }
        end
      end
    end

    context 'when runner_type is :group_type' do
      let(:post_args) { {} }

      context 'when group_id is specified' do
        let(:runner_attrs) { { runner_type: 'group_type', group_id: group.id } }

        context 'when user has sufficient permissions' do
          let(:current_user) { group_owner }

          it_behaves_like 'creates a runner'
        end

        it_behaves_like 'returns forbidden when user does not have sufficient permissions'
      end

      context 'when group_id is not specified' do
        let(:runner_attrs) { { runner_type: 'group_type' } }
        let(:current_user) { group_owner }

        it 'fails to create runner with :bad_request' do
          expect do
            request

            expect(response).to have_gitlab_http_status(:bad_request)
            expect(json_response['error']).to include('group_id is missing')
          end.not_to change { Ci::Runner.count }
        end
      end
    end

    context 'when runner_type is :project_type' do
      let(:post_args) { {} }

      context 'when project_id is specified' do
        let(:runner_attrs) { { runner_type: 'project_type', project_id: project.id } }

        context 'when user has sufficient permissions' do
          let(:current_user) { group_owner }

          it_behaves_like 'creates a runner'
        end

        it_behaves_like 'returns forbidden when user does not have sufficient permissions'
      end

      context 'when project_id is not specified' do
        let(:runner_attrs) { { runner_type: 'project_type' } }
        let(:current_user) { group_owner }

        it 'fails to create runner with :bad_request' do
          expect do
            request

            expect(response).to have_gitlab_http_status(:bad_request)
            expect(json_response['error']).to include('project_id is missing')
          end.not_to change { Ci::Runner.count }
        end
      end
    end

    context 'with missing runner_type' do
      let(:runner_attrs) { {} }
      let(:current_user) { admin }

      it 'fails to create runner with :bad_request' do
        expect do
          request

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(json_response['error']).to eq('runner_type is missing, runner_type does not have a valid value')
        end.not_to change { Ci::Runner.count }
      end
    end

    context 'with unknown runner_type' do
      let(:runner_attrs) { { runner_type: 'unknown' } }
      let(:current_user) { admin }

      it 'fails to create runner with :bad_request' do
        expect do
          request

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(json_response['error']).to eq('runner_type does not have a valid value')
        end.not_to change { Ci::Runner.count }
      end
    end

    it 'returns a 401 error if unauthorized' do
      post api(path), params: runner_attrs

      expect(response).to have_gitlab_http_status(:unauthorized)
    end
  end
end