NextJS Amplify auth cognito not authenticated on server aws - amazon-web-services

I'm using cognito for authentication of my app.
In local enviroment everthing it's ok whether launch yarn dev or yarn build and yarn start.
In the amplify server deploy the SSR authentication not working: return always "not authenticated".
This is mine package.json:
{
"name": "xxxxxxxxxxxx",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start -p ${PORT:=3000}",
"lint": "next lint"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.1.2",
"#fortawesome/free-regular-svg-icons": "^6.1.2",
"#fortawesome/free-solid-svg-icons": "^6.1.2",
"#fortawesome/react-fontawesome": "^0.1.18",
"#improbable-eng/grpc-web": "^0.14.0",
"#improbable-eng/grpc-web-node-http-transport": "^0.14.0",
"#nivo/bar": "^0.74.0",
"#nivo/core": "^0.74.0",
"#nivo/geo": "^0.74.0",
"#nivo/pie": "^0.74.0",
"#nivo/scatterplot": "^0.74.0",
"#nivo/treemap": "^0.74.0",
"apexcharts": "^3.35.3",
"aws-amplify": "^4.3.34",
"axios": "^0.24.0",
"bootstrap": "^5.2.0",
"cors": "^2.8.5",
"emotion": "^11.0.0",
"eslint-config-next": "^12.2.4",
"google-protobuf": "^3.17.2",
"human-readable-numbers": "^0.9.5",
"jspdf": "^2.5.0",
"next": "12.0.0",
"next-i18next": "^12.0.0",
"rc-slider": "10.0.1",
"react": "^17.0.2",
"react-apexcharts": "^1.4.0",
"react-bootstrap": "^2.4.0",
"react-dom": "^17.0.2",
"react-read-more-read-less": "^1.0.7",
"react-sparklines": "^1.7.0",
"react-toastify": "^9.0.8",
"react-tradingview-widget": "^1.3.2",
"sass": "1.32.13",
"sharp": "^0.29.3",
"swr": "^0.5.6",
"xmlhttprequest": "^1.8.0"
},
"devDependencies": {
"eslint": "7.32.0"
}
}
This is _app.js (pages/_app.js):
import getConfig from "next/config";
import { appWithTranslation } from "next-i18next";
import "../public/app.scss";
import { Amplify } from "aws-amplify";
import awsExports from "../src/aws-exports";
import React from "react";
import AuthContext from "../components/context/AuthContext";
import { Header } from "../components/dashboard/Header";
import { Footer } from "../components/dashboard/Footer";
import { SSRProvider } from "react-bootstrap";
Amplify.configure({ ...awsExports, ssr: true });
export const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
function App({ Component, pageProps }) {
return (
<SSRProvider>
<AuthContext>
<Header />
<Component {...pageProps} />
<Footer />
</AuthContext>
</SSRProvider>
)
}
export default appWithTranslation(App);
The test page (pages/test.js):
import { withSSRContext } from "aws-amplify";
export default function Test({user}) {
return <h5>{user}</h5>
}
export async function getServerSideProps({req}) {
const { Auth } = withSSRContext({ req });
try {
const user = await Auth.currentAuthenticatedUser();
return {
props: {
msg: user.username
},
};
} catch (err) {
console.log(err)
return {
props: {
msg: err
}
}
}
}
That's the error: "The user is not authenticated"
But if I use useEffect in function to retrieve user all is working good.

Oh wow! It's weird. Disabling Restrict access to app resolve the problem (https://docs.aws.amazon.com/amplify/latest/userguide/access-control.html).
Anyone that can answer scientifically?

Related

SyntaxError: Unexpected token '?' in upgrading smart contract using #openzeppelin/hardhat-upgrades

