~ursinha/launchpad/add-all-fl-tests

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
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Security policies for using content objects."""

__metaclass__ = type
__all__ = ['AuthorizationBase']

from zope.interface import implements, Interface
from zope.component import getAdapter, getUtility

from canonical.launchpad.interfaces.account import IAccount
from lp.registry.interfaces.announcement import IAnnouncement
from lp.soyuz.interfaces.archive import IArchive
from lp.soyuz.interfaces.archivepermission import (
    IArchivePermissionSet)
from lp.soyuz.interfaces.archiveauthtoken import IArchiveAuthToken
from lp.soyuz.interfaces.archivesubscriber import (
    IArchiveSubscriber, IPersonalArchiveSubscription)
from lp.code.interfaces.branch import (
    IBranch, user_has_special_branch_access)
from lp.code.interfaces.branchmergeproposal import (
    IBranchMergeProposal)
from lp.code.interfaces.branchsubscription import (
    IBranchSubscription)
from lp.bugs.interfaces.bug import IBug
from lp.bugs.interfaces.bugattachment import IBugAttachment
from lp.bugs.interfaces.bugbranch import IBugBranch
from lp.bugs.interfaces.bugnomination import IBugNomination
from lp.bugs.interfaces.bugtracker import IBugTracker
from lp.soyuz.interfaces.build import IBuild
from lp.soyuz.interfaces.builder import IBuilder, IBuilderSet
from lp.code.interfaces.codeimport import ICodeImport
from lp.code.interfaces.codeimportjob import (
    ICodeImportJobSet, ICodeImportJobWorkflow)
from lp.code.interfaces.codeimportmachine import (
    ICodeImportMachine)
from lp.code.interfaces.codereviewcomment import (
    ICodeReviewComment, ICodeReviewCommentDeletion)
from lp.code.interfaces.codereviewvote import (
    ICodeReviewVoteReference)
from lp.registry.interfaces.distribution import IDistribution
from lp.registry.interfaces.distributionmirror import (
    IDistributionMirror)
from lp.registry.interfaces.distributionsourcepackage import (
    IDistributionSourcePackage)
from lp.registry.interfaces.distroseries import IDistroSeries
from lp.translations.interfaces.distroserieslanguage import (
    IDistroSeriesLanguage)
from canonical.launchpad.interfaces.emailaddress import IEmailAddress
from lp.registry.interfaces.entitlement import IEntitlement
from canonical.launchpad.interfaces.hwdb import (
    IHWDBApplication, IHWDevice, IHWDeviceClass, IHWDriver, IHWDriverName,
    IHWDriverPackageName, IHWSubmission, IHWSubmissionDevice, IHWVendorID)
from lp.services.worlddata.interfaces.language import ILanguage, ILanguageSet
from lp.translations.interfaces.languagepack import ILanguagePack
from canonical.launchpad.interfaces.launchpad import (
    IBazaarApplication, IHasBug, IHasDrivers, ILaunchpadCelebrities)
from lp.registry.interfaces.role import IHasOwner
from lp.registry.interfaces.location import IPersonLocation
from lp.registry.interfaces.mailinglist import IMailingListSet
from lp.registry.interfaces.milestone import (
    IMilestone, IProjectMilestone)
from canonical.launchpad.interfaces.oauth import (
    IOAuthAccessToken, IOAuthRequestToken)
from lp.soyuz.interfaces.packageset import IPackagesetSet
from lp.translations.interfaces.pofile import IPOFile
from lp.translations.interfaces.potemplate import (
    IPOTemplate, IPOTemplateSubset)
from lp.soyuz.interfaces.publishing import (
    IBinaryPackagePublishingHistory, ISourcePackagePublishingHistory)
from lp.soyuz.interfaces.queue import (
    IPackageUpload, IPackageUploadQueue)
from canonical.launchpad.interfaces.packaging import IPackaging
from lp.registry.interfaces.person import (
    IPerson, ITeam, PersonVisibility)
from lp.registry.interfaces.pillar import IPillar
from lp.registry.interfaces.poll import (
    IPoll, IPollOption, IPollSubset)
from lp.registry.interfaces.product import IProduct, IProductSet
from lp.registry.interfaces.productrelease import (
    IProductRelease, IProductReleaseFile)
from lp.registry.interfaces.productseries import IProductSeries
from lp.registry.interfaces.project import IProject, IProjectSet
from lp.code.interfaces.seriessourcepackagebranch import (
    ISeriesSourcePackageBranch, IMakeOfficialBranchLinks)
from lp.registry.interfaces.sourcepackage import ISourcePackage
from lp.soyuz.interfaces.sourcepackagerelease import (
    ISourcePackageRelease)
from lp.blueprints.interfaces.specification import ISpecification
from lp.blueprints.interfaces.specificationbranch import (
    ISpecificationBranch)
from lp.blueprints.interfaces.specificationsubscription import (
    ISpecificationSubscription)
from lp.blueprints.interfaces.sprint import ISprint
from lp.blueprints.interfaces.sprintspecification import (
    ISprintSpecification)
from lp.registry.interfaces.teammembership import ITeamMembership
from lp.translations.interfaces.translationgroup import (
    ITranslationGroup, ITranslationGroupSet)
from lp.translations.interfaces.translationimportqueue import (
    ITranslationImportQueue, ITranslationImportQueueEntry)
from lp.translations.interfaces.translationsperson import (
    ITranslationsPerson)
from lp.translations.interfaces.translator import (
    ITranslator, IEditTranslator)

from canonical.launchpad.webapp.authorization import check_permission
from canonical.launchpad.webapp.interfaces import IAuthorization

from lp.answers.interfaces.faq import IFAQ
from lp.answers.interfaces.faqtarget import IFAQTarget
from lp.answers.interfaces.question import IQuestion
from lp.answers.interfaces.questiontarget import IQuestionTarget


class AuthorizationBase:
    implements(IAuthorization)
    permission = None
    usedfor = None

    def __init__(self, obj):
        self.obj = obj

    def checkUnauthenticated(self):
        """See `IAuthorization.checkUnauthenticated`.

        :return: True or False.
        """
        return False

    def checkAuthenticated(self, user):
        """Return True if the given person has the given permission.

        This method is implemented by security adapters that have not
        been updated to work in terms of IAccount.

        :return: True or False.
        """
        return False

    def checkAccountAuthenticated(self, account):
        """See `IAuthorization.checkAccountAuthenticated`.

        :return: True or False.
        """
        # For backward compatibility, delegate to one of
        # checkAuthenticated() or checkUnauthenticated().
        person = IPerson(account, None)
        if person is None:
            return self.checkUnauthenticated()
        else:
            return self.checkAuthenticated(person)


class ViewByLoggedInUser(AuthorizationBase):
    """The default ruleset for the launchpad.View permission.

    By default, any logged-in user can see anything. More restrictive
    rulesets are defined in other IAuthorization implementations.
    """
    permission = 'launchpad.View'
    usedfor = Interface

    def checkAuthenticated(self, user):
        """Any authenticated user can see this object."""
        return True


class AdminByAdminsTeam(AuthorizationBase):
    permission = 'launchpad.Admin'
    usedfor = Interface

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)


class AdminByCommercialTeamOrAdmins(AuthorizationBase):
    permission = 'launchpad.Commercial'
    usedfor = Interface

    def checkAuthenticated(self, user):
        celebrities = getUtility(ILaunchpadCelebrities)
        return (user.inTeam(celebrities.commercial_admin)
                or user.inTeam(celebrities.admin))


class ReviewByRegistryExpertsOrAdmins(AuthorizationBase):
    permission = 'launchpad.ProjectReview'
    usedfor = None

    def checkAuthenticated(self, user):
        celebrities = getUtility(ILaunchpadCelebrities)
        return (user.inTeam(celebrities.registry_experts)
                or user.inTeam(celebrities.admin))

class ReviewProduct(ReviewByRegistryExpertsOrAdmins):
    usedfor = IProduct


class ReviewProductSet(ReviewByRegistryExpertsOrAdmins):
    usedfor = IProductSet


class ReviewProject(ReviewByRegistryExpertsOrAdmins):
    usedfor = IProject


class ReviewProjectSet(ReviewByRegistryExpertsOrAdmins):
    usedfor = IProjectSet




class ViewPillar(AuthorizationBase):
    usedfor = IPillar
    permission = 'launchpad.View'

    def checkUnauthenticated(self):
        return self.obj.active

    def checkAuthenticated(self, user):
        """The Admins & Commercial Admins can see inactive pillars."""
        if self.obj.active:
            return True
        else:
            celebrities = getUtility(ILaunchpadCelebrities)
            return (user.inTeam(celebrities.commercial_admin)
                    or user.inTeam(celebrities.registry_experts)
                    or user.inTeam(celebrities.admin))


class EditAccount(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IAccount

    def checkAccountAuthenticated(self, account):
        if account == self.obj:
            return True
        user = IPerson(account, None)
        return (user is not None and
                user.inTeam(getUtility(ILaunchpadCelebrities).admin))


class ViewAccount(EditAccount):
    permission = 'launchpad.View'


class EditOAuthAccessToken(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IOAuthAccessToken

    def checkAuthenticated(self, user):
        return (self.obj.person == user
                or user.inTeam(getUtility(ILaunchpadCelebrities).admin))


class EditOAuthRequestToken(EditOAuthAccessToken):
    permission = 'launchpad.Edit'
    usedfor = IOAuthRequestToken


class EditBugNominationStatus(AuthorizationBase):
    permission = 'launchpad.Driver'
    usedfor = IBugNomination

    def checkAuthenticated(self, user):
        return self.obj.canApprove(user)


class EditByOwnersOrAdmins(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IHasOwner

    def checkAuthenticated(self, user):
        return (user.inTeam(self.obj.owner)
                or user.inTeam(getUtility(ILaunchpadCelebrities).admin))


class EditProduct(EditByOwnersOrAdmins):
    usedfor = IProduct


class EditPackaging(EditByOwnersOrAdmins):
    usedfor = IPackaging


class EditProductReleaseFile(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IProductReleaseFile

    def checkAuthenticated(self, user):
        return EditProductRelease(self.obj.productrelease).checkAuthenticated(
            user)


class AdminDistributionMirrorByDistroOwnerOrMirrorAdminsOrAdmins(
        AuthorizationBase):
    permission = 'launchpad.Admin'
    usedfor = IDistributionMirror

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.distribution.owner) or
                user.inTeam(admins) or
                user.inTeam(self.obj.distribution.mirror_admin))


class EditDistributionMirrorByOwnerOrDistroOwnerOrMirrorAdminsOrAdmins(
        AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IDistributionMirror

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.owner) or user.inTeam(admins) or
                user.inTeam(self.obj.distribution.owner) or
                user.inTeam(self.obj.distribution.mirror_admin))


class EditSpecificationBranch(AuthorizationBase):

    usedfor = ISpecificationBranch
    permission = 'launchpad.Edit'

    def checkAuthenticated(self, user):
        """See `IAuthorization.checkAuthenticated`.

        :return: True or False.
        """
        return True


class ViewSpecificationBranch(EditSpecificationBranch):

    permission = 'launchpad.View'

    def checkUnauthenticated(self):
        """See `IAuthorization.checkUnauthenticated`.

        :return: True or False.
        """
        return True


class EditSpecificationByTargetOwnerOrOwnersOrAdmins(AuthorizationBase):
    """We want everybody "related" to a specification to be able to edit it.
    You are related if you have a role on the spec, or if you have a role on
    the spec target (distro/product) or goal (distroseries/productseries).
    """

    permission = 'launchpad.Edit'
    usedfor = ISpecification

    def checkAuthenticated(self, user):
        assert self.obj.target
        admins = getUtility(ILaunchpadCelebrities).admin
        goaldrivers = []
        goalowner = None
        if self.obj.goal is not None:
            goalowner = self.obj.goal.owner
            goaldrivers = self.obj.goal.drivers
        for driver in goaldrivers:
            if user.inTeam(driver):
                return True
        return (user.inTeam(self.obj.target.owner) or
                user.inTeam(goalowner) or
                user.inTeam(self.obj.owner) or
                user.inTeam(self.obj.drafter) or
                user.inTeam(self.obj.assignee) or
                user.inTeam(self.obj.approver) or
                user.inTeam(admins))


class AdminSpecification(AuthorizationBase):
    permission = 'launchpad.Admin'
    usedfor = ISpecification

    def checkAuthenticated(self, user):
        assert self.obj.target
        targetowner = self.obj.target.owner
        targetdrivers = self.obj.target.drivers
        for driver in targetdrivers:
            if user.inTeam(driver):
                return True
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.target.owner) or
                user.inTeam(admins))


class DriverSpecification(AuthorizationBase):
    permission = 'launchpad.Driver'
    usedfor = ISpecification

    def checkAuthenticated(self, user):
        # If no goal is proposed for the spec then there can be no
        # drivers for it - we use launchpad.Driver on a spec to decide
        # if the person can see the page which lets you decide whether
        # to accept the goal, and if there is no goal then this is
        # extremely difficult to do :-)
        return (
            self.obj.goal and
            check_permission("launchpad.Driver", self.obj.goal))


class EditSprintSpecification(AuthorizationBase):
    """The sprint owner or driver can say what makes it onto the agenda for
    the sprint.
    """
    permission = 'launchpad.Driver'
    usedfor = ISprintSpecification

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.sprint.owner) or
                user.inTeam(self.obj.sprint.driver) or
                user.inTeam(admins))


class DriveSprint(AuthorizationBase):
    """The sprint owner or driver can say what makes it onto the agenda for
    the sprint.
    """
    permission = 'launchpad.Driver'
    usedfor = ISprint

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.owner) or
                user.inTeam(self.obj.driver) or
                user.inTeam(admins))


class Sprint(AuthorizationBase):
    """An attendee, owner, or driver of a sprint."""
    permission = 'launchpad.View'
    usedfor = ISprint

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.owner) or
                user.inTeam(self.obj.driver) or
                user in [attendance.attendee
                         for attendance in self.obj.attendances] or
                user.inTeam(admins))


class EditSpecificationSubscription(AuthorizationBase):
    """The subscriber, and people related to the spec or the target of the
    spec can determine who is essential."""
    permission = 'launchpad.Edit'
    usedfor = ISpecificationSubscription

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        if self.obj.specification.goal is not None:
            for driver in self.obj.specification.goal.drivers:
                if user.inTeam(driver):
                    return True
        else:
            for driver in self.obj.specification.target.drivers:
                if user.inTeam(driver):
                    return True
        return (user.inTeam(self.obj.person) or
                user.inTeam(self.obj.specification.owner) or
                user.inTeam(self.obj.specification.assignee) or
                user.inTeam(self.obj.specification.drafter) or
                user.inTeam(self.obj.specification.approver) or
                user.inTeam(admins))


class OnlyRosettaExpertsAndAdmins(AuthorizationBase):
    """Base class that allow access to Rosetta experts and Launchpad admins.
    """

    def checkAuthenticated(self, user):
        """Allow Launchpad's admins and Rosetta experts edit all fields."""
        celebrities = getUtility(ILaunchpadCelebrities)
        return (user.inTeam(celebrities.admin) or
                user.inTeam(celebrities.rosetta_experts))


class AdminProductTranslations(AuthorizationBase):
    permission = 'launchpad.TranslationsAdmin'
    usedfor = IProduct

    def checkAuthenticated(self, user):
        """Is the user able to manage `IProduct` translations settings?

        Any Launchpad/Launchpad Translations administrator or owners are
        able to change translation settings for a product.
        """
        celebrities = getUtility(ILaunchpadCelebrities)
        return (user.inTeam(self.obj.owner) or
                user.inTeam(celebrities.admin) or
                user.inTeam(celebrities.rosetta_experts))


class AdminSeriesByVCSImports(AuthorizationBase):
    permission = 'launchpad.Admin'
    usedfor = IProductSeries

    def checkAuthenticated(self, user):
        vcs_imports = getUtility(ILaunchpadCelebrities).vcs_imports
        return user.inTeam(vcs_imports)


class EditProjectMilestoneNever(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IProjectMilestone

    def checkAuthenticated(self, user):
        """IProjectMilestone is a fake content object."""
        return False

class EditMilestoneByTargetOwnerOrAdmins(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IMilestone

    def checkAuthenticated(self, user):
        """Authorize the product or distribution owner."""
        celebrities = getUtility(ILaunchpadCelebrities)
        if user.inTeam(celebrities.admin):
            return True
        if (self.obj.series_target is not None
            and user.inTeam(self.obj.series_target.driver)):
            # The user is a release manager.
            # XXX sinzui 2009-07-18 bug=40978: The series_target should never
            # be None, but Milestones in the production DB are like this.
            return True
        return user.inTeam(self.obj.target.owner)


class AdminMilestoneByLaunchpadAdmins(AuthorizationBase):
    permission = 'launchpad.Admin'
    usedfor = IMilestone

    def checkAuthenticated(self, user):
        """Only the Launchpad admins need this, we are only going to use it
        for connecting up series and distroseriess where we did not have
        them."""
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)


class EditTeamByTeamOwnerOrLaunchpadAdmins(AuthorizationBase):
    permission = 'launchpad.Owner'
    usedfor = ITeam

    def checkAuthenticated(self, user):
        """Only the team owner and Launchpad admins need this.
        """
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(self.obj.teamowner) or user.inTeam(admins)


class EditTeamByTeamOwnerOrTeamAdminsOrAdmins(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = ITeam

    def checkAuthenticated(self, user):
        """The team owner and team admins have launchpad.Edit on that team.

        The Launchpad admins also have launchpad.Edit on all teams.
        """
        return can_edit_team(self.obj, user)


class EditTeamMembershipByTeamOwnerOrTeamAdminsOrAdmins(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = ITeamMembership

    def checkAuthenticated(self, user):
        return can_edit_team(self.obj.team, user)


# XXX: 2008-08-01, salgado: At some point we should protect ITeamMembership
# with launchpad.View so that this adapter is used.  For now, though, it's
# going to be used only on the webservice (which explicitly checks for
# launchpad.View) so that we don't leak memberships of private teams.
class ViewTeamMembership(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = ITeamMembership

    def checkUnauthenticated(self):
        """Unauthenticated users can only view public memberships."""
        return self.obj.team.visibility == PersonVisibility.PUBLIC

    def checkAuthenticated(self, user):
        """Verify that the user can view the team's membership.

        Anyone can see a public team's membership. Only a team member or
        a Launchpad admin can view a private membership.
        """
        if self.obj.team.visibility == PersonVisibility.PUBLIC:
            return True
        admins = getUtility(ILaunchpadCelebrities).admin
        if user.inTeam(admins) or user.inTeam(self.obj.team):
            return True
        return False


class EditPersonBySelfOrAdmins(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IPerson

    def checkAuthenticated(self, user):
        """A user can edit the Person who is herself.

        The admin team can also edit any Person.
        """
        admins = getUtility(ILaunchpadCelebrities).admin
        return self.obj.id == user.id or user.inTeam(admins)


class EditTranslationsPersonByPerson(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = ITranslationsPerson

    def checkAuthenticated(self, user):
        person = self.obj.person
        admins = getUtility(ILaunchpadCelebrities).admin
        return person == user or user.inTeam(admins)


class EditPersonLocation(AuthorizationBase):
    permission = 'launchpad.EditLocation'
    usedfor = IPerson

    def checkAuthenticated(self, user):
        """Anybody can edit a person's location until that person sets it.

        Once a person sets his own location that information can only be
        changed by the person himself or admins.
        """
        location = self.obj.location
        if location is None:
            # No PersonLocation entry exists for this person, so anybody can
            # change this person's location.
            return True

        # There is a PersonLocation entry for this person, so we'll check its
        # details to find out whether or not the user can edit them.
        if (location.visible
            and (location.latitude is None
                 or location.last_modified_by != self.obj)):
            # No location has been specified yet or it has been specified
            # by a non-authoritative source (not the person himself), so
            # anybody can change it.
            return True
        else:
            admins = getUtility(ILaunchpadCelebrities).admin
            # The person himself and LP admins can always change that person's
            # location.
            return user == self.obj or user.inTeam(admins)


class ViewPersonLocation(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = IPersonLocation

    def checkUnauthenticated(self):
        return self.obj.visible

    def checkAuthenticated(self, user):
        if self.obj.visible:
            return True
        else:
            admins = getUtility(ILaunchpadCelebrities).admin
            return user == self.obj.person or user.inTeam(admins)


class EditPersonBySelf(AuthorizationBase):
    permission = 'launchpad.Special'
    usedfor = IPerson

    def checkAuthenticated(self, user):
        """A user can edit the Person who is herself."""
        return self.obj.id == user.id


class EditAccountBySelf(AuthorizationBase):
    permission = 'launchpad.Special'
    usedfor = IAccount

    def checkAccountAuthenticated(self, account):
        """A user can edit the Account who is herself."""
        return self.obj == account


class ViewPublicOrPrivateTeamMembers(AuthorizationBase):
    """Restrict viewing of private memberships of teams.

    Only members of a team with a private membership can view the
    membership list.
    """
    permission = 'launchpad.View'
    usedfor = IPerson

    def checkUnauthenticated(self):
        """Unauthenticated users can only view public memberships."""
        if self.obj.visibility == PersonVisibility.PUBLIC:
            return True
        return False

    def checkAccountAuthenticated(self, account):
        """See `IAuthorization.checkAccountAuthenticated`.

        Verify that the user can view the team's membership.

        Anyone can see a public team's membership. Only a team member
        or a Launchpad admin can view a private membership.
        """
        if self.obj.visibility == PersonVisibility.PUBLIC:
            return True
        user = IPerson(account, None)
        if user is None:
            return False
        admins = getUtility(ILaunchpadCelebrities).admin
        if user.inTeam(admins) or user.inTeam(self.obj):
            return True
        return False


class EditPollByTeamOwnerOrTeamAdminsOrAdmins(
        EditTeamMembershipByTeamOwnerOrTeamAdminsOrAdmins):
    permission = 'launchpad.Edit'
    usedfor = IPoll


class EditPollSubsetByTeamOwnerOrTeamAdminsOrAdmins(
        EditPollByTeamOwnerOrTeamAdminsOrAdmins):
    permission = 'launchpad.Edit'
    usedfor = IPollSubset


class EditPollOptionByTeamOwnerOrTeamAdminsOrAdmins(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IPollOption

    def checkAuthenticated(self, user):
        return can_edit_team(self.obj.poll.team, user)


class AdminDistribution(AdminByAdminsTeam):
    """Soyuz involves huge chunks of data in the archive and librarian,
    so for the moment we are locking down admin and edit on distributions
    and distroseriess to the Launchpad admin team."""
    permission = 'launchpad.Admin'
    usedfor = IDistribution


class EditDistributionByDistroOwnersOrAdmins(AuthorizationBase):
    """The owner of a distribution should be able to edit its
    information; it is mainly administrative data, such as bug
    contacts. Note that creation of new distributions and distribution
    series is still protected with launchpad.Admin"""
    permission = 'launchpad.Edit'
    usedfor = IDistribution

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.owner) or
                user.inTeam(admins))


class AppendDistributionByDriversOrOwnersOrAdmins(AuthorizationBase):
    """Distribution drivers, owners, and admins may plan releases.

    Drivers of `IDerivativeDistribution`s can create series. Owners and
    admins can create series for all `IDistribution`s.
    """
    permission = 'launchpad.Append'
    usedfor = IDistribution

    def checkAuthenticated(self, user):
        if user.inTeam(self.obj.driver) and not self.obj.full_functionality:
            # Drivers of derivative distributions can create a series that
            # they will be the release manager for.
            return True
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.owner) or
                user.inTeam(admins))


class EditDistributionSourcePackageByDistroOwnersOrAdmins(AuthorizationBase):
    """The owner of a distribution should be able to edit its source
    package information"""
    permission = 'launchpad.Edit'
    usedfor = IDistributionSourcePackage

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.distribution.owner) or
                user.inTeam(admins))


class AdminDistroSeries(AdminByAdminsTeam):
    """Soyuz involves huge chunks of data in the archive and librarian,
    so for the moment we are locking down admin and edit on distributions
    and distroseriess to the Launchpad admin team.

    NB: Please consult with SABDFL before modifying this permission because
        changing it could cause the archive to get rearranged, with tons of
        files moved to the new namespace, and mirrors would get very very
        upset. Then James T would be on your case.
    """
    permission = 'launchpad.Admin'
    usedfor = IDistroSeries


class EditDistroSeriesByOwnersOrDistroOwnersOrAdmins(AuthorizationBase):
    """The owner of the distro series should be able to modify some of the
    fields on the IDistroSeries

    NB: there is potential for a great mess if this is not done correctly so
    please consult with Kiko and MDZ on the mailing list before modifying
    these permissions.
    """
    permission = 'launchpad.Edit'
    usedfor = IDistroSeries

    def checkAuthenticated(self, user):
        if (user.inTeam(self.obj.driver)
            and not self.obj.distribution.full_functionality):
            # The series driver (release manager) may edit a series if the
            # distribution is an `IDerivativeDistribution`
            return True
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.owner) or
                user.inTeam(self.obj.distribution.owner) or
                user.inTeam(admins))


class SeriesDrivers(AuthorizationBase):
    """Drivers can approve or decline features and target bugs.

    Drivers exist for distribution and product series.  Distribution and
    product owners are implicitly drivers too.
    """
    permission = 'launchpad.Driver'
    usedfor = IHasDrivers

    def checkAuthenticated(self, user):
        for driver in self.obj.drivers:
            if user.inTeam(driver):
                return True
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(self.obj.owner) or user.inTeam(admins)


class ViewProductSeries(AuthorizationBase):

    usedfor = IProductSeries
    permision = 'launchpad.View'

    def checkUnauthenticated(self):
        """See `IAuthorization.checkUnauthenticated`.

        :return: True or False.
        """
        return True

    def checkAuthenticated(self, user):
        """See `IAuthorization.checkAuthenticated`.

        :return: True or False.
        """
        return True


class EditProductSeries(EditByOwnersOrAdmins):
    usedfor = IProductSeries

    def checkAuthenticated(self, user):
        """Allow product owner, Rosetta Experts, or admins."""
        if (user.inTeam(self.obj.product.owner) or
            user.inTeam(self.obj.driver)):
            # The user is the owner of the product, or the release manager.
            return True
        # Rosetta experts need to be able to upload translations.
        rosetta_experts = getUtility(ILaunchpadCelebrities).rosetta_experts
        if user.inTeam(rosetta_experts):
            return True
        return EditByOwnersOrAdmins.checkAuthenticated(
            self, user)


