How to use _authenticate method in Playwright Internal

Best JavaScript code snippet using playwright-internal

auth.spec.js

Source:auth.spec.js Github

copy

Full Screen

1var PodioErrors = require('../lib/PodioErrors');2var auth = require('../lib/auth');3var sinon = require('sinon');4var _ = require('lodash');5describe('auth', function() {6 describe('isAuthenticated', function() {7 it('should resolve if authObject is populated', function(done) {8 var host = {9 authObject: {10 accessToken: 'adbcdegt'11 },12 refreshAuthFromStore: sinon.spy(function (callback) {13 callback()14 })15 };16 auth.isAuthenticated.call(host).then(function () {17 done();18 });19 });20 it('should reject if authObject is populated', function(done) {21 var host = {22 authObject: void 0,23 refreshAuthFromStore: sinon.spy(function (callback) {24 callback()25 })26 };27 auth.isAuthenticated.call(host).catch(function () {28 done();29 });30 });31 it('should call _hasClientSideRedirect and reject if no authObject exists', function(done) {32 var host = {33 refreshAuthFromStore: sinon.spy(function (callback) {34 callback()35 }),36 _hasClientSideRedirect: sinon.stub().returns(false)37 };38 auth.isAuthenticated.call(host).catch(function () {39 expect(host._hasClientSideRedirect.calledOnce).toBe(true);40 done();41 });42 });43 it('should call refreshAuthFromStore if a callback is provided', function() {44 var host = {45 refreshAuthFromStore: sinon.stub().returns(false)46 };47 var callback = sinon.stub();48 auth.isAuthenticated.call(host, callback);49 expect(_.isFunction(callback)).toBe(true);50 expect(host.refreshAuthFromStore.calledOnce).toBe(true);51 });52 });53 describe('getAccessToken', function() {54 it('should call _authenticate with the right responseData', function() {55 var host = {56 authType: 'server',57 _authenticate: sinon.stub(),58 _onAccessTokenAcquired: function() {}59 };60 var authCode = 'e123';61 var redirectURL = 'https://www.myapp.com/oauth';62 var expectedResponseData = {63 grant_type: 'authorization_code',64 code: authCode,65 redirect_uri: redirectURL66 };67 auth.getAccessToken.apply(host, [authCode, redirectURL]);68 expect(host._authenticate.calledOnce).toBe(true);69 expect(host._authenticate.getCall(0).args[0]).toEqual(expectedResponseData);70 });71 it('should throw an exception if authType is not server', function() {72 var host = {73 authType: 'client'74 };75 var callback = sinon.stub();76 auth.getAccessToken.call(host, 'e123', 'http://redirect.url/', callback);77 var expectedError = new Error('In authentication types other than server access token is delivered through a redirect');78 expect(_.isFunction(callback)).toBe(true);79 expect(callback.calledOnce).toBe(true);80 expect(callback.getCall(0).args[0]).toEqual(expectedError);81 });82 });83 describe('setAccessToken', function() {84 it('should set the OAuth object', function() {85 var host = {};86 var responseData = {87 access_token: 'a123',88 refresh_token: 'b123',89 expires_in: 4434,90 ref: {},91 transfer_token: 'c123'92 };93 auth.setAccessToken.call(host, responseData);94 expect(host.authObject).not.toEqual(void 0);95 expect(host.authObject.accessToken).toEqual(responseData.access_token);96 expect(host.authObject.refreshToken).toEqual(responseData.refresh_token);97 expect(host.authObject.expiresIn).toEqual(responseData.expires_in);98 expect(host.authObject.ref).toEqual(responseData.ref);99 expect(host.authObject.transferToken).toEqual(responseData.transfer_token);100 });101 });102 describe('getAuthorizationURL', function() {103 it('should return the correct authorization URL for the client auth', function() {104 var redirectURL = 'https://www.myapp.com/oauth';105 var host = {106 apiURL: 'https://api.podio.com',107 authType: 'client',108 clientId: 123109 };110 111 var expectedURL = 'https://podio.com/oauth/authorize?client_id=123&redirect_uri=https%3A%2F%2Fwww.myapp.com%2Foauth&response_type=token';112 113 expect(auth.getAuthorizationURL.call(host, redirectURL)).toBe(expectedURL);114 });115 it('should return the correct authorization URL for the server auth', function() {116 var redirectURL = 'https://www.myapp.com/oauth';117 118 var host = {119 apiURL: 'https://podio.com',120 authType: 'server',121 clientId: 123122 };123 var expectedURL = 'https://podio.com/oauth/authorize?client_id=123&redirect_uri=https%3A%2F%2Fwww.myapp.com%2Foauth&response_type=code';124 expect(auth.getAuthorizationURL.call(host, redirectURL)).toBe(expectedURL);125 });126 it('should throw an error when retrieving an auth URL for password auth', function() {127 var redirectURL = 'https://www.myapp.com/oauth';128 var host = {129 authType: 'password',130 clientId: 123131 };132 var errorText = 'Authorization URLs are not supported for password authentication';133 expect(auth.getAuthorizationURL.bind(host, redirectURL)).toThrow(new Error(errorText));134 });135 });136 describe('authenticateWithCredentialsForOffering', function() {137 it('should call authenticate with credentials and the correct grant type', function() {138 var host = {139 _authenticate: sinon.stub()140 };141 var username = 'user@podio.com';142 var password = 'password';143 var expected = {144 grant_type: 'password',145 username: username,146 password: password147 };148 auth.authenticateWithCredentialsForOffering.call(host, username, password);149 expect(host._authenticate.calledOnce).toBe(true);150 expect(host._authenticate.getCall(0).args[0]).toEqual(expected);151 expect(_.isFunction(host._authenticate.getCall(0).args[1])).toBe(true);152 });153 it('should call onAccessTokenAcquired with correct parameters when authentication succeeds', function() {154 var responseData = {};155 var host = {156 _authenticate: sinon.stub().callsArgWith(1, null, responseData),157 _onAccessTokenAcquired: sinon.stub()158 };159 var username = 'user@podio.com';160 var password = 'password';161 var callback = function() {};162 auth.authenticateWithCredentialsForOffering.call(host, username, password, null, callback);163 expect(host._onAccessTokenAcquired.calledOnce).toBe(true);164 expect(host._onAccessTokenAcquired.calledWithExactly(responseData, callback)).toBe(true);165 });166 });167 describe('authenticateWithApp', function() {168 it('should call _authenticate with appId, appToken and correct grand type', function() {169 var host = {170 _authenticate: sinon.stub()171 };172 var expectedData = {173 grant_type: 'app',174 app_id: 123,175 app_token: 'e123'176 };177 auth.authenticateWithApp.call(host, 123, 'e123');178 expect(host._authenticate.calledOnce).toBe(true);179 expect(host._authenticate.getCall(0).args[0]).toEqual(expectedData);180 });181 it('should call _onAccessTokenAcquired with responseData and callback when auth is completed', function() {182 var authData = { access_token: 'a321' };183 var callback = function() {};184 var host = {185 _authenticate: sinon.stub().callsArgWith(1, null, authData),186 _onAccessTokenAcquired: sinon.stub()187 };188 auth.authenticateWithApp.call(host, 123, 'e123', callback);189 expect(host._onAccessTokenAcquired.calledOnce).toBe(true);190 expect(host._onAccessTokenAcquired.calledWithExactly(authData, callback)).toBe(true);191 });192 it('should not call _onAccessTokenAcquired when auth failed and call the callback', function() {193 var callback = sinon.stub();194 var err = new Error();195 var host = {196 _authenticate: sinon.stub().callsArgWith(1, err),197 _onAccessTokenAcquired: sinon.stub()198 };199 auth.authenticateWithApp.call(host, 123, 'e123', callback);200 expect(host._onAccessTokenAcquired.called).toBe(false);201 expect(callback.called).toBe(true);202 expect(callback.calledWithExactly(err)).toBe(true);203 });204 });205 describe('_getAuthFromStore', function() {206 it('should get auth data from the session store and store it in memory', function() {207 var authObject = { accessToken: 'e123' };208 var callback = sinon.stub();209 var host = {210 sessionStore: { get: sinon.stub().callsArgWith(1, authObject) },211 authType: 'client'212 };213 auth._getAuthFromStore.call(host, callback);214 expect(host.sessionStore.get.calledOnce).toBe(true);215 expect(host.sessionStore.get.getCall(0).args[0]).toEqual(host.authType);216 expect(_.isFunction(host.sessionStore.get.getCall(0).args[1])).toBe(true);217 expect(host.authObject).toEqual(authObject);218 expect(callback.calledOnce).toBe(true);219 });220 it('should call the callback function if provided', function() {221 var authObject = { accessToken: 'e123' };222 var host = {223 sessionStore: { get: sinon.stub().callsArgWith(1, authObject) },224 authType: 'client'225 };226 var callback = sinon.stub();227 auth._getAuthFromStore.call(host, callback);228 expect(_.isFunction(callback)).toBe(true);229 expect(callback.calledOnce).toBe(true);230 });231 it('should not call callback if not specified and get auth data from the session store and store it in memory', function() {232 var authObject = { accessToken: 'e123' };233 var host = {234 sessionStore: { get: sinon.stub().callsArgWith(1, authObject) },235 authType: 'client'236 };237 auth._getAuthFromStore.call(host);238 expect(host.sessionStore.get.calledOnce).toBe(true);239 expect(host.sessionStore.get.getCall(0).args[0]).toEqual(host.authType);240 expect(_.isFunction(host.sessionStore.get.getCall(0).args[1])).toBe(true);241 expect(host.authObject).toEqual(authObject);242 });243 });244 describe('_hasClientSideRedirect', function() {245 it('should return false for non client auth', function() {246 var host = {247 authType: 'server'248 };249 expect(auth._hasClientSideRedirect.call(host)).toBe(false);250 });251 it('should save access token if it is present in the hash fragment and return true', function() {252 var params = { access_token: 123 };253 var utils = {254 _getHashParams: sinon.stub().returns(params)255 };256 var host = {257 authType: 'client',258 _getUtils: sinon.stub().returns(utils),259 _onAccessTokenAcquired: sinon.stub()260 };261 expect(auth._hasClientSideRedirect.call(host)).toBe(true);262 expect(host._onAccessTokenAcquired.calledOnce).toBe(true);263 expect(host._onAccessTokenAcquired.getCall(0).args[0]).toEqual(params);264 });265 it('should not attempt to save the token and return false if no hash parameters are present in the client auth', function() {266 var utils = {267 _getHashParams: sinon.stub().returns({})268 };269 var host = {270 authType: 'client',271 _getUtils: sinon.stub().returns(utils),272 _onAccessTokenAcquired: sinon.stub()273 };274 expect(auth._hasClientSideRedirect.call(host)).toBe(false);275 expect(host._onAccessTokenAcquired.called).toBe(false);276 });277 });278 describe('_onAccessTokenAcquired', function() {279 var responseData = {280 access_token: 'e123',281 refresh_token: 'a321',282 expires_in: 4434,283 ref: {}284 };285 var oAuthObject = {286 accessToken: 'e123',287 refreshToken: 'a321',288 expiresIn: 4434,289 ref: {}290 };291 it('should set an OAuth object correctly', function() {292 var host = {};293 auth._onAccessTokenAcquired.call(host, responseData, function() {});294 expect(host.authObject).toEqual(oAuthObject);295 });296 it('should save an authObject in the session store and provide a callback', function() {297 var host = {298 sessionStore: {299 set: sinon.stub()300 },301 authType: 'client'302 };303 auth._onAccessTokenAcquired.call(host, responseData, function() {});304 expect(host.sessionStore.set.calledOnce).toBe(true);305 expect(host.sessionStore.set.getCall(0).args[0]).toEqual(oAuthObject);306 expect(host.sessionStore.set.getCall(0).args[1]).toEqual('client');307 expect(_.isFunction(host.sessionStore.set.getCall(0).args[2])).toBe(true);308 });309 it('should call the callback if no session store is provided', function() {310 var callback = sinon.stub();311 var host = {};312 auth._onAccessTokenAcquired.call(host, responseData, callback);313 expect(callback.calledOnce).toBe(true);314 expect(callback.getCall(0).args[0]).toEqual(null);315 expect(callback.getCall(0).args[1]).toEqual(responseData);316 });317 it('should not fail trying to call the callback if none is provided', function() {318 var host = {};319 auth._onAccessTokenAcquired.call(host, responseData);320 expect(true).toBe(true);321 });322 });323 describe('_clearAuthentication', function() {324 it('should remove the authObject and call sessionStore with an empty auth object', function() {325 var host = {326 authObject: {},327 authType: 'client',328 sessionStore: { set: sinon.stub() }329 };330 auth._clearAuthentication.call(host);331 expect(host.authObject).toBeUndefined();332 expect(host.sessionStore.set.calledOnce).toBe(true);333 expect(host.sessionStore.set.calledWithExactly({}, 'client')).toBe(true);334 });335 });336 describe('_authenticate', function() {337 it('should construct the request data and url correctly', function() {338 var host = {339 apiURL: 'http://sub.podio.com',340 clientId: 123,341 clientSecret: 'secret',342 _authRequest: sinon.stub()343 };344 var requestData = { grant_type: 'authorization_code' };345 var expectedRequestData = {346 grant_type: 'authorization_code',347 client_id: 123,348 client_secret: 'secret'349 };350 auth._authenticate.call(host, requestData);351 expect(host._authRequest.calledOnce).toBe(true);352 expect(host._authRequest.getCall(0).args[0]).toEqual('http://sub.podio.com/oauth/token');353 expect(host._authRequest.getCall(0).args[1]).toEqual(expectedRequestData);354 });355 });356 describe('_onAuthResponse', function() {357 it('should call the callback with the body if response is ok', function() {358 var callback = sinon.stub();359 var url = 'https://api.podio.com:443/oauth/token';360 auth._onAuthResponse(callback, 'authorization_code', url, null, { ok: true, body: 'body' });361 expect(callback.calledOnce).toBe(true);362 expect(callback.calledWithExactly(null, 'body')).toBe(true);363 });364 it('should raise an exception if authentication failed', function() {365 var url = 'https://api.podio.com:443/oauth/token';366 var errorMessage = 'Authentication for authorization_code failed. Reason: 42';367 var PodioAuthorizationError = function(message, status, url) {368 this.message = message;369 this.status = status;370 this.url = url;371 this.name = 'PodioAuthorizationError';372 };373 var response = {374 ok: false,375 body: { error_description: '42' },376 status: 401377 };378 var callback = sinon.stub();379 auth._onAuthResponse(callback, 'authorization_code', url, new PodioAuthorizationError(errorMessage, 401, url), response);380 expect(callback.calledOnce).toBe(true);381 expect(callback.calledWithExactly(new PodioAuthorizationError(errorMessage, 401, url), void 0)).toBe(true);382 });383 });384 describe('_refreshToken', function() {385 it('should call authenticate with the refresh token, clear previous authentication', function() {386 var host = {387 authObject: {388 refreshToken: 123389 },390 _authenticate: sinon.stub(),391 _clearAuthentication: sinon.stub()392 };393 var expectedOptions = {394 grant_type: 'refresh_token',395 refresh_token: 123396 };397 auth._refreshToken.call(host);398 expect(host._authenticate.calledOnce).toBe(true);399 expect(host._authenticate.getCall(0).args[0]).toEqual(expectedOptions);400 expect(host._clearAuthentication.calledOnce).toBe(true);401 });402 it('should call _onAccessTokenAcquired when authentication is done', function() {403 var callbackFn = function() {};404 var responseData = { accessToken: 123 };405 var host = {406 authObject: {407 refreshToken: 123408 },409 _authenticate: function(requestData, callback) {410 callback(null, responseData);411 },412 _onAccessTokenAcquired: sinon.stub(),413 _clearAuthentication: sinon.stub()414 };415 auth._refreshToken.call(host, callbackFn);416 expect(host._onAccessTokenAcquired.calledOnce).toBe(true);417 expect(host._onAccessTokenAcquired.calledWithExactly(responseData, callbackFn)).toBe(true);418 });419 it('should call an onTokenWillRefresh callback if present and client side authentication is chosen', function() {420 var callbackFn = function() {};421 var host = {422 authObject: {},423 _clearAuthentication: function() {},424 authType: 'client',425 onTokenWillRefresh: sinon.stub(),426 _onAccessTokenAcquired: sinon.stub(),427 _authenticate: sinon.stub()428 };429 auth._refreshToken.call(host, callbackFn);430 expect(host.onTokenWillRefresh.calledOnce).toBe(true);431 expect(host.onTokenWillRefresh.calledWithExactly(callbackFn)).toBe(true);432 expect(host._authenticate.called).toBe(false);433 expect(host._onAccessTokenAcquired.called).toBe(false);434 });435 });...

Full Screen

Full Screen

routes.dev.js

Source:routes.dev.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports["default"] = void 0;6var _express = require("express");7var _user = _interopRequireDefault(require("./controllers/user.controller"));8var _service = _interopRequireDefault(require("./controllers/service.controller"));9var _expert = _interopRequireDefault(require("./controllers/expert.controller"));10var _category = _interopRequireDefault(require("./controllers/category.controller"));11var _appointment = _interopRequireDefault(require("./controllers/appointment.controller"));12var _employee = _interopRequireDefault(require("./controllers/employee.controller"));13var _rating = _interopRequireDefault(require("./controllers/rating.controller"));14var _authenticate = _interopRequireDefault(require("./middleware/authenticate"));15var _profileMedia = _interopRequireDefault(require("./middleware/profile-media"));16var _errorHandler = _interopRequireDefault(require("./middleware/error-handler"));17var _employeeAuth = _interopRequireDefault(require("./middleware/employee-auth"));18var _expertAuth = _interopRequireDefault(require("./middleware/expert-auth"));19var _adminAuth = _interopRequireDefault(require("./middleware/admin-auth"));20function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }21/* eslint-disable max-len */22var routes = new _express.Router(); // Users Routes23routes.post('/api/users/register', _user["default"].register);24routes.post('/api/users/login', _user["default"].login);25routes.post('/api/users/resetPassword', _authenticate["default"], _user["default"].resetPassword);26routes.post('/api/users/sendforgetPasswordEmail', _user["default"].sendForgetPassEmail);27routes.post('/api/users/forgetPassword/:userId/:token', _user["default"].forgetPassword);28routes.post('/api/users/addAppointment', _authenticate["default"], _appointment["default"].addAppointment);29routes.get('/api/users/getAppointmentHistory', _authenticate["default"], _appointment["default"].getAppointmentHistory);30routes.get('/api/users/getScheduleAppointment', _authenticate["default"], _appointment["default"].getScheduleAppointment);31routes.post('/api/users/createAppointmentCharge', _authenticate["default"], _appointment["default"].createAppointmentCharge);32routes.post('/api/users/changeProfile', _authenticate["default"], _user["default"].changeProfile);33routes.get('/api/users/deactivateAccount', _authenticate["default"], _user["default"].deactivateAccount);34routes.get('/api/users/getProfile', _authenticate["default"], _user["default"].getProfile);35routes.post('/api/users/changePicture', [_authenticate["default"], _profileMedia["default"].fields([{36 name: 'imageUrl',37 maxCount: 138}])], _user["default"].changePicture); // Experts Routes39routes.get('/api/experts/:serviceId', _expert["default"].getServiceExperts);40routes.get('/api/expertDetail/:expertId', _expert["default"].getExpertDetail);41routes.get('/api/getExperts', _expert["default"].getAllExperts);42routes.get('/api/getExpertProfile', [_authenticate["default"], _expertAuth["default"]], _expert["default"].getExpertProfile);43routes.post('/api/editExpertProfile', [_authenticate["default"], _expertAuth["default"]], _expert["default"].editExpertProfile);44routes.get('/api/getExpertAppointmentsByStatus/:status', [_authenticate["default"], _expertAuth["default"]], _expert["default"].getExpertAppointmentsByStatus);45routes.post('/api/changeExpertAppointmentStatus', [_authenticate["default"], _expertAuth["default"]], _expert["default"].changeExpertAppointmentStatus);46routes.post('/api/addExpertEmployee', [_authenticate["default"], _expertAuth["default"], _profileMedia["default"].fields([{47 name: 'imageUrl',48 maxCount: 149}])], _expert["default"].addExpertEmployee);50routes.get('/api/getExpertAllAppointments', [_authenticate["default"], _expertAuth["default"]], _expert["default"].getExpertAllAppointments);51routes.get('/api/getExpertEmployees', [_authenticate["default"], _expertAuth["default"]], _expert["default"].getExpertEmployees);52routes.get('/api/getExpertStats', [_authenticate["default"], _expertAuth["default"]], _expert["default"].getExpertStats);53routes.post('/api/deleteExpertEmployee', [_authenticate["default"], _expertAuth["default"]], _expert["default"].deleteExpertEmployee);54routes.post('/api/expertAssignAppointment', [_authenticate["default"], _expertAuth["default"]], _expert["default"].expertAssignAppointment);55routes.post('/api/changeExpertPicture', [_authenticate["default"], _expertAuth["default"], _profileMedia["default"].fields([{56 name: 'imageUrl',57 maxCount: 158}])], _expert["default"].changeExpertPicture); // Employee Routes59routes.get('/api/getEmployeeStats', [_authenticate["default"], _employeeAuth["default"]], _employee["default"].getEmployeeStats);60routes.get('/api/getEmployeeProfile', [_authenticate["default"], _employeeAuth["default"]], _employee["default"].getEmployeeProfile);61routes.get('/api/getEmployeeAppointmentStatus/:status', [_authenticate["default"], _employeeAuth["default"]], _employee["default"].getEmployeeAppointmentStatus);62routes.post('/api/getEmployeeAssignAppointments', [_authenticate["default"], _employeeAuth["default"]], _employee["default"].getEmployeeAssignAppointments);63routes.post('/api/changeEmployeeAppointmentStatus', [_authenticate["default"], _employeeAuth["default"]], _employee["default"].changeEmployeeAppointmentStatus); // Services Routes64routes.get('/api/services', _service["default"].getServices); // Rating Routes65routes.post('/api/addAppointmentRating', _rating["default"].addAppointmentRating); // Category Routes66routes.get('/api/categories/:serviceId', _category["default"].getServiceCategories);67routes.use(_errorHandler["default"]);68var _default = routes;...

Full Screen

Full Screen

controller.test.js

Source:controller.test.js Github

copy

Full Screen

...1011 it('When calling authenticate and it doesn\'t receive a key, it should throw an error', async () => {12 const sut = new Controller({});1314 await expect(sut._authenticate()).rejects.toThrowError('An API key is required');15 });1617 it('When calling authenticate with a key, it should call fetch with the right URL', async () => {18 const mockAccountURL = 'http://mock.com/';19 const mockKey = 'mockKey';20 const expectedURL = `${mockAccountURL}/authorize`;21 jest.spyOn(fetchModule, 'fetch').mockResolvedValue({status: 204});22 const sut = new Controller({accountServiceURL: mockAccountURL});2324 await expect(sut._authenticate(mockKey)).resolves.toBeUndefined();25 expect(fetchModule.fetch).toHaveBeenCalledWith({url: expectedURL, headers: {'Authorization': mockKey}});26 });2728 it('When calling authenticate and the key is rejected, it should throw an error', async () => {29 const mockKey = 'mockKey';30 const mockAccountURL = 'http://mock.com/';31 const expectedURL = `${mockAccountURL}/authorize`;32 const mockErrorResponse = 'Not authorized error mock';33 jest.spyOn(fetchModule, 'fetch').mockImplementation(() => {throw new Error(mockErrorResponse)});34 const sut = new Controller({accountServiceURL: mockAccountURL});3536 await expect(sut._authenticate(mockKey)).rejects.toThrowError(mockErrorResponse);37 expect(fetchModule.fetch).toHaveBeenCalledWith({url: expectedURL, headers: {'Authorization': mockKey}});38 });3940 it('When calling get, it should call callToStringOrArray with the right parameters', async () => {41 jest.spyOn(utils, 'callForStringOrArray').mockImplementation(() => { });42 jest.spyOn(Controller.prototype, '_authenticate').mockResolvedValue();43 const cuit = "23-39916309-5";44 const mockKey = 'MockAPIKey';4546 const sut = new Controller({});4748 await sut.get({ parameters: cuit, key: mockKey });4950 expect(utils.callForStringOrArray).toHaveBeenCalledWith({ argument: cuit, stringCallback: expect.any(Function), arrayCallback: expect.any(Function) }); ...

Full Screen

Full Screen

Login.js

Source:Login.js Github

copy

Full Screen

...24 //this._authenticate = this._authenticate.bind(this)25 }26 handleKeyDown(event){27 if(event.key === 'Enter'){28 this._authenticate('login');29 }30 }31 _authenticate = function (buttonPressed) {32 //close all Alerts33 Alert.closeAll();34 //disable text boxes35 this.setState({ formDisabled: true });36 //validate email/pw37 var email = this.refs["email"].value;38 var password = this.refs["password"].value;39 //check email40 if (!email.includes('@')) {41 Alert.warning("<div style='color:#FF1744; text-align:center'> invalid email </div>", this.alertOptions);42 this.setState({ formDisabled: false });43 }44 //check pw45 else if (password.length < 6) {46 //alert('password must be at least 6 characters');47 Alert.warning("<div style='color:#FF1744; text-align:center'>password length must be 6+</div>", this.alertOptions);48 this.setState({ formDisabled: false });49 }50 //both are valid51 else {52 //encrypt pw and send request for login/signup53 var User = {54 email: email,55 password: password56 };57 if (buttonPressed === 'signup') {58 //env.API_URL59 axios.post(env.API_URL + '/auth/register', User)60 .then((res) => {61 //use res from server62 if (res.data.success === true) {63 Alert.success("<div style='color:#67c26f; text-align:center'>Account has been registered! Please log in</div>",this.alertOptions);64 localStorage.setItem("token", res.data.token);65 }66 else {67 Alert.error(res.data.message);68 }69 })70 .catch((err) => {71 //alert user there was a server error72 Alert.error("<div style='color:#FF1744; text-align:center'>Server error. Please try again later.</div>", this.alertOptions);73 });74 this.setState({ formDisabled: false });75 }76 else if (buttonPressed === 'login') {77 axios.post(env.API_URL + '/auth/login', User)78 .then((res) => {79 //use res from server80 if (res.data.success === true) {81 Alert.success("<div style='color:#67c26f; text-align:center'>Login Successful!</div>", this.alertOptions);82 localStorage.setItem("token", res.data.token);83 //redirect to dashboard if signin successful84 setTimeout(this.props.history.push("/Dashboard"), 2000);85 }86 else {87 //else enable form fields again and display error88 Alert.error("<div style='color:#FF1744; text-align:center'>login failed. " + res.data.message + "</div>", this.alertOptions);89 this.setState({ formDisabled: false });90 }91 })92 .catch((err) => {93 //alert user there was a server error94 Alert.error("<div style='color:#FF1744; text-align:center'>Error: " + String(err) + "</div>", this.alertOptions);95 this.setState({ formDisabled: false });96 });97 }98 }99 }100 render() {101 return (102 <div className='login'>103 <h3 id='loginHeader'>Account Details</h3>104 <form onSubmit={this._onSubmit}>105 <input name='email' placeholder='email@domail.com' ref='email'106 type='text' disabled={this.state.formDisabled} onKeyDown={this.handleKeyDown.bind(this)} />107 <input id='pw' name='password' placeholder='Password' ref='password'108 type='password' disabled={this.state.formDisabled} onKeyDown={this.handleKeyDown.bind(this)} />109 <Alert stack={{ limit: 2, spacing: 50 }} />110 {/* <br/> */}111 <input id='login' type='button' defaultValue='Sign in' ref='signin'112 onClick={() => this._authenticate('login')} />113 <hr />114 <input id='signup' type='button' defaultValue='Sign up' ref='signup'115 onClick={() => this._authenticate('signup')} />116 </form>117 </div>118 );119 }120}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1"use strict";2var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");3var _dotenv = _interopRequireDefault(require("dotenv"));4var _express = _interopRequireDefault(require("express"));5var _movies = _interopRequireDefault(require("./api/movies"));6var _bodyParser = _interopRequireDefault(require("body-parser"));7require("./db");8var _expressSession = _interopRequireDefault(require("express-session"));9var _authenticate = _interopRequireDefault(require("./authenticate"));10var _loglevel = _interopRequireDefault(require("loglevel"));11var _seedData = require("./seedData");12var _users = _interopRequireDefault(require("./api/users"));13var _upcomingMovies = _interopRequireDefault(require("./api/upcomingMovies"));14var _nowplayingMovies = _interopRequireDefault(require("./api/nowplayingMovies"));15var _people = _interopRequireDefault(require("./api/people"));16_dotenv["default"].config();17if (process.env.NODE_ENV === 'test') {18 _loglevel["default"].setLevel('warn');19} else {20 _loglevel["default"].setLevel('info');21}22if (process.env.SEED_DB === 'true') {23 (0, _seedData.loadUsers)();24 (0, _seedData.loadMovies)();25 (0, _seedData.loadUpcomingMovies)();26 (0, _seedData.loadNowplayingMovies)();27 (0, _seedData.loadPeople)();28} // eslint-disable-next-line no-unused-vars29var errHandler = function errHandler(err, req, res, next) {30 /* if the error in development then send stack trace to display whole error,31 if it's in production then just send error message */32 // eslint-disable-next-line no-undef33 if (process.env.NODE_ENV === 'production') {34 return res.status(500).send("Something went wrong!");35 }36 res.status(500).send("Hey!! You caught the error \uD83D\uDC4D\uD83D\uDC4D, ".concat(err.stack, " "));37};38var app = (0, _express["default"])();39var port = process.env.PORT; // app.use(session({40// secret: 'ilikecake',41// resave: true,42// saveUninitialized: true43// }));44app.use(_authenticate["default"].initialize());45app.use(_bodyParser["default"].json());46app.use(_bodyParser["default"].urlencoded());47app.use(_express["default"]["static"]('public'));48app.use('/api/users', _users["default"]);49app.use('/api/movies', _authenticate["default"].authenticate('jwt', {50 session: false51}), _movies["default"]);52app.use('/api/upcomingMovies', _authenticate["default"].authenticate('jwt', {53 session: false54}), _upcomingMovies["default"]);55app.use('/api/nowplayingMovies', _authenticate["default"].authenticate('jwt', {56 session: false57}), _nowplayingMovies["default"]);58app.use('/api/people', _authenticate["default"].authenticate('jwt', {59 session: false60}), _people["default"]);61app.use(errHandler);62var server = app.listen(port, function () {63 _loglevel["default"].info("Server running at ".concat(port));64});...

Full Screen

Full Screen

AuthScreen.js

Source:AuthScreen.js Github

copy

Full Screen

...31 error: null,32 };33 constructor(props) {34 super(props);35 this._authenticate();36 }37 render() {38 return null;39 }40 _authenticate = () => {41 ApiServer.authenticate()42 .then(response => {43 if (response) {44 this.props.navigation.navigate('Main');45 } else {46 this.setState({47 authenticated: false,48 });49 Alert.alert('Authentication Error', 'You must authenticate before you can use the functionalities of this app.', [50 { text: 'OK', onPress: () => { this._authenticate() } }51 ], { cancelable: false });52 }53 })54 .catch(error => {55 this.setState({56 authenticated: false,57 error: error,58 });59 Alert.alert('Authentication Error', 'Unable to authenticate with remote server: ' + this.state.error.message, [60 { text: 'OK', onPress: () => { this._authenticate() } }61 ], { cancelable: false });62 });63 };...

Full Screen

Full Screen

Project.route.js

Source:Project.route.js Github

copy

Full Screen

1'use strict';2var _express = _interopRequireDefault(require("express"));3var _authenticate = require("../middleware/authenticate");4var _Project = require("../controllers/Project.controller");5function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }6const api = _express.default.Router();7api.post('/project', _authenticate.authorization, _Project.projectStore);8api.get('/projects', _authenticate.authorization, _Project.getProjects);9api.get('/project/:id', _authenticate.authorization, _Project.getProject);10api.put('/project/:id', _authenticate.authorization, _Project.updateProject);11api.delete('/project/:id', _authenticate.authorization, _Project.deleteProject);...

Full Screen

Full Screen

User.route.js

Source:User.route.js Github

copy

Full Screen

1'use strict';2var _express = _interopRequireDefault(require("express"));3var _authenticate = require("../middleware/authenticate");4var _User = require("../controllers/User.controller");5function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }6const api = _express.default.Router();7api.post('/singup', _User.singup);8api.post('/singin', _User.singin);9api.get('/user/:id', _authenticate.authorization, _User.getUser);10api.put('/user/:id', _authenticate.authorization, _User.updateUser);11api.delete('/user/:id', _authenticate.authorization, _User.deleteUser);12api.get('/verified/:id', _User.verified);...

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._authenticate({ username: 'username', password: 'password' });7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();

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.waitForSelector('input[type="text"]');7 await page.type('input[type="text"]', 'playwright');8 await page.click('input[type="submit"]');9 await page.waitForSelector('h3');10 const searchResults = await page.$$('h3');11 console.log(searchResults.length);12 await browser.close();13})();14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch({ headless: true });17 const context = await browser.newContext();18 const page = await context.newPage();19 await page.waitForSelector('input[type="text"]');20 await page.type('input[type="text"]', 'playwright');21 await page.click('input[type="submit"]');22 await page.waitForSelector('h3');23 const searchResults = await page.$$('h3');24 console.log(searchResults.length);25 await browser.close();26})();27const { chromium } = require('playwright');28(async () => {29 const browser = await chromium.launch({30 proxy: {31 }32 });33 const context = await browser.newContext();34 const page = await context.newPage();35 await page.waitForSelector('input[type="text"]');36 await page.type('input[type="text"]', 'playwright');37 await page.click('input[type="submit"]');38 await page.waitForSelector('h3');39 const searchResults = await page.$$('h3');40 console.log(searchResults.length);41 await browser.close();42})();43const { chromium } = require('playwright');44(async () => {45 const browser = await chromium.launch({46 proxy: {

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const cookies = await page.context().cookies();7 console.log(cookies);8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _authenticate } = require('playwright');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 await _authenticate(context, {7 });8 const page = await context.newPage();9})();10### `async _authenticate(context, credentials)`11const { _authenticate } = require('playwright');12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch({ headless: false });15 const context = await browser.newContext();16 await _authenticate(context, {17 });18 const page = await context.newPage();19})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Internal } = require('@playwright/test');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const internal = new Internal(page);8 const credentials = { username: 'username', password: 'password' };9 await internal._authenticate(credentials);10 await browser.close();11})();12Please see [CONTRIBUTING.md](

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _authenticate } = require('playwright/lib/server/browserType');2const browser = await _authenticate({ name: 'chromium' }, { headless: false });3const context = await browser.newContext();4const page = await context.newPage();5const playwrightAuthenticate = require('playwright-authenticate');6const browser = await playwrightAuthenticate({ name: 'chromium' }, { headless: false });7const context = await browser.newContext();8const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Internal } = require('playwright/lib/server/chromium/crConnection');2const { chromium } = require('playwright');3const { chromium: { launch } } = require('playwright');4const internal = new Internal();5(async () => {6 const browser = await launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 await internal._authenticate(page, 'username', 'password');10 await browser.close();11})();12#### internal._authenticate(page, username, password)

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