Protractor- Non angular OAuth Login redirecting to angular site - protractor

We are using Protractor+Cucumber+Typescript combination.
Using protractor we are trying to login (Non angular OAuth) which redirects to application page (angular site). Following is our setup
feature file:
docsLogin.feature
Feature: Login to Docs
#TendukeLoginScenario
Scenario: Login to Docs application
Given I am on Tenduke login page
When Enter username and password
Then I click on Sign in button
Then I create a new folder
docsLoginPage.ts
import { $, element,by } from 'protractor';
export class TendukeLoginPageObject {
public usernameTextBox: any;
public passwordTextBox: any;
public signInButton: any;
public search: any;
public searchBox: any;
constructor() {
this.usernameTextBox = $("input[name='userName']");
this.passwordTextBox = $("input[name='password']");
this.signInButton = $("button[class='btn btn-primary']");
this.search = $("span[class='fa fa-search']");
this.searchBox = element(by.model('searchString'));
}
}
tenDukeLogin.ts
import { browser,element, by, } from 'protractor';
import { TendukeLoginPageObject } from '../pages/docsLoginPage';
import { defineSupportCode } from 'cucumber';
let chai = require('chai').use(require('chai-as-promised'));
let expect = chai.expect;
defineSupportCode(function ({ Given, When, Then }) {
let login: TendukeLoginPageObject = new TendukeLoginPageObject();
Given(/^I am on Tenduke login page$/, async () => {
browser.waitForAngularEnabled(false);
await expect(browser.getTitle()).to.eventually.equal('Sign in');
});
When(/^Enter username and password$/, async () => {
await login.usernameTextBox.sendKeys('abc#abc.com');
await login.passwordTextBox.sendKeys('12345');
});
Then(/^I click on Sign in button$/, async () => {
await (login.signInButton.click()).then(function(){
//browser.driver.wait((docs.plusIcon), 15000);
browser.wait((login.search).isPresent);
});
//await expect(browser.getTitle()).to.eventually.equal('Docs');
});
Then(/^I create a new folder$/, async () => {
//await browser.sleep(40000);
browser.waitForAngularEnabled();
await (login.search.click()).then(function(){
browser.wait((login.searchBox).isPresent);
});
});
})
Config.ts
import { browser, Config } from 'protractor';
export let config: Config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
SELENIUM_PROMISE_MANAGER: false,
baseUrl: 'http://abc/content',
capabilities: {
browserName: 'chrome'
},
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
specs: [
'../../features/docsLogin.feature'
],
onPrepare: () => {
browser.ignoreSynchronization = true;
browser.manage().window().maximize();
},
cucumberOpts: {
compiler: "ts:ts-node/register",
strict: true,
format: ['pretty'],
require: ['../../stepdefinitions/*.ts', '../../support/*.ts'],
tags: '#TypeScriptScenario or #CucumberScenario or
#TendukeLoginScenario'
}
};
After clicking Sign in button browser closing immediately before
loading the application page.
We tried even adding some wait statement after Sign in but after timeout browser is closing. Not able to perform any action on Angular page after login.
protractor-typescript-cucumber#2.0.0 test E:\ProtractorTest\protractor-
cucumber-typescript
protractor typeScript/config/config.js
[18:10:52] I/launcher - Running 1 instances of WebDriver
[18:10:52] I/hosted - Using the selenium server at
http://127.0.0.1:4444/wd/hub
Feature: Login to Docs
#TendukeLoginScenario
Scenario: Login to Docs application
√ Given I am on Tenduke login page
√ When Enter username and password
(node:9096) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): TypeError: Cannot read property 'parentElementArrayFinder' of undefined
√ Then I click on Sign in button
x Then I create a new folder
Failures:
1) Scenario: Login to Docs application - features\docsLogin.feature:4
Step: Then I create a new folder - features\docsLogin.feature:8
Step Definition: stepdefinitions\tenDukeLogin.ts:29
Message:
NoSuchElementError: No element found using locator: By(css selector,
span[class='fa fa-search'])
at WebDriverError (E:\ProtractorTest\protractor-cucumber-
typescript\node_modules\selenium-webdriver\lib\error.js:27:5)
at NoSuchElementError (E:\ProtractorTest\protractor-cucumber-
typescript\node_modules\selenium-webdriver\lib\error.js:168:5)
at elementArrayFinder.getWebElements.then
(E:\ProtractorTest\protractor-cucumber-
typescript\node_modules\protractor\lib\element.ts:851:17)
at process._tickCallback (internal/process/next_tick.js:109:7)Error
at ElementArrayFinder.applyAction_ (E:\ProtractorTest\protractor-
cucumber-typescript\node_modules\protractor\lib\element.ts:482:23)
at ElementArrayFinder.(anonymous function) [as click]
(E:\ProtractorTest\protractor-cucumber-
typescript\node_modules\protractor\lib\element.ts:96:21)
at ElementFinder.(anonymous function) [as click]
(E:\ProtractorTest\protractor-cucumber-
typescript\node_modules\protractor\lib\element.ts:873:14)
at E:\ProtractorTest\protractor-cucumber-
typescript\stepdefinitions\tenDukeLogin.ts:32:29
at next (native)
at E:\ProtractorTest\protractor-cucumber-
typescript\stepdefinitions\tenDukeLogin.ts:7:71
at __awaiter (E:\ProtractorTest\protractor-cucumber-typescript\stepdefinitions\tenDukeLogin.ts:3:12)
at World.Then (E:\ProtractorTest\protractor-cucumber-typescript\stepdefinitions\tenDukeLogin.ts:29:37)
1 scenario (1 failed)
4 steps (1 failed, 3 passed)
0m04.194s
Cucumber HTML report E:\ProtractorTest\protractor-cucumber-
typescript/reports/html/cucumber_reporter.html generated successfully.
[18:11:03] I/launcher - 0 instance(s) of WebDriver still running
[18:11:03] I/launcher - chrome #01 failed 1 test(s)
[18:11:03] I/launcher - overall: 1 failed spec(s)
[18:11:03] E/launcher - Process exited with error code 1
npm ERR! Test failed. See above for more details.

Could you explain me why do you use async over there?
Do you have any other steps with asycn which works?
Try to replace tenDukeLogin.ts with:
import {defineSupportCode} from 'cucumber';
import {browser, ExpectedConditions} from 'protractor';
import {TendukeLoginPageObject} from '../pages/docsLoginPage';
const chai = require('chai').use(require('chai-as-promised'));
const expect = chai.expect;
defineSupportCode(({ Given, When, Then }) => {
const login: TendukeLoginPageObject = new TendukeLoginPageObject();
Given(/^I am on Tenduke login page$/, () => {
browser.waitForAngularEnabled(false);
return expect(browser.getTitle()).to.eventually.equal('Sign in');
});
When(/^Enter username and password$/, () => {
login.usernameTextBox.sendKeys('abc#abc.com');
return login.passwordTextBox.sendKeys('12345');
});
Then(/^I click on Sign in button$/, () => {
return (login.signInButton.click()).then(() => {
return browser.wait(ExpectedConditions.visibilityOf(login.search), 5000);
});
});
Then(/^I create a new folder$/, () => {
browser.waitForAngularEnabled();
return (login.search.click()).then(() => {
return browser.wait(ExpectedConditions.visibilityOf(login.searchBox), 5000);
});
});
});
Drop me a line does it fix your issue.

Related

How to add custom logs in Protractor test reports

I'm trying to add some custom logs to my protractor test report. I've app log file in my project folder which has the logs captured using log4js. I want these log entries to be shown in my test report as well. Currently I'm using chercher report. Since I'm a beginner to protractor, I'm not sure how to do this. Can anybody help me on this? Thanks in advance!
spec.js
fdescribe('Protractor Perfecto Demo', function () {
it('should pass test', function () {
browser.reportingClient.stepStart('Step 1: Navigate Google');
browser.driver.get('https://www.google.com'); //Navigate to google.com
browser.reportingClient.stepEnd();
//Locate the search box element and insert text
//Click on search button
browser.reportingClient.stepStart('Step 2: Send Keys');
browser.driver.findElement(by.name('q')).sendKeys('PerfectoCode GitHub');
browser.reportingClient.stepEnd();
browser.reportingClient.stepStart('Step 3: Click');
browser.driver.findElement(by.css('#tsbb > div')).click();
browser.reportingClient.stepEnd();
});
//This test should fail
it('should fail test', function () {
browser.reportingClient.stepStart('Step 1: Navigate Google');
browser.driver.get('https://www.google.com'); //Navigate to google.com
browser.reportingClient.stepEnd();
//Locate the search box element and insert text
//Click on search button
browser.reportingClient.stepStart('Step 2: Send Keys');
browser.driver.findElement(by.name('q')).sendKeys('PerfectoCode GitHub');
browser.reportingClient.stepEnd();
browser.reportingClient.stepStart('Step 3: Click');
browser.driver.findElement(by.css('#tsbbbsdasd > div')).click();
browser.reportingClient.stepEnd();
});
afterAll(function(done){
process.nextTick(done);
});
});
conf.js
var reportingClient;
exports.config = {
//Remote address
// seleniumAddress: 'https://MY_HOST.perfectomobile.com/nexperience/perfectomobile/wd/hub',
directConnect: true,
//Capabilities to be passed to the webdriver instance.
capabilities: {
browserName: 'chrome'
// user: 'MY_USER',
// password: 'MY_PASS',
// platformName: 'Android',
//deviceName: '123456',
},
//Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['./tests/SignupAutomation_spec.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
defaultTimeoutInterval: 120000 // Time to wait in ms before a test fails. Default value = 30000
},
onComplete: function () {
// Output report URL
return reportingClient.getReportUrl().then(
function (url) {
console.log(`Report url = ${url}`);
}
);
},
onPrepare: function () {
const Reporting = require('perfecto-reporting');
reportingClient = new Reporting.Perfecto.PerfectoReportingClient(new Reporting.Perfecto.PerfectoExecutionContext({
webdriver: browser.driver,
tags: ['javascript driver']
}));
browser.reportingClient = reportingClient;
var myReporter = {
specStarted: function (result) {
reportingClient.testStart(result.fullName);
},
specDone: function (result) {
if (result.status === 'failed') {
const failure = result.failedExpectations[result.failedExpectations.length - 1];
reportingClient.testStop({
status: Reporting.Constants.results.failed,
message: `${failure.message} ${failure.stack}`
});
} else {
reportingClient.testStop({
status: Reporting.Constants.results.passed
});
}
}
}
jasmine.getEnv().addReporter(myReporter);
}
}
While running this I'm getting below error:
An error was thrown in an afterAll
AfterAll JavascriptError: javascript error: end is not defined
(Session info: chrome=90.0.4430.212)
(Driver info: chromedriver=90.0.4430.24 (4c6d850f087da467d926e8eddb76550aed655991-refs/branch-heads/4430#{#429}),platform=Windows NT 10.0.19042 x86_64)

How to make browser close and open for each scenario in a feature - protractor and cucumberjs

This question might be a duplicate, but i am not as expected, so raising again.
I am creating a new protractor framework in our project. My application has login screen which i need to login with different user details for each case in a feature. I have two scenarios in a feature file. When i run, the browser should open the login page and do some action and close the browser for each scenario, and it has to do the same thing for every scenario, but am not seeing this happen. When i run, it happens for first scenario and from second it fails. Could someone help me on this?
i have tried with different options with After hook, restartBrowserBetweenTests but no luck.
conf.js
import { browser } from "protractor";
export const config = {
// chromeDriver: './drivers/chromedriver',
// seleniumServerJar: './drivers/selenium-server-standalone-3.12.0.jar',
seleniumAddress: 'http://localhost:4444/wd/hub',
// baseUrl: '<url>',
SELENIUM_PROMISE_MANAGER: false,
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['--disable-extensions=true']
}
},
// restartBrowserBetweenTests: true,
specs: [
'./features/*.feature'
],
cucumberOpts: {
require: [
'./features/step_definitions/*.js',
'./support/*.js'
],
format: ['json:results/report.json'],
tags: [
//"#smoke",
//"#regression"
],
strict: true
},
disableChecks: true,
onPrepare: function () {
browser.manage().deleteAllCookies();
browser.manage().window().maximize();
browser.ignoreSynchronization = true;
},
getPageTimeout: 100000,
allScriptsTimeout: 500000
}
hooks.ks
import { Before, BeforeAll, After, AfterAll } from "cucumber";
import { browser } from "protractor";
import { config } from "../protractorConf"
Before( {timeout: 2 * 20000}, async () => {
// await browser.get(config.baseUrl)
})
// After( {timeout: 2 * 5000}, async () => {
// await browser.close()
// })
AfterAll( {timeout: 2 * 5000}, async () => {
await browser.quit()
})
steps.js
import { Given, When, Then } from "cucumber"
import { expect } from "chai";
import { browser } from "protractor";
import * as loginPage from "../pages/loginPage"
import * as welcomePage from "../pages/welcomePage"
import * as verificationPage from "../pages/verificationPanelPage"
import * as homePage from "../pages/homePage";
const stepTimeoutExpiry = {timeout: 2 * 5000}
let globalLoanNumber = ""
Given(/^Launch SATURN app with "(.*?)" and "(.*?)"$/, stepTimeoutExpiry, async (user, pass) => {
await browser.get('<url>')
await loginPage.login(user, pass)
})
When(/^I search a loan by "(.*?)" as "(.*?)" in search page$/, stepTimeoutExpiry, async (searchType, loanNumber) => {
globalLoanNumber = loanNumber
await welcomePage.selectSearchType()
if (searchType === "Loan Number") {
await welcomePage.selectLoanNumber()
}
await welcomePage.enterLoanNumber(loanNumber)
await welcomePage.clickSearchAccountBtn()
})
When(/^I skip the verification details on verification page$/, stepTimeoutExpiry, async () => {
await verificationPage.skipVerification()
})
Then(/^I must see the Saturn "(.*?)" page for this account$/, stepTimeoutExpiry, async (homeText) => {
// await homePage.isHomeLinkAvailable()
expect(await homePage.isHomeLinkAvailable()).to.be.true
expect(await homePage.getAccountNumberText()).to.equal(globalLoanNumber)
})
feature file
Feature: Running sample feature
Scenario: Login to Saturn and verify it works
Given Launch SATURN app with "user" and "pass"
When I search a loan by "Loan Number" as "0535003974" in search page
And I skip the verification details on verification page
Then I must see the Saturn "Home" page for this account
Scenario: Login to Saturn and verify it works for the second time
Given Launch SATURN app with "user" and "pass"
When I search a loan by "Loan Number" as "0535003974" in search page
And I skip the verification details on verification page
Then I must see the Saturn "Home" page for this account
below is the error, when i run.
λ npm run test
> protractortest#1.0.0 test c:\<user>\ATDDProtractorTest
> babel-node node_modules/protractor/bin/protractor protractorConf.js --presets-env
(node:12828) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[10:55:12] I/launcher - Running 1 instances of WebDriver
[10:55:12] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
.......F---.
Failures:
1) Scenario: Login to Saturn and verify it works for the second time # features\testone.feature:9
√ Before # support\hooks.js:5
× Given Launch SATURN app with "user" and "pass" # features\step_definitions\testOne.steps.js:13
Error: function timed out, ensure the promise resolves within 10000 milliseconds
at Timeout._onTimeout (c:\Manimaran\ATDDProtractorTest\node_modules\cucumber\src\user_code_runner.js:61:18)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
- When I search a loan by "Loan Number" as "0535003974" in search page # features\step_definitions\testOne.steps.js:19
- And I skip the verification details on verification page # features\step_definitions\testOne.steps.js:30
- Then I must see the Saturn "Home" page for this account # features\step_definitions\testOne.steps.js:34
√ After # node_modules\protractor-cucumber-framework\lib\resultsCapturer.js:25
2 scenarios (1 failed, 1 passed)
8 steps (1 failed, 3 skipped, 4 passed)
0m20.442s
[10:55:40] I/launcher - 0 instance(s) of WebDriver still running
[10:55:40] I/launcher - chrome #01 failed 1 test(s)
[10:55:40] I/launcher - overall: 1 failed spec(s)
loginpage.js
import { element, by, browser } from "protractor";
const userName = element(by.id('username'));
const passWord = element(by.id('password'));
const signOn = element(by.xpath('.//a[contains(#title,"Sign In")]'));
const EC = protractor.ExpectedConditions
const isVisibilityOf = EC.visibilityOf(userName)
export const login = async (user, pass) => {
await browser.wait(isVisibilityOf, 10000)
await userName.sendKeys(user);
await passWord.sendKeys(pass);
await signOn.click();
}
For protractor, before any spec be executed, an browser instance(session) will be init and hand over the session to spec runner which manage to execute specs.
If you want to close session after each scenario/feature, you have to create an new session and pass down the new session to the original spec runner. I think it's not easy to implement this for us without learning protractor source code deeply.
I prefer to recommend following solutions more easy from our side:
1) delete cookie in After hook, protractor supply such API to do that
2) open logout url in After hook if your app has such url, otherwise you
can click logout button.
Actually, you can put the delete cookie, open logout url or click logout button at the beginning of your login function, then open login url. With that After hook is unnecessary.

browser is not catching given url when i am running the step definition file in protractor-cucumber

I am new to this protractor-cucumber.please correct me if i am going wrong.
i am using protractor 3.2.2
when i am run feature file, it gives correct output.but when i am run step definition, the browser not taking the given url.
My feature file is given below.
Feature: Login page test
Scenario: Verify whether the user is able to view the login page while
giving the URL.
Given I go to "http://localhost:4200/login"
When The URL of the page should be "http://localhost:4200/login"
My step definition file is given below.
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
this.Given('I go to {string}', function (string) {
browser.get(string);
});
this.When('The URL of the page should be {string}', function (string) {
expect(browser.getCurrentUrl()).to.eventually.equal(string);
});
}
My config. file is given below
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
allScriptsTimeout: 11000,
specs: [
'features/*.feature'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/login',
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
cucumberOpts: {
require: 'features/step_definitions/*.js',
tags: false,
format: 'pretty',
profile: false,
'no-source': true
} };
The error showing when i am run 'protractor protractor.conf.js' is given below.
Using ChromeDriver directly...
[launcher] Running 1 instances of WebDriver
(node:7508) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use
os.tmpdir() instead.
[7884:6800:1229/145724.847:ERROR:browser_gpu_channel_host_factory.cc(107)]
Failed to launch GPU process.
DevTools listening on ws://127.0.0.1:12425/devtools/browser/74f2a81c-51c2-
4a8a-afec-26166a388d1f
C:\Users\CS1027C\AppData\Roaming\npm\node_modules\protractor\node_modules\se
lenium-webdriver\http\index.js:365
onError(new Error(message));
^
Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:54206
at ClientRequest.<anonymous> (C:\Users\CS1027C\AppData\Roaming\npm\node_modu
les\protractor\node_modules\selenium-webdriver\http\index.js:365:15)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at Socket.socketErrorListener (_http_client.js:387:9)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
From: Task: WebDriver.createSession()
at acquireSession (C:\Users\CS1027C\AppData\Roaming\npm\node_modules\protrac
tor\node_modules\selenium-webdriver\lib\webdriver.js:62:22)
at Function.createSession (C:\Users\CS1027C\AppData\Roaming\npm\node_modules
\protractor\node_modules\selenium-webdriver\lib\webdriver.js:295:12)
at new Driver (C:\Users\CS1027C\AppData\Roaming\npm\node_modules\protractor\
node_modules\selenium-webdriver\chrome.js:778:38)
at DirectDriverProvider.getNewDriver (C:\Users\CS1027C\AppData\Roaming\npm\n
ode_modules\protractor\built\driverProviders\direct.js:69:16)
at Runner.createBrowser (C:\Users\CS1027C\AppData\Roaming\npm\node_modules\p
rotractor\built\runner.js:203:37)
at C:\Users\CS1027C\AppData\Roaming\npm\node_modules\protractor\built\runner
.js:293:21
at _fulfilled (C:\Users\CS1027C\AppData\Roaming\npm\node_modules\protractor\
node_modules\q\q.js:834:54)
at self.promiseDispatch.done (C:\Users\CS1027C\AppData\Roaming\npm\node_modu
les\protractor\node_modules\q\q.js:863:30)
at Promise.promise.promiseDispatch (C:\Users\CS1027C\AppData\Roaming\npm\nod
e_modules\protractor\node_modules\q\q.js:796:13)
at C:\Users\CS1027C\AppData\Roaming\npm\node_modules\protractor\node_modules
\q\q.js:556:49
[launcher] Process exited with error code 1
From the error message:
Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:54206,
your issue should caused by using lower chromedriver with higher Chrome browser, upgrade the chromedriver should fix your problem.
And change the cucumberOpts in your config file as below:
cucumberOpts: {
monochrome: true,
strict: true,
plugin: ["pretty"],
require: [
'features/step_definitions/*.js'
],
tags: ''
}
Change your step defintion file as below: (if you use Cucumber 1 or below)
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
this.Given('I go to "(.*?)"', function (url) {
browser.get(url);
});
this.When('The URL of the page should be "(.*?)"', function (url) {
expect(browser.getCurrentUrl()).to.eventually.equal(url);
});
};
Change your step defition file as below (if you use Cucumber 2 or above)
var {defineSupportCode} = require('cucumber');
defineSupportCode(function ({ Given, When, Then }) {
Given('I go to "(.*?)"', function (url) {
browser.get(url);
});
When('The URL of the page should be "(.*?)"', function (url) {
expect(browser.getCurrentUrl()).to.eventually.equal(url);
});
});

How to set up unit tests in sailsjs

I cannot run sailsjs unit tests. It seems sails cannot be lifted,
my test (/test/unit/test.js):
var Sails = require('sails');
var app;
before(function() {
console.log('before');
Sails.lift({
log: {
level: 'error'
}
}, function(err, server) {
console.log('lifted');
app = server;
done(err, app);
});
});
// Global after hook
after(function(done) {
app.lower(done);
});
describe('mailer service', function() {
it('should connect to gmail', function() {
console.log(app);
});
});
In my app folder I run: mocha test/unit/test.js
The "app" variable is undefined, console.log('lifted') is not being triggered. What am I doing wrong?
First of all.
You need to call before with a done parameter :
before(function(done){...})
Does your app lift succesfully when you run it with ?
sails lift

Custom authenticator with Ember simple auth + Ember CLI

I'm trying to write a custom authenticator, similar to the one from this example in the docs. The goal is to be able to retrieve the currently logged in user via session.user.
I'm using Ember CLI, so in initializers/authentication.js I have
import Ember from 'ember';
var customAuthenticator = Ember.SimpleAuth.Authenticators.Devise.extend({
authenticate: function(credentials) {
debugger;
}
});
export default {
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
user: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
// register the custom authenticator so the session can find it
container.register('authenticator:custom', customAuthenticator);
Ember.SimpleAuth.setup(container, application, {
routeAfterAuthentication: 'landing-pages',
authorizerFactory: 'ember-simple-auth-authorizer:devise'
});
}
};
When I try to authenticate, I get the following error:
TypeError: Cannot read property 'authenticate' of undefined
at __exports__.default.Ember.ObjectProxy.extend.authenticate
Any idea why?
As of Simple Auth 0.6.4, you can now do something like:
index.html:
window.ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:devise',
session: 'session:withCurrentUser'
};
initializers/customize-session.js:
import Ember from 'ember';
import Session from 'simple-auth/session';
var SessionWithCurrentUser = Session.extend({
currentUser: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.container.lookup('store:main').find('user', userId);
}
}.property('user_id')
});
export default {
name: 'customize-session',
initialize: function(container) {
container.register('session:withCurrentUser', SessionWithCurrentUser);
}
};
You would need to do something like this:
Em.SimpleAuth.Authenticators.OAuth2.reopen
serverTokenEndpoint: "http://myapp.com/token"
authenticate: (credentials) ->
new Em.RSVP.Promise (resolve, reject) =>
data =
grant_type: "password"
username: credentials.identification
password: credentials.password
#makeRequest(data).then (response) =>
# success call
, (xhr, status, error) ->
# fail call
What I think might be happening is that you are registering the authenticator with the application and not the authenticator itself?
The problem is that the AMD build does not currently automatically register the extension libraries' components (see https://github.com/simplabs/ember-simple-auth/issues/198). I'll change that in the next release and will probably also adopt the documentation to be more focussed on the AMD build instead of the browserified version. For the moment you'd have to run this in your initializer
container.register(
'ember-simple-auth-authorizer:devise',
Ember.SimpleAuth.Authorizers.Devise
);
container.register(
'ember-simple-auth-authenticator:devise',
Ember.SimpleAuth.Authenticators.Devise
);