How to use identity method in backstopjs

Best JavaScript code snippet using backstopjs

createIdentityPool.js

Source:createIdentityPool.js Github

copy

Full Screen

1#!/usr/bin/env node2const path = require('path');3const awscommon = require(path.join(__dirname, 'awscommonutils'));4const fs = require('fs');5const YAML = require('yamljs');6const AwsRequest = require(path.join(__dirname, 'AwsRequest'));7const argv = require('yargs')8.usage('Create the identity pools required for the project.\nIf identity pools with the same name already exist a new pool will not be created and the existing pool infomation will be used.\nUsage: $0 [options]')9.alias('s','baseDefinitionsFile')10.describe('s','yaml file that contains information about your API')11.default('s','./base.definitions.yaml')12.help('h')13.alias('h', 'help')14.argv;15if (!fs.existsSync(argv.baseDefinitionsFile)) {16 throw new Error("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");17}18var baseDefinitions = YAML.load(argv.baseDefinitionsFile);19var AWSCLIUserProfile = "default";20if (!awscommon.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {21 AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;22} else {23 console.log("using \"default\" AWSCLIUserProfile");24}25console.log("## Creating Identity Pools ##");26awscommon.verifyPath(baseDefinitions, ['cognitoIdentityPoolInfo', 'identityPools'], 'o', "definitions file \""+argv.baseDefinitionsFile+"\"").exitOnError();27var numIdentityPools = Object.keys(baseDefinitions.cognitoIdentityPoolInfo.identityPools).length;28var successDecCount = numIdentityPools;29// first lets get the identity pools to see if one with our name exists already30getIdentityPools(function (serverIdentityPools) {31 // now see which ones are valid and which ones need to be created32 var poolCreateRequests = [];33 Object.keys(baseDefinitions.cognitoIdentityPoolInfo.identityPools).forEach(function (identityPoolKey) {34 var identityPoolName;35 if (awscommon.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {36 identityPoolName = baseDefinitions.environment.AWSResourceNamePrefix + identityPoolKey;37 } else {38 throw new Error("Please assign a AWSResourceNamePrefix at 'environment.AWSResourceNamePrefix' in base definitions file '" + argv.baseDefinitionsFile + "'.");39 }40 var poolDef = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey];41 if (serverIdentityPools) {42 for (var index = 0; index < serverIdentityPools.IdentityPools.length; index ++) {43 if (identityPoolName === serverIdentityPools.IdentityPools[index].IdentityPoolName) {44 baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].identityPoolId = serverIdentityPools.IdentityPools[index].IdentityPoolId;45 console.log("Found identity pool \"" + identityPoolName + "\" on aws.");46 setRoles(identityPoolKey);47 updateRolePolicyDocumentStatementConditions(identityPoolKey);48 numIdentityPools --;49 successDecCount --;50 if (numIdentityPools === 0) {51 writeout();52 return;53 } else {54 break;55 }56 }57 }58 }59 // validate to make sure we have everything60 awscommon.verifyPath(poolDef, ['allowUnauthedIdentities'], 'b', "identity pool definition \"" + identityPoolKey + "\"").exitOnError();61 awscommon.verifyPath(poolDef, ['authProviders'], 'o', "identity pool definition \"" + identityPoolKey + "\"").exitOnError();62 var params={63 'identity-pool-name': {type: 'string', value: identityPoolName},64 'profile': {type: 'string', value:AWSCLIUserProfile}65 };66 params[(poolDef.allowUnauthedIdentities ? 'allow-unauthenticated-identities': 'no-allow-unauthenticated-identities')] = {type: 'none'};67 Object.keys(poolDef.authProviders).forEach(function(authProvider) {68 switch (authProvider) {69 case 'custom':70 awscommon.verifyPath(poolDef.authProviders,['custom', 'developerProvider'],'s','custom developer provider for pool "' + identityPoolKey + '""').exitOnError();71 params['developer-provider-name'] = {type: 'string', value:poolDef.authProviders.custom.developerProvider};72 break;73 default:74 }75 });76 poolCreateRequests.push(77 AwsRequest.createRequest({78 serviceName:'cognito-identity',79 functionName:'create-identity-pool',80 context: {poolName: identityPoolName, poolKey: identityPoolKey},81 returnSchema:'json',82 returnValidation:[{path:['IdentityPoolId'], type:'s'}],83 parameters:params84 })85 );86 });87 AwsRequest.createBatch(poolCreateRequests, function (batch) {88 batch.requestArray.forEach(function (request) {89 if (request.response.error) {90 console.log(request.response.error);91 console.log("Failed to create pool " + request.context.poolName + ".");92 } else {93 console.log("Successfully created pool " + request.context.poolName + ".");94 successDecCount --;95 baseDefinitions.cognitoIdentityPoolInfo.identityPools[request.context.poolKey].identityPoolId = request.response.parsedJSON.IdentityPoolId;96 setRoles(request.context.poolKey);97 updateRolePolicyDocumentStatementConditions(request.context.poolKey);98 }99 });100 writeout();101 }).startRequest();102});103function writeout() {104 // now delete role105 awscommon.updateFile(argv.baseDefinitionsFile, function () {106 return YAML.stringify(baseDefinitions, 15);107 }, function (backupErr, writeErr) {108 if (backupErr) {109 console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". pool id was not updated.");110 throw backupErr;111 }112 if (writeErr) {113 console.log("Unable to write updated definitions file.");114 throw writeErr;115 }116 if (successDecCount !== 0) {117 console.log("Some creation operations failed.");118 }119 });120}121function getIdentityPools (doneCallback) {122 AwsRequest.createRequest({123 serviceName:'cognito-identity',124 functionName:'list-identity-pools',125 returnSchema:'json',126 returnValidation:[{path:['IdentityPools','IdentityPoolId'], type:'s'},127 {path:['IdentityPools','IdentityPoolName'], type:'s'}],128 parameters:{129 'max-results': {type: 'string', value:'15'},130 'profile': {type: 'string', value:AWSCLIUserProfile}131 }132 }, function(request) {133 if (request.response.error) {134 console.log(request.response.error);135 doneCallback(null);136 return;137 }138 doneCallback(request.response.parsedJSON);139 }).startRequest();140}141function setRoles(identityPoolKey){142 if (!awscommon.verifyPath(baseDefinitions, ['cognitoIdentityPoolInfo', 'identityPools', identityPoolKey, 'roles'], 'o',"").isVerifyError) {143 var roles = {};144 // TODO GET ROLE ARN!!!145 roles = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].roles;146 var identityPoolRoles = {};147 Object.keys(roles).forEach(function (roleType) {148 identityPoolRoles[roleType] = baseDefinitions.cognitoIdentityPoolInfo.roleDefinitions[roles[roleType]].arnRole;149 });150 AwsRequest.createRequest({151 serviceName: 'cognito-identity',152 functionName: 'set-identity-pool-roles',153 context: {poolKey: identityPoolKey},154 returnSchema:'none',155 parameters: {156 'identity-pool-id' : {type:'string', value:baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].identityPoolId},157 'roles' : {type: 'JSONObject', value:identityPoolRoles},158 'profile': {type: 'string', value:AWSCLIUserProfile}159 }160 },161 function (roleReq) {162 if (roleReq.response.error) {163 throw roleReq.response.error;164 } else {165 console.log("Set Roles for \"" + roleReq.context.poolKey + "\"");166 }167 }).startRequest();168 }169}170function updateRolePolicyDocumentStatementConditions(identityPoolKey) {171 // first get the role172 var roles = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].roles;173 Object.keys(roles).forEach(function (roleType) {174 var role = roles[roleType];175 if (!awscommon.verifyPath(baseDefinitions,['cognitoIdentityPoolInfo','identityPools',identityPoolKey,'rolePolicyDocumentStatementConditions',role],'a').isVerifyError) {176 // get the role177 var roleName;178 if (awscommon.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {179 roleName = baseDefinitions.environment.AWSResourceNamePrefix + role;180 }181 AwsRequest.createRequest({182 serviceName: 'iam',183 functionName: 'get-role',184 context: {poolKey: identityPoolKey, roleKey:role, roleName: roleName},185 returnSchema:'json',186 parameters: {187 'role-name' : {type:'string', value:roleName},188 'profile': {type: 'string', value:AWSCLIUserProfile}189 }190 },191 function (roleReq) {192 if (roleReq.response.error) {193 console.log("no policy document statemets for role \"" + roleReq.context.roleKey + "to update. Is the role created?");194 console.log(roleReq.response.error);195 } else {196 if (!awscommon.verifyPath(roleReq.response.parsedJSON,['Role','AssumeRolePolicyDocument','Statement'],'a').isVerifyError) {197 // for each matching policy action add the conditions198 var statementArray = roleReq.response.parsedJSON.Role.AssumeRolePolicyDocument.Statement;199 var conditionArray = baseDefinitions.cognitoIdentityPoolInfo.identityPools[roleReq.context.poolKey].rolePolicyDocumentStatementConditions[role];200 for (var conditionIndex = 0; conditionIndex < conditionArray.length; conditionIndex ++) {201 for (var statementIndex = 0; statementIndex < statementArray.length; statementIndex ++) {202 if (statementArray[statementIndex].Action === conditionArray[conditionIndex].Action) {203 statementArray[statementIndex].Condition = conditionArray[conditionIndex].Condition;204 // we may want to replace the identity pool ID in some of the conditions205 Object.keys(statementArray[statementIndex].Condition).forEach(function(conditionType) {206 var theCondition = statementArray[statementIndex].Condition[conditionType];207 Object.keys(theCondition).forEach(function(conditionTypeParam) {208 var val = theCondition[conditionTypeParam];209 if (val === '$identityPoolId') {210 theCondition[conditionTypeParam] = baseDefinitions.cognitoIdentityPoolInfo.identityPools[roleReq.context.poolKey].identityPoolId;211 }212 });213 });214 }215 }216 }217 // UPDATE THE MODIFIED POLICY218 AwsRequest.createRequest({219 serviceName: 'iam',220 functionName: 'update-assume-role-policy',221 context: {poolKey: roleReq.context.poolKey, roleName:roleReq.context.roleName},222 returnSchema:'none',223 parameters: {224 'role-name': {type:'string', value:roleReq.context.roleName},225 'policy-document': {type: 'JSONObject', value:roleReq.response.parsedJSON.Role.AssumeRolePolicyDocument},226 'profile': {type: 'string', value:AWSCLIUserProfile},227 }228 },229 function (putPolReq) {230 if (putPolReq.response.error) {231 console.log("Error updating policy doc for role \"" + putPolReq.context.roleName + "\"");232 console.log(putPolReq.response.error);233 } else {234 console.log("Updated policy doc for role \"" + putPolReq.context.roleName + "\"");235 }236 }).startRequest();237 }238 }239 }).startRequest();240 }241 });...

Full Screen

Full Screen

IdentityHashMap.js

Source:IdentityHashMap.js Github

copy

Full Screen

1$_L(["java.util.AbstractMap","$.AbstractSet","$.Iterator","$.Map","$.MapEntry"],"java.util.IdentityHashMap",["java.lang.IllegalArgumentException","$.IllegalStateException","java.util.AbstractCollection","$.ConcurrentModificationException","java.util.MapEntry.Type","java.util.NoSuchElementException"],function(){2c$=$_C(function(){3this.elementData=null;4this.$size=0;5this.threshold=0;6this.modCount=0;7$_Z(this,arguments);8},java.util,"IdentityHashMap",java.util.AbstractMap,[java.util.Map,java.io.Serializable,Cloneable]);9$_K(c$,10function(){11this.construct(21);12});13$_K(c$,14function(maxSize){15$_R(this,java.util.IdentityHashMap,[]);16if(maxSize>=0){17this.$size=0;18this.threshold=this.getThreshold(maxSize);19this.elementData=this.newElementArray(this.computeElementArraySize());20}else{21throw new IllegalArgumentException();22}},"~N");23$_M(c$,"getThreshold",24($fz=function(maxSize){25return maxSize>3?maxSize:3;26},$fz.isPrivate=true,$fz),"~N");27$_M(c$,"computeElementArraySize",28($fz=function(){29return(Math.floor((this.threshold*10000)/7500))*2;30},$fz.isPrivate=true,$fz));31$_M(c$,"newElementArray",32($fz=function(s){33return new Array(s);34},$fz.isPrivate=true,$fz),"~N");35$_K(c$,36function(map){37this.construct(map.size()<6?11:map.size()*2);38this.putAllImpl(map);39},"java.util.Map");40$_M(c$,"massageValue",41($fz=function(value){42return((value===java.util.IdentityHashMap.NULL_OBJECT)?null:value);43},$fz.isPrivate=true,$fz),"~O");44$_V(c$,"clear",45function(){46this.$size=0;47for(var i=0;i<this.elementData.length;i++){48this.elementData[i]=null;49}50this.modCount++;51});52$_V(c$,"containsKey",53function(key){54if(key==null){55key=java.util.IdentityHashMap.NULL_OBJECT;56}var index=this.findIndex(key,this.elementData);57return this.elementData[index]===key;58},"~O");59$_V(c$,"containsValue",60function(value){61if(value==null){62value=java.util.IdentityHashMap.NULL_OBJECT;63}for(var i=1;i<this.elementData.length;i=i+2){64if(this.elementData[i]===value){65return true;66}}67return false;68},"~O");69$_V(c$,"get",70function(key){71if(key==null){72key=java.util.IdentityHashMap.NULL_OBJECT;73}var index=this.findIndex(key,this.elementData);74if(this.elementData[index]===key){75var result=this.elementData[index+1];76return this.massageValue(result);77}return null;78},"~O");79$_M(c$,"getEntry",80($fz=function(key){81if(key==null){82key=java.util.IdentityHashMap.NULL_OBJECT;83}var index=this.findIndex(key,this.elementData);84if(this.elementData[index]===key){85return this.getEntry(index);86}return null;87},$fz.isPrivate=true,$fz),"~O");88$_M(c$,"getEntry",89($fz=function(index){90var key=this.elementData[index];91var value=this.elementData[index+1];92if(key===java.util.IdentityHashMap.NULL_OBJECT){93key=null;94}if(value===java.util.IdentityHashMap.NULL_OBJECT){95value=null;96}return new java.util.IdentityHashMap.IdentityHashMapEntry(key,value);97},$fz.isPrivate=true,$fz),"~N");98$_M(c$,"findIndex",99($fz=function(key,array){100var length=array.length;101var index=this.getModuloHash(key,length);102var last=(index+length-2)%length;103while(index!=last){104if(array[index]===key||(array[index]==null)){105break;106}index=(index+2)%length;107}108return index;109},$fz.isPrivate=true,$fz),"~O,~A");110$_M(c$,"getModuloHash",111($fz=function(key,length){112return((System.identityHashCode(key)&0x7FFFFFFF)%(Math.floor(length/2)))*2;113},$fz.isPrivate=true,$fz),"~O,~N");114$_V(c$,"put",115function(key,value){116var _key=key;117var _value=value;118if(_key==null){119_key=java.util.IdentityHashMap.NULL_OBJECT;120}if(_value==null){121_value=java.util.IdentityHashMap.NULL_OBJECT;122}var index=this.findIndex(_key,this.elementData);123if(this.elementData[index]!==_key){124this.modCount++;125if(++this.$size>this.threshold){126this.rehash();127index=this.findIndex(_key,this.elementData);128}this.elementData[index]=_key;129this.elementData[index+1]=null;130}var result=this.elementData[index+1];131this.elementData[index+1]=_value;132return this.massageValue(result);133},"~O,~O");134$_V(c$,"putAll",135function(map){136this.putAllImpl(map);137},"java.util.Map");138$_M(c$,"rehash",139($fz=function(){140var newlength=this.elementData.length<<1;141if(newlength==0){142newlength=1;143}var newData=this.newElementArray(newlength);144for(var i=0;i<this.elementData.length;i=i+2){145var key=this.elementData[i];146if(key!=null){147var index=this.findIndex(key,newData);148newData[index]=key;149newData[index+1]=this.elementData[i+1];150}}151this.elementData=newData;152this.computeMaxSize();153},$fz.isPrivate=true,$fz));154$_M(c$,"computeMaxSize",155($fz=function(){156this.threshold=(Math.floor((Math.floor(this.elementData.length/ 2)) * 7500 /10000));157},$fz.isPrivate=true,$fz));158$_V(c$,"remove",159function(key){160if(key==null){161key=java.util.IdentityHashMap.NULL_OBJECT;162}var hashedOk;163var index;164var next;165var hash;166var result;167var object;168index=next=this.findIndex(key,this.elementData);169if(this.elementData[index]!==key){170return null;171}result=this.elementData[index+1];172var length=this.elementData.length;173while(true){174next=(next+2)%length;175object=this.elementData[next];176if(object==null){177break;178}hash=this.getModuloHash(object,length);179hashedOk=hash>index;180if(next<index){181hashedOk=hashedOk||(hash<=next);182}else{183hashedOk=hashedOk&&(hash<=next);184}if(!hashedOk){185this.elementData[index]=object;186this.elementData[index+1]=this.elementData[next+1];187index=next;188}}189this.$size--;190this.modCount++;191this.elementData[index]=null;192this.elementData[index+1]=null;193return this.massageValue(result);194},"~O");195$_V(c$,"entrySet",196function(){197return new java.util.IdentityHashMap.IdentityHashMapEntrySet(this);198});199$_V(c$,"keySet",200function(){201if(this.$keySet==null){202this.$keySet=(($_D("java.util.IdentityHashMap$1")?0:java.util.IdentityHashMap.$IdentityHashMap$1$()),$_N(java.util.IdentityHashMap$1,this,null));203}return this.$keySet;204});205$_V(c$,"values",206function(){207if(this.valuesCollection==null){208this.valuesCollection=(($_D("java.util.IdentityHashMap$2")?0:java.util.IdentityHashMap.$IdentityHashMap$2$()),$_N(java.util.IdentityHashMap$2,this,null));209}return this.valuesCollection;210});211$_V(c$,"equals",212function(object){213if(this===object){214return true;215}if($_O(object,java.util.Map)){216var map=object;217if(this.size()!=map.size()){218return false;219}var set=this.entrySet();220return set.equals(map.entrySet());221}return false;222},"~O");223$_M(c$,"clone",224function(){225try{226return $_U(this,java.util.IdentityHashMap,"clone",[]);227}catch(e){228if($_O(e,CloneNotSupportedException)){229return null;230}else{231throw e;232}233}234});235$_V(c$,"isEmpty",236function(){237return this.$size==0;238});239$_V(c$,"size",240function(){241return this.$size;242});243$_M(c$,"putAllImpl",244($fz=function(map){245if(map.entrySet()!=null){246$_U(this,java.util.IdentityHashMap,"putAll",[map]);247}},$fz.isPrivate=true,$fz),"java.util.Map");248c$.$IdentityHashMap$1$=function(){249$_H();250c$=$_W(java.util,"IdentityHashMap$1",java.util.AbstractSet);251$_V(c$,"contains",252function(object){253return this.b$["java.util.IdentityHashMap"].containsKey(object);254},"~O");255$_V(c$,"size",256function(){257return this.b$["java.util.IdentityHashMap"].size();258});259$_V(c$,"clear",260function(){261this.b$["java.util.IdentityHashMap"].clear();262});263$_V(c$,"remove",264function(key){265if(this.b$["java.util.IdentityHashMap"].containsKey(key)){266this.b$["java.util.IdentityHashMap"].remove(key);267return true;268}return false;269},"~O");270$_V(c$,"iterator",271function(){272return new java.util.IdentityHashMap.IdentityHashMapIterator((($_D("java.util.IdentityHashMap$1$1")?0:java.util.IdentityHashMap.$IdentityHashMap$1$1$()),$_N(java.util.IdentityHashMap$1$1,this,null)),this.b$["java.util.IdentityHashMap"]);273});274c$=$_P();275};276c$.$IdentityHashMap$1$1$=function(){277$_H();278c$=$_W(java.util,"IdentityHashMap$1$1",null,java.util.MapEntry.Type);279$_V(c$,"get",280function(entry){281return entry.key;282},"java.util.MapEntry");283c$=$_P();284};285c$.$IdentityHashMap$2$=function(){286$_H();287c$=$_W(java.util,"IdentityHashMap$2",java.util.AbstractCollection);288$_V(c$,"contains",289function(object){290return this.b$["java.util.IdentityHashMap"].containsValue(object);291},"~O");292$_V(c$,"size",293function(){294return this.b$["java.util.IdentityHashMap"].size();295});296$_V(c$,"clear",297function(){298this.b$["java.util.IdentityHashMap"].clear();299});300$_V(c$,"iterator",301function(){302return new java.util.IdentityHashMap.IdentityHashMapIterator((($_D("java.util.IdentityHashMap$2$1")?0:java.util.IdentityHashMap.$IdentityHashMap$2$1$()),$_N(java.util.IdentityHashMap$2$1,this,null)),this.b$["java.util.IdentityHashMap"]);303});304$_V(c$,"remove",305function(object){306var it=this.iterator();307while(it.hasNext()){308if(object===it.next()){309it.remove();310return true;311}}312return false;313},"~O");314c$=$_P();315};316c$.$IdentityHashMap$2$1$=function(){317$_H();318c$=$_W(java.util,"IdentityHashMap$2$1",null,java.util.MapEntry.Type);319$_V(c$,"get",320function(entry){321return entry.value;322},"java.util.MapEntry");323c$=$_P();324};325$_H();326c$=$_T(java.util.IdentityHashMap,"IdentityHashMapEntry",java.util.MapEntry);327$_V(c$,"equals",328function(a){329if(this===a){330return true;331}if($_O(a,java.util.Map.Entry)){332var b=a;333return(this.key===b.getKey())&&(this.value===b.getValue());334}return false;335},"~O");336$_V(c$,"hashCode",337function(){338return System.identityHashCode(this.key)^System.identityHashCode(this.value);339});340$_V(c$,"toString",341function(){342return this.key+"="+this.value;343});344c$=$_P();345$_H();346c$=$_C(function(){347this.position=0;348this.lastPosition=0;349this.associatedMap=null;350this.expectedModCount=0;351this.type=null;352this.canRemove=false;353$_Z(this,arguments);354},java.util.IdentityHashMap,"IdentityHashMapIterator",null,java.util.Iterator);355$_K(c$,356function(a,b){357this.associatedMap=b;358this.type=a;359this.expectedModCount=b.modCount;360},"java.util.MapEntry.Type,java.util.IdentityHashMap");361$_V(c$,"hasNext",362function(){363while(this.position<this.associatedMap.elementData.length){364if(this.associatedMap.elementData[this.position]==null){365this.position+=2;366}else{367return true;368}}369return false;370});371$_M(c$,"checkConcurrentMod",372function(){373if(this.expectedModCount!=this.associatedMap.modCount){374throw new java.util.ConcurrentModificationException();375}});376$_V(c$,"next",377function(){378this.checkConcurrentMod();379if(!this.hasNext()){380throw new java.util.NoSuchElementException();381}var a=this.associatedMap.getEntry(this.position);382this.lastPosition=this.position;383this.position+=2;384this.canRemove=true;385return this.type.get(a);386});387$_V(c$,"remove",388function(){389this.checkConcurrentMod();390if(!this.canRemove){391throw new IllegalStateException();392}this.canRemove=false;393this.associatedMap.remove(this.associatedMap.elementData[this.lastPosition]);394this.position=this.lastPosition;395this.expectedModCount++;396});397c$=$_P();398$_H();399c$=$_C(function(){400this.associatedMap=null;401$_Z(this,arguments);402},java.util.IdentityHashMap,"IdentityHashMapEntrySet",java.util.AbstractSet);403$_K(c$,404function(a){405$_R(this,java.util.IdentityHashMap.IdentityHashMapEntrySet,[]);406this.associatedMap=a;407},"java.util.IdentityHashMap");408$_M(c$,"hashMap",409function(){410return this.associatedMap;411});412$_V(c$,"size",413function(){414return this.associatedMap.$size;415});416$_V(c$,"clear",417function(){418this.associatedMap.clear();419});420$_V(c$,"remove",421function(a){422if(this.contains(a)){423this.associatedMap.remove((a).getKey());424return true;425}return false;426},"~O");427$_V(c$,"contains",428function(a){429if($_O(a,java.util.Map.Entry)){430var b=this.associatedMap.getEntry((a).getKey());431return b!=null&&b.equals(a);432}return false;433},"~O");434$_V(c$,"iterator",435function(){436return new java.util.IdentityHashMap.IdentityHashMapIterator((($_D("java.util.IdentityHashMap$IdentityHashMapEntrySet$1")?0:java.util.IdentityHashMap.IdentityHashMapEntrySet.$IdentityHashMap$IdentityHashMapEntrySet$1$()),$_N(java.util.IdentityHashMap$IdentityHashMapEntrySet$1,this,null)),this.associatedMap);437});438c$.$IdentityHashMap$IdentityHashMapEntrySet$1$=function(){439$_H();440c$=$_W(java.util,"IdentityHashMap$IdentityHashMapEntrySet$1",null,java.util.MapEntry.Type);441$_V(c$,"get",442function(a){443return a;444},"java.util.MapEntry");445c$=$_P();446};447c$=$_P();448$_S(c$,449"DEFAULT_MAX_SIZE",21,450"loadFactor",7500);451c$.NULL_OBJECT=c$.prototype.NULL_OBJECT=new JavaObject();...

Full Screen

Full Screen

core.js

Source:core.js Github

copy

Full Screen

1var systemObject = {2 defaultMax : 10,3 buttonsMax : 5,4 tableMax : [], 5 currentPage : [],6 tableData : [],7 tableDataIndex : [],8 tableDataText : [], 9 tableDataFiltered : [],10 pagesAll : [],11 recordsAll : [],12 blocksAll : [],13 blockCurrent : [],14 indexStart : [],15 indexEnd : [],16 indexPrevious : [],17 indexNext : [],18 isEmpty : function(thisValue) {19 "use strict";20 if ($.isArray(thisValue)) {21 return thisValue.length > 0 ? false : true;22 } else {23 return thisValue !== '' && typeof thisValue !== 'undefined' ? false : true;24 }25 },26 outerHtml : function(obj) {27 "use strict";28 return obj.wrap('<div>').parent().html(); 29 },30 setCurrentPage : function(thisIdentity, thisPage) {31 "use strict";32 thisPage = !this.isEmpty(thisPage) ? thisPage : 1;33 this.currentPage[thisIdentity] = thisPage;34 $('#' + thisIdentity).attr('data-page', thisPage);35 },36 pagingTemplate : function(thisIdentity, thisButtons) {37 "use strict";38 if (!this.isEmpty(thisButtons)) {39 var thisPaging = '<ul class="paging" data-form="' + thisIdentity + '">';40 thisPaging += thisButtons;41 thisPaging += '</ul>';42 return thisPaging;43 }44 },45 feedPaging : function(thisIdentity, thisButtons) {46 "use strict";47 // replace pagination48 $('#' + thisIdentity + 'Paging').html(this.pagingTemplate(thisIdentity, thisButtons));49 // replace number of records50 $('#' + thisIdentity + 'Count').html(this.recordsAll[thisIdentity]);51 // replace page52 $('#' + thisIdentity + 'Page').html(this.currentPage[thisIdentity]);53 // replace page of54 $('#' + thisIdentity + 'PageOf').html(this.pagesAll[thisIdentity]);55 },56 pagingLoad : function(thisIdentity, thisArray) {57 "use strict";58 if (!this.isEmpty(thisIdentity)) {59 var thisButtons = [];60 if (!this.isEmpty(thisArray)) {61 62 if ($('#' + thisIdentity + 'Paging').length > 0) {63 64 // first / previous buttons65 if (this.currentPage[thisIdentity] > 1) {66 67 thisButtons.push('<li><span data-index="1">&lt;&lt;</span></li>');68 thisButtons.push('<li><span data-index="' + parseInt((this.currentPage[thisIdentity] - 1), 10) + '">&lt;</span></li>');69 70 } else {71 72 thisButtons.push('<li class="inactive">&lt;&lt;</li>');73 thisButtons.push('<li class="inactive">&lt;</li>');74 75 }76 77 // previous block button78 if (this.blockCurrent[thisIdentity] > 1) {79 thisButtons.push('<li><span data-index="' + this.indexPrevious[thisIdentity] + '">...</span></li>');80 } 81 82 // middle buttons83 for (var i = this.indexStart[thisIdentity]; i <= this.indexEnd[thisIdentity]; i++) {84 var thisButton;85 if (i == this.currentPage[thisIdentity]) {86 thisButton = '<li><span class="active">' + i + '</span></li>';87 } else {88 thisButton = '<li><span data-index="' + i + '">' + i + '</span></li>';89 }90 thisButtons.push(thisButton);91 }92 93 // next block button94 if (this.blockCurrent[thisIdentity] < this.blocksAll[thisIdentity]) {95 thisButtons.push('<li><span data-index="' + this.indexNext[thisIdentity] + '">...</span></li>');96 }97 98 // next / last buttons99 if (this.currentPage[thisIdentity] < this.pagesAll[thisIdentity]) {100 101 thisButtons.push('<li><span data-index="' + (parseInt(this.currentPage[thisIdentity], 10) + 1) + '">&gt;</span></li>'); 102 thisButtons.push('<li><span data-index="' + this.pagesAll[thisIdentity] + '">&gt;&gt;</span></li>');103 104 } else {105 106 thisButtons.push('<li class="inactive">&gt;</li>'); 107 thisButtons.push('<li class="inactive">&gt;&gt;</li>');108 109 }110 111 this.feedPaging(thisIdentity, thisButtons.join(''));112 113 }114 115 } else {116 117 // if array is empty118 thisButtons.push('<li class="inactive">&lt;&lt;</li>'); 119 thisButtons.push('<li class="inactive">&lt;</li>');120 thisButtons.push('<li class="inactive">1</li>');121 thisButtons.push('<li class="inactive">&gt;</li>'); 122 thisButtons.push('<li class="inactive">&gt;&gt;</li>');123 124 this.feedPaging(thisIdentity, thisButtons.join(''));125 126 }127 }128 },129 calculate : function(thisIdentity, thisArray) {130 "use strict";131 // all records132 this.recordsAll[thisIdentity] = thisArray.length;133 // rounding up the number of pages134 this.pagesAll[thisIdentity] = Math.ceil(this.recordsAll[thisIdentity] / this.tableMax[thisIdentity]);135 // correct current page if necessary136 this.currentPage[thisIdentity] = this.currentPage[thisIdentity] < this.pagesAll[thisIdentity] ?137 this.currentPage[thisIdentity] : this.pagesAll[thisIdentity];138 // setting current page number139 this.setCurrentPage(thisIdentity, this.currentPage[thisIdentity]);140 // calculate blocks141 this.blocksAll[thisIdentity] = Math.ceil(this.pagesAll[thisIdentity] / this.buttonsMax);142 this.blockCurrent[thisIdentity] = Math.ceil(this.currentPage[thisIdentity] / this.buttonsMax);143 // start index144 this.indexStart[thisIdentity] = Math.ceil( 145 ( 146 (this.blockCurrent[thisIdentity] - 1) * this.buttonsMax 147 ) + 1 148 );149 // if there is only one block150 // or it's the last block151 // get the right number of buttons152 var thisButtonsMaxEnd = this.buttonsMax;153 if (this.blockCurrent[thisIdentity] == this.blocksAll[thisIdentity]) {154 // if there's only one block of buttons155 if (this.blocksAll[thisIdentity] == 1) {156 thisButtonsMaxEnd = this.pagesAll[thisIdentity];157 } else {158 thisButtonsMaxEnd = Math.ceil(159 parseInt( (this.pagesAll[thisIdentity] - this.indexStart[thisIdentity]), 10) + 1160 );161 }162 }163 this.indexEnd[thisIdentity] = parseInt(164 ( (this.indexStart[thisIdentity] - 1) + thisButtonsMaxEnd ), 10165 );166 this.indexPrevious[thisIdentity] = parseInt(167 (this.indexStart[thisIdentity] - this.buttonsMax), 10168 );169 this.indexNext[thisIdentity] = parseInt(170 (this.indexEnd[thisIdentity] + 1), 10171 );172 },173 paging : function(obj) {174 "use strict";175 obj.live('click', function(e) {176 e.preventDefault();177 var thisIdentity = $(this).closest('ul').attr('data-form');178 var thisIndex = $(this).attr('data-index');179 if (!systemObject.isEmpty(thisIdentity)) {180 // update current page number181 systemObject.setCurrentPage(thisIdentity, thisIndex);182 if (!systemObject.isEmpty(systemObject.tableDataFiltered[thisIdentity])) {183 systemObject.limit(thisIdentity, systemObject.tableDataFiltered[thisIdentity]);184 } else {185 systemObject.limit(thisIdentity, systemObject.tableData[thisIdentity]);186 }187 }188 });189 },190 limit : function(thisIdentity, thisArray) {191 "use strict";192 if (!this.isEmpty(thisIdentity)) {193 this.calculate(thisIdentity, thisArray);194 if (!this.isEmpty(thisArray)) {195 var thisFiltered = [];196 if (this.pagesAll[thisIdentity] > 1) {197 var thisStartIndex = ( 198 parseInt((this.currentPage[thisIdentity] - 1), 10) * 199 this.tableMax[thisIdentity]200 );201 var thisEndIndex = (202 parseInt(thisStartIndex, 10) + this.tableMax[thisIdentity]203 );204 thisFiltered = thisArray.slice(thisStartIndex, thisEndIndex);205 } else {206 thisFiltered = thisArray.slice(0, this.tableMax[thisIdentity]);207 }208 $('#' + thisIdentity + 'Table tbody').html(thisFiltered.join(''));209 } else {210 var thisSpan = $('#' + thisIdentity + 'Table th').length;211 var thisNoRecords = '<tr><td colspan="' + thisSpan + '"';212 thisNoRecords += ' class="bgOrange">';213 thisNoRecords += 'There are no records matching your search criteria.';214 thisNoRecords += '</td></tr>'; 215 $('#' + thisIdentity + 'Table tbody').html($(thisNoRecords).show());216 }217 this.pagingLoad(thisIdentity, thisArray);218 } 219 },220 loadTable : function(obj) {221 "use strict";222 if (obj.length > 0) {223 $.each(obj, function() {224 var thisObj = $(this);225 var thisUrl = thisObj.attr('data-url');226 var thisIdentity = thisObj.attr('id');227 var thisMax = thisObj.attr('data-max');228 systemObject.tableMax[thisIdentity] = !systemObject.isEmpty(thisMax) ? 229 parseInt(thisMax, 10) : systemObject.defaultMax;230 var thisCurrentPage = thisObj.attr('data-page');231 systemObject.currentPage[thisIdentity] = !systemObject.isEmpty(thisCurrentPage) ? 232 parseInt(thisCurrentPage, 10) : 1;233 $.ajax({234 type : 'GET',235 url : thisUrl,236 dataType : 'json',237 success : function(data) {238 if (data && data.rows && data.rowsIndex && data.text) {239 systemObject.tableData[thisIdentity] = data.rows;240 systemObject.tableDataIndex[thisIdentity] = data.rowsIndex;241 systemObject.tableDataText[thisIdentity] = data.text;242 systemObject.limit(thisIdentity, systemObject.tableData[thisIdentity]);243 }244 }245 });246 });247 }248 },249 search : function(obj) {250 "use strict";251 $.each(obj, function() {252 var thisObj = $(this);253 var thisIdentity = thisObj.attr('data-form');254 thisObj.live('keyup keypress', function(e) {255 var thisCode = (e.keyCode ? e.keyCode : e.which);256 if (thisCode === 13) {257 e.preventDefault();258 } else {259 if (!systemObject.isEmpty(systemObject.tableData[thisIdentity])) {260 if (e.type === 'keyup') {261 systemObject.setCurrentPage(thisIdentity);262 systemObject.tableDataFiltered[thisIdentity] = [];263 var thisValue = $(this).val().toLowerCase();264 if (!systemObject.isEmpty(thisValue)) {265 var thisValues = thisValue.split(' ');266 for (var tIndex in systemObject.tableDataText[thisIdentity]) {267 $.each(thisValues, function(k, v) {268 if (systemObject.tableDataText[thisIdentity][tIndex].indexOf(v) !== -1) {269 var thisItem = systemObject.outerHtml($(systemObject.tableDataIndex[thisIdentity][tIndex]));270 systemObject.tableDataFiltered[thisIdentity].push(thisItem);271 return false;272 }273 });274 }275 systemObject.limit(thisIdentity, systemObject.tableDataFiltered[thisIdentity]);276 } else {277 systemObject.limit(thisIdentity, systemObject.tableData[thisIdentity]);278 }279 }280 }281 }282 });283 });284 }285};286$(function() {287 "use strict";288 systemObject.loadTable($('.loadTable'));289 systemObject.paging($('.paging li span'));290 systemObject.search($('.search'));...

Full Screen

Full Screen

custom_oauth_server.js

Source:custom_oauth_server.js Github

copy

Full Screen

1/*globals OAuth*/2import _ from 'underscore';3const logger = new Logger('CustomOAuth');4const Services = {};5const BeforeUpdateOrCreateUserFromExternalService = [];6export class CustomOAuth {7 constructor(name, options) {8 logger.debug('Init CustomOAuth', name, options);9 this.name = name;10 if (!Match.test(this.name, String)) {11 throw new Meteor.Error('CustomOAuth: Name is required and must be String');12 }13 if (Services[this.name]) {14 Services[this.name].configure(options);15 return;16 }17 Services[this.name] = this;18 this.configure(options);19 this.userAgent = 'Meteor';20 if (Meteor.release) {21 this.userAgent += `/${ Meteor.release }`;22 }23 Accounts.oauth.registerService(this.name);24 this.registerService();25 this.addHookToProcessUser();26 }27 configure(options) {28 if (!Match.test(options, Object)) {29 throw new Meteor.Error('CustomOAuth: Options is required and must be Object');30 }31 if (!Match.test(options.serverURL, String)) {32 throw new Meteor.Error('CustomOAuth: Options.serverURL is required and must be String');33 }34 if (!Match.test(options.tokenPath, String)) {35 options.tokenPath = '/oauth/token';36 }37 if (!Match.test(options.identityPath, String)) {38 options.identityPath = '/me';39 }40 this.serverURL = options.serverURL;41 this.tokenPath = options.tokenPath;42 this.identityPath = options.identityPath;43 this.tokenSentVia = options.tokenSentVia;44 this.identityTokenSentVia = options.identityTokenSentVia;45 this.usernameField = (options.usernameField || '').trim();46 this.mergeUsers = options.mergeUsers;47 if (this.identityTokenSentVia == null || this.identityTokenSentVia === 'default') {48 this.identityTokenSentVia = this.tokenSentVia;49 }50 if (!/^https?:\/\/.+/.test(this.tokenPath)) {51 this.tokenPath = this.serverURL + this.tokenPath;52 }53 if (!/^https?:\/\/.+/.test(this.identityPath)) {54 this.identityPath = this.serverURL + this.identityPath;55 }56 if (Match.test(options.addAutopublishFields, Object)) {57 Accounts.addAutopublishFields(options.addAutopublishFields);58 }59 }60 getAccessToken(query) {61 const config = ServiceConfiguration.configurations.findOne({service: this.name});62 if (!config) {63 throw new ServiceConfiguration.ConfigError();64 }65 let response = undefined;66 const allOptions = {67 headers: {68 'User-Agent': this.userAgent, // http://doc.gitlab.com/ce/api/users.html#Current-user69 Accept: 'application/json'70 },71 params: {72 code: query.code,73 redirect_uri: OAuth._redirectUri(this.name, config),74 grant_type: 'authorization_code',75 state: query.state76 }77 };78 // Only send clientID / secret once on header or payload.79 if (this.tokenSentVia === 'header') {80 allOptions['auth'] = `${ config.clientId }:${ OAuth.openSecret(config.secret) }`;81 } else {82 allOptions['params']['client_secret'] = OAuth.openSecret(config.secret);83 allOptions['params']['client_id'] = config.clientId;84 }85 try {86 response = HTTP.post(this.tokenPath, allOptions);87 } catch (err) {88 const error = new Error(`Failed to complete OAuth handshake with ${ this.name } at ${ this.tokenPath }. ${ err.message }`);89 throw _.extend(error, {response: err.response});90 }91 let data;92 if (response.data) {93 data = response.data;94 } else {95 data = JSON.parse(response.content);96 }97 if (data.error) { //if the http response was a json object with an error attribute98 throw new Error(`Failed to complete OAuth handshake with ${ this.name } at ${ this.tokenPath }. ${ data.error }`);99 } else {100 return data.access_token;101 }102 }103 getIdentity(accessToken) {104 const params = {};105 const headers = {106 'User-Agent': this.userAgent // http://doc.gitlab.com/ce/api/users.html#Current-user107 };108 if (this.identityTokenSentVia === 'header') {109 headers['Authorization'] = `Bearer ${ accessToken }`;110 } else {111 params['access_token'] = accessToken;112 }113 try {114 const response = HTTP.get(this.identityPath, {115 headers,116 params117 });118 let data;119 if (response.data) {120 data = response.data;121 } else {122 data = JSON.parse(response.content);123 }124 logger.debug('Identity response', JSON.stringify(data, null, 2));125 return data;126 } catch (err) {127 const error = new Error(`Failed to fetch identity from ${ this.name } at ${ this.identityPath }. ${ err.message }`);128 throw _.extend(error, {response: err.response});129 }130 }131 registerService() {132 const self = this;133 OAuth.registerService(this.name, 2, null, (query) => {134 const accessToken = self.getAccessToken(query);135 // console.log 'at:', accessToken136 let identity = self.getIdentity(accessToken);137 if (identity) {138 // Set 'id' to '_id' for any sources that provide it139 if (identity._id && !identity.id) {140 identity.id = identity._id;141 }142 // Fix for Reddit143 if (identity.result) {144 identity = identity.result;145 }146 // Fix WordPress-like identities having 'ID' instead of 'id'147 if (identity.ID && !identity.id) {148 identity.id = identity.ID;149 }150 // Fix Auth0-like identities having 'user_id' instead of 'id'151 if (identity.user_id && !identity.id) {152 identity.id = identity.user_id;153 }154 if (identity.CharacterID && !identity.id) {155 identity.id = identity.CharacterID;156 }157 // Fix Dataporten having 'user.userid' instead of 'id'158 if (identity.user && identity.user.userid && !identity.id) {159 if (identity.user.userid_sec && identity.user.userid_sec[0]) {160 identity.id = identity.user.userid_sec[0];161 } else {162 identity.id = identity.user.userid;163 }164 identity.email = identity.user.email;165 }166 // Fix for Xenforo [BD]API plugin for 'user.user_id; instead of 'id'167 if (identity.user && identity.user.user_id && !identity.id) {168 identity.id = identity.user.user_id;169 identity.email = identity.user.user_email;170 }171 // Fix general 'phid' instead of 'id' from phabricator172 if (identity.phid && !identity.id) {173 identity.id = identity.phid;174 }175 // Fix Keycloak-like identities having 'sub' instead of 'id'176 if (identity.sub && !identity.id) {177 identity.id = identity.sub;178 }179 // Fix general 'userid' instead of 'id' from provider180 if (identity.userid && !identity.id) {181 identity.id = identity.userid;182 }183 // Fix when authenticating from a meteor app with 'emails' field184 if (!identity.email && (identity.emails && Array.isArray(identity.emails) && identity.emails.length >= 1)) {185 identity.email = identity.emails[0].address ? identity.emails[0].address : undefined;186 }187 }188 // console.log 'id:', JSON.stringify identity, null, ' '189 const serviceData = {190 _OAuthCustom: true,191 accessToken192 };193 _.extend(serviceData, identity);194 const data = {195 serviceData,196 options: {197 profile: {198 name: identity.name || identity.username || identity.nickname || identity.CharacterName || identity.userName || identity.preferred_username || (identity.user && identity.user.name)199 }200 }201 };202 // console.log data203 return data;204 });205 }206 retrieveCredential(credentialToken, credentialSecret) {207 return OAuth.retrieveCredential(credentialToken, credentialSecret);208 }209 getUsername(data) {210 let username = '';211 username = this.usernameField.split('.').reduce(function(prev, curr) {212 return prev ? prev[curr] : undefined;213 }, data);214 if (!username) {215 throw new Meteor.Error('field_not_found', `Username field "${ this.usernameField }" not found in data`, data);216 }217 return username;218 }219 addHookToProcessUser() {220 BeforeUpdateOrCreateUserFromExternalService.push((serviceName, serviceData/*, options*/) => {221 if (serviceName !== this.name) {222 return;223 }224 if (this.usernameField) {225 const username = this.getUsername(serviceData);226 const user = RocketChat.models.Users.findOneByUsername(username);227 if (!user) {228 return;229 }230 // User already created or merged231 if (user.services && user.services[serviceName] && user.services[serviceName].id === serviceData.id) {232 return;233 }234 if (this.mergeUsers !== true) {235 throw new Meteor.Error('CustomOAuth', `User with username ${ user.username } already exists`);236 }237 const serviceIdKey = `services.${ serviceName }.id`;238 const update = {239 $set: {240 [serviceIdKey]: serviceData.id241 }242 };243 RocketChat.models.Users.update({_id: user._id}, update);244 }245 });246 Accounts.validateNewUser((user) => {247 if (!user.services || !user.services[this.name] || !user.services[this.name].id) {248 return true;249 }250 if (this.usernameField) {251 user.username = this.getUsername(user.services[this.name]);252 }253 return true;254 });255 }256}257const updateOrCreateUserFromExternalService = Accounts.updateOrCreateUserFromExternalService;258Accounts.updateOrCreateUserFromExternalService = function(/*serviceName, serviceData, options*/) {259 for (const hook of BeforeUpdateOrCreateUserFromExternalService) {260 hook.apply(this, arguments);261 }262 return updateOrCreateUserFromExternalService.apply(this, arguments);...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import signal from 'pico-signals';2import { assertApp } from '../identities';3import { UnknownSessionError, IdentityRevokedError } from '../utils/errors';4import { loadSessions, createSession, removeSession, assertSessionOptions } from './session';5class Sessions {6 #sessions;7 #storage;8 #identities;9 #identityListeners = new Map();10 #onDestroy = signal();11 constructor(sessions, storage, identities) {12 this.#sessions = sessions;13 this.#storage = storage;14 this.#identities = identities;15 this.#identities.onLoad(this.#handleIdentitiesLoad);16 this.#identities.onChange(this.#handleIdentitiesChange);17 }18 get(sessionId) {19 const session = this.#sessions[sessionId];20 if (!session || !session.isValid(sessionId)) {21 throw new UnknownSessionError(sessionId);22 }23 return session;24 }25 isValid(sessionId) {26 const session = this.#sessions[sessionId];27 return Boolean(session && session.isValid());28 }29 async create(identityId, app, options) {30 assertApp(app);31 assertSessionOptions(options);32 const identity = this.#identities.get(identityId);33 if (identity.isRevoked()) {34 throw new IdentityRevokedError(`Unable to create session for revoked identity: ${identityId}`);35 }36 const session = this.#getSessionByIdentityAndAppId(identityId, app.id);37 if (session) {38 if (session.isValid()) {39 return session;40 }41 await this.destroy(session.getId());42 }43 const newSession = await createSession(identity, app, options, this.#storage, this.#identities);44 const newSessionId = newSession.getId();45 this.#sessions[newSessionId] = newSession;46 try {47 await identity.apps.add(app);48 await identity.apps.linkCurrentDevice(app.id);49 } catch (err) {50 delete this.#sessions[newSessionId];51 try {52 await removeSession(newSessionId, this.#storage).catch(() => {});53 } catch (err) {54 console.warn(`Unable to remove session "${newSessionId}" after failed attempt to create app "${app.id}" or link it to "${identityId}". Will cleanup on when identities got loaded again.`, err);55 }56 throw err;57 }58 return newSession;59 }60 async destroy(sessionId) {61 const session = this.#sessions[sessionId];62 if (!session) {63 return;64 }65 await removeSession(sessionId, this.#storage);66 delete this.#sessions[sessionId];67 const appId = session.getAppId();68 const identityId = session.getIdentityId();69 if (this.#identities.isLoaded() && this.#identities.has(identityId)) {70 const identity = this.#identities.get(identityId);71 try {72 await identity.apps.unlinkCurrentDevice(appId);73 } catch (err) {74 console.warn(`Something went wrong unlinking current device with app "${appId}" for identity "${identityId}". Will retry on reload.`, err);75 }76 }77 this.#onDestroy.dispatch(sessionId, session.getMeta());78 }79 onDestroy(fn) {80 return this.#onDestroy.add(fn);81 }82 #getSessionByIdentityAndAppId = (identityId, appId, sessions = this.#sessions) =>83 Object.values(sessions).find((session) => session.getAppId() === appId && session.getIdentityId() === identityId);84 #getSessionsByIdentityId = (identityId, sessions = this.#sessions) =>85 Object.values(sessions).filter((session) => session.getIdentityId() === identityId);86 #destroySessionsByIdentityId = async (identityId) => {87 const identitySessions = this.#getSessionsByIdentityId(identityId);88 await Promise.all(identitySessions.map((session) => this.destroy(session.getId())));89 }90 #addIdentityListeners = (identityId) => {91 if (this.#identityListeners.has(identityId)) {92 return;93 }94 const identity = this.#identities.get(identityId);95 const removeRevokeListener = identity.onRevoke((...args) => this.#handleIdentityRevoke(identityId, ...args));96 const removeLinkChangeListener = identity.apps.onLinkCurrentChange((...args) => this.#handleLinkCurrentChange(identityId, ...args));97 this.#identityListeners.set(identityId, { removeRevokeListener, removeLinkChangeListener });98 }99 #removeIdentityListeners = (identityId) => {100 if (!this.#identityListeners.has(identityId)) {101 return;102 }103 const listeners = this.#identityListeners.get(identityId);104 listeners.removeRevokeListener();105 listeners.removeLinkChangeListener();106 this.#identityListeners.delete(identityId);107 }108 #handleIdentitiesLoad = () => {109 Object.values(this.#identities.list()).forEach((identity) => {110 const apps = identity.apps.list();111 const identityId = identity.getId();112 apps.forEach((app) => {113 const session = this.#getSessionByIdentityAndAppId(identityId, app.id);114 if (!session) {115 identity.apps.unlinkCurrentDevice(app.id)116 .catch((err) => console.warn(`Something went wrong unlinking current device with app "${app.id}" for identity "${identityId}". Will retry on reload.`, err));117 }118 });119 this.#addIdentityListeners(identity.getId());120 });121 Object.values(this.#sessions).forEach((session) => {122 const sessionId = session.getId();123 const identityId = session.getIdentityId();124 if (!this.#identities.has(identityId) || this.#identities.get(identityId).isRevoked()) {125 this.destroy(sessionId)126 .catch((err) => console.warn(`Something went wrong destroying session "${sessionId}" for identity "${identityId}". Will retry on reload.`, err));127 }128 });129 }130 #handleIdentitiesChange = async (identities, operation) => {131 const { type, id: identityId } = operation;132 if (type !== 'remove') {133 this.#addIdentityListeners(identityId);134 return;135 }136 try {137 await this.#destroySessionsByIdentityId(identityId);138 this.#removeIdentityListeners(identityId);139 } catch (err) {140 console.warn(`Something went wrong destroying sessions for removed identity "${identityId}". Will retry on reload.`);141 }142 }143 #handleIdentityRevoke = async (identityId) => {144 try {145 await this.#destroySessionsByIdentityId(identityId);146 } catch (err) {147 console.warn(`Something went wrong destroying sessions for revoked identity "${identityId}". Will retry on reload.`);148 }149 }150 #handleLinkCurrentChange = async (identityId, { appId, isLinked }) => {151 const session = this.#getSessionByIdentityAndAppId(identityId, appId);152 if (session && !isLinked) {153 const sessionId = session.getId();154 try {155 await this.destroy(session.getId());156 } catch (err) {157 console.warn(`Something went wrong destroying session "${sessionId}" for app "${appId}" of identity "${identityId}" . Will retry on reload.`);158 }159 } else if (!session && isLinked) {160 console.warn(`App "${appId}" of identity "${identityId}" is linked but there's no session. Will fix on reload.`);161 }162 }163}164const createSessions = async (storage, identities) => {165 const sessions = await loadSessions(storage);166 return new Sessions(sessions, storage, identities);167};...

Full Screen

Full Screen

identity-test.js

Source:identity-test.js Github

copy

Full Screen

...6 "identity": {7 topic: load("scale/identity").expression("d3.scale.identity"),8 "domain and range": {9 "are identical": function(identity) {10 var x = identity();11 assert.strictEqual(x.domain, x.range);12 assert.strictEqual(x.domain(), x.range());13 var x = identity().domain([-10, 0, 100]);14 assert.deepEqual(x.range(), [-10, 0, 100]);15 var x = identity().range([-10, 0, 100]);16 assert.deepEqual(x.domain(), [-10, 0, 100]);17 },18 "default to [0, 1]": function(identity) {19 var x = identity();20 assert.deepEqual(x.domain(), [0, 1]);21 assert.deepEqual(x.range(), [0, 1]);22 assert.strictEqual(x(.5), .5);23 },24 "coerce values to numbers": function(identity) {25 var x = identity().domain([new Date(1990, 0, 1), new Date(1991, 0, 1)]);26 assert.typeOf(x.domain()[0], "number");27 assert.typeOf(x.domain()[1], "number");28 assert.strictEqual(x.domain()[0], +new Date(1990, 0, 1));29 assert.strictEqual(x.domain()[1], +new Date(1991, 0, 1));30 assert.typeOf(x(new Date(1989, 09, 20)), "number");31 assert.strictEqual(x(new Date(1989, 09, 20)), +new Date(1989, 09, 20));32 var x = identity().domain(["0", "1"]);33 assert.typeOf(x.domain()[0], "number");34 assert.typeOf(x.domain()[1], "number");35 assert.strictEqual(x(.5), .5);36 var x = identity().domain([new Number(0), new Number(1)]);37 assert.typeOf(x.domain()[0], "number");38 assert.typeOf(x.domain()[1], "number");39 assert.strictEqual(x(.5), .5);40 var x = identity().range([new Date(1990, 0, 1), new Date(1991, 0, 1)]);41 assert.typeOf(x.range()[0], "number");42 assert.typeOf(x.range()[1], "number");43 assert.strictEqual(x.range()[0], +new Date(1990, 0, 1));44 assert.strictEqual(x.range()[1], +new Date(1991, 0, 1));45 assert.typeOf(x(new Date(1989, 09, 20)), "number");46 assert.strictEqual(x(new Date(1989, 09, 20)), +new Date(1989, 09, 20));47 var x = identity().range(["0", "1"]);48 assert.typeOf(x.range()[0], "number");49 assert.typeOf(x.range()[1], "number");50 assert.strictEqual(x(.5), .5);51 var x = identity().range([new Number(0), new Number(1)]);52 assert.typeOf(x.range()[0], "number");53 assert.typeOf(x.range()[1], "number");54 assert.strictEqual(x(.5), .5);55 },56 "can specify a polyidentity domain and range": function(identity) {57 var x = identity().domain([-10, 0, 100]);58 assert.deepEqual(x.domain(), [-10, 0, 100]);59 assert.strictEqual(x(-5), -5);60 assert.strictEqual(x(50), 50);61 assert.strictEqual(x(75), 75);62 var x = identity().range([-10, 0, 100]);63 assert.deepEqual(x.range(), [-10, 0, 100]);64 assert.strictEqual(x(-5), -5);65 assert.strictEqual(x(50), 50);66 assert.strictEqual(x(75), 75);67 },68 "do not affect the identity function": function(identity) {69 var x = identity().domain([Infinity, NaN]);70 assert.strictEqual(x(42), 42);71 assert.strictEqual(x.invert(-42), -42);72 }73 },74 "is the identity function": function(identity) {75 var x = identity().domain([1, 2]);76 assert.strictEqual(x(.5), .5);77 assert.strictEqual(x(1), 1);78 assert.strictEqual(x(1.5), 1.5);79 assert.strictEqual(x(2), 2);80 assert.strictEqual(x(2.5), 2.5);81 },82 "coerces input to a number": function(identity) {83 var x = identity().domain([1, 2]);84 assert.strictEqual(x("2"), 2);85 },86 "invert": {87 "is the identity function": function(identity) {88 var x = identity().domain([1, 2]);89 assert.strictEqual(x.invert(.5), .5);90 assert.strictEqual(x.invert(1), 1);91 assert.strictEqual(x.invert(1.5), 1.5);92 assert.strictEqual(x.invert(2), 2);93 assert.strictEqual(x.invert(2.5), 2.5);94 },95 "coerces range value to numbers": function(identity) {96 var x = identity().range(["0", "2"]);97 assert.strictEqual(x.invert("1"), 1);98 var x = identity().range([new Date(1990, 0, 1), new Date(1991, 0, 1)]);99 assert.strictEqual(x.invert(new Date(1990, 6, 2, 13)), +new Date(1990, 6, 2, 13));100 var x = identity().range(["#000", "#fff"]);101 assert.isNaN(x.invert("#999"));102 },103 "coerces input to a number": function(identity) {104 var x = identity().domain([1, 2]);105 assert.strictEqual(x.invert("2"), 2);106 }107 },108 "ticks": {109 "generates ticks of varying degree": function(identity) {110 var x = identity();111 assert.deepEqual(x.ticks(1).map(x.tickFormat(1)), [0, 1]);112 assert.deepEqual(x.ticks(2).map(x.tickFormat(2)), [0, .5, 1]);113 assert.deepEqual(x.ticks(5).map(x.tickFormat(5)), [0, .2, .4, .6, .8, 1]);114 assert.deepEqual(x.ticks(10).map(x.tickFormat(10)), [0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1]);115 var x = identity().domain([1, 0]);116 assert.deepEqual(x.ticks(1).map(x.tickFormat(1)), [0, 1]);117 assert.deepEqual(x.ticks(2).map(x.tickFormat(2)), [0, .5, 1]);118 assert.deepEqual(x.ticks(5).map(x.tickFormat(5)), [0, .2, .4, .6, .8, 1]);119 assert.deepEqual(x.ticks(10).map(x.tickFormat(10)), [0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1]);120 },121 "formats ticks with the appropriate precision": function(identity) {122 var x = identity().domain([.123456789, 1.23456789]);123 assert.strictEqual(x.tickFormat(1)(x.ticks(1)[0]), "1");124 assert.strictEqual(x.tickFormat(2)(x.ticks(2)[0]), "0.5");125 assert.strictEqual(x.tickFormat(4)(x.ticks(4)[0]), "0.2");126 assert.strictEqual(x.tickFormat(8)(x.ticks(8)[0]), "0.2");127 assert.strictEqual(x.tickFormat(16)(x.ticks(16)[0]), "0.2");128 assert.strictEqual(x.tickFormat(32)(x.ticks(32)[0]), "0.15");129 assert.strictEqual(x.tickFormat(64)(x.ticks(64)[0]), "0.14");130 assert.strictEqual(x.tickFormat(128)(x.ticks(128)[0]), "0.13");131 assert.strictEqual(x.tickFormat(256)(x.ticks(256)[0]), "0.125");132 }133 },134 "copy": {135 "changes to the domain or range are isolated": function(identity) {136 var x = identity(), y = x.copy();137 x.domain([1, 2]);138 assert.deepEqual(y.domain(), [0, 1]);139 y.domain([2, 3]);140 assert.deepEqual(x.domain(), [1, 2]);141 assert.deepEqual(y.domain(), [2, 3]);142 var x = identity(), y = x.copy();143 x.range([1, 2]);144 assert.deepEqual(y.range(), [0, 1]);145 y.range([2, 3]);146 assert.deepEqual(x.range(), [1, 2]);147 assert.deepEqual(y.range(), [2, 3]);148 }149 }150 }151});...

Full Screen

Full Screen

numerical-integration.js

Source:numerical-integration.js Github

copy

Full Screen

...9 if (func == "reciprocal") {10 sum += reciprocal(i-h*(1-k));11 }12 if (func == "identity") {13 sum += identity(i-h*(1-k));14 } 15 }16 sum *= h;17}18function integrateTrapezoid(func, a, b, n) {19 var h = (b-a)/n;20 var sum = 0;21 for (var i = a, j=a; i < b; i+=(b/n), ++j) {22 if (func == "cube") {23 if (i < b-1) {24 sum += cube(i) + cube(i+1); 25 } else {26 sum += cube(i) + cube(i+1-b);27 }28 } 29 if (func == "reciprocal") {30 if (i < b-1) {31 sum += reciprocal(i) + reciprocal(i+1); 32 } else {33 sum += reciprocal(i) + reciprocal(i+1-b);34 }35 } 36 if (func == "identity") {37 if (i < b-1) {38 sum += identity(i) + identity(i+1); 39 } else {40 sum += identity(i) + identity(i+1-b);41 }42 } 43 }44 sum *= h/2;45}46function integrateSimpsons(func, a, b, n) {47 var h = (b-a)/h;48 var sum = 0;49 for (var i = a, j=a; i < b; i+=(b/n), ++j) {50 if (func == "cube") {51 if (i < b -1) {52 sum += cube(i) + (4 * cube(i - (h / 2))) + cube(i + 1);53 } else {54 sum += cube(i) + (4 * cube(i - (h / 2))) + cube(i + 1 - b);55 }56 }57 if (func == "reciprocal") {58 if (i < b -1) {59 sum += reciprocal(i) + (4 * reciprocal(i - (h / 2))) + reciprocal(i + 1);60 } else {61 sum += reciprocal(i) + (4 * reciprocal(i - (h / 2))) + reciprocal(i + 1 - b);62 }63 }64 if (func == "identity") {65 if (i < b -1) {66 sum += identity(i) + (4 * identity(i - (h / 2))) + identity(i + 1);67 } else {68 sum += identity(i) + (4 * identity(i - (h / 2))) + identity(i + 1 - b);69 }70 }71 }72 sum *= h/6;73}74function cube(x) {75 return (x*x*x+aVar);76}77function reciprocal(x) {78 return 1/(x+aVar);79}80function identity(x) {81 return x+aVar;82}83function executeTask(i) {84integrateRectagle("cube",0,1,100,0);85integrateRectagle("cube",0,1,100,0.5);86integrateRectagle("cube",0,1,100,1);87integrateTrapezoid("cube",0,1,100);88integrateSimpsons("cube",0,1,100);89integrateRectagle("reciprocal",1,100,1000,0);90integrateRectagle("reciprocal",1,100,1000,0.5);91integrateRectagle("reciprocal",1,100,1000,1);92integrateTrapezoid("reciprocal",1,100,1000);93integrateSimpsons("reciprocal",1,100,1000);94integrateRectagle("identity",0,5000,5000000,0);...

Full Screen

Full Screen

principal.service.js

Source:principal.service.js Github

copy

Full Screen

...34 function hasAuthority (authority) {35 if (!_authenticated) {36 return $q.when(false);37 }38 return this.identity().then(function(_id) {39 return _id.authorities && _id.authorities.indexOf(authority) !== -1;40 }, function(){41 return false;42 });43 }44 function identity (force) {45 var deferred = $q.defer();46 if (force === true) {47 _identity = undefined;48 }49 // check and see if we have retrieved the identity data from the server.50 // if we have, reuse it by immediately resolving51 if (angular.isDefined(_identity)) {52 deferred.resolve(_identity);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 {3 },4 {5 }6 {7 }8 paths: {9 },10 engineOptions: {11 },12};13module.exports = async (page, scenario, vp) => {14 console.log('SCENARIO > ' + scenario.label);15 await require('./loadCookies')(page, scenario);16};17module.exports = async (page, scenario, vp) => {18 console.log('SCENARIO > ' + scenario.label);19 await require('./loadCookies')(page, scenario);20};21module.exports = async (page, scenario) => {22 const cookies = require(scenario.cookiePath);23 if (cookies.length) {24 for (const cookie of cookies) {25 await page.setCookie(cookie);26 }27 await page.goto(scenario.url, {waitUntil: 'networkidle2'});28 }29};30[{"

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 {3 },4 {5 }6 {7 }8 paths: {9 },10 engineOptions: {11 },12};13module.exports = async (page, scenario) => {14 console.log('SCENARIO > ' + scenario.label);15 const cookies = require('./cookies.json');16 await page.setCookie(...cookies);17 await page.goto(scenario.url, { waitUntil: 'domcontentloaded' });18 await page.waitFor(500);19};20module.exports = async (page, scenario, vp) => {21 console.log('SCENARIO > ' + scenario.label);22 await page.waitFor(500);23};24 {

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 {3 },4 {5 },6 {7 }8 {9 }10 paths: {11 },12 engineOptions: {13 },14}15module.exports = async (page, scenario) => {16 console.log('onBefore.js has run for ' + scenario.label);17 await require('./login')(page, scenario);18};19module.exports = async (page, scenario) => {20 console.log('onReady.js has run for ' + scenario.label);21};22module.exports = async (page, scenario) => {23 console.log('login.js has run for ' + scenario.label);24 await page.type('#username', 'test');25 await page.type('#password

Full Screen

Using AI Code Generation

copy

Full Screen

1var backstopjs = require('backstopjs');2var path = require('path');3var config = {4 {5 },6 {7 },8 {9 }10 {11 }12 "paths": {13 },14};15backstopjs('reference', { config: config })16 .then(function () {17 console.log('Reference created');18 backstopjs('test', { config: config })19 .then(function () {20 console.log('Test completed');21 })22 .catch(function (error) {23 console.error(error);24 });25 })26 .catch(function (error) {27 console.error(error);28 });

Full Screen

Using AI Code Generation

copy

Full Screen

1var backstop = require('backstopjs');2backstop('reference', {config: 'backstop.json'});3var backstop = require('backstopjs');4backstop('test', {config: 'backstop.json'});5{6 {7 },8 {9 },10 {11 }12 {13 }14 "paths": {15 },16 "engineOptions": {17 },18}

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = async (page, scenario) => {2 const cookies = scenario.cookiePath ? require(scenario.cookiePath) : [];3 await require("./loadCookies")(page, cookies);4 await page.evaluate(async () => {5 await window._backstopTools.identity();6 });7};8module.exports = async (page, cookies) => {9 for (const cookie of cookies) {10 await page.setCookie(cookie);11 }12};

Full Screen

Using AI Code Generation

copy

Full Screen

1var backstopjs = require('backstopjs');2var reference = backstopjs('reference');3var test = backstopjs('test');4var backstopjs = require('backstopjs');5var reference = backstopjs('reference');6var test = backstopjs('test');7var backstopjs = require('backstopjs');8var reference = backstopjs('reference');9var test = backstopjs('test');10var backstopjs = require('backstopjs');11var reference = backstopjs('reference');12var test = backstopjs('test');13var backstopjs = require('backstopjs');14var reference = backstopjs('reference');15var test = backstopjs('test');16var backstopjs = require('backstopjs');17var reference = backstopjs('reference');18var test = backstopjs('test');19var backstopjs = require('backstopjs');20var reference = backstopjs('reference');21var test = backstopjs('test');22var backstopjs = require('backstopjs');23var reference = backstopjs('reference');24var test = backstopjs('test');25var backstopjs = require('backstopjs');26var reference = backstopjs('reference');27var test = backstopjs('test');28var backstopjs = require('backstopjs');29var reference = backstopjs('reference');30var test = backstopjs('test');31var backstopjs = require('backstopjs');32var reference = backstopjs('reference');33var test = backstopjs('test');34var backstopjs = require('backstopjs');

Full Screen

Using AI Code Generation

copy

Full Screen

1const backstop = require('backstopjs');2backstop('reference', {config: 'backstop.json'}).then(() => {3 console.log('Reference completed');4}).catch((e) => {5 console.log('Error', e);6});7{8 {9 },10 {11 }12 {13 }14 "paths": {15 },16 "engineOptions": {17 },18}19 return backstop('reference', {config: 'backstop.json'}).then(() => {

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = function (casper, scenario, vp) {2 casper.evaluate(function () {3 var element = document.querySelector("body");4 element.setAttribute("data-identity", "body");5 });6};7module.exports = function (casper, scenario, vp) {8 casper.evaluate(function () {9 var element = document.querySelector("body");10 element.setAttribute("data-identity", "body");11 });12};13module.exports = function (casper, scenario, vp) {14 casper.evaluate(function () {15 var element = document.querySelector("body");16 element.setAttribute("data-identity", "body");17 });18};19module.exports = function (casper, scenario, vp) {20 casper.evaluate(function () {21 var element = document.querySelector("body");22 element.setAttribute("data-identity", "body");23 });24};25module.exports = function (casper, scenario, vp) {26 casper.evaluate(function () {27 var element = document.querySelector("body");28 element.setAttribute("data-identity", "body");29 });30};31module.exports = function (casper, scenario, vp) {32 casper.evaluate(function () {33 var element = document.querySelector("body");34 element.setAttribute("data-identity", "body");35 });36};37module.exports = function (casper, scenario, vp) {38 casper.evaluate(function () {39 var element = document.querySelector("body");40 element.setAttribute("data-identity", "body");41 });42};43module.exports = function (casper, scenario, vp) {44 casper.evaluate(function () {45 var element = document.querySelector("body");46 element.setAttribute("data-identity", "body");47 });48};49module.exports = function (casper, scenario, vp) {50 casper.evaluate(function () {51 var element = document.querySelector("body");52 element.setAttribute("data-identity", "body");53 });54};55module.exports = function (casper, scenario, vp)

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = function (casper, scenario, vp) {2 casper.echo('SCENARIO > ' + scenario.label);3 var id = scenario.label;4 var idSelector = 'a[href="#' + id + '"]';5 casper.waitForSelector(idSelector, function () {6 casper.click(idSelector);7 casper.wait(1000);8 });9};10{11 {12 }13 {14 }15 "paths": {16 },17 "engineOptions": {18 },19}

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 backstopjs 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