class EditBugTask(AuthorizationBase):
    """Permission checker for editing objects linked to a bug.

    Allow any logged-in user to edit objects linked to public
    bugs. Allow only explicit subscribers to edit objects linked to
    private bugs.
    """
    permission = 'launchpad.Edit'
    usedfor = IHasBug

    def checkAuthenticated(self, user):
        admins = getUtility(ILaunchpadCelebrities).admin

        if user.inTeam(admins):
            # Admins can always edit bugtasks, whether they're reported on a
            # private bug or not.
            return True

        if not self.obj.bug.private:
            # This is a public bug, so anyone can edit it.
            return True
        else:
            # This is a private bug, and we know the user isn't an admin, so
            # we'll only allow editing if the user is explicitly subscribed to
            # this bug.
            for subscription in self.obj.bug.subscriptions:
                if user.inTeam(subscription.person):
                    return True

            return False


class PublicToAllOrPrivateToExplicitSubscribersForBugTask(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = IHasBug

    def checkAuthenticated(self, user):
        return self.obj.bug.userCanView(user)

    def checkUnauthenticated(self):
        """Allow anonymous users to see non-private bugs only."""
        return not self.obj.bug.private


class EditPublicByLoggedInUserAndPrivateByExplicitSubscribers(
    AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IBug

    def checkAuthenticated(self, user):
        """Allow any logged in user to edit a public bug, and only
        explicit subscribers to edit private bugs.
        """
        admins = getUtility(ILaunchpadCelebrities).admin
        if not self.obj.private:
            # This is a public bug.
            return True
        elif user.inTeam(admins):
            # Admins can edit all bugs.
            return True
        else:
            # This is a private bug. Only explicit subscribers may edit it.
            for subscription in self.obj.subscriptions:
                if user.inTeam(subscription.person):
                    return True

        return False

    def checkUnauthenticated(self):
        """Never allow unauthenticated users to edit a bug."""
        return False


class PublicToAllOrPrivateToExplicitSubscribersForBug(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = IBug

    def checkAuthenticated(self, user):
        """Allow any user to see non-private bugs, but only explicit
        subscribers to see private bugs.
        """
        return self.obj.userCanView(user)

    def checkUnauthenticated(self):
        """Allow anonymous users to see non-private bugs only."""
        return not self.obj.private


class EditBugBranch(EditPublicByLoggedInUserAndPrivateByExplicitSubscribers):
    permission = 'launchpad.Edit'
    usedfor = IBugBranch

    def __init__(self, bug_branch):
        # The same permissions as for the BugBranch's bug should apply
        # to the BugBranch itself.
        EditPublicByLoggedInUserAndPrivateByExplicitSubscribers.__init__(
            self, bug_branch.bug)


class ViewBugAttachment(PublicToAllOrPrivateToExplicitSubscribersForBug):
    """Security adapter for viewing a bug attachment.

    If the user is authorized to view the bug, he's allowed to view the
    attachment.
    """
    permission = 'launchpad.View'
    usedfor = IBugAttachment

    def __init__(self, bugattachment):
        PublicToAllOrPrivateToExplicitSubscribersForBug.__init__(
            self, bugattachment.bug)


class EditBugAttachment(
    EditPublicByLoggedInUserAndPrivateByExplicitSubscribers):
    """Security adapter for editing a bug attachment.

    If the user is authorized to view the bug, he's allowed to edit the
    attachment.
    """
    permission = 'launchpad.Edit'
    usedfor = IBugAttachment

    def __init__(self, bugattachment):
        EditPublicByLoggedInUserAndPrivateByExplicitSubscribers.__init__(
            self, bugattachment.bug)


class ViewAnnouncement(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = IAnnouncement

    def checkUnauthenticated(self):
        """Let anonymous users see published announcements."""
        if self.obj.published:
            return True
        return False

    def checkAuthenticated(self, user):
        """Keep project news invisible to end-users unless they are project
        admins, until the announcements are published."""

        # Every user can view published announcements.
        if self.obj.published:
            return True

        # Project drivers can view any project announcements.
        assert self.obj.target
        if self.obj.target.drivers:
            for driver in self.obj.target.drivers:
                if user.inTeam(driver):
                    return True
        if user.inTeam(self.obj.target.owner):
            return True

        # Launchpad admins can view any announcement.
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)


class EditAnnouncement(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IAnnouncement

    def checkAuthenticated(self, user):
        """Allow the project owner and drivers to edit any project news."""

        assert self.obj.target
        if self.obj.target.drivers:
            for driver in self.obj.target.drivers:
                if user.inTeam(driver):
                    return True
        if user.inTeam(self.obj.target.owner):
            return True

        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)


class UseApiDoc(AuthorizationBase):
    permission = 'zope.app.apidoc.UseAPIDoc'
    usedfor = Interface

    def checkAuthenticated(self, user):
        return True


class OnlyBazaarExpertsAndAdmins(AuthorizationBase):
    """Base class that allows only the Launchpad admins and Bazaar
    experts."""

    def checkAuthenticated(self, user):
        bzrexperts = getUtility(ILaunchpadCelebrities).bazaar_experts
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins) or user.inTeam(bzrexperts)


class OnlyVcsImportsAndAdmins(AuthorizationBase):
    """Base class that allows only the Launchpad admins and VCS Imports
    experts."""

    def checkAuthenticated(self, user):
        vcsexpert = getUtility(ILaunchpadCelebrities).vcs_imports
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins) or user.inTeam(vcsexpert)


class AdminTheBazaar(OnlyVcsImportsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = IBazaarApplication


class EditCodeImport(OnlyVcsImportsAndAdmins):
    """Control who can edit the object view of a CodeImport.

    Currently, we restrict the visibility of the new code import
    system to members of ~vcs-imports and Launchpad admins.
    """
    permission = 'launchpad.Edit'
    usedfor = ICodeImport


class SeeCodeImportJobSet(OnlyVcsImportsAndAdmins):
    """Control who can see the CodeImportJobSet utility.

    Currently, we restrict the visibility of the new code import
    system to members of ~vcs-imports and Launchpad admins.
    """
    permission = 'launchpad.View'
    usedfor = ICodeImportJobSet


class EditCodeImportJobWorkflow(OnlyVcsImportsAndAdmins):
    """Control who can use the CodeImportJobWorkflow utility.

    Currently, we restrict the visibility of the new code import
    system to members of ~vcs-imports and Launchpad admins.
    """
    permission = 'launchpad.Edit'
    usedfor = ICodeImportJobWorkflow


class EditCodeImportMachine(OnlyVcsImportsAndAdmins):
    """Control who can edit the object view of a CodeImportMachine.

    Access is restricted to members of ~vcs-imports and Launchpad admins.
    """
    permission = 'launchpad.Edit'
    usedfor = ICodeImportMachine


class AdminPOTemplateDetails(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = IPOTemplate

    def checkAuthenticated(self, user):
        """Allow LP/Translations admins, and for distros, owners and
        translation group owners.
        """
        if OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user):
            return True

        template = self.obj
        if template.distroseries is not None:
            distro = template.distroseries.distribution
            if user.inTeam(distro.owner):
                return True
            translation_group = distro.translationgroup
            if translation_group and user.inTeam(translation_group.owner):
                return True

        return False


class EditPOTemplateDetails(AdminPOTemplateDetails, EditByOwnersOrAdmins):
    permission = 'launchpad.Edit'
    usedfor = IPOTemplate

    def checkAuthenticated(self, user):
        """Allow anyone with admin rights; owners, product owners and
        distribution owners; and for distros, translation group owners.
        """
        if (self.obj.productseries is not None and
            user.inTeam(self.obj.productseries.product.owner)):
            # The user is the owner of the product.
            return True

        return (
            AdminPOTemplateDetails.checkAuthenticated(self, user) or
            EditByOwnersOrAdmins.checkAuthenticated(self, user))


# XXX: Carlos Perello Marin 2005-05-24 bug=753:
# This should be using SuperSpecialPermissions when implemented.
class AddPOTemplate(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Append'
    usedfor = IProductSeries


class EditPOFileDetails(EditByOwnersOrAdmins):
    usedfor = IPOFile

    def checkAuthenticated(self, user):
        """Allow anyone that can edit translations, owner, experts and admis.
        """
        rosetta_experts = getUtility(ILaunchpadCelebrities).rosetta_experts

        return (EditByOwnersOrAdmins.checkAuthenticated(self, user) or
                self.obj.canEditTranslations(user) or
                user.inTeam(rosetta_experts))


class AdminTranslator(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = ITranslator

    def checkAuthenticated(self, user):
        """Allow the owner of a translation group to edit the translator
        of any language in the group."""
        return (user.inTeam(self.obj.translationgroup.owner) or
                OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user))


class EditTranslator(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Edit'
    usedfor = IEditTranslator

    def checkAuthenticated(self, user):
        """Allow the translator and the group owner to edit parts of
        the translator entry."""
        return (user.inTeam(self.obj.translator) or
                user.inTeam(self.obj.translationgroup.owner) or
                OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user))


class EditTranslationGroup(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Edit'
    usedfor = ITranslationGroup

    def checkAuthenticated(self, user):
        """Allow the owner of a translation group to edit the translator
        of any language in the group."""
        return (user.inTeam(self.obj.owner) or
                OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user))


class EditTranslationGroupSet(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = ITranslationGroupSet


class DownloadFullSourcePackageTranslations(OnlyRosettaExpertsAndAdmins):
    """Restrict full `SourcePackage` translation downloads.

    Experience shows that the export queue can easily get swamped by
    large export requests.  Email leads us to believe that many of the
    users making these requests are looking for language packs, or for
    individual translations rather than the whole package.  That's why
    this class defines who is allowed to make those requests.
    """

    permission = 'launchpad.ExpensiveRequest'
    usedfor = ISourcePackage

    def _userInAnyOfTheTeams(self, user, archive_permissions):
        if archive_permissions is None or len(archive_permissions) == 0:
            return False
        for permission in archive_permissions:
            if user.inTeam(permission.person):
                return True
        return False

    def checkAuthenticated(self, user):
        """Define who may download these translations.

        Admins and Translations admins have access, as does the owner of
        the translation group (if applicable) and distribution uploaders.
        """
        distribution = self.obj.distribution
        translation_group = distribution.translationgroup
        return (
            # User is admin of some relevant kind.
            OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user) or
            # User is part of the 'driver' team for the distribution.
            (self._userInAnyOfTheTeams(user, distribution.uploaders)) or
            # User is owner of applicable translation group.
            (translation_group is not None and
             user.inTeam(translation_group.owner)))


class EditBugTracker(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IBugTracker

    def checkAuthenticated(self, user):
        """Any logged-in user can edit a bug tracker."""
        return True


class EditProductRelease(EditByOwnersOrAdmins):
    permission = 'launchpad.Edit'
    usedfor = IProductRelease

    def checkAuthenticated(self, user):
        if (user.inTeam(self.obj.productseries.owner) or
            user.inTeam(self.obj.productseries.product.owner) or
            user.inTeam(self.obj.productseries.driver)):
            # The user is an owner or a release manager.
            return True
        return EditByOwnersOrAdmins.checkAuthenticated(
            self, user)


class AdminTranslationImportQueueEntry(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = ITranslationImportQueueEntry

    def checkAuthenticated(self, user):
        if OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user):
            return True

        # As a special case, the Ubuntu translation group owners can
        # manage Ubuntu uploads.
        if self.obj.is_targeted_to_ubuntu:
            group = self.obj.distroseries.distribution.translationgroup
            if group is not None and user.inTeam(group.owner):
                return True

        return False


class EditTranslationImportQueueEntry(AdminTranslationImportQueueEntry):
    permission = 'launchpad.Edit'
    usedfor = ITranslationImportQueueEntry

    def checkAuthenticated(self, user):
        """Anyone who can admin an entry, plus its owner, can edit it.
        """
        if AdminTranslationImportQueueEntry.checkAuthenticated(self, user):
            return True
        if user.inTeam(self.obj.importer):
            return True

        return False


class AdminTranslationImportQueue(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = ITranslationImportQueue


class EditPackageUploadQueue(AdminByAdminsTeam):
    permission = 'launchpad.Edit'
    usedfor = IPackageUploadQueue

    def checkAuthenticated(self, user):
        """Check user presence in admins or distroseries upload admin team."""
        if AdminByAdminsTeam.checkAuthenticated(self, user):
            return True

        permission_set = getUtility(IArchivePermissionSet)
        permissions = permission_set.componentsForQueueAdmin(
            self.obj.distroseries.main_archive, user)
        return permissions.count() > 0


class EditPackageUpload(AdminByAdminsTeam):
    permission = 'launchpad.Edit'
    usedfor = IPackageUpload

    def checkAuthenticated(self, user):
        """Return True if user has an ArchivePermission or is an admin.

        If it's a delayed-copy, check if the user can upload to its targeted
        archive.
        """
        if AdminByAdminsTeam.checkAuthenticated(self, user):
            return True

        if self.obj.is_delayed_copy:
            archive_append = AppendArchive(self.obj.archive)
            return archive_append.checkAuthenticated(user)

        permission_set = getUtility(IArchivePermissionSet)
        permissions = permission_set.componentsForQueueAdmin(
            self.obj.archive, user)
        if permissions.count() == 0:
            return False
        allowed_components = set(
            permission.component for permission in permissions)
        existing_components = self.obj.components
        # The intersection of allowed_components and
        # existing_components must be equal to existing_components
        # to allow the operation to go ahead.
        return (allowed_components.intersection(existing_components)
                == existing_components)


class AdminByBuilddAdmin(AuthorizationBase):
    permission = 'launchpad.Admin'

    def checkAuthenticated(self, user):
        """Allow admins and buildd_admins."""
        lp_admin = getUtility(ILaunchpadCelebrities).admin
        if user.inTeam(lp_admin):
            return True
        buildd_admin = getUtility(ILaunchpadCelebrities).buildd_admin
        return user.inTeam(buildd_admin)


class AdminBuilderSet(AdminByBuilddAdmin):
    usedfor = IBuilderSet


class AdminBuilder(AdminByBuilddAdmin):
    usedfor = IBuilder


# XXX cprov 2006-07-31: As soon as we have external builders, as presumed
# in the original plan, we should grant some rights to the owners and
# that's what Edit is for.
class EditBuilder(AdminByBuilddAdmin):
    permission = 'launchpad.Edit'
    usedfor = IBuilder


class AdminBuildRecord(AdminByBuilddAdmin):
    usedfor = IBuild


class EditBuildRecord(AdminByBuilddAdmin):
    permission = 'launchpad.Edit'
    usedfor = IBuild

    def checkAuthenticated(self, user):
        """Check write access for user and different kinds of archives.

        Allow
            * BuilddAdmins, for any archive.
            * The PPA owner for PPAs
            * users with upload permissions (for the respective distribution)
              otherwise.
        """
        if AdminByBuilddAdmin.checkAuthenticated(self, user):
            return True

        # If it's a PPA or a copy archive only allow its owner.
        if self.obj.archive.is_ppa or self.obj.archive.is_copy:
            return (self.obj.archive.owner and
                    user.inTeam(self.obj.archive.owner))

        # Primary or partner section here: is the user in question allowed
        # to upload to the respective component? Allow user to retry build
        # if so.
        if self.obj.archive.canUpload(user, self.obj.current_component):
            return True
        else:
            return self.obj.archive.canUpload(
                user, self.obj.sourcepackagerelease.sourcepackagename)


class ViewBuildRecord(EditBuildRecord):
    permission = 'launchpad.View'

    # This code MUST match the logic in IBuildSet.getBuildsForBuilder()
    # otherwise users are likely to get 403 errors, or worse.

    def checkAuthenticated(self, user):
        """Private restricts to admins and archive members."""
        if not self.obj.archive.private:
            # Anyone can see non-private archives.
            return True

        if user.inTeam(self.obj.archive.owner):
            # Anyone in the PPA team gets the nod.
            return True

        # LP admins may also see it.
        lp_admin = getUtility(ILaunchpadCelebrities).admin
        if user.inTeam(lp_admin):
            return True

        # If the permission check on the sourcepackagerelease for this
        # build passes then it means the build can be released from
        # privacy since the source package is published publicly.
        # This happens when copy-package is used to re-publish a private
        # package in the primary archive.
        auth_spr = ViewSourcePackageRelease(self.obj.sourcepackagerelease)
        if auth_spr.checkAuthenticated(user):
            return True

        # You're not a celebrity, get out of here.
        return False

    def checkUnauthenticated(self):
        """Unauthenticated users can see the build if it's not private."""
        if not self.obj.archive.private:
            return True

        # See comment above.
        auth_spr = ViewSourcePackageRelease(self.obj.sourcepackagerelease)
        return auth_spr.checkUnauthenticated()


class AdminQuestion(AdminByAdminsTeam):
    permission = 'launchpad.Admin'
    usedfor = IQuestion

    def checkAuthenticated(self, user):
        """Allow only admins and owners of the question pillar target."""
        context = self.obj.product or self.obj.distribution
        return (AdminByAdminsTeam.checkAuthenticated(self, user) or
                user.inTeam(context.owner))


class ModerateQuestion(AdminQuestion):
    permission = 'launchpad.Moderate'
    usedfor = IQuestion

    def checkAuthenticated(self, user):
        """Allow user who can administer the question and answer contacts."""
        if AdminQuestion.checkAuthenticated(self, user):
            return True
        for answer_contact in self.obj.target.answer_contacts:
            if user.inTeam(answer_contact):
                return True
        return False


class QuestionOwner(AuthorizationBase):
    permission = 'launchpad.Owner'
    usedfor = IQuestion

    def checkAuthenticated(self, user):
        """Allow the question's owner."""
        return user.inTeam(self.obj.owner)


class ModerateFAQTarget(EditByOwnersOrAdmins):
    permission = 'launchpad.Moderate'
    usedfor = IFAQTarget

    def checkAuthenticated(self, user):
        """Allow people with launchpad.Edit or an answer contact."""
        if EditByOwnersOrAdmins.checkAuthenticated(self, user):
            return True
        if IQuestionTarget.providedBy(self.obj):
            for answer_contact in self.obj.answer_contacts:
                if user.inTeam(answer_contact):
                    return True
        return False


class EditFAQ(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IFAQ

    def checkAuthenticated(self, user):
        """Everybody who has launchpad.Moderate on the FAQ target is allowed.
        """
        return ModerateFAQTarget(self.obj.target).checkAuthenticated(user)


def can_edit_team(team, user):
    """Return True if the given user has edit rights for the given team."""
    if user.inTeam(getUtility(ILaunchpadCelebrities).admin):
        return True
    else:
        return team in user.getAdministratedTeams()


class AdminLanguageSet(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = ILanguageSet


class AdminLanguage(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = ILanguage


class AccessBranch(AuthorizationBase):
    """Controls visibility of branches.

    A person can see the branch if the branch is public, they are the owner
    of the branch, they are in the team that owns the branch, subscribed to
    the branch, or a launchpad administrator.
    """
    permission = 'launchpad.View'
    usedfor = IBranch

    def _checkBranchAuthenticated(self, branch, user):
        if not branch.private:
            return True
        if user.inTeam(branch.owner):
            return True
        for subscriber in branch.subscribers:
            if user.inTeam(subscriber):
                return True
        return user_has_special_branch_access(user)

    def checkAuthenticated(self, user, checked_branches=None):
        if checked_branches is None:
            checked_branches = []
        if self.obj in checked_branches:
            return True
        can_access = self._checkBranchAuthenticated(self.obj, user)
        if can_access and self.obj.stacked_on is not None:
            checked_branches.append(self.obj)
            access = getAdapter(
                self.obj.stacked_on, IAuthorization, name='launchpad.View')
            can_access = access.checkAuthenticated(user, checked_branches)
        return can_access

    def checkUnauthenticated(self, checked_branches=None):
        if checked_branches is None:
            checked_branches = []
        if self.obj in checked_branches:
            return True
        can_access = not self.obj.private
        if can_access and self.obj.stacked_on is not None:
            checked_branches.append(self.obj)
            access = getAdapter(
                self.obj.stacked_on, IAuthorization, name='launchpad.View')
            can_access = access.checkUnauthenticated(checked_branches)
        return can_access


class EditBranch(AuthorizationBase):
    """The owner, bazaar experts or admins can edit branches."""
    permission = 'launchpad.Edit'
    usedfor = IBranch

    def checkAuthenticated(self, user):
        return (user.inTeam(self.obj.owner) or
                user_has_special_branch_access(user))


class AdminBranch(AuthorizationBase):
    """The bazaar experts or admins can administer branches."""
    permission = 'launchpad.Admin'
    usedfor = IBranch

    def checkAuthenticated(self, user):
        celebs = getUtility(ILaunchpadCelebrities)
        return (user.inTeam(celebs.admin) or
                user.inTeam(celebs.bazaar_experts))


class AdminPOTemplateSubset(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = IPOTemplateSubset


class AdminDistroSeriesLanguage(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.Admin'
    usedfor = IDistroSeriesLanguage


class AdminDistroSeriesTranslations(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.TranslationsAdmin'
    usedfor = IDistroSeries


class BranchSubscriptionEdit(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IBranchSubscription

    def checkAuthenticated(self, user):
        """Is the user able to edit a branch subscription?

        Any team member can edit a branch subscription for their team.
        Launchpad Admins can also edit any branch subscription.
        """
        celebs = getUtility(ILaunchpadCelebrities)
        return (user.inTeam(self.obj.person) or
                user.inTeam(celebs.admin) or
                user.inTeam(celebs.bazaar_experts))


class BranchSubscriptionView(BranchSubscriptionEdit):
    permission = 'launchpad.View'


class BranchMergeProposalView(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = IBranchMergeProposal

    def checkAuthenticated(self, user):
        """Is the user able to view the branch merge proposal?

        The user can see a merge proposal between two branches
        that the user can see.
        """
        return (AccessBranch(self.obj.source_branch).checkAuthenticated(user)
                and
                AccessBranch(self.obj.target_branch).checkAuthenticated(user))

    def checkUnauthenticated(self):
        """Is anyone able to view the branch merge proposal?

        Anyone can see a merge proposal between two public branches.
        """
        return (AccessBranch(self.obj.source_branch).checkUnauthenticated()
                and
                AccessBranch(self.obj.target_branch).checkUnauthenticated())


class CodeReviewVoteReferenceEdit(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = ICodeReviewVoteReference

    def checkAuthenticated(self, user):
        """Only the affected teams may change the review request.

        The registrant may reassign the request to another entity.
        A member of the review team may assign it to themselves.
        A person to whom it is assigned may delegate it to someone else.
        """
        return (user.inTeam(self.obj.reviewer) or
                user.inTeam(self.obj.registrant))


class CodeReviewCommentView(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = ICodeReviewComment

    def checkAuthenticated(self, user):
        """Is the user able to view the code review comment?

        The user can see a code review comment if they can see the branch
        merge proposal.
        """
        bmp_checker = BranchMergeProposalView(self.obj.branch_merge_proposal)
        return bmp_checker.checkAuthenticated(user)

    def checkUnauthenticated(self):
        """Are not-logged-in people able to view the code review comment?

        They can see a code review comment if they can see the branch merge
        proposal.
        """
        bmp_checker = BranchMergeProposalView(self.obj.branch_merge_proposal)
        return bmp_checker.checkUnauthenticated()


class CodeReviewCommentDelete(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = ICodeReviewCommentDeletion

    def checkAuthenticated(self, user):
        """Is the user able to view the code review message?

        The user can see a code review message if they can see the branch
        merge proposal.
        """
        bmp_checker = BranchMergeProposalEdit(self.obj.branch_merge_proposal)
        return bmp_checker.checkAuthenticated(user)

    def checkUnauthenticated(self):
        """Are not-logged-in people able to view the code review message?

        They can see a code review message if they can see the branch merge
        proposal.
        """
        bmp_checker = BranchMergeProposalEdit(self.obj.branch_merge_proposal)
        return bmp_checker.checkUnauthenticated()


class BranchMergeProposalEdit(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IBranchMergeProposal

    def checkAuthenticated(self, user):
        """Is the user able to edit the branch merge request?

        The user is able to edit if they are:
          * the registrant of the merge proposal
          * the owner of the source_branch
          * the owner of the target_branch
          * the reviewer for the target_branch
          * an administrator
        """
        celebs = getUtility(ILaunchpadCelebrities)
        return (user.inTeam(self.obj.registrant) or
                user.inTeam(self.obj.source_branch.owner) or
                user.inTeam(self.obj.target_branch.owner) or
                user.inTeam(self.obj.target_branch.reviewer) or
                user.inTeam(celebs.admin) or
                user.inTeam(celebs.bazaar_experts))


class ViewEntitlement(AuthorizationBase):
    """Permissions to view IEntitlement objects.

    Allow the owner of the entitlement, the entitlement registrant,
    or any member of the team or any admin to view the entitlement.
    """
    permission = 'launchpad.View'
    usedfor = IEntitlement

    def checkAuthenticated(self, user):
        """Is the user able to view an Entitlement attribute?

        Any team member can edit a branch subscription for their team.
        Launchpad Admins can also edit any branch subscription.
        """
        admins = getUtility(ILaunchpadCelebrities).admin
        return (user.inTeam(self.obj.person) or
                user.inTeam(self.obj.registrant) or
                user.inTeam(admins))


class AdminDistroSeriesLanguagePacks(
    OnlyRosettaExpertsAndAdmins,
    EditDistroSeriesByOwnersOrDistroOwnersOrAdmins):
    permission = 'launchpad.LanguagePacksAdmin'
    usedfor = IDistroSeries

    def checkAuthenticated(self, user):
        """Is the user able to manage `IDistroSeries` language packs?

        Any Launchpad/Launchpad Translations administrator, people allowed to
        edit distroseries or members of IDistribution.language_pack_admin team
        are able to change the language packs available.
        """
        return (
            OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user) or
            EditDistroSeriesByOwnersOrDistroOwnersOrAdmins.checkAuthenticated(
                self, user) or
            user.inTeam(self.obj.distribution.language_pack_admin))


class AdminDistributionTranslations(OnlyRosettaExpertsAndAdmins,
                                    EditDistributionByDistroOwnersOrAdmins):
    permission = 'launchpad.TranslationsAdmin'
    usedfor = IDistribution

    def checkAuthenticated(self, user):
        """Is the user able to manage `IDistribution` translations settings?

        Any Launchpad/Launchpad Translations administrator or people allowed
        to edit distribution details are able to change translation settings
        for a distribution.
        """
        return (
            OnlyRosettaExpertsAndAdmins.checkAuthenticated(self, user) or
            EditDistributionByDistroOwnersOrAdmins.checkAuthenticated(
                self, user))


class AdminLanguagePack(OnlyRosettaExpertsAndAdmins):
    permission = 'launchpad.LanguagePacksAdmin'
    usedfor = ILanguagePack


class ViewHWSubmission(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = IHWSubmission

    def checkAuthenticated(self, user):
        """Can the user view the submission details?

        Submissions that not marked private are publicly visible,
        private submissions may only be accessed by their owner and by
        admins.
        """
        if not self.obj.private:
            return True

        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(self.obj.owner) or user.inTeam(admins)

    def checkUnauthenticated(self):
        return not self.obj.private


class EditHWSubmission(AdminByAdminsTeam):
    permission = 'launchpad.Edit'
    usedfor = IHWSubmission


class ViewHWDBBase(AuthorizationBase):
    """Base class to restrict access to HWDB data to members of the HWDB team.
    """
    permission = 'launchpad.View'

    def checkAuthenticated(self, user):
        """We give for now access only to Canonical employees."""
        hwdb_team = getUtility(ILaunchpadCelebrities).hwdb_team
        return user.inTeam(hwdb_team)

    def checkUnauthenticated(self):
        """No access for anonymous users."""
        return False


class ViewHWDriver(ViewHWDBBase):
    usedfor = IHWDriver


class ViewHWDriverName(ViewHWDBBase):
    usedfor = IHWDriverName


class ViewHWDriverPackageName(ViewHWDBBase):
    usedfor = IHWDriverPackageName


class ViewHWVendorID(ViewHWDBBase):
    usedfor = IHWVendorID


class ViewHWDevice(ViewHWDBBase):
    usedfor = IHWDevice


class ViewHWSubmissionDevice(ViewHWDBBase):
    usedfor = IHWSubmissionDevice


class ViewHWDBApplication(ViewHWDBBase):
    usedfor = IHWDBApplication


class ViewHWDeviceClass(ViewHWDBBase):
    usedfor = IHWDeviceClass


class ViewArchive(AuthorizationBase):
    """Restrict viewing of private archives.

    Only admins or members of a team with a private membership can
    view the archive.
    """
    permission = 'launchpad.View'
    usedfor = IArchive

    def checkAuthenticated(self, user):
        """Verify that the user can view the archive.

        Anyone can see a public and enabled archive.

        Only Launchpad admins and uploaders can view private or disabled
        archives.
        """
        # No further checks are required if the archive is public and
        # enabled.
        if not self.obj.private and self.obj.enabled:
            return True

        # Administrator are allowed to view private archives.
        celebrities = getUtility(ILaunchpadCelebrities)
        if (user.inTeam(celebrities.admin)
            or user.inTeam(celebrities.commercial_admin)):
            return True

        # Owners can view the PPA.
        if user.inTeam(self.obj.owner):
            return True

        # Uploaders can view private PPAs.
        if self.obj.is_ppa and self.obj.canUpload(user):
            return True

        return False

    def checkUnauthenticated(self):
        """Unauthenticated users can see the PPA if it's not private."""
        return not self.obj.private and self.obj.enabled


class AppendArchive(AuthorizationBase):
    """Restrict appending (upload and copy) operations on archives.

    No one can upload to disabled archives.

    PPA upload rights are managed via `IArchive.canUpload`;

    Appending to PRIMARY, PARTNER or COPY archives is restricted to owners.

    Appending to ubuntu main archives can also be done by the
    'ubuntu-security' celebrity.
    """
    permission = 'launchpad.Append'
    usedfor = IArchive

    def checkAuthenticated(self, user):
        if not self.obj.enabled:
            return False

        if user.inTeam(self.obj.owner):
            return True

        if self.obj.is_ppa and self.obj.canUpload(user):
            return True

        celebrities = getUtility(ILaunchpadCelebrities)
        if (self.obj.is_main and
            self.obj.distribution == celebrities.ubuntu and
            user.inTeam(celebrities.ubuntu_security)):
            return True

        return False


class ViewArchiveAuthToken(AuthorizationBase):
    """Restrict viewing of archive tokens.

    The user just needs to be mentioned in the token, have append privilege
    to the archive or be an admin.
    """
    permission = "launchpad.View"
    usedfor = IArchiveAuthToken

    def checkAuthenticated(self, user):
        if user == self.obj.person:
            return True
        auth_edit = EditArchiveAuthToken(self.obj)
        return auth_edit.checkAuthenticated(user)


class EditArchiveAuthToken(AuthorizationBase):
    """Restrict editing of archive tokens.

    The user should have append privileges to the context archive, or be an
    admin.
    """
    permission = "launchpad.Edit"
    usedfor = IArchiveAuthToken

    def checkAuthenticated(self, user):
        auth_append = AppendArchive(self.obj.archive)
        if auth_append.checkAuthenticated(user):
            return True
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)


class ViewPersonalArchiveSubscription(AuthorizationBase):
    """Restrict viewing of personal archive subscriptions (non-db class).

    The user should be the subscriber, have append privilege to the archive
    or be an admin.
    """
    permission = "launchpad.View"
    usedfor = IPersonalArchiveSubscription

    def checkAuthenticated(self, user):
        if user == self.obj.subscriber:
            return True
        append_archive = AppendArchive(self.obj.archive)

        if append_archive.checkAuthenticated(user):
            return True

        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)


class ViewArchiveSubscriber(AuthorizationBase):
    """Restrict viewing of archive subscribers.

    The user should be the subscriber, have append privilege to the
    archive or be an admin.
    """
    permission = "launchpad.View"
    usedfor = IArchiveSubscriber

    def checkAuthenticated(self, user):
        if user.inTeam(self.obj.subscriber):
            return True
        auth_edit = EditArchiveSubscriber(self.obj)
        return auth_edit.checkAuthenticated(user)


class EditArchiveSubscriber(AuthorizationBase):
    """Restrict editing of archive subscribers.

    The user should have append privilege to the archive or be an admin.
    """
    permission = "launchpad.Edit"
    usedfor = IArchiveSubscriber

    def checkAuthenticated(self, user):
        auth_append = AppendArchive(self.obj.archive)
        if auth_append.checkAuthenticated(user):
            return True
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)


class ViewSourcePackagePublishingHistory(AuthorizationBase):
    """Restrict viewing of source publications."""
    permission = "launchpad.View"
    usedfor = ISourcePackagePublishingHistory

    def checkAuthenticated(self, user):
        view_archive = ViewArchive(self.obj.archive)
        if view_archive.checkAuthenticated(user):
            return True
        admins = getUtility(ILaunchpadCelebrities).admin
        return user.inTeam(admins)

    def checkUnauthenticated(self):
        return not self.obj.archive.private


class ViewBinaryPackagePublishingHistory(ViewSourcePackagePublishingHistory):
    """Restrict viewing of binary publications."""
    usedfor = IBinaryPackagePublishingHistory


class ViewSourcePackageRelease(AuthorizationBase):
    """Restrict viewing of source packages.

    Packages that are only published in private archives are subject to the
    same viewing rules as the archive (see class ViewArchive).

    If the package is published in any non-private archive, then it is
    automatically viewable even if the package is also published in
    a private archive.
    """
    permission = 'launchpad.View'
    usedfor = ISourcePackageRelease

    def checkAuthenticated(self, user):
        """Verify that the user can view the sourcepackagerelease."""
        for archive in self.obj.published_archives:
            auth_archive = ViewArchive(archive)
            if auth_archive.checkAuthenticated(user):
                return True
        return False

    def checkUnauthenticated(self):
        """Check unauthenticated users.

        Unauthenticated users can see the package as long as it's published
        in a non-private archive.
        """
        for archive in self.obj.published_archives:
            if not archive.private:
                return True
        return False


class MailingListApprovalByExperts(AuthorizationBase):
    permission = 'launchpad.Admin'
    usedfor = IMailingListSet

    def checkAuthenticated(self, user):
        experts = getUtility(ILaunchpadCelebrities).mailing_list_experts
        return user.inTeam(experts)


class ConfigureTeamMailingList(AuthorizationBase):
    permission = 'launchpad.MailingListManager'
    usedfor = ITeam

    def checkAuthenticated(self, user):
        """Check to see if the user can manage a mailing list.

        A team's owner or administrator, the Launchpad administrators, and
        Launchpad mailing list experts can all manage a team's mailing list
        through its +mailinglist page.

        :param user: The user whose permission is being checked.
        :type user: `IPerson`
        :return: True if the user can manage a mailing list, otherwise False.
        :rtype: boolean
        """
        # The team owner, the Launchpad mailing list experts and the Launchpad
        # administrators can all view a team's +mailinglist page.
        celebrities = getUtility(ILaunchpadCelebrities)
        team = ITeam(self.obj)
        return (
            (team is not None and team in user.getAdministratedTeams()) or
            user.inTeam(celebrities.admin) or
            user.inTeam(celebrities.mailing_list_experts))


class ViewEmailAddress(AuthorizationBase):
    permission = 'launchpad.View'
    usedfor = IEmailAddress

    def checkUnauthenticated(self):
        """See `AuthorizationBase`."""
        # Email addresses without an associated Person cannot be seen by
        # anonymous users.
        if self.obj.person is None:
            return False
        return not self.obj.person.hide_email_addresses

    def checkAccountAuthenticated(self, account):
        """Can the user see the details of this email address?

        If the email address' owner doesn't want his email addresses to be
        hidden, anyone can see them.  Otherwise only the owner himself or
        admins can see them.
        """
        # Always allow users to see their own email addresses.
        if self.obj.account == account:
            return True

        if not (self.obj.person is None or
                self.obj.person.hide_email_addresses):
            return True

        user = IPerson(account, None)
        if user is None:
            return False

        celebrities = getUtility(ILaunchpadCelebrities)
        return (self.obj.person is not None and user.inTeam(self.obj.person)
                or user.inTeam(celebrities.commercial_admin)
                or user.inTeam(celebrities.registry_experts)
                or user.inTeam(celebrities.admin))


class EditEmailAddress(EditByOwnersOrAdmins):
    permission = 'launchpad.Edit'
    usedfor = IEmailAddress

    def checkAccountAuthenticated(self, account):
        # Always allow users to see their own email addresses.
        if self.obj.account == account:
            return True
        return super(EditEmailAddress, self).checkAccountAuthenticated(
            account)


class EditArchivePermissionSet(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IArchivePermissionSet

    def checkAuthenticated(self, user):
        """Users must be an admin or a member of the tech board."""
        celebrities = getUtility(ILaunchpadCelebrities)
        return (
            user.inTeam(celebrities.admin)
            or user.inTeam(celebrities.ubuntu_techboard))


class LinkOfficialSourcePackageBranches(AuthorizationBase):
    """Who can source packages to their official branches?

    Only members of the ~ubuntu-branches celebrity team! Or admins.
    """

    permission = 'launchpad.Edit'
    usedfor = IMakeOfficialBranchLinks

    def checkUnauthenticated(self):
        return False

    def checkAuthenticated(self, user):
        celebrities = getUtility(ILaunchpadCelebrities)
        return (
            user.inTeam(celebrities.ubuntu_branches)
            or user.inTeam(celebrities.admin))


class ChangeOfficialSourcePackageBranchLinks(AuthorizationBase):
    """Who can change the links from source packages to their branches?

    Only members of the ~ubuntu-branches celebrity team! Or admins.
    """

    permission = 'launchpad.Edit'
    usedfor = ISeriesSourcePackageBranch

    def checkUnauthenticated(self):
        return False

    def checkAuthenticated(self, user):
        celebrities = getUtility(ILaunchpadCelebrities)
        return (
            user.inTeam(celebrities.ubuntu_branches)
            or user.inTeam(celebrities.admin))


class EditPackagesetSet(AuthorizationBase):
    permission = 'launchpad.Edit'
    usedfor = IPackagesetSet

    def checkAuthenticated(self, user):
        """Users must be an admin or a member of the tech board."""
        celebrities = getUtility(ILaunchpadCelebrities)
        return (
            user.inTeam(celebrities.admin)
            or user.inTeam(celebrities.ubuntu_techboard))