I am trying to deploy an upgradable smart contract on polygon Mumbai tesnet. I am getting this error
smart-contract/node_modules/#openzeppelin/hardhat-upgrades/dist/index.js:108
compiler.settings ?? (compiler.settings = {});
^
SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Object.require.extensions.<computed> [as .js] (/Users/jagdish/workspace/speedrun-simple-nft-example/smart-contract/node_modules/ts-node/src/index.ts:1587:43)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/Users/jagdish/workspace/speedrun-simple-nft-example/smart-contract/hardhat.config.ts:4:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
while trying to run the deploy script.
here are my configs and deploy scripts:
hardhart.config.ts
import { task } from "hardhat/config";
// import "#nomiclabs/hardhat-waffle";
import 'hardhat-watcher';
import '#openzeppelin/hardhat-upgrades';
import '#nomiclabs/hardhat-ethers';
import dotenv from "dotenv"
dotenv.config()
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
watcher: {
compilation: {
tasks: ['compile'],
},
node: {
tasks: ['node'],
},
},
networks: {
matic: {
url: "https://polygon-rpc.com/",
accounts: [process.env.ACCOUNT_PRIVATE_KEY]
},
matic_mumbai: {
url: "https://rpc-mumbai.maticvigil.com",
accounts: [process.env.ACCOUNT_PRIVATE_KEY]
}
}
};
deploy.ts
import { ethers, upgrades } from "hardhat";
async function main() {
const contract = await ethers.getContractFactory("YourCollectible");
console.log("Deploying Contract ...");
const c = await upgrades.deployProxy(contract, { constructorArgs: ["Your Collectables", "YCB"] })
// const c = await contract.deploy("Your Collectable", "YCB");
await c.deployed();
console.log("Contract deployed to:", c.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
package.json
{
"name": "smart-contract",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"run": "hardhat compile",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.6",
"#nomiclabs/hardhat-waffle": "^2.0.3",
"#openzeppelin/hardhat-upgrades": "^1.20.0",
"#typechain/hardhat": "^6.1.2",
"chai": "^4.3.6",
"ethereum-waffle": "^3.4.4",
"ethers": "^5.6.9",
"hardhat": "^2.9.9",
"hardhat-watcher": "^2.3.0",
"ts-node": "^10.8.1",
"typescript": "^4.7.4"
},
"dependencies": {
"#openzeppelin/contracts": "^4.7.0",
"dotenv": "^16.0.1"
}
}
I am not sure whether it is the node version issue in my local or do I have to downgrade the #openzeppelin/hardhat-upgrades version (I have tried that).
Node version: v12.22.10
Can anyone help on this
I had the same problem with node 12. Problem solved after updating to node 16 and running yarn again.

Can’t get expoToken in Expo Notification, due to Failed resolution of: Lcom/google/firebase/iid/FirebaseInstanceId;

Good afternoon, hope you guys have a good day, i'm already building some apps using expo bare workflow, and need to use Expo Notification, i'm following all the instruction, from expo notification documentations, and fcm configurations, to setup firebase, but, when i'm tryin to get expoToken, i got this warning, looks like this:
Error: Encountered an exception while calling native method: Exception occurred while executing exported method getDevicePushTokenAsync on module ExpoPushTokenManager: Failed resolution of: Lcom/google/firebase/iid/FirebaseInstanceId;
and I've made sure that my package name is the same as the package I registered in firebase, can you guys help me? pleasee :slight_smile:
this is addtional information:
Getting Expo Token
const getToken = async () => {
console.log("TOKEN CHECK");
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
};
App.js
{
"name": "myapp",
"displayName": "myapp",
"expo": {
"name": "myapp",
"slug": "myapp",
"version": "1.0.0",
"assetBundlePatterns": [
"**/*"
]
},
"android": {
"googleServicesFile": "./google-services.json",
"useNextNotificationsApi": true
}
}
Package.json
{
"main": "index.js",
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"web": "expo start --web",
"start": "react-native start"
},
"dependencies": {
"#dudigital/react-native-zoomable-view": "^1.0.16",
"#react-native-async-storage/async-storage": "^1.15.5",
"#react-native-community/masked-view": "^0.1.11",
"#react-native-community/netinfo": "^6.0.0",
"#react-native-firebase/app": "^12.0.0",
"#react-native-firebase/firestore": "^12.0.0",
"#react-native-firebase/storage": "^12.0.0",
"#react-native-picker/picker": "^1.16.1",
"#react-navigation/material-bottom-tabs": "^5.3.15",
"#react-navigation/native": "^5.9.4",
"#react-navigation/stack": "^5.14.5",
"expo": "~41.0.1",
"expo-av": "~9.1.2",
"expo-image-manipulator": "~9.1.0",
"expo-image-picker": "~10.1.4",
"expo-notifications": "~0.11.6",
"expo-splash-screen": "~0.10.2",
"expo-status-bar": "~1.0.4",
"expo-updates": "~0.5.4",
"expo-web-browser": "~9.1.0",
"firebase": "^8.6.5",
"moment": "^2.29.1",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "~0.63.4",
"react-native-calendars": "^1.1263.0",
"react-native-custom-qr-codes-expo": "^2.2.0",
"react-native-datepicker": "^1.7.2",
"react-native-gesture-handler": "~1.10.2",
"react-native-linear-gradient": "^2.5.6",
"react-native-orientation-locker": "^1.3.1",
"react-native-paper": "^4.9.1",
"react-native-raw-bottom-sheet": "^2.2.0",
"react-native-reanimated": "~2.1.0",
"react-native-render-html": "^5.1.1",
"react-native-responsive-screen": "^1.4.2",
"react-native-safe-area-context": "^3.2.0",
"react-native-screens": "~3.0.0",
"react-native-shimmer-placeholder": "^2.0.7",
"react-native-svg": "12.1.0",
"react-native-unimodules": "~0.13.3",
"react-native-vector-icons": "^8.1.0",
"react-native-web": "~0.13.12",
"react-native-webview": "^11.6.2"
},
"devDependencies": {
"#babel/core": "^7.9.0"
},
"private": true
}
screenshot:
someImages
You have to do two things:
In bare workflow, the Notifications.getExpoPushTokenAsync() method needs to provide the experienceId attributes.
const expoPushToken = await Notifications.getExpoPushTokenAsync({ experienceId });
console.log({ expoPushToken });
return expoPushToken.data;
You have to modify your /android/app/build.gradle to add 'com.google.firebase:firebase-iid:17.0.2'
dependencies {
implementation 'com.google.firebase:firebase-iid:17.0.2'
...
}

How to fix error import Vue from 'vue' results in SyntaxError: Unexpected identifier

I'm trying to setup a test framework for a Vue.js project that I'm working on. I'm trying to use Jest for this but I end up with an error I don't seem to find a solution for. When I'm trying to run the tests, I get a syntax error in the terminal.
The error I'm getting is:
Test suite failed to run
Import Vue from 'vue';
^^^
SyntaxError: Unexpected identifier"
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
I've been looking around but I can't find a solution that helps me..
When removing the import of Vue, the test passes.
I run the tests by command npm run tests
// package.json
{
"name": "mlink-pwa",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"tests": "NODE_ENV=testing vue-cli-service test:unit"
},
"dependencies": {
"chart.js": "^2.7.3",
"chartjs-plugin-labels": "^1.1.0",
"countup.js": "^1.9.3",
"dexie": "^2.0.4",
"gauge-chart": "^0.4.3",
"moment": "^2.22.2",
"progressbar.js": "^1.0.1",
"raven-js": "^3.27.0",
"register-service-worker": "^1.5.2",
"vue": "^2.5.17",
"vue-countup-v2": "^2.0.0",
"vue-i18n": "^8.3.2",
"vue-router": "^3.0.2",
"vuedraggable": "^2.16.0",
"vuelidate": "^0.7.4",
"vuex": "^3.0.1"
},
"devDependencies": {
"#babel/preset-env": "^7.3.1",
"#vue/cli": "^3.1.3",
"#vue/cli-plugin-babel": "^3.1.1",
"#vue/cli-plugin-e2e-nightwatch": "^3.4.0",
"#vue/cli-plugin-eslint": "^3.1.5",
"#vue/cli-plugin-pwa": "^3.1.2",
"#vue/cli-plugin-unit-jest": "^3.4.0",
"#vue/cli-service": "^3.1.4",
"#vue/eslint-config-standard": "^4.0.0",
"#vue/test-utils": "^1.0.0-beta.25",
"babel": "^6.23.0",
"babel-core": "7.0.0-bridge.0",
"babel-jest": "^24.1.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"eslint-plugin-jasmine": "^2.10.1",
"jasmine": "^3.3.1",
"node-sass": "^4.10.0",
"sass-loader": "^7.1.0",
"vue-jest": "^3.0.2",
"vue-template-compiler": "^2.5.17"
}
}
// jest.config.js
module.exports = {
moduleFileExtensions: ['js', 'json', 'vue'],
transform: {
'^.+\\.jsx?$': 'babel-jest',
'^.+\\.vue$': 'vue-jest'
},
clearMocks: true,
coverageDirectory: "coverage",
};
// babel.config.js
module.exports = {
env: {
testing: {
presets: [
['env', { modules: false }],
'#babel/preset-env',
'#vue/app'
],
plugins: [
'transform-es2015-modules-commonjs'
]
}
}
}
// first.spec.js - THIS FAILS
import Vue from 'vue'
describe('', () => {
it('first test', () => {
expect(true).toEqual(true);
});
});
// first.spec.js - THIS PASSES
describe('', () => {
it('first test', () => {
expect(true).toEqual(true);
});
});
Expected:
I expect the test suite to run and the test to pass.
Actual:
The test suite does not run.
This is a problem with a particular version of vue-cli. Installing the latest and starting a new project resolves the issue. Or alternately do this in a "mock" project and copy all the npm dependency versions over to your existing project.

Unit test with enzyme, mocha, sinon and reactjs. How to see what the spy is called with?

I have tried to work out why this test is failing but cannot determine the reason, because I cannot see what the sinon spy object is being called with.
Is there a better way to test sinon.calledWith so it will show the result and expected result?
In the test below the following check passes expect(onLoginClick.called).to.equal(true); but this does not expect(onLoginClick.calledWith(expected)).to.equal(true);.
Any ideas why?
How can I check myself by seeing the actual value onLoginClick is called with vs the expected?
I am running the tests via "npm run test", the project can be cloned and run from https://github.com/Rob-Leggett/react_redux_webpack
Thanks for any answers and time taken to assist with this question.
Test
import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import Login from '../app/components/login/Login';
describe('<Login/>', function () {
it('should click login button with credentials', () => {
// given
const expected = { username: 'test', password: 'user' };
const errors = [];
const onLoginClick = sinon.spy();
const wrapper = mount(<Login errors={errors} onLoginClick={onLoginClick} />);
// when
wrapper.ref('username').simulate('change', {target: {value: 'test'}});
wrapper.ref('password').simulate('change', {target: {value: 'user'}});
wrapper.find('button').simulate('click');
// then
//expect(onLoginClick.calledWith(expected)).to.equal(true);
expect(onLoginClick.called).to.equal(true);
});
});
Component
import React, { Component, PropTypes } from 'react'
export default class Login extends Component {
renderErrors() {
const { errors } = this.props;
return errors.map((error, i) => {
return (
<p key={i} style={{color:'red'}}>{error}</p>
);
});
}
render() {
return (
<div>
<input type='text' ref='username' className="form-control" style={{ marginRight: '5px' }} placeholder='Username'/>
<input type='password' ref='password' className="form-control" style={{ marginRight: '5px' }} placeholder='Password'/>
<button onClick={() => this.handleLogin()} className="btn btn-primary">
Login
</button>
{this.renderErrors()}
</div>
)
}
handleLogin() {
const { onLoginClick } = this.props;
const credentials = {
username: this.refs.username.value.trim(),
password: this.refs.password.value.trim()
};
onLoginClick(credentials)
}
}
Login.propTypes = {
onLoginClick: PropTypes.func.isRequired,
errors: PropTypes.arrayOf(PropTypes.string)
};
package.json
{
"name": "react_redux_webpack_client",
"version": "1.0.0",
"description": "A ReactJS Client",
"scripts": {
"test": "mocha test/helpers/browser.js test/**/*.spec.js",
"dev": "webpack-dev-server --content-base public/ --hot --inline",
"build": "webpack -p --display-error-details"
},
"repository": {
"type": "git",
"url": "https://github.com/Rob-Leggett/react_redux_webpack.git"
},
"author": "Robert Leggett",
"license": "MIT",
"homepage": "https://github.com/Rob-Leggett/react_redux_webpack",
"bugs": {
"url": "https://github.com/Rob-Leggett/react_redux_webpack/issues"
},
"devDependencies": {
"chai": "^3.5.0",
"css-loader": "^0.26.1",
"enzyme": "^2.7.1",
"extract-text-webpack-plugin": "^1.0.1",
"html-webpack-plugin": "^2.26.0",
"jsdom": "^9.9.1",
"mocha": "^3.2.0",
"node-sass": "^4.3.0",
"react-addons-test-utils": "^15.4.2",
"sass-loader": "^4.1.1",
"sinon": "^1.17.7",
"style-loader": "^0.13.1",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-register": "^6.22.0",
"body-parser": "^1.15.2",
"classnames": "^2.2.5",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-redux": "^5.0.2",
"redux": "^3.6.0",
"redux-thunk": "^2.2.0",
"whatwg-fetch": "^2.0.1"
}
}
To find out more then true/false in your test, you can can get the args from the Sinon spy like this:
const spyCall = onLoginClick.getCall(0);
expect(spyCall.args[0]).to.equal(expected)
Now the failing test should show you the args you really got.
See http://sinonjs.org/docs/

core_1.profide is not a function - core_1.provide(auth_1.FirebaseAuth, {

I am using Ionic 2:
Your system information:
ordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 0.0.47
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.9.2
Xcode version: Not installed
When I run ionic serve, I get the following errors in the CLI:
[13:55:44] ionic-app-scripts 0.0.47
[13:55:44] watch started ...
[13:55:44] build dev started ...
[13:55:44] clean started ...
[13:55:44] clean finished in 16 ms
[13:55:44] copy started ...
[13:55:44] transpile started ...
[13:55:52] template error, "E:\Development\IDE\ionic-apps\theWhoZoo-chat\src\pages\login\build\pages\login\login.html":
Error: ENOENT: no such file or directory, open
'E:\Development\IDE\ionic-apps\theWhoZoo-chat\src\pages\login\build\pages\login\login.html'
[13:55:52] template error, "E:\Development\IDE\ionic-apps\theWhoZoo-chat\src\pages\home\build\pages\home\home.html":
Error: ENOENT: no such file or directory, open
'E:\Development\IDE\ionic-apps\theWhoZoo-chat\src\pages\home\build\pages\home\home.html'
[13:55:52] transpile finished in 8.10 s
[13:55:52] webpack started ...
[13:55:53] copy finished in 8.46 s
[13:56:13] webpack finished in 20.63 s
[13:56:13] sass started ...
[13:56:16] sass finished in 3.37 s
[13:56:16] build dev finished in 32.15 s
[13:56:17] watch ready in 32.35 s
[13:56:17] dev server running: http://localhost:8100/
And the following in the browser when the page tries to open:
There error is occurring here in main.js (core_1.provide(auth_1.FirebaseAuth, {):
exports.AngularFire = AngularFire;
exports.COMMON_PROVIDERS = [
core_1.provide(auth_1.FirebaseAuth, {
useExisting: auth_1.AngularFireAuth
}),
{
provide: tokens_1.FirebaseApp,
useFactory: _getFirebase,
deps: [tokens_1.FirebaseConfig]
},
auth_1.AngularFireAuth,
AngularFire,
database_1.FirebaseDatabase
];
If anyone can help me resolve this, I would appreciate it.
More info:
app.module.ts
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { FIREBASE_PROVIDERS, defaultFirebase } from 'angularfire2';
#NgModule({
declarations: [
MyApp,
HomePage,
LoginPage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
LoginPage
],
providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler },
FIREBASE_PROVIDERS, defaultFirebase({
apiKey: "xxxxx-xxxx",
authDomain: "xxxx.firebaseapp.com",
databaseURL: "https://xxxx.firebaseio.com",
storageBucket: "xxxx.appspot.com"
})]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { FirebaseAuth } from 'angularfire2';
//declare var firebase: any;
import firebase from 'firebase'
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any = LoginPage;
constructor(platform: Platform, private auth: FirebaseAuth) {
firebase.initializeApp({
apiKey: "xxxx-xxx",
authDomain: "xxxx.firebaseapp.com",
databaseURL: "https://xxxx.firebaseio.com",
storageBucket: "xxxx.appspot.com"
});
this.auth.subscribe((data) => {
if (data) {
window.localStorage.setItem('uid', data.auth.uid);
window.localStorage.setItem('displayName', data.auth.displayName);
window.localStorage.setItem('photoURL', data.auth.photoURL);
this.rootPage = HomePage;
}
});
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}
home.ts
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {LoginPage} from '../login/login';
import {
FirebaseAuth,
AngularFire,
FirebaseListObservable
} from 'angularfire2';
#Component({
templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
firelist: FirebaseListObservable<any>;
chat: any;
constructor(public nav: NavController, public af: AngularFire, public auth: FirebaseAuth) {
this.firelist = this.af.database.list('/chat', { //mengambil data
query: {
orderByChild: 'negativtimestamp', //order dari data yang terbaru
}
});
}
chatSend(va, vi) { //mengirim pesan chat
this.af.database.list('/chat').push({ // menambahkan data chat ke firebase
uid: window.localStorage.getItem('uid'),
img: window.localStorage.getItem('photoURL'),
username: window.localStorage.getItem('displayName'),
chat_text: va.chatText,
timestamp: Date.now(),
negativtimestamp: -Date.now() //buat nanti ambil data yang terbaru
})
this.chat = '';
}
logout() { // melakukan logout
window.localStorage.removeItem('email'); // remove email dari localStorage
window.localStorage.removeItem('uid'); // remove uid dari localStorage
window.localStorage.removeItem('displayName'); // remove displayName dari localStorage
this.auth.logout();
this.nav.setRoot(LoginPage);// kembali ke halaman LoginPage
}
}
login.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {FirebaseAuth, AuthProviders, AuthMethods} from 'angularfire2';
import {HomePage} from '../home/home';
#Component({
templateUrl: 'build/pages/login/login.html',
})
export class LoginPage {
constructor(private nav: NavController, public auth: FirebaseAuth) {
}
LoginGoogle(){
this.auth.login({
provider: AuthProviders.Google,
method: AuthMethods.Redirect,
}).then((Data) => {
this.nav.setRoot(HomePage);
}).catch((error) => {
console.log(error);
})
}
}
pacjage.json
{
"name": "ionic-hello-world",
"author": "Ionic Framework",
"homepage": "http://ionicframework.com/",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"#angular/common": "2.2.1",
"#angular/compiler": "2.2.1",
"#angular/compiler-cli": "2.2.1",
"#angular/core": "2.2.1",
"#angular/forms": "2.2.1",
"#angular/http": "2.2.1",
"#angular/platform-browser": "2.2.1",
"#angular/platform-browser-dynamic": "2.2.1",
"#angular/platform-server": "2.2.1",
"#ionic/storage": "1.1.7",
"angularfire2": "^2.0.0-beta.3-0930330",
"firebase": "^3.3.0",
"ionic-angular": "2.0.0-rc.4",
"ionic-native": "2.2.11",
"ionicons": "3.0.0",
"rxjs": "5.0.0-beta.12",
"zone.js": "0.6.26"
},
"devDependencies": {
"#ionic/app-scripts": "0.0.47",
"typescript": "^2.0.9"
},
"cordovaPlugins": [
"cordova-plugin-whitelist",
"cordova-plugin-console",
"cordova-plugin-statusbar",
"cordova-plugin-device",
"cordova-plugin-splashscreen",
"ionic-plugin-keyboard"
],
"cordovaPlatforms": [],
"description": "theWhoZoo-chat: An Ionic project"
}
you need to correct your login.ts. home.ts near
#Component({
templateUrl: 'login.html'
})
Upgraded to latest angularfire2 and this fixed it.
npm install firebase angularfire2#latest --save