How to use permitted method in hypothesis

Best Python code snippet using hypothesis

generate_name_constraints.py

Source:generate_name_constraints.py Github

copy

Full Screen

...57 return "NAME CONSTRAINTS"58 def union_from(self, c):59 self.permitted.extend(c.permitted)60 self.excluded.extend(c.excluded)61 def add_permitted(self, general_name):62 self.permitted.append(general_name)63 def add_excluded(self, general_name):64 self.excluded.append(general_name)65 def __str__(self):66 s = "asn1 = SEQUENCE:nameConstraintsSequence\n[nameConstraintsSequence]\n"67 if self.permitted or self.force_permitted_sequence:68 s += "permittedSubtrees = IMPLICIT:0,SEQUENCE:permittedSubtreesSequence\n"69 if self.excluded or self.force_excluded_sequence:70 s += "excludedSubtrees = IMPLICIT:1,SEQUENCE:excludedSubtreesSequence\n"71 if self.permitted or self.force_permitted_sequence:72 s += "[permittedSubtreesSequence]\n"73 for n, subtree in enumerate(self.permitted):74 s += 'subtree%i = SEQUENCE:permittedSubtree%i\n' % (n, n)75 if self.excluded or self.force_excluded_sequence:76 s += "[excludedSubtreesSequence]\n"77 for n, subtree in enumerate(self.excluded):78 s += 'subtree%i = SEQUENCE:excludedSubtree%i\n' % (n, n)79 for n, subtree in enumerate(self.permitted):80 s += '[permittedSubtree%i]\n%s\n' % (n, subtree)81 for n, subtree in enumerate(self.excluded):82 s += '[excludedSubtree%i]\n%s\n' % (n, subtree)83 return s84def other_name():85 i = random.randint(0, sys.maxint)86 s = 'otherName = IMPLICIT:0,SEQUENCE:otherNameSequence%i\n' % i87 s += '[otherNameSequence%i]\n' % i88 s += 'type_id = OID:1.2.3.4.5\n'89 s += 'value = FORMAT:HEX,OCTETSTRING:DEADBEEF\n'90 return s91def rfc822_name(name):92 return 'rfc822Name = IMPLICIT:1,IA5STRING:' + name93def dns_name(name):94 return 'dNSName = IMPLICIT:2,IA5STRING:' + name95def x400_address():96 i = random.randint(0, sys.maxint)97 s = 'x400Address = IMPLICIT:3,SEQUENCE:x400AddressSequence%i\n' % i98 s += '[x400AddressSequence%i]\n' % i99 s += 'builtinstandardattributes = SEQUENCE:BuiltInStandardAttributes%i\n' % i100 s += '[BuiltInStandardAttributes%i]\n' % i101 s += 'countryname = EXPLICIT:1A,PRINTABLESTRING:US\n'102 return s103def directory_name(name):104 return str(name).replace(105 'asn1 = SEQUENCE', 'directoryName = EXPLICIT:4,SEQUENCE')106def edi_party_name():107 i = random.randint(0, sys.maxint)108 s = 'ediPartyName = IMPLICIT:5,SEQUENCE:ediPartyNameSequence%i\n' % i109 s += '[ediPartyNameSequence%i]\n' % i110 s += 'partyName = IMPLICIT:1,UTF8:foo\n'111 return s112def uniform_resource_identifier(name):113 return 'uniformResourceIdentifier = IMPLICIT:6,IA5STRING:' + name114def ip_address(addr, enforce_length=True):115 if enforce_length:116 assert len(addr) in (4,16)117 addr_str = ""118 for addr_byte in addr:119 addr_str += '%02X'%(addr_byte)120 return 'iPAddress = IMPLICIT:7,FORMAT:HEX,OCTETSTRING:' + addr_str121def ip_address_range(addr, netmask, enforce_length=True):122 if enforce_length:123 assert len(addr) == len(netmask)124 assert len(addr) in (4,16)125 addr_str = ""126 netmask_str = ""127 for addr_byte, mask_byte in map(None, addr, netmask):128 assert (addr_byte & ~mask_byte) == 0129 addr_str += '%02X'%(addr_byte)130 netmask_str += '%02X'%(mask_byte)131 return ('iPAddress = IMPLICIT:7,FORMAT:HEX,OCTETSTRING:' + addr_str +132 netmask_str)133def registered_id(oid):134 return 'registeredID = IMPLICIT:8,OID:' + oid135def with_min_max(val, minimum=None, maximum=None):136 s = val137 s += '\n'138 assert '\n[' not in s139 if minimum is not None:140 s += 'minimum = IMPLICIT:0,INTEGER:%i\n' % minimum141 if maximum is not None:142 s += 'maximum = IMPLICIT:1,INTEGER:%i\n' % maximum143 return s144def main():145 dnsname_constraints = NameConstraintsGenerator()146 dnsname_constraints.add_permitted(dns_name("permitted.example.com"))147 dnsname_constraints.add_permitted(dns_name("permitted.example2.com"))148 dnsname_constraints.add_permitted(dns_name("permitted.example3.com."))149 dnsname_constraints.add_permitted(dns_name("alsopermitted.example.com"))150 dnsname_constraints.add_excluded(dns_name("excluded.permitted.example.com"))151 dnsname_constraints.add_permitted(152 dns_name("stillnotpermitted.excluded.permitted.example.com"))153 dnsname_constraints.add_excluded(dns_name("extraneousexclusion.example.com"))154 generate(dnsname_constraints, "dnsname.pem")155 dnsname_constraints2 = NameConstraintsGenerator()156 dnsname_constraints2.add_permitted(dns_name("com"))157 dnsname_constraints2.add_excluded(dns_name("foo.bar.com"))158 generate(dnsname_constraints2, "dnsname2.pem")159 dnsname_constraints3 = NameConstraintsGenerator()160 dnsname_constraints3.add_permitted(dns_name(".bar.com"))161 generate(dnsname_constraints3, "dnsname-permitted_with_leading_dot.pem")162 dnsname_constraints4 = NameConstraintsGenerator()163 dnsname_constraints4.add_excluded(dns_name(".bar.com"))164 generate(dnsname_constraints4, "dnsname-excluded_with_leading_dot.pem")165 dnsname_constraints5 = NameConstraintsGenerator()166 dnsname_constraints5.add_permitted(dns_name(".."))167 generate(dnsname_constraints5, "dnsname-permitted_two_dot.pem")168 c = NameConstraintsGenerator()169 c.add_excluded(dns_name("excluded.permitted.example.com"))170 generate(c, "dnsname-excluded.pem")171 c = NameConstraintsGenerator()172 c.add_permitted(dns_name("permitted.example.com"))173 c.add_excluded(dns_name(""))174 generate(c, "dnsname-excludeall.pem")175 c = NameConstraintsGenerator()176 c.add_permitted(dns_name("permitted.example.com"))177 c.add_excluded(dns_name("."))178 generate(c, "dnsname-exclude_dot.pem")179 ipaddress_constraints = NameConstraintsGenerator()180 ipaddress_constraints.add_permitted(181 ip_address_range((192,168,0,0),(255,255,0,0)))182 ipaddress_constraints.add_excluded(183 ip_address_range((192,168,5,0),(255,255,255,0)))184 ipaddress_constraints.add_permitted(185 ip_address_range((192,168,5,32),(255,255,255,224)))186 ipaddress_constraints.add_permitted(187 ip_address_range((192,167,5,32),(255,255,255,224)))188 ipaddress_constraints.add_excluded(189 ip_address_range((192,166,5,32),(255,255,255,224)))190 ipaddress_constraints.add_permitted(ip_address_range(191 (1,2,3,4,5,6,7,8,9,10,11,12,0,0,0,0),192 (255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0)))193 ipaddress_constraints.add_excluded(ip_address_range(194 (1,2,3,4,5,6,7,8,9,10,11,12,5,0,0,0),195 (255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0)))196 ipaddress_constraints.add_permitted(ip_address_range(197 (1,2,3,4,5,6,7,8,9,10,11,12,5,32,0,0),198 (255,255,255,255,255,255,255,255,255,255,255,255,255,224,0,0)))199 ipaddress_constraints.add_permitted(ip_address_range(200 (1,2,3,4,5,6,7,8,9,10,11,11,5,32,0,0),201 (255,255,255,255,255,255,255,255,255,255,255,255,255,224,0,0)))202 ipaddress_constraints.add_excluded(ip_address_range(203 (1,2,3,4,5,6,7,8,9,10,11,10,5,32,0,0),204 (255,255,255,255,255,255,255,255,255,255,255,255,255,224,0,0)))205 generate(ipaddress_constraints, "ipaddress.pem")206 c = NameConstraintsGenerator()207 c.add_permitted(ip_address_range((192,168,1,3),(255,255,255,255)))208 generate(c, "ipaddress-permit_singlehost.pem")209 c = NameConstraintsGenerator()210 c.add_permitted(ip_address_range((0,0,0,0),(0,0,0,0)))211 generate(c, "ipaddress-permit_all.pem")212 c = NameConstraintsGenerator()213 c.add_permitted(ip_address_range((0x80,0,0,0),(0x80,0,0,0)))214 generate(c, "ipaddress-permit_prefix1.pem")215 c = NameConstraintsGenerator()216 c.add_permitted(ip_address_range((192,168,1,2),(255,255,255,254)))217 generate(c, "ipaddress-permit_prefix31.pem")218 c = NameConstraintsGenerator()219 c.add_permitted(ip_address_range((192,168,1,0),(255,255,255,253)))220 generate(c, "ipaddress-invalid_mask_not_contiguous_1.pem")221 c = NameConstraintsGenerator()222 c.add_permitted(ip_address_range((192,168,0,0),(255,253,0,0)))223 generate(c, "ipaddress-invalid_mask_not_contiguous_2.pem")224 c = NameConstraintsGenerator()225 c.add_permitted(ip_address_range((0,0,0,0),(0x40,0,0,0)))226 generate(c, "ipaddress-invalid_mask_not_contiguous_3.pem")227 c = NameConstraintsGenerator()228 c.add_permitted(ip_address_range((192,0,0,0),(0xFF,0,0xFF,0)))229 generate(c, "ipaddress-invalid_mask_not_contiguous_4.pem")230 c = NameConstraintsGenerator()231 c.add_excluded(ip_address_range((192,168,5,0),(255,255,255,0)))232 generate(c, "ipaddress-excluded.pem")233 c = NameConstraintsGenerator()234 c.add_permitted(ip_address_range((192,168,0,0),(255,255,0,0)))235 c.add_permitted(ip_address_range((1,2,3,4,5,6,7,8,9,10,11,12,0,0,0,0),236 (255,255,255,255,255,255,255,255,237 255,255,255,255,0,0,0,0)))238 c.add_excluded(ip_address_range((0,0,0,0),(0,0,0,0)))239 c.add_excluded(ip_address_range((0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),240 (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)))241 generate(c, "ipaddress-excludeall.pem")242 c = NameConstraintsGenerator()243 c.add_permitted(ip_address_range((192,168,0,0),(255,255,255,0)))244 c.add_permitted(ip_address_range((192,168,5,0,0),(255,255,255,0,0),245 enforce_length=False))246 generate(c, "ipaddress-invalid_addr.pem")247 n_us = generate_names.NameGenerator()248 n_us.add_rdn().add_attr('countryName', 'PRINTABLESTRING', 'US')249 generate(n_us, "name-us.pem")250 n_us_az = copy.deepcopy(n_us)251 n_us_az.add_rdn().add_attr('stateOrProvinceName', 'UTF8', 'Arizona')252 generate(n_us_az, "name-us-arizona.pem")253 n_us_ca = copy.deepcopy(n_us)254 n_us_ca.add_rdn().add_attr('stateOrProvinceName', 'UTF8', 'California')255 generate(n_us_ca, "name-us-california.pem")256 n_us_ca_mountain_view = copy.deepcopy(n_us_ca)257 n_us_ca_mountain_view.add_rdn().add_attr(258 'localityName', 'UTF8', 'Mountain View')259 generate(n_us_ca_mountain_view, "name-us-california-mountain_view.pem")260 n_jp = generate_names.NameGenerator()261 n_jp.add_rdn().add_attr('countryName', 'PRINTABLESTRING', 'JP')262 generate(n_jp, "name-jp.pem")263 n_jp_tokyo = copy.deepcopy(n_jp)264 n_jp_tokyo.add_rdn().add_attr(265 'stateOrProvinceName', 'UTF8', '\xe6\x9d\xb1\xe4\xba\xac', 'FORMAT:UTF8')266 generate(n_jp_tokyo, "name-jp-tokyo.pem")267 n_us_az_foodotcom = copy.deepcopy(n_us_az)268 n_us_az_foodotcom.add_rdn().add_attr('commonName', 'UTF8', 'foo.com')269 generate(n_us_az_foodotcom, "name-us-arizona-foo.com.pem")270 n_us_az_permittedexamplecom = copy.deepcopy(n_us_az)271 n_us_az_permittedexamplecom.add_rdn().add_attr('commonName', 'UTF8',272 'permitted.example.com')273 generate(n_us_az_permittedexamplecom,274 "name-us-arizona-permitted.example.com.pem")275 n_us_ca_permittedexamplecom = copy.deepcopy(n_us_ca)276 n_us_ca_permittedexamplecom.add_rdn().add_attr('commonName', 'UTF8',277 'permitted.example.com')278 generate(n_us_ca_permittedexamplecom,279 "name-us-california-permitted.example.com.pem")280 n_us_az_ip1111 = copy.deepcopy(n_us_az)281 n_us_az_ip1111.add_rdn().add_attr('commonName', 'UTF8', '1.1.1.1')282 generate(n_us_az_ip1111, "name-us-arizona-1.1.1.1.pem")283 n_us_az_192_168_1_1 = copy.deepcopy(n_us_az)284 n_us_az_192_168_1_1.add_rdn().add_attr('commonName', 'UTF8', '192.168.1.1')285 generate(n_us_az_192_168_1_1, "name-us-arizona-192.168.1.1.pem")286 n_us_az_ipv6 = copy.deepcopy(n_us_az)287 n_us_az_ipv6.add_rdn().add_attr('commonName', 'UTF8',288 '102:304:506:708:90a:b0c::1')289 generate(n_us_az_ipv6, "name-us-arizona-ipv6.pem")290 n_us_ca_192_168_1_1 = copy.deepcopy(n_us_ca)291 n_us_ca_192_168_1_1.add_rdn().add_attr('commonName', 'UTF8', '192.168.1.1')292 generate(n_us_ca_192_168_1_1, "name-us-california-192.168.1.1.pem")293 n_us_az_email = copy.deepcopy(n_us_az)294 n_us_az_email.add_rdn().add_attr('emailAddress', 'IA5STRING',295 'bar@example.com')296 generate(n_us_az_email, "name-us-arizona-email.pem")297 n_ca = generate_names.NameGenerator()298 n_ca.add_rdn().add_attr('countryName', 'PRINTABLESTRING', 'CA')299 generate(n_ca, "name-ca.pem")300 n_de = generate_names.NameGenerator()301 n_de.add_rdn().add_attr('countryName', 'PRINTABLESTRING', 'DE')302 generate(n_de, "name-de.pem")303 n_empty = generate_names.NameGenerator()304 generate(n_empty, "name-empty.pem")305 directoryname_constraints = NameConstraintsGenerator()306 directoryname_constraints.add_permitted(directory_name(n_us))307 directoryname_constraints.add_excluded(directory_name(n_us_ca))308 directoryname_constraints.add_permitted(directory_name(n_us_ca_mountain_view))309 directoryname_constraints.add_excluded(directory_name(n_de))310 directoryname_constraints.add_permitted(directory_name(n_jp_tokyo))311 generate(directoryname_constraints, "directoryname.pem")312 c = NameConstraintsGenerator()313 c.union_from(directoryname_constraints)314 c.union_from(dnsname_constraints)315 generate(c, "directoryname_and_dnsname.pem")316 c = NameConstraintsGenerator()317 c.union_from(directoryname_constraints)318 c.union_from(dnsname_constraints)319 c.union_from(ipaddress_constraints)320 generate(c, "directoryname_and_dnsname_and_ipaddress.pem")321 c = NameConstraintsGenerator()322 c.add_excluded(directory_name(n_us_ca))323 generate(c, "directoryname-excluded.pem")324 c = NameConstraintsGenerator()325 c.add_permitted(directory_name(n_us))326 c.add_excluded(directory_name(n_empty))327 generate(c, "directoryname-excludeall.pem")328 san = SubjectAltNameGenerator()329 san.add_name(dns_name("permitted.example.com"))330 san.add_name(ip_address((192,168,1,2)))331 san.add_name(directory_name(n_us_az))332 generate(san, "san-permitted.pem")333 san2 = copy.deepcopy(san)334 san2.add_name(335 dns_name("foo.stillnotpermitted.excluded.permitted.example.com"))336 generate(san2, "san-excluded-dnsname.pem")337 san2 = copy.deepcopy(san)338 san2.add_name(ip_address((192,168,5,5)))339 generate(san2, "san-excluded-ipaddress.pem")340 san2 = copy.deepcopy(san)341 san2.add_name(directory_name(n_us_ca_mountain_view))342 generate(san2, "san-excluded-directoryname.pem")343 san = SubjectAltNameGenerator()344 san.add_name(other_name())345 generate(san, "san-othername.pem")346 san = SubjectAltNameGenerator()347 san.add_name(rfc822_name("foo@example.com"))348 generate(san, "san-rfc822name.pem")349 san = SubjectAltNameGenerator()350 san.add_name(dns_name("foo.example.com"))351 generate(san, "san-dnsname.pem")352 san = SubjectAltNameGenerator()353 san.add_name(x400_address())354 generate(san, "san-x400address.pem")355 san = SubjectAltNameGenerator()356 san.add_name(directory_name(n_us))357 generate(san, "san-directoryname.pem")358 san = SubjectAltNameGenerator()359 san.add_name(uniform_resource_identifier('http://example.com'))360 generate(san, "san-uri.pem")361 san = SubjectAltNameGenerator()362 san.add_name(ip_address((192,168,6,7)))363 generate(san, "san-ipaddress4.pem")364 san = SubjectAltNameGenerator()365 san.add_name(ip_address((0xFE, 0x80, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,366 13, 14)))367 generate(san, "san-ipaddress6.pem")368 san = SubjectAltNameGenerator()369 san.add_name(registered_id("1.2.3.4"))370 generate(san, "san-registeredid.pem")371 san = SubjectAltNameGenerator()372 generate(san, "san-invalid-empty.pem")373 san = SubjectAltNameGenerator()374 san.add_name(ip_address((192,168,0,5,0), enforce_length=False))375 generate(san, "san-invalid-ipaddress.pem")376 c = NameConstraintsGenerator()377 c.add_permitted(other_name())378 generate(c, "othername-permitted.pem")379 c = NameConstraintsGenerator()380 c.add_excluded(other_name())381 generate(c, "othername-excluded.pem")382 c = NameConstraintsGenerator()383 c.add_permitted(rfc822_name("foo@example.com"))384 generate(c, "rfc822name-permitted.pem")385 c = NameConstraintsGenerator()386 c.add_excluded(rfc822_name("foo@example.com"))387 generate(c, "rfc822name-excluded.pem")388 c = NameConstraintsGenerator()389 c.add_permitted(x400_address())390 generate(c, "x400address-permitted.pem")391 c = NameConstraintsGenerator()392 c.add_excluded(x400_address())393 generate(c, "x400address-excluded.pem")394 c = NameConstraintsGenerator()395 c.add_permitted(edi_party_name())396 generate(c, "edipartyname-permitted.pem")397 c = NameConstraintsGenerator()398 c.add_excluded(edi_party_name())399 generate(c, "edipartyname-excluded.pem")400 c = NameConstraintsGenerator()401 c.add_permitted(uniform_resource_identifier("http://example.com"))402 generate(c, "uri-permitted.pem")403 c = NameConstraintsGenerator()404 c.add_excluded(uniform_resource_identifier("http://example.com"))405 generate(c, "uri-excluded.pem")406 c = NameConstraintsGenerator()407 c.add_permitted(registered_id("1.2.3.4"))408 generate(c, "registeredid-permitted.pem")409 c = NameConstraintsGenerator()410 c.add_excluded(registered_id("1.2.3.4"))411 generate(c, "registeredid-excluded.pem")412 c = NameConstraintsGenerator()413 generate(c, "invalid-no_subtrees.pem")414 c = NameConstraintsGenerator(force_permitted_sequence=True)415 generate(c, "invalid-empty_permitted_subtree.pem")416 c = NameConstraintsGenerator(force_excluded_sequence=True)417 generate(c, "invalid-empty_excluded_subtree.pem")418 c = NameConstraintsGenerator()419 c.add_permitted(with_min_max(dns_name("permitted.example.com"), minimum=0))420 generate(c, "dnsname-with_min_0.pem")421 c = NameConstraintsGenerator()422 c.add_permitted(with_min_max(dns_name("permitted.example.com"), minimum=1))423 generate(c, "dnsname-with_min_1.pem")424 c = NameConstraintsGenerator()425 c.add_permitted(with_min_max(426 dns_name("permitted.example.com"), minimum=0, maximum=2))427 generate(c, "dnsname-with_min_0_and_max.pem")428 c = NameConstraintsGenerator()429 c.add_permitted(with_min_max(430 dns_name("permitted.example.com"), minimum=1, maximum=2))431 generate(c, "dnsname-with_min_1_and_max.pem")432 c = NameConstraintsGenerator()433 c.add_permitted(with_min_max(dns_name("permitted.example.com"), maximum=2))434 generate(c, "dnsname-with_max.pem")435if __name__ == '__main__':...

Full Screen

Full Screen

AuthAPI.js

Source:AuthAPI.js Github

copy

Full Screen

1define(function(require, exports) {2 var $ = require('jquery');3 var config = require('appConfig');4 var ko = require('knockout');5 var cookie = require('services/CookieAPI');6 var TOKEN_HEADER = 'Bearer';7 var LOCAL_STORAGE_PERMISSIONS_KEY = "permissions";8 const httpService = require('services/http');9 const AUTH_PROVIDERS = {10 IAP: 'AtlasGoogleSecurity',11 };12 const signInOpened = ko.observable(false);13 function getBearerToken() {14 return localStorage.bearerToken && localStorage.bearerToken !== 'null' && localStorage.bearerToken !== 'undefined' ? localStorage.bearerToken : null;15 }16 var authProviders = config.authProviders.reduce(function(result, current) {17 result[config.api.url + current.url] = current;18 return result;19 }, {});20 var getServiceUrl = function () {21 return config.webAPIRoot;22 };23 var token = ko.observable(getBearerToken());24 var getAuthorizationHeader = function () {25 if (!token()) {26 return null;27 }28 return TOKEN_HEADER + ' ' + token();29 };30 $.ajaxSetup({31 beforeSend: function(xhr, settings) {32 if (!authProviders[settings.url] && settings.url.startsWith(config.api.url)) {33 xhr.setRequestHeader('Authorization', getAuthorizationHeader());34 }35 }36 });37 var subject = ko.observable();38 var permissions = ko.observable();39 var fullName = ko.observable();40 const authProvider = ko.observable();41 authProvider.subscribe(provider => {42 if (provider === AUTH_PROVIDERS.IAP) {43 const id = 'google-iap-refresher';44 const iframe = `<iframe id="${id}" src="/_gcp_iap/session_refresher" style="position: absolute; width:0;height:0;border:0; border:none;"></iframe>`;45 $('#' + id).remove();46 $('body').append(iframe);47 }48 });49 const loadUserInfo = function() {50 return new Promise((resolve, reject) => $.ajax({51 url: config.api.url + 'user/me',52 method: 'GET',53 success: function (info, textStatus, jqXHR) {54 permissions(info.permissions.map(p => p.permission));55 subject(info.login);56 authProvider(jqXHR.getResponseHeader('x-auth-provider'));57 fullName(info.name ? info.name : info.login);58 resolve();59 },60 error: function (err) {61 if (err.status === 401) {62 console.log('User is not authed');63 subject(null);64 resolve();65 } else {66 reject('Cannot retrieve user info');67 }68 }69 }));70 };71 var tokenExpirationDate = ko.pureComputed(function() {72 if (!token()) {73 return null;74 }75 try {76 var expirationInSeconds = parseJwtPayload(token()).exp;77 return new Date(expirationInSeconds * 1000);78 } catch (e) {79 return new Date();80 }81 });82 const tokenExpired = ko.observable(false);83 const askLoginOnTokenExpire = (function() {84 let expirationTimeout;85 return () => {86 if (expirationTimeout) {87 clearTimeout(expirationTimeout);88 }89 if (!token()) {90 tokenExpired(false);91 return;92 }93 if (tokenExpirationDate() > new Date()) {94 tokenExpired(false);95 expirationTimeout = setTimeout(96 () => {97 tokenExpired(true);98 signInOpened(true);99 expirationTimeout = null;100 },101 tokenExpirationDate() - new Date()102 );103 } else {104 tokenExpired(true);105 }106 }107 })();108 askLoginOnTokenExpire();109 tokenExpirationDate.subscribe(askLoginOnTokenExpire);110 window.addEventListener('storage', function(event) {111 if (event.storageArea === localStorage) {112 let bearerToken = getBearerToken();113 if (bearerToken !== token()) {114 token(bearerToken);115 }116 }117 }, false);118 token.subscribe(function(newValue) {119 localStorage.bearerToken = newValue;120 cookie.setField("bearerToken", newValue);121 });122 var isAuthenticated = ko.computed(() => {123 if (!config.userAuthenticationEnabled) {124 return true;125 }126 return !!subject();127 });128 var handleAccessDenied = function(xhr) {129 switch (xhr.status) {130 case 401:131 resetAuthParams();132 break;133 case 403:134 refreshToken();135 break;136 }137 }138 var checkPermission = function(permission, etalon) {139 // etalon may be like '*:read,write:etc'140 if (!etalon || !permission) {141 return false;142 }143 if (permission == etalon) {144 return true;145 }146 var etalonLevels = etalon.split(':');147 var permissionLevels = permission.split(':');148 if (etalonLevels.length != permissionLevels.length) {149 return false;150 }151 for (var i = 0; i < permissionLevels.length; i++) {152 var pLevel = permissionLevels[i];153 var eLevels = etalonLevels[i].split(',');154 if (eLevels.indexOf('*') < 0 && eLevels.indexOf(pLevel) < 0) {155 return false;156 }157 }158 return true;159 };160 var isPermitted = function (permission) {161 if (!config.userAuthenticationEnabled) {162 return true;163 }164 var etalons = permissions();165 if (!etalons) {166 return false;167 }168 for (var i = 0; i < etalons.length; i++) {169 if (checkPermission(permission, etalons[i])) {170 return true;171 }172 }173 return false;174 };175 function base64urldecode(arg) {176 var s = arg;177 s = s.replace(/-/g, '+'); // 62nd char of encoding178 s = s.replace(/_/g, '/'); // 63rd char of encoding179 switch (s.length % 4) // Pad with trailing '='s180 {181 case 0: break; // No pad chars in this case182 case 2: s += "=="; break; // Two pad chars183 case 3: s += "="; break; // One pad char184 default: throw new Error("Illegal base64url string!");185 }186 return window.atob(s); // Standard base64 decoder187 };188 function parseJwtPayload(jwt) {189 var parts = jwt.split(".");190 if (parts.length != 3) {191 throw new Error("JSON Web Token must have three parts");192 }193 var payload = base64urldecode(parts[1]);194 return $.parseJSON(payload);195 };196 var refreshTokenPromise = null;197 var isPromisePending = function(p) {198 return p && typeof p === 'object' && typeof p.status === 'function' && p.status() === 'pending';199 }200 var refreshToken = function() {201 if (!isPromisePending(refreshTokenPromise)) {202 refreshTokenPromise = httpService.doGet(getServiceUrl() + "user/refresh");203 refreshTokenPromise.then(({ data, headers }) => {204 setAuthParams(headers.get(TOKEN_HEADER), data.permissions);205 });206 refreshTokenPromise.catch(() => {207 resetAuthParams();208 });209 }210 return refreshTokenPromise;211 }212 var isPermittedCreateConceptset = function() {213 return isPermitted('conceptset:post');214 }215 var isPermittedReadConceptsets = function () {216 return isPermitted('conceptset:get');217 };218 var isPermittedUpdateConceptset = function(conceptsetId) {219 return (isPermitted('conceptset:' + conceptsetId + ':put') && isPermitted('conceptset:' + conceptsetId + ':items:put')) || (isPermitted('conceptset:*:put') && isPermitted('conceptset:*:items:put'));220 };221 var isPermittedDeleteConceptset = function(id) {222 return isPermitted('conceptset:' + id + ':delete');223 };224 var isPermittedReadIRs = function () {225 return isPermitted('ir:get');226 };227 var isPermittedEditIR = function (id) {228 return isPermitted('ir:' + id + ':put');229 };230 var isPermittedCreateIR = function () {231 return isPermitted('ir:post');232 };233 var isPermittedDeleteIR = function(id) {234 return isPermitted('ir:' + id + ':delete');235 };236 var isPermittedCopyIR = function(id) {237 return isPermitted('ir:' + id + ':copy:get');238 };239 var isPermittedReadEstimations = function () {240 return isPermitted('comparativecohortanalysis:get');241 };242 var isPermittedEditSourcePriortiy = function() {243 return isPermitted('source:*:daimons:*:set-priority:post')244 };245 var isPermittedReadEstimation = function (id) {246 return isPermitted('comparativecohortanalysis:' + id + ':get');247 };248 var isPermittedCreateEstimation = function() {249 return isPermitted('comparativecohortanalysis:post');250 };251 const isPermittedDeleteEstimation = function(id) {252 return isPermitted(`comparativecohortanalysis:${id}:delete`);253 }254 var isPermittedReadPlps = function() {255 return isPermitted('plp:get');256 };257 var isPermittedCreatePlp = function () {258 return isPermitted('plp:post');259 };260 var isPermittedReadPlp = function(id) {261 return isPermitted('plp:' + id + ':get');262 };263 var isPermittedDeletePlp = function(id) {264 return isPermitted('plp:' + id + ':delete');265 };266 var isPermittedCopyPlp = function(id) {267 return isPermitted(`plp:${id}:copy:get`);268 }269 var isPermittedSearch = function() {270 return isPermitted('vocabulary:*:search:*:get');271 };272 var isPermittedViewCdmResults = function () {273 return isPermitted('cdmresults:*:get');274 };275 var isPermittedViewProfiles = function (sourceKey) {276 return isPermitted(`${sourceKey}:person:*:get`);277 };278 var isPermittedViewProfileDates = function() {279 return isPermitted('*:person:*:get:dates');280 };281 var isPermittedReadCohort = function(id) {282 return isPermitted('cohortdefinition:' + id + ':get') && isPermitted('cohortdefinition:sql:post');283 }284 var isPermittedReadCohorts = function() {285 return isPermitted('cohortdefinition:get');286 }287 var isPermittedCreateCohort = function() {288 return isPermitted('cohortdefinition:post');289 }290 var isPermittedCopyCohort = function(id) {291 return isPermitted('cohortdefinition:' + id + ':copy:get');292 }293 var isPermittedUpdateCohort = function(id) {294 var permission = 'cohortdefinition:' + id + ':put';295 return isPermitted(permission);296 }297 var isPermittedDeleteCohort = function(id) {298 var permission = 'cohortdefinition:' + id + ':delete';299 var allPermissions = 'cohortdefinition:delete';300 return isPermitted(permission) || isPermitted(allPermissions);301 }302 var isPermittedGenerateCohort = function(cohortId, sourceKey) {303 return isPermitted('cohortdefinition:' + cohortId + ':generate:' + sourceKey + ':get') &&304 isPermitted('cohortdefinition:' + cohortId + ':info:get');305 }306 var isPermittedReadCohortReport = function(cohortId, sourceKey) {307 return isPermitted('cohortdefinition:' + cohortId + ':report:' + sourceKey + ':get');308 }309 var isPermittedReadJobs = function() {310 return isPermitted('job:execution:get');311 }312 var isPermittedEditConfiguration = function() {313 return isPermitted('configuration:edit:ui')314 }315 var isPermittedCreateSource = function() {316 return isPermitted('source:post');317 }318 var isPermittedReadSource = function(key) {319 return isPermitted('source:' + key + ':get');320 }321 var isPermittedCheckSourceConnection = function(key) {322 return isPermitted('source:connection:' + key + ':get');323 }324 var isPermittedEditSource = function(key) {325 return isPermitted('source:' + key + ':put');326 }327 var isPermittedDeleteSource = function(key) {328 return isPermitted('source:' + key + ':delete');329 }330 var isPermittedReadRoles = function() {331 return isPermitted('role:get');332 }333 var isPermittedReadRole = function (roleId) {334 var permitted =335 isPermitted('role:' + roleId + ':get') &&336 isPermitted('permission:get') &&337 isPermitted('role:' + roleId + ':permissions:get') &&338 isPermitted('user:get') &&339 isPermitted('role:' + roleId + ':users:get');340 return permitted;341 }342 var isPermittedEditRole = function(roleId) {343 return isPermitted('role:' + roleId + ':put');344 }345 var isPermittedCreateRole = function() {346 return isPermitted('role:post');347 }348 var isPermittedDeleteRole = function(roleId) {349 return isPermitted('role:' + roleId + ':delete');350 }351 var isPermittedEditRoleUsers = function(roleId) {352 return isPermitted('role:' + roleId + ':users:*:put') && isPermitted('role:' + roleId + ':users:*:delete');353 }354 var isPermittedEditRolePermissions = function(roleId) {355 return isPermitted('role:' + roleId + ':permissions:*:put') && isPermitted('role:' + roleId + ':permissions:*:delete');356 }357 const isPermittedGetAllNotifications = function() {358 return isPermitted('notifications:get');359 };360 const isPermittedGetViewedNotifications = function() {361 return isPermitted('notifications:viewed:get');362 };363 const isPermittedPostViewedNotifications = function() {364 return isPermitted('notifications:viewed:post');365 };366 const isPermittedImportUsers = function() {367 return isPermitted('user:import:post') && isPermitted('user:import:*:post');368 }369 const hasSourceAccess = function (sourceKey) {370 return isPermitted(`source:${sourceKey}:access`) || /* For 2.5.* and below */ isPermitted(`cohortdefinition:*:generate:${sourceKey}:get`);371 }372 const isPermittedRunAs = () => isPermitted('user:runas:post');373 const setAuthParams = (tokenHeader, permissionsStr = '') => {374 !!tokenHeader && token(tokenHeader);375 !!permissionsStr && permissions(permissionsStr.split('|'));376 };377 var resetAuthParams = function () {378 token(null);379 subject(null);380 permissions(null);381 };382 const runAs = function(login, success, error) {383 return $.ajax({384 method: 'POST',385 url: config.webAPIRoot + 'user/runas',386 data: {387 login,388 },389 success,390 error,391 });392 };393 var api = {394 AUTH_PROVIDERS: AUTH_PROVIDERS,395 token: token,396 subject: subject,397 fullName,398 tokenExpirationDate: tokenExpirationDate,399 tokenExpired: tokenExpired,400 authProvider: authProvider,401 setAuthParams: setAuthParams,402 resetAuthParams: resetAuthParams,403 getAuthorizationHeader: getAuthorizationHeader,404 handleAccessDenied: handleAccessDenied,405 refreshToken: refreshToken,406 isAuthenticated: isAuthenticated,407 signInOpened: signInOpened,408 isPermitted: isPermitted,409 isPermittedGetAllNotifications: isPermittedGetAllNotifications,410 isPermittedGetViewedNotifications: isPermittedGetViewedNotifications,411 isPermittedPostViewedNotifications: isPermittedPostViewedNotifications,412 isPermittedCreateConceptset: isPermittedCreateConceptset,413 isPermittedUpdateConceptset: isPermittedUpdateConceptset,414 isPermittedDeleteConceptset: isPermittedDeleteConceptset,415 isPermittedReadConceptsets: isPermittedReadConceptsets,416 isPermittedReadCohorts: isPermittedReadCohorts,417 isPermittedReadCohort: isPermittedReadCohort,418 isPermittedCreateCohort: isPermittedCreateCohort,419 isPermittedCopyCohort: isPermittedCopyCohort,420 isPermittedUpdateCohort: isPermittedUpdateCohort,421 isPermittedDeleteCohort: isPermittedDeleteCohort,422 isPermittedGenerateCohort: isPermittedGenerateCohort,423 isPermittedReadCohortReport: isPermittedReadCohortReport,424 isPermittedReadJobs: isPermittedReadJobs,425 isPermittedEditConfiguration: isPermittedEditConfiguration,426 isPermittedEditSourcePriority: isPermittedEditSourcePriortiy,427 isPermittedReadRoles: isPermittedReadRoles,428 isPermittedReadRole: isPermittedReadRole,429 isPermittedEditRole: isPermittedEditRole,430 isPermittedCreateRole: isPermittedCreateRole,431 isPermittedDeleteRole: isPermittedDeleteRole,432 isPermittedEditRoleUsers: isPermittedEditRoleUsers,433 isPermittedEditRolePermissions: isPermittedEditRolePermissions,434 isPermittedReadIRs: isPermittedReadIRs,435 isPermittedCreateIR: isPermittedCreateIR,436 isPermittedEditIR: isPermittedEditIR,437 isPermittedDeleteIR: isPermittedDeleteIR,438 isPermittedCopyIR,439 isPermittedReadEstimations: isPermittedReadEstimations,440 isPermittedReadEstimation: isPermittedReadEstimation,441 isPermittedCreateEstimation: isPermittedCreateEstimation,442 isPermittedDeleteEstimation,443 isPermittedReadPlps: isPermittedReadPlps,444 isPermittedReadPlp: isPermittedReadPlp,445 isPermittedCreatePlp: isPermittedCreatePlp,446 isPermittedDeletePlp: isPermittedDeletePlp,447 isPermittedCopyPlp: isPermittedCopyPlp,448 isPermittedSearch: isPermittedSearch,449 isPermittedViewCdmResults: isPermittedViewCdmResults,450 isPermittedViewProfiles: isPermittedViewProfiles,451 isPermittedViewProfileDates: isPermittedViewProfileDates,452 isPermittedReadSource: isPermittedReadSource,453 isPermittedCreateSource: isPermittedCreateSource,454 isPermittedEditSource: isPermittedEditSource,455 isPermittedDeleteSource: isPermittedDeleteSource,456 isPermittedCheckSourceConnection: isPermittedCheckSourceConnection,457 isPermittedImportUsers,458 hasSourceAccess,459 isPermittedRunAs,460 loadUserInfo,461 TOKEN_HEADER,462 runAs,463 };464 return api;...

Full Screen

Full Screen

access-permit.js

Source:access-permit.js Github

copy

Full Screen

1function formSelectChangeAction(){2 let formId = $("#formName").val();3 let ownerId = $("#userId").val();4 let permittedUserId = $("#permittedUser").val();5 $("#loader").show();6 $.ajax({7 type: 'GET',8 dataType: 'json',9 url: './getPermitUserAndInvoiceNoList',10 data: {11 formId: formId,12 ownerId : ownerId,13 permittedUserId: permittedUserId14 },15 success: function(data){16 console.log(data.fileList);17 $("#fileList").empty();18 drawFileList(data.fileList);19 $("#permittedUserList").empty();20 drawPermittedUserList(data.permittedUser);21 $("#loader").hide();22 },23 error: function(jqXHR, textStatus,errorThrown){24 }25 });26}27function checkAllAction(){28 let isCheckAllSelect = $("#permitAll").prop('checked');29 if(isCheckAllSelect){30 $(".checkbox").prop('checked',true);31 }else{32 $(".checkbox").prop('checked',false);33 }34}35function memberAddAction(){36 let permittedUserId = $("#permittedUser").val();37 let permittedUserName = $("#permittedUser option:selected").text();38 let rows = $("#memberList tr");39 let isExist = false;40 let length = rows.length;41 for(let i=0;i<length;i++){42 let row = rows[i];43 if(permittedUserId == row.getAttribute('data-member-id')){44 isExist = true;45 break;46 }47 }48 if(permittedUserId != 0){49 if(!isExist){50 $("#memberList").append(`<tr id='mRow-${length+1}' data-row-type='newRow' data-member-id='${permittedUserId}'>51 <td>${length+1}</td>52 <td>${permittedUserName}</td>53 <td><i class="fa fa-trash" onclick="deleteMember('${length+1}')" style="cursor : pointer;"> </i></td>54 </tr>`)55 }56 }else{57 alert("Please Select Member....")58 }59 60}61function deleteMember(id){62 if(confirm("Are you sure to delete")){63 if($("#mRow-"+id).attr('data-row-type')=='newRow'){64 $("#mRow-"+id).remove();65 }else{66 $("#mRow-"+id).remove();67 }68 69 }70}71function saveAction(){72 let formId = $("#formName").val();73 let permittedUserId = $("#permittedUser").val();74 let rows = $("#fileList tr");75 let userId = $("#userId").val();76 let permittedUserIds = '';77 let permittedFileList = [];78 rows.each((index,row)=>{79 80 let id = row.id;81 if($("#permitCheck-"+id).prop('checked')){82 permittedFileList.push({83 resourceType : formId,84 resourceId : row.id,85 ownerId: userId,86 permittedUserId: permittedUserId,87 entryBy : userId 88 })89 }90 91 })92 if(formId != '0'){93 if(permittedUserId != '0'){94 95 if(confirm("Are you sure to Save Group")){96 $.ajax({97 type: 'POST',98 dataType: 'json',99 url: './submitFileAccessPermit',100 data: {101 fileAccessPermit : JSON.stringify({102 resourceType : formId,103 ownerId: userId,104 permittedUserId: permittedUserId,105 permittedFileList: permittedFileList106 })107 },108 success: function(data){109 if(data.result == "success"){110 alert("Access Permit Successful");111 // $("#groupList").empty();112 // drawGroupList(data.groupList);113 }114 },115 error: function(jqXHR, textStatus,errorThrown){116 117 }118 });119 }120 121 }else{122 alert("Please Select Permitted...");123 }124 }else{125 alert("Please Enter Group Name")126 }127}128function userListClick(permitUserId){129 $("#permittedUser").val(permitUserId).change();130}131function refreshAction(){132 location.reload();133}134function setGroup(groupId){135 $.ajax({136 type: 'GET',137 dataType: 'json',138 url: './getGroupInfo',139 data: {140 groupId : groupId141 },142 success: function(data){143 $("#memberList").empty();144 drawMemberList(data.memberList);145 $("#groupId").val(groupId);146 $("#btnSave").hide();147 $("#btnEdit").show();148 },149 error: function(jqXHR, textStatus,errorThrown){150 }151 });152}153function drawMemberList(data){154 let rows = '';155 $("#groupName").val(data[0].groupName);156 for(let i=0;i<data.length;i++){157 let member = data[i];158 rows += `<tr id='mRow-${member.autoId}' data-row-type='oldRow' data-member-id='${member.permittedUserId}'>159 <td>${i+1}</td>160 <td>${member.permittedUserName}</td>161 <td><i class="fa fa-trash" onclick="deleteMember('${member.autoId}')" style="cursor : pointer;"> </i></td>162 </tr>`;163 }164 $("#memberList").append(rows);165}166function drawFileList(data){167 let rows = '';168 for(let i=0;i<data.length;i++){169 let file = data[i];170 rows += `<tr id='${file.id}'>171 <td>${i+1}</td>172 <td>${file.formName}</td>173 <td>${file.fileNo}</td>174 <td><input type="checkbox" class='checkbox' id="permitCheck-${file.id}" ${file.permit=="0"?"":"checked"}></td>175 </tr>`;176 }177 $("#fileList").append(rows);178}179function drawPermittedUserList(data){180 let rows = '';181 for(let i=0;i<data.length;i++){182 let member = data[i];183 rows += `<tr id='permittedUser-${member.id}' style='cursor:pointer;' onclick='userListClick("${member.id}")'>184 <td>${i+1}</td>185 <td>${member.fullName}</td>186 </tr>`;187 }188 $("#permittedUserList").append(rows);...

Full Screen

Full Screen

address_and_contact.py

Source:address_and_contact.py Github

copy

Full Screen

1# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors2# License: GNU General Public License v3. See license.txt3from __future__ import unicode_literals4import frappe5def load_address_and_contact(doc, key):6 """Loads address list and contact list in `__onload`"""7 from erpnext.utilities.doctype.address.address import get_address_display8 doc.get("__onload").addr_list = [a.update({"display": get_address_display(a)}) \9 for a in frappe.get_all("Address",10 fields="*", filters={key: doc.name},11 order_by="is_primary_address desc, modified desc")]12 if doc.doctype != "Lead":13 doc.get("__onload").contact_list = frappe.get_all("Contact",14 fields="*", filters={key: doc.name},15 order_by="is_primary_contact desc, modified desc")16def has_permission(doc, ptype, user):17 links = get_permitted_and_not_permitted_links(doc.doctype)18 if not links.get("not_permitted_links"):19 # optimization: don't determine permissions based on link fields20 return True21 # True if any one is True or all are empty22 names = []23 for df in (links.get("permitted_links") + links.get("not_permitted_links")):24 doctype = df.options25 name = doc.get(df.fieldname)26 names.append(name)27 if name and frappe.has_permission(doctype, ptype, doc=name):28 return True29 if not any(names):30 return True31 else:32 return False33def get_permission_query_conditions_for_contact(user):34 return get_permission_query_conditions("Contact")35def get_permission_query_conditions_for_address(user):36 return get_permission_query_conditions("Address")37def get_permission_query_conditions(doctype):38 links = get_permitted_and_not_permitted_links(doctype)39 if not links.get("not_permitted_links"):40 # when everything is permitted, don't add additional condition41 return ""42 43 elif not links.get("permitted_links"):44 conditions = []45 46 # when everything is not permitted47 for df in links.get("not_permitted_links"):48 # like ifnull(customer, '')='' and ifnull(supplier, '')=''49 conditions.append("ifnull(`tab{doctype}`.`{fieldname}`, '')=''".format(doctype=doctype, fieldname=df.fieldname))50 51 return "( " + " and ".join(conditions) + " )"52 else:53 conditions = []54 for df in links.get("permitted_links"):55 # like ifnull(customer, '')!='' or ifnull(supplier, '')!=''56 conditions.append("ifnull(`tab{doctype}`.`{fieldname}`, '')!=''".format(doctype=doctype, fieldname=df.fieldname)) 57 return "( " + " or ".join(conditions) + " )"58def get_permitted_and_not_permitted_links(doctype):59 permitted_links = []60 not_permitted_links = []61 meta = frappe.get_meta(doctype)62 for df in meta.get_link_fields():63 if df.options not in ("Customer", "Supplier", "Sales Partner"):64 continue65 if frappe.has_permission(df.options):66 permitted_links.append(df)67 else:68 not_permitted_links.append(df)69 return {70 "permitted_links": permitted_links,71 "not_permitted_links": not_permitted_links...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful