How to use _authenticate method in qawolf

Best JavaScript code snippet using qawolf

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 { _authenticate } = require("@qawolf/browser");2const { launch } = require("@qawolf/browser");3const { type } = require("@qawolf/browser");4const { click } = require("@qawolf/browser");5const { toMatchSnapshot } = require("expect");6expect.extend({ toMatchSnapshot });7jest.setTimeout(60000);8let browser;9let page;10beforeAll(async () => {11 browser = await launch();12});13afterAll(() => browser.close());14beforeEach(async () => {15 page = await browser.newPage();16});17afterEach(async () => {18 await page.close();19});20test("test", async () => {21 await _authenticate(page, {22 });23 await type(page, "input[name=q]", "qawolf");24 await click(page, "input[type=submit]");25 await page.waitForSelector(".g");26 const snapshot = await page.screenshot();27 expect(snapshot).toMatchSnapshot();28});29I am running this test in my local machine (windows 10) and I am getting the following error:30const { _authenticate } = require("@qawolf/browser");31const { launch } = require("@qawolf/browser");32const { type } = require("@qawolf/browser");33const { click } = require("@qawolf/browser");34const { toMatchSnapshot } = require("expect");35expect.extend({ toMatchSnapshot });36jest.setTimeout(60000);37let browser;38let page;39beforeAll(async () => {40 browser = await launch();41});42afterAll(() => browser.close());43beforeEach(async () => {44 page = await browser.newPage();45});46afterEach(async () => {47 await page.close();48});49test("test", async () => {50 await _authenticate(page, {51 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _authenticate } = require('@qawolf/browser');2const { _create } = require('@qawolf/browser');3const { _launch } = require('@qawolf/browser');4const { _navigate } = require('@qawolf/browser');5const { _type } = require('@qawolf/browser');6const { _click } = require('@qawolf/browser');7const { _select } = require('@qawolf/browser');8const { _press } = require('@qawolf/browser');9const { _check } = require('@qawolf/browser');10const { _uncheck } = require('@qawolf/browser');11const { _fill } = require('@qawolf/browser');12const { _waitFor } = require('@qawolf/browser');13const { _close } = require('@qawolf/browser');14const { _wait } = require('@qawolf/browser');15const { _waitForNavigation } = require('@qawolf/browser');16const { _waitForSelector } = require('@qawolf/browser');17const { _waitForText } = require('@qawolf/browser');18const { _waitForURL } = require('@qawolf/browser');19const { _waitForXPath } = require('@qawolf/browser');20const { _waitForFunction } = require('@qaw

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const { _authenticate } = require("qawolf/src/authenticate");3const { _create } = require("qawolf/src/create");4const { _build } = require("qawolf/src/build");5const { _launch } = require("qawolf/src/launch");6const { _run } = require("qawolf/src/run");7const { _test } = require("qawolf/src/test");8const { _buildCode } = require("qawolf/src/buildCode");9const { _buildCodeForBrowser } = require("qawolf/src/buildCodeForBrowser");10const { _buildCodeForContext } = require("qawolf/src/buildCodeForContext");11const { _buildCodeForPage } = require("qawolf/src/buildCodeForPage");12const { _createBrowser } = require("qawolf/src/createBrowser");13const { _createContext } = require("qawolf/src/createContext");14const { _createPage } = require("qawolf/src/createPage");15const { _createPageForBrowser } = require("qawolf/src/createPageForBrowser");16const { _createPageForContext } = require("qawolf/src/createPageForContext");17const { _createPageForPage } = require("qawolf/src/createPageForPage");18const { _createPageForTarget } = require("qawolf/src/createPageForTarget");19const { _createTarget } = require("qawolf/src/createTarget");20const { _evaluate } = require("qawolf/src/evaluate");21const { _evaluateForBrowser } = require("qawolf/src/evaluateForBrowser");22const { _evaluateForContext } = require("qawolf/src/evaluateForContext");23const { _evaluateForPage } = require("qawolf/src/evaluateForPage");24const { _evaluateForTarget } = require("qawolf/src/evaluateForTarget");25const { _getBrowser } = require("qawolf/src/getBrowser");26const { _getBrowserForBrowser } = require("qawolf/src/getBrowserForBrowser");27const { _getBrowserForContext } = require("qawolf/src/getBrowserForContext");28const { _getBrowserForPage } = require("qawolf/src/getBrowserForPage");29const { _getBrowserForTarget } = require("qawolf/src

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const { _authenticate } = require("qawolf/src/auth");3async function main() {4 const browser = await qawolf.launch();5 const page = await browser.newPage();6 await _authenticate(page, "username", "password");7}8main();9const qawolf = require("qawolf");10const { _authenticate } = require("qawolf/src/auth");11async function main() {12 const browser = await qawolf.launch();13 const page = await browser.newPage();14 await _authenticate(page, "username", "password");15}16main();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _authenticate } = require("@qawolf/browser");2const browser = await _authenticate("testuser");3const { _authenticate } = require("@qawolf/browser");4const browser = await _authenticate("testuser");5console.log(browser._authenticate);6const { _authenticate } = require("@qawolf/browser");7const browser = await _authenticate("testuser");8console.log(browser._authenticate);9console.log(typeof browser._authenticate);

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