How to use PromptAuth method in Playwright Internal

Best JavaScript code snippet using playwright-internal

BrowserElementPromptService.jsm

Source:BrowserElementPromptService.jsm Github

copy

Full Screen

...12r.buttons.push(ret);r.indexToButtonNumberMap.push(buttonNumber);}13buildButton(button0Title,0);buildButton(button1Title,1);buildButton(button2Title,2);14if(r.defaultButton===-1){throw new Components.Exception("Default button won't be shown",Cr.NS_ERROR_FAILURE);}15return r;},};function BrowserElementAuthPrompt(){}16BrowserElementAuthPrompt.prototype={QueryInterface:XPCOMUtils.generateQI([Ci.nsIAuthPrompt2]),promptAuth:function promptAuth(channel,level,authInfo){throw Cr.NS_ERROR_NOT_IMPLEMENTED;},asyncPromptAuth:function asyncPromptAuth(channel,callback,context,level,authInfo){debug("asyncPromptAuth");if((authInfo.flags&Ci.nsIAuthInformation.AUTH_PROXY)&&(authInfo.flags&Ci.nsIAuthInformation.ONLY_PASSWORD)){throw Cr.NS_ERROR_FAILURE;}17let frame=this._getFrameFromChannel(channel);if(!frame){debug("Cannot get frame, asyncPromptAuth fail");throw Cr.NS_ERROR_FAILURE;}18let browserElementParent=BrowserElementPromptService.getBrowserElementParentForFrame(frame);if(!browserElementParent){debug("Failed to load browser element parent.");throw Cr.NS_ERROR_FAILURE;}19let consumer={QueryInterface:XPCOMUtils.generateQI([Ci.nsICancelable]),callback:callback,context:context,cancel:function(){this.callback.onAuthCancelled(this.context,false);this.callback=null;this.context=null;}};let[hostname,httpRealm]=this._getAuthTarget(channel,authInfo);let hashKey=level+"|"+hostname+"|"+httpRealm;let asyncPrompt=this._asyncPrompts[hashKey];if(asyncPrompt){asyncPrompt.consumers.push(consumer);return consumer;}20asyncPrompt={consumers:[consumer],channel:channel,authInfo:authInfo,level:level,inProgress:false,browserElementParent:browserElementParent};this._asyncPrompts[hashKey]=asyncPrompt;this._doAsyncPrompt();return consumer;},_asyncPrompts:{},_asyncPromptInProgress:new WeakMap(),_doAsyncPrompt:function(){21let hashKey=null;for(let key in this._asyncPrompts){let prompt=this._asyncPrompts[key];if(!this._asyncPromptInProgress.get(prompt.browserElementParent)){hashKey=key;break;}}22if(!hashKey)23return;let prompt=this._asyncPrompts[hashKey];let[hostname,httpRealm]=this._getAuthTarget(prompt.channel,prompt.authInfo);this._asyncPromptInProgress.set(prompt.browserElementParent,true);prompt.inProgress=true;let self=this;let callback=function(ok,username,password){debug("Async auth callback is called, ok = "+24ok+", username = "+username);25delete self._asyncPrompts[hashKey];prompt.inProgress=false;self._asyncPromptInProgress.delete(prompt.browserElementParent);26let flags=prompt.authInfo.flags;if(username){if(flags&Ci.nsIAuthInformation.NEED_DOMAIN){ let idx=username.indexOf("\\");if(idx==-1){prompt.authInfo.username=username;}else{prompt.authInfo.domain=username.substring(0,idx);prompt.authInfo.username=username.substring(idx+1);}}else{prompt.authInfo.username=username;}}27if(password){prompt.authInfo.password=password;}28for each(let consumer in prompt.consumers){if(!consumer.callback){29continue;}30try{if(ok){debug("Ok, calling onAuthAvailable to finish auth");consumer.callback.onAuthAvailable(consumer.context,prompt.authInfo);}else{debug("Cancelled, calling onAuthCancelled to finish auth.");consumer.callback.onAuthCancelled(consumer.context,true);}}catch(e){}}31self._doAsyncPrompt();};let runnable={run:function(){prompt.browserElementParent.promptAuth(self._createAuthDetail(prompt.channel,prompt.authInfo),callback);}}32Services.tm.currentThread.dispatch(runnable,Ci.nsIThread.DISPATCH_NORMAL);},_getFrameFromChannel:function(channel){let loadContext=channel.notificationCallbacks.getInterface(Ci.nsILoadContext);return loadContext.topFrameElement;},_createAuthDetail:function(channel,authInfo){let[hostname,httpRealm]=this._getAuthTarget(channel,authInfo);return{host:hostname,realm:httpRealm,username:authInfo.username,isOnlyPassword:!!(authInfo.flags&Ci.nsIAuthInformation.ONLY_PASSWORD)};},_getAuthTarget:function(channel,authInfo){let hostname=this._getFormattedHostname(channel.URI);33let realm=authInfo.realm;if(!realm)34realm=hostname;return[hostname,realm];},_getFormattedHostname:function(uri){let scheme=uri.scheme;let hostname=scheme+"://"+uri.host;35let port=uri.port;if(port!=-1){let handler=Services.io.getProtocolHandler(scheme);if(port!=handler.defaultPort)36hostname+=":"+port;}37return hostname;}};function AuthPromptWrapper(oldImpl,browserElementImpl){this._oldImpl=oldImpl;this._browserElementImpl=browserElementImpl;}38AuthPromptWrapper.prototype={QueryInterface:XPCOMUtils.generateQI([Ci.nsIAuthPrompt2]),promptAuth:function(channel,level,authInfo){if(this._canGetParentElement(channel)){return this._browserElementImpl.promptAuth(channel,level,authInfo);}else{return this._oldImpl.promptAuth(channel,level,authInfo);}},asyncPromptAuth:function(channel,callback,context,level,authInfo){if(this._canGetParentElement(channel)){return this._browserElementImpl.asyncPromptAuth(channel,callback,context,level,authInfo);}else{return this._oldImpl.asyncPromptAuth(channel,callback,context,level,authInfo);}},_canGetParentElement:function(channel){try{let context=channel.notificationCallbacks.getInterface(Ci.nsILoadContext);let frame=context.topFrameElement;if(!frame){ return!!context.nestedFrameId;}39if(!BrowserElementPromptService.getBrowserElementParentForFrame(frame))40return false;return true;}catch(e){return false;}}};function BrowserElementPromptFactory(toWrap){this._wrapped=toWrap;}41BrowserElementPromptFactory.prototype={classID:Components.ID("{24f3d0cf-e417-4b85-9017-c9ecf8bb1299}"),QueryInterface:XPCOMUtils.generateQI([Ci.nsIPromptFactory]),_mayUseNativePrompt:function(){try{return Services.prefs.getBoolPref("browser.prompt.allowNative");}catch(e){return true;}},_getNativePromptIfAllowed:function(win,iid,err){if(this._mayUseNativePrompt())42return this._wrapped.getPrompt(win,iid);else{throw err;}},getPrompt:function(win,iid){43 if(!win)44return this._getNativePromptIfAllowed(win,iid,Cr.NS_ERROR_INVALID_ARG);if(iid.number!=Ci.nsIPrompt.number&&iid.number!=Ci.nsIAuthPrompt2.number){debug("We don't recognize the requested IID ("+iid+", "+"allowed IID: "+"nsIPrompt="+Ci.nsIPrompt+", "+"nsIAuthPrompt2="+Ci.nsIAuthPrompt2+")");return this._getNativePromptIfAllowed(win,iid,Cr.NS_ERROR_INVALID_ARG);}45let browserElementChild=BrowserElementPromptService.getBrowserElementChildForWindow(win);if(iid.number===Ci.nsIAuthPrompt2.number){debug("Caller requests an instance of nsIAuthPrompt2.");if(browserElementChild){46return new BrowserElementAuthPrompt().QueryInterface(iid);}47if(this._mayUseNativePrompt()){return new AuthPromptWrapper(this._wrapped.getPrompt(win,iid),new BrowserElementAuthPrompt().QueryInterface(iid)).QueryInterface(iid);}else{48return new BrowserElementAuthPrompt().QueryInterface(iid);}}49if(!browserElementChild){debug("We can't find a browserElementChild for "+50win+", "+win.location);return this._getNativePromptIfAllowed(win,iid,Cr.NS_ERROR_FAILURE);}51debug("Returning wrapped getPrompt for "+win);return new BrowserElementPrompt(win,browserElementChild).QueryInterface(iid);}};this.BrowserElementPromptService={QueryInterface:XPCOMUtils.generateQI([Ci.nsIObserver,Ci.nsISupportsWeakReference]),_initialized:false,_init:function(){if(this._initialized){return;}52if(!this._browserFramesPrefEnabled()){var prefs=Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);prefs.addObserver(BROWSER_FRAMES_ENABLED_PREF,this,true);return;}...

Full Screen

Full Screen

calAuthUtils.jsm

Source:calAuthUtils.jsm Github

copy

Full Screen

1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */4Components.utils.import("resource://calendar/modules/calUtils.jsm");5/*6 * Authentication helper code7 */8EXPORTED_SYMBOLS = ["cal"]; // even though it's defined in calUtils.jsm, import needs this9cal.auth = {10 /**11 * Auth prompt implementation - Uses password manager if at all possible.12 */13 Prompt: function calPrompt() {14 this.mReturnedLogins = {};15 },16 /**17 * Tries to get the username/password combination of a specific calendar name18 * from the password manager or asks the user.19 *20 * @param in aTitle The dialog title.21 * @param in aCalendarName The calendar name or url to look up. Can be null.22 * @param inout aUsername The username that belongs to the calendar.23 * @param inout aPassword The password that belongs to the calendar.24 * @param inout aSavePassword Should the password be saved?25 * @param in aFixedUsername Whether the user name is fixed or editable26 * @return Could a password be retrieved?27 */28 getCredentials: function calGetCredentials(aTitle,29 aCalendarName,30 aUsername,31 aPassword,32 aSavePassword,33 aFixedUsername) {34 if (typeof aUsername != "object" ||35 typeof aPassword != "object" ||36 typeof aSavePassword != "object") {37 throw new Components.Exception("", Components.results.NS_ERROR_XPC_NEED_OUT_OBJECT);38 }39 let watcher = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]40 .getService(Components.interfaces.nsIWindowWatcher);41 let prompter = watcher.getNewPrompter(null);42 // Only show the save password box if we are supposed to.43 let savepassword = null;44 if (cal.getPrefSafe("signon.rememberSignons", true)) {45 savepassword = cal.calGetString("passwordmgr", "rememberPassword", null, "passwordmgr");46 }47 let aText;48 if (aFixedUsername) {49 aText = cal.calGetString("commonDialogs", "EnterPasswordFor", [aUsername.value, aCalendarName], "global");50 return prompter.promptPassword(aTitle,51 aText,52 aPassword,53 savepassword,54 aSavePassword);55 } else {56 aText = cal.calGetString("commonDialogs", "EnterUserPasswordFor", [aCalendarName], "global");57 return prompter.promptUsernameAndPassword(aTitle,58 aText,59 aUsername,60 aPassword,61 savepassword,62 aSavePassword);63 }64 },65 /**66 * Helper to insert/update an entry to the password manager.67 *68 * @param aUserName The username69 * @param aPassword The corresponding password70 * @param aHostName The corresponding hostname71 * @param aRealm The password realm (unused on branch)72 */73 passwordManagerSave: function calPasswordManagerSave(aUsername, aPassword, aHostName, aRealm) {74 cal.ASSERT(aUsername);75 cal.ASSERT(aPassword);76 try {77 let loginManager = Components.classes["@mozilla.org/login-manager;1"]78 .getService(Components.interfaces.nsILoginManager);79 let logins = loginManager.findLogins({}, aHostName, null, aRealm);80 let newLoginInfo = Components.classes["@mozilla.org/login-manager/loginInfo;1"]81 .createInstance(Components.interfaces.nsILoginInfo);82 newLoginInfo.init(aHostName, null, aRealm, aUsername, aPassword, "", "");83 if (logins.length > 0) {84 loginManager.modifyLogin(logins[0], newLoginInfo);85 } else {86 loginManager.addLogin(newLoginInfo);87 }88 } catch (exc) {89 cal.ASSERT(false, exc);90 }91 },92 /**93 * Helper to retrieve an entry from the password manager.94 *95 * @param in aUsername The username to search96 * @param out aPassword The corresponding password97 * @param aHostName The corresponding hostname98 * @param aRealm The password realm (unused on branch)99 * @return Does an entry exist in the password manager100 */101 passwordManagerGet: function calPasswordManagerGet(aUsername, aPassword, aHostName, aRealm) {102 cal.ASSERT(aUsername);103 if (typeof aPassword != "object") {104 throw new Components.Exception("", Components.results.NS_ERROR_XPC_NEED_OUT_OBJECT);105 }106 try {107 let loginManager = Components.classes["@mozilla.org/login-manager;1"]108 .getService(Components.interfaces.nsILoginManager);109 if (!loginManager.getLoginSavingEnabled(aUsername)) {110 return false;111 }112 let logins = loginManager.findLogins({}, aHostName, null, aRealm);113 for each (let loginInfo in logins) {114 if (loginInfo.username == aUsername) {115 aPassword.value = loginInfo.password;116 return true;117 }118 }119 } catch (exc) {120 cal.ASSERT(false, exc);121 }122 return false;123 },124 /**125 * Helper to remove an entry from the password manager126 *127 * @param aUsername The username to remove.128 * @param aHostName The corresponding hostname129 * @param aRealm The password realm (unused on branch)130 * @return Could the user be removed?131 */132 passwordManagerRemove: function calPasswordManagerRemove(aUsername, aHostName, aRealm) {133 cal.ASSERT(aUsername);134 try {135 let loginManager = Components.classes["@mozilla.org/login-manager;1"]136 .getService(Components.interfaces.nsILoginManager);137 let logins = loginManager.findLogins({}, aHostName, null, aRealm);138 for each (let loginInfo in logins) {139 if (loginInfo.username == aUsername) {140 loginManager.removeLogin(loginInfo);141 return true;142 }143 }144 } catch (exc) {145 }146 return false;147 }148};149/**150 * Calendar Auth prompt implementation. This instance of the auth prompt should151 * be used by providers and other components that handle authentication using152 * nsIAuthPrompt2 and friends.153 *154 * This implementation guarantees there are no request loops when an invalid155 * password is stored in the login-manager.156 *157 * There is one instance of that object per calendar provider.158 */159cal.auth.Prompt.prototype = {160 getPasswordInfo: function capGPI(aPasswordRealm) {161 let username;162 let password;163 let found = false;164 let loginManager = Components.classes["@mozilla.org/login-manager;1"]165 .getService(Components.interfaces.nsILoginManager);166 let logins = loginManager.findLogins({}, aPasswordRealm.prePath, null, aPasswordRealm.realm);167 if (logins.length) {168 username = logins[0].username;169 password = logins[0].password;170 found = true;171 }172 if (found) {173 let keyStr = aPasswordRealm.prePath +":" + aPasswordRealm.realm;174 let now = new Date();175 // Remove the saved password if it was already returned less176 // than 60 seconds ago. The reason for the timestamp check is that177 // nsIHttpChannel can call the nsIAuthPrompt2 interface178 // again in some situation. ie: When using Digest auth token179 // expires.180 if (this.mReturnedLogins[keyStr] &&181 now.getTime() - this.mReturnedLogins[keyStr].getTime() < 60000) {182 cal.LOG("Credentials removed for: user=" + username + ", host="+aPasswordRealm.prePath+", realm="+aPasswordRealm.realm);183 delete this.mReturnedLogins[keyStr];184 cal.auth.passwordManagerRemove(username,185 aPasswordRealm.prePath,186 aPasswordRealm.realm);187 return {found: false, username: username};188 }189 else {190 this.mReturnedLogins[keyStr] = now;191 }192 }193 return {found: found, username: username, password: password};194 },195 /**196 * Requests a username and a password. Implementations will commonly show a197 * dialog with a username and password field, depending on flags also a198 * domain field.199 *200 * @param aChannel201 * The channel that requires authentication.202 * @param level203 * One of the level constants NONE, PW_ENCRYPTED, SECURE.204 * @param authInfo205 * Authentication information object. The implementation should fill in206 * this object with the information entered by the user before207 * returning.208 *209 * @retval true210 * Authentication can proceed using the values in the authInfo211 * object.212 * @retval false213 * Authentication should be cancelled, usually because the user did214 * not provide username/password.215 *216 * @note Exceptions thrown from this function will be treated like a217 * return value of false.218 */219 promptAuth: function capPA(aChannel, aLevel, aAuthInfo) {220 let hostRealm = {};221 hostRealm.prePath = aChannel.URI.prePath;222 hostRealm.realm = aAuthInfo.realm;223 let port = aChannel.URI.port;224 if (port == -1) {225 let handler = cal.getIOService().getProtocolHandler(aChannel.URI.scheme)226 .QueryInterface(Components.interfaces.nsIProtocolHandler);227 port = handler.defaultPort;228 }229 hostRealm.passwordRealm = aChannel.URI.host + ":" + port + " (" + aAuthInfo.realm + ")";230 let pw = this.getPasswordInfo(hostRealm);231 aAuthInfo.username = pw.username;232 if (pw && pw.found) {233 aAuthInfo.password = pw.password;234 return true;235 } else {236 let prompter2 = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]237 .getService(Components.interfaces.nsIPromptFactory)238 .getPrompt(null, Components.interfaces.nsIAuthPrompt2);239 return prompter2.promptAuth(aChannel, aLevel, aAuthInfo);240 }241 },242 /**243 * Asynchronously prompt the user for a username and password.244 * This has largely the same semantics as promptAuth(),245 * but must return immediately after calling and return the entered246 * data in a callback.247 *248 * If the user closes the dialog using a cancel button or similar,249 * the callback's nsIAuthPromptCallback::onAuthCancelled method must be250 * called.251 * Calling nsICancelable::cancel on the returned object SHOULD close the252 * dialog and MUST call nsIAuthPromptCallback::onAuthCancelled on the provided253 * callback.254 *255 * @throw NS_ERROR_NOT_IMPLEMENTED256 * Asynchronous authentication prompts are not supported;257 * the caller should fall back to promptUsernameAndPassword().258 */259 asyncPromptAuth : function capAPA(aChannel, // nsIChannel260 aCallback, // nsIAuthPromptCallback261 aContext, // nsISupports262 aLevel, // PRUint32263 aAuthInfo // nsIAuthInformation264 ) {265 var self = this;266 let promptlistener = {267 onPromptStart: function() {268 res=self.promptAuth(aChannel, aLevel, aAuthInfo);269 if (res) {270 this.onPromptAuthAvailable();271 return true;272 }273 this.onPromptCanceled();274 return false;275 },276 onPromptAuthAvailable : function() {277 aCallback.onAuthAvailable(aContext, aAuthInfo);278 },279 onPromptCanceled : function() {280 aCallback.onAuthCancelled(aContext, true);281 }282 };283 var asyncprompter = Components.classes["@mozilla.org/messenger/msgAsyncPrompter;1"]284 .getService(Components.interfaces.nsIMsgAsyncPrompter);285 asyncprompter.queueAsyncAuthPrompt(aChannel.URI.spec, false, promptlistener);286 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import React from "react";2import PouchDB from "pouchdb";3import upsert from "pouchdb-upsert";4import firebase from "firebase/app";5import "firebase/firestore";6const parseAuthObj = (meAuth) => {7 var {8 uid,9 displayName,10 photoURL,11 email,12 emailVerified,13 phoneNumber,14 isAnonymous,15 tenantId,16 providerData,17 apiKey,18 appName,19 authDomain,20 stsTokenManager,21 refreshToken,22 accessToken,23 expirationTime,24 redirectEventId,25 lastLoginAt,26 createdAt,27 multiFactor28 } = meAuth;29 return {30 _id: uid,31 uid,32 displayName,33 photoURL,34 email,35 emailVerified,36 phoneNumber,37 isAnonymous,38 tenantId,39 providerData,40 apiKey,41 appName,42 authDomain,43 stsTokenManager,44 refreshToken,45 accessToken,46 expirationTime,47 redirectEventId,48 lastLoginAt,49 createdAt,50 multiFactor: JSON.stringify(multiFactor)51 };52};53const standardCatch = (err) => console.log("react-fuffer: " + err.message);54const optsForPouchDB = {55 revs_limit: 1, //revision-history56 auto_compaction: true //zipped...57};58//const deletion = (d, db) => db.remove(d).catch(standardCatch);59const destroy = (db) => db.destroy();60const set = (db, c) =>61 !c._id62 ? window.alert(63 "pouchdb needs ._id key:value: JSON.parse= " + JSON.parse(c)64 ) &&65 db66 .destroy()67 .then(() => null)68 .catch(standardCatch)69 : db //has upsert plugin from class constructor70 .upsert(c._id, (copy) => {71 copy = { ...c }; //pouch-db \(construct, protocol)\72 return copy; //return a copy, don't displace immutable object fields73 })74 .then(75 () => null /*"success"*/76 /** or77 notes.find((x) => x._id === c._id)78 ? this.db79 .post(c)80 .then(() => null)81 .catch(standardCatch)82 : deletion(c) && set(db, c); 83 */84 )85 .catch(standardCatch);86const read = async (db, notes /*={}*/) =>87 //let notes = {};88 await db89 .allDocs({ include_docs: true })90 .then(91 (92 allNotes //new Promise cannot handle JSON objects, Promise.all() doesn't93 ) =>94 Promise.all(95 allNotes.rows.map(async (n) => await (notes[n.doc.key] = n.doc))96 )97 // && and .then() are functionally the same;98 )99 .catch(standardCatch);100class ADB {101 constructor(name) {102 PouchDB.plugin(upsert);103 const title = "meAuth";104 this.db = new PouchDB(title, optsForPouchDB);105 }106 deleteKeys = () => destroy(this.db);107 store = (key) => set(this.db, key);108 readAuth = async (notes = {}) =>109 //let notes = {};110 await read(this.db, notes);111}112class PromptAuth extends React.Component {113 constructor(props) {114 super(props);115 var storedAuth = undefined;116 let adb = new ADB();117 this.state = {118 adb,119 storedAuth,120 tickets: [],121 myCommunities: [],122 folders: []123 };124 }125 promptAuth = () =>126 this.state.adb127 .readAuth()128 .then((result) => {129 const { verbose } = this.props;130 if (result.length === 0) {131 verbose && console.log("REACT-LOCAL-FIREBASE: no user stored...");132 } else {133 var msg = null;134 var storedAuth = result[0];135 if (!storedAuth) return (msg = "new authdb");136 var meAuth = { ...storedAuth };137 if (storedAuth.isAnonymous) {138 msg = "REACT-LOCAL-FIREBASE: authdb is anonymous";139 meAuth.multiFactor = JSON.parse(meAuth.multiFactor);140 } else if (storedAuth._id !== "none")141 msg = "REACT-LOCAL-FIREBASE: authdb is identifiable";142 verbose && console.log(msg);143 this.setState(144 {145 storedAuth146 },147 () =>148 this.props.setFireAuth({149 meAuth150 })151 //reused152 );153 }154 })155 .catch((err) => console.log(err));156 componentDidMount = () => {157 this.promptAuth();158 };159 storeAuth = (meAuth, logout, hasPermission) => {160 const { verbose } = this.props;161 const store = (storedAuth, method, logout) =>162 this.state.adb[method](storedAuth)163 .then((res) =>164 this.setState(165 {166 storedAuth167 },168 () => this.props.setFireAuth({ isStored: res, logout })169 )170 )171 .catch(standardCatch);172 if (Object.keys(meAuth).length === 0)173 return this.props.setFireAuth({ meAuth: {} }, () =>174 store({ _id: "none" }, "store", logout)175 );176 verbose && console.log("REACT-LOCAL-FIREBASE: " + meAuth.uid + " found");177 var stripped = parseAuthObj(meAuth);178 if (this.state.storedAuth !== stripped) {179 //getUserData from update180 //new meAuth object181 this.props.setFireAuth({ meAuth });182 verbose &&183 console.log(184 "REACT-LOCAL-FIREBASE: " + meAuth.uid + " being stored grant" //+ stripped.isAnonymous ? "" : "?"185 );186 if (stripped.isAnonymous) return store(stripped, "store");187 var stor = true;188 if (!hasPermission) {189 stor = window.confirm(190 "is this a private device? if so, can we store your auth data?" +191 `(${stripped.displayName},${stripped.phoneNumber},${stripped.email})`192 );193 }194 if (stor) {195 store(stripped, "store");196 }197 }198 };199 getUserInfo = async (verbose, auth, storedAuth) => {200 if (this.props.meAuth && this.props.meAuth.isAnonymous)201 return await new Promise((resolve) => resolve("login?"));202 var msg = null;203 if (storedAuth !== undefined) {204 msg =205 "REACT-LOCAL-FIREBASE: " +206 storedAuth.uid +207 " is stored, saving on costs here";208 if (!storedAuth.multiFactor) {209 msg =210 "REACT-LOCAL-FIREBASE: " +211 storedAuth.uid +212 " is substandard; !meAuth1.multiFactor, deleting these from pouchdb..";213 this.state.adb.deleteKeys();214 } else {215 msg =216 storedAuth.uid + ": JSON.parse-ing 'meAuth1.multiFactor' object..";217 var meAuth = { ...this.props.meAuth };218 meAuth.multiFactor = JSON.parse(storedAuth.multiFactor);219 this.props.setFireAuth({ meAuth });220 //anonymous221 if (meAuth.isAnonymous) {222 console.log(meAuth.uid + " is anonymous");223 } else this.storeAuth(storedAuth, false, true);224 }225 verbose && console.log(msg);226 }227 !auth &&228 firebase.auth().onAuthStateChanged((meAuth) => {229 verbose &&230 console.log("REACT-LOCAL-FIREBASE: firebase authentication called");231 if (!meAuth)232 return firebase233 .auth()234 .signInAnonymously()235 .then(() => {236 verbose &&237 console.log("REACT-LOCAL-FIREBASE: getting fake user data...");238 var answer = window.confirm("login?");239 if (answer) this.props.onPromptToLogin();240 })241 .catch(standardCatch);242 this.storeAuth(meAuth);243 }, standardCatch);244 //strict promise245 return await new Promise(246 (resolve) =>247 meAuth &&248 meAuth.constructor === Object &&249 meAuth.isAnonymous &&250 meAuth251 .delete()252 .then(() => {253 window.alert(254 "REACT-LOCAL-FIREBASE: successfully removed anonymous account"255 );256 verbose &&257 console.log(258 "REACT-LOCAL-FIREBASresolve(meAuth.isAnonymous)E: " +259 meAuth.uid +260 " is logged in"261 );262 resolve(meAuth.isAnonymous);263 })264 .catch(standardCatch)265 );266 };267 render() {268 const { verbose, auth } = this.props;269 const { storedAuth } = this.state;270 return (271 <div>272 <div273 ref={this.props.pa}274 style={this.props.style}275 onClick={async () => {276 this.storeAuth(...this.props.storableAuth);277 this.props.clearStore();278 }}279 />280 <div281 ref={this.props.fwd}282 style={this.props.style}283 onClick={async () => {284 this.props.onStart();285 var res;286 if (this.props.reset) {287 res = await this.storeAuth({});288 this.props.resetResetAuth();289 } else {290 res = await this.getUserInfo(verbose, auth, storedAuth);291 if (res === "login?") this.props.onPromptToLogin();292 }293 if (res) this.props.onFinish(); //res.isAnonymous294 }}295 />296 </div>297 );298 }299}300export default React.forwardRef((props, getRefs) => {301 const { pa, fwd } = props.getRefs();302 return <PromptAuth fwd={fwd} pa={pa} {...props} />;303});304/*export default React.forwardRef((props, ref) => {305 return <PromptAuth fwd={ref.fwd} pa={ref.pa} {...props} />;306});*/307/**308 * 309 {React.forwardRef((props, ref) =>310 React.createElement(311 <div312 ref={ref}313 style={this.props.style}314 onClick={async () => {315 this.props.onStart();316 const res = await this.getUserInfo(verbose, auth, storedAuth);317 if (res === "login?") this.props.onPromptToLogin();318 if (res) this.props.onFinish(); //res.isAnonymous319 }}320 />,321 props322 )323 )}...

Full Screen

Full Screen

test_authpromptwrapper.js

Source:test_authpromptwrapper.js Github

copy

Full Screen

1// NOTE: This tests code outside of Necko. The test still lives here because2// the contract is part of Necko.3// TODO:4// - HTTPS5// - Proxies6const nsIAuthInformation = Components.interfaces.nsIAuthInformation;7const nsIAuthPromptAdapterFactory = Components.interfaces.nsIAuthPromptAdapterFactory;8function run_test() {9 const contractID = "@mozilla.org/network/authprompt-adapter-factory;1";10 if (!(contractID in Components.classes)) {11 print("No adapter factory found, skipping testing");12 return;13 }14 var adapter = Components.classes[contractID].getService();15 do_check_eq(adapter instanceof nsIAuthPromptAdapterFactory, true);16 // NOTE: xpconnect lets us get away with passing an empty object here17 // For this part of the test, we only care that this function returns18 // success19 do_check_neq(adapter.createAdapter({}), null);20 const host = "www.mozilla.org";21 var info = {22 username: "",23 password: "",24 domain: "",25 flags: nsIAuthInformation.AUTH_HOST,26 authenticationScheme: "basic",27 realm: "secretrealm"28 };29 const CALLED_PROMPT = 1 << 0;30 const CALLED_PROMPTUP = 1 << 1;31 const CALLED_PROMPTP = 1 << 2;32 function Prompt1() {}33 Prompt1.prototype = {34 called: 0,35 rv: true,36 user: "foo\\bar",37 pw: "bar",38 scheme: "http",39 QueryInterface: function authprompt_qi(iid) {40 if (iid.equals(Components.interfaces.nsISupports) ||41 iid.equals(Components.interfaces.nsIAuthPrompt))42 return this;43 throw Components.results.NS_ERROR_NO_INTERFACE;44 },45 prompt: function ap1_prompt(title, text, realm, save, defaultText, result) {46 this.called |= CALLED_PROMPT;47 this.doChecks(text, realm);48 return this.rv;49 },50 promptUsernameAndPassword:51 function ap1_promptUP(title, text, realm, savePW, user, pw)52 {53 this.called |= CALLED_PROMPTUP;54 this.doChecks(text, realm);55 user.value = this.user;56 pw.value = this.pw;57 return this.rv;58 },59 promptPassword: function ap1_promptPW(title, text, realm, save, pwd) {60 this.called |= CALLED_PROMPTP;61 this.doChecks(text, realm);62 pwd.value = this.pw;63 return this.rv;64 },65 doChecks: function ap1_check(text, realm) {66 if (this.scheme == "http")67 do_check_eq(host + ":80 (" + info.realm + ")", realm);68 else69 do_check_eq(this.scheme + "://" + host, realm);70 do_check_neq(text.indexOf(host), -1);71 if (info.flags & nsIAuthInformation.ONLY_PASSWORD) {72 // Should have the username in the text73 do_check_neq(text.indexOf(info.username), -1);74 } else {75 // Make sure that we show the realm if we have one and that we don't76 // show "" otherwise77 if (info.realm != "")78 do_check_neq(text.indexOf(info.realm), -1);79 else80 do_check_eq(text.indexOf('""'), -1);81 // No explicit port in the URL; message should not contain -182 // for those cases83 do_check_eq(text.indexOf("-1"), -1);84 }85 }86 };87 // Also have to make up a channel88 var ios = Components.classes["@mozilla.org/network/io-service;1"]89 .getService(Components.interfaces.nsIIOService);90 var chan = ios.newChannel("http://" + host, "", null);91 function do_tests(expectedRV) {92 var prompt1;93 var wrapper;94 // 1: The simple case95 prompt1 = new Prompt1();96 prompt1.rv = expectedRV;97 wrapper = adapter.createAdapter(prompt1);98 var rv = wrapper.promptAuth(chan, 0, info);99 do_check_eq(rv, prompt1.rv);100 do_check_eq(prompt1.called, CALLED_PROMPTUP);101 if (rv) {102 do_check_eq(info.domain, "");103 do_check_eq(info.username, prompt1.user);104 do_check_eq(info.password, prompt1.pw);105 }106 info.domain = "";107 info.username = "";108 info.password = "";109 // 2: Only ask for a PW110 prompt1 = new Prompt1();111 prompt1.rv = expectedRV;112 info.flags |= nsIAuthInformation.ONLY_PASSWORD;113 // Initialize the username so that the prompt can show it114 info.username = prompt1.user;115 wrapper = adapter.createAdapter(prompt1);116 rv = wrapper.promptAuth(chan, 0, info);117 do_check_eq(rv, prompt1.rv);118 do_check_eq(prompt1.called, CALLED_PROMPTP);119 if (rv) {120 do_check_eq(info.domain, "");121 do_check_eq(info.username, prompt1.user); // we initialized this122 do_check_eq(info.password, prompt1.pw);123 }124 info.flags &= ~nsIAuthInformation.ONLY_PASSWORD;125 info.domain = "";126 info.username = "";127 info.password = "";128 // 3: user, pw and domain129 prompt1 = new Prompt1();130 prompt1.rv = expectedRV;131 info.flags |= nsIAuthInformation.NEED_DOMAIN;132 wrapper = adapter.createAdapter(prompt1);133 rv = wrapper.promptAuth(chan, 0, info);134 do_check_eq(rv, prompt1.rv);135 do_check_eq(prompt1.called, CALLED_PROMPTUP);136 if (rv) {137 do_check_eq(info.domain, "foo");138 do_check_eq(info.username, "bar");139 do_check_eq(info.password, prompt1.pw);140 }141 info.flags &= ~nsIAuthInformation.NEED_DOMAIN;142 info.domain = "";143 info.username = "";144 info.password = "";145 // 4: username that doesn't contain a domain146 prompt1 = new Prompt1();147 prompt1.rv = expectedRV;148 info.flags |= nsIAuthInformation.NEED_DOMAIN;149 prompt1.user = "foo";150 wrapper = adapter.createAdapter(prompt1);151 rv = wrapper.promptAuth(chan, 0, info);152 do_check_eq(rv, prompt1.rv);153 do_check_eq(prompt1.called, CALLED_PROMPTUP);154 if (rv) {155 do_check_eq(info.domain, "");156 do_check_eq(info.username, prompt1.user);157 do_check_eq(info.password, prompt1.pw);158 }159 info.flags &= ~nsIAuthInformation.NEED_DOMAIN;160 info.domain = "";161 info.username = "";162 info.password = "";163 // 5: FTP164 var ftpchan = ios.newChannel("ftp://" + host, "", null);165 prompt1 = new Prompt1();166 prompt1.rv = expectedRV;167 prompt1.scheme = "ftp";168 wrapper = adapter.createAdapter(prompt1);169 var rv = wrapper.promptAuth(ftpchan, 0, info);170 do_check_eq(rv, prompt1.rv);171 do_check_eq(prompt1.called, CALLED_PROMPTUP);172 if (rv) {173 do_check_eq(info.domain, "");174 do_check_eq(info.username, prompt1.user);175 do_check_eq(info.password, prompt1.pw);176 }177 info.domain = "";178 info.username = "";179 info.password = "";180 }181 do_tests(true);182 do_tests(false);...

Full Screen

Full Screen

loggedprompter.js

Source:loggedprompter.js Github

copy

Full Screen

...40 cancel: function() {}41 };42 }43 log(LOG_DEBUG, "Not restricted " + key);44 return _p.asyncPromptAuth(channel, callback, context, level, info);45 },46 restrictLogin: function(uri) {47 const key = uriToKey(uri);48 restricted.set(key, true);49 },50 allowLogin: function(uri) {51 const key = uriToKey(uri);52 log(LOG_DEBUG, "Lifting restriction " + key);53 restricted.delete(key, true);54 }55 };56 });57 /**58 * Property providing nsIPrompt...

Full Screen

Full Screen

LoginLink.jsx

Source:LoginLink.jsx Github

copy

Full Screen

1import React from 'react';2import {useDispatch} from "react-redux";3import getUser from "../utils/getUser";4import {clear, setUser} from "../reduxSlices/userInfoSlice";5function popupCloseHandler() {6 // This is intentional7}8function promptAuth() {9 // pop a popup that points to a page that auto-closes (window.close())10 // if the user is not authenticated, it will redirect to the auth server which will redirect back and the popup should auto-close11 const popup = window.open(`${process.env.REACT_APP_API_BASE}/auto-close`, '', 'width=600, height=600');12 // auto-check if the pop-up is closed (either auto-closed or manually)13 // if so, call the handler that is set on a per usage basis and will most likely be a call to window.location.reload()14 const interval = setInterval(() => {15 if (popup.closed) {16 clearInterval(interval);17 popupCloseHandler();18 }19 }, 100);20}21/**22 * Wraps some element with an `a` tag. Clicking on it will pop the auth popup23 * Attempting to pop the popup automatically (without a user event) is24 * blocked by most browsers (popup blockers)25 *26 * @param attrs27 * @returns {JSX.Element}28 * @constructor29 */30function LoginLink(attrs) {31 const dispatch = useDispatch();32 popupCloseHandler = () => {33 getUser().then((maybeUser) => {34 if (maybeUser) {35 dispatch(setUser(maybeUser))36 } else {37 dispatch(clear())38 }39 });40 }41 return <a href="#" onClick={(e) => { e.preventDefault(); promptAuth()}} {...attrs}>{attrs.children}</a>;42}...

Full Screen

Full Screen

crud.js

Source:crud.js Github

copy

Full Screen

1'use strict';2const promptService = require('../../prompts/service');3const promptEntity = require('../../prompts/entity');4const promptEntityPlural = require('../../prompts/entity-plural');5const promptAuth = require('../../prompts/auth');6const promptFields = require('../../prompts/fields');7const promptSortableFields = require('../../prompts/sortable-fields');8const promptAvailableFilters = require('../../prompts/available-filters');9const promptAddViews = require('../../prompts/add-views');10const apiList = require('./api-list');11const apiGet = require('./api-get');12const apiPost = require('./api-post');13const apiPut = require('./api-put');14const { ensureOptions } = require('../../utils');15const getPrompts = () => [16 promptService,17 promptEntity,18 promptEntityPlural,19 promptAuth,20 promptFields,21 promptSortableFields,22 promptAvailableFilters,23 promptAddViews24];25module.exports.command = 'create-crud';26module.exports.describe = 'Create an entity CRUD operations';27module.exports.builder = yargs => {28 return yargs29 .option('service', {30 alias: 's',31 description: 'The current service name (in dash case)',32 type: 'string'33 })34 .option('entity', {35 alias: 'e',36 description: 'The CRUD entity',37 type: 'string'38 })39 .help();40};41module.exports.handler = async argv => {42 const options = await ensureOptions(getPrompts(), argv);43 await apiList.handler(options);44 await apiGet.handler(options);45 await apiPost.handler(options);46 await apiPut.handler(options);...

Full Screen

Full Screen

Home.js

Source:Home.js Github

copy

Full Screen

1import React from 'react';2import './Home.css';3import '../Components.css';4import Header from '../Header';5import {Link} from 'react-router-dom';6export default class Home extends React.Component {7 componentDidMount(){8 document.title = "MangaReminder";9 }10 render(){11 return(12 <div>13 <Header/>14 <div className="home">15 <text className="titleText">16 The easiest way to receive email reminders on your favorite manga.17 </text>18 <PromptAuth/>);19 </div>20 </div>21 );22 }23}24const HomeList = (props) => {25 return(26 <div className="homeList">27 28 </div>29 );30}31const PromptAuth = (props) => {32 return(33 <div className="promptAuth">34 <Link to="/login" className="buttonLink">Log In</Link>35 <Link to="/signup" className="buttonLink">Sign Up</Link>36 </div>37 );...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('text=Get started');7 await page.waitForNavigation();8 await page.click('text=Docs');9 await page.waitForNavigation();10 await page.click('text=API');11 await page.waitForNavigation();12 await page.click('text=Internal API');13 await page.waitForNavigation();14 await page.click('text=class: BrowserType');15 await page.waitForNavigation();16 await page.click('text=launch');17 await page.waitForNavigation();18 await page.click('text=Options');19 await page.waitForNavigation();20 await page.click('text=BrowserContextOptions');21 await page.waitForNavigation();22 await page.click('text=Proxy');23 await page.waitForNavigation();24 await page.click('text=ProxyAuth');25 await page.waitForNavigation();26 await page.click('text=ProxyAuth');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('text=Get started');7 await page.fill('input[name="email"]', 'email');8 await page.fill('input[name="password"]', 'password');9 await page.click('text=Log in');10 await page.screenshot({ path: `example.png` });11 await browser.close();12})();13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.click('text=Get started');19 await page.fill('input[name="email"]', 'email');20 await page.fill('input[name="password"]', 'password');21 await page.click('text=Log in');22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: `example.png` });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: `example.png` });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: `example.png` });39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.screenshot({ path

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 await context.tracing.start({ screenshots: true, snapshots: true });6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 await context.tracing.stop({ path: `trace.zip` });9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch({ headless: false });14 const context = await browser.newContext();15 await context.tracing.start({ screenshots: true, snapshots: true });16 const page = await context.newPage();17 await page.screenshot({ path: `example.png` });18 await context.tracing.stop({ path: `trace.zip` });19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch({ headless: false });24 const context = await browser.newContext();25 await context.tracing.start({ screenshots: true, snapshots: true });26 const page = await context.newPage();27 await page.screenshot({ path: `example.png` });28 await context.tracing.stop({ path: `trace.zip` });29 await browser.close();30})();31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch({ headless: false });34 const context = await browser.newContext();35 await context.tracing.start({ screenshots: true, snapshots: true });36 const page = await context.newPage();37 await page.screenshot({ path: `example.png` });38 await context.tracing.stop({ path: `trace.zip` });39 await browser.close();40})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { PromptAuth } = require('playwright/lib/internal/auth');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const promptAuth = new PromptAuth(page);8 await promptAuth.authenticate('user', 'password');9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12const { chromium } = require('playwright');13const { PromptAuth } = require('playwright/lib/internal/auth');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 const promptAuth = new PromptAuth(page);19 await promptAuth.authenticate('user', 'password');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch({12 });13 const context = await browser.newContext();14 const page = await context.newPage();15 await browser.close();16})();17const { chromium

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2let browser = await chromium.launch({ headless: false, slowMo: 1000 });3let context = await browser.newContext();4let page = await context.newPage();5await page.click('text="Sign in"');6await page.fill('text="Email or phone"', '

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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