I keep receiving the error that the session var is not defined. I've looked at other answers on here about restarting ember serve to remove any caching issues but I've tried that multiple times and I've followed the emberfire guide to the letter. Does anyone have any idea what could be going wrong? The authentication succeeds but the session doesn't get bound to. Here are my files:
/app/routes/application.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.query('post', {
orderBy: 'timestamp',
limitToLast: 3
});
},
actions: {
authenticate: function(username, pass) {
this.get('session').open('firebase', {
provider: "password",
email: username,
password: pass
}).then(function (data) {
console.log(data.currentUser);
console.log(session);
});
}
}
});
/app/torii-adapters
import Ember from 'ember';
import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';
export default ToriiFirebaseAdapter.extend({
firebase: Ember.inject.service()
});
/config/environment.js
var ENV = {
modulePrefix: 'website',
environment: environment,
contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
firebase: 'https://REMOVED.firebaseio.com/',
torii: {
sessionServiceName: 'session'
},
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
I was having the same issue following the tutorial for emberfire. I solved the issue by explicitly install torii via npm:
npm install torii
Restarted the server and all is well.
Related
I was implementing a role based authentication using next-auth v4 using CognitoProvider which I modified to add a role but the role attribute is not passed in the final session json
import NextAuth from "next-auth/next";
function CognitoProvider(options) {
return {
id: "cognito",
name: "Cognito",
type: "oauth",
wellKnown: `${options.issuer}/.well-known/openid-configuration`,
idToken: true,
profile(profile) {
console.log(profile);
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture,
role: profile["cognito:groups"],
};
},
options,
};
}
export default NextAuth({
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_DOAMIN,
}),
],
callbacks: {
session: (props) => {
console.log(props);
return props.session;
},
},
});
Below is the console log of profile object
role: profile["cognito:groups"]
Actual Object
I have added a user to admin group and wanted him to access a specific route in my NextJS app.
Any help would be appreciated.
You need to configure the jwt and session callbacks to include more data in the session.
From Next-Auth docs:
If you want to make something available you added to the token [...] via the jwt() callback, you have to explicitly forward it here [the session() callback] to make it available to the client.
To add the user's role:
export default NextAuth({
// ...
callbacks: {
jwt({ token, account, profile }) {
if (account) {
// modify token
token.role = profile.role;
}
return token;
},
session({ session, token }) {
// Send properties to the client
if (session.user) {
// modify session
session.user.roles = token.role;
}
return session;
},
},
});
Then in your route, you would get the user's role from the session session.user.role
I just finished my project in Strapi and deployed in AWS, when I run my Public ipv4 :1337 says: 'server is running successully' but when I want to log in admin panel just spinning and not showing panel.
server.js
module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
cron: { enabled: true},
url: env('URL', 'http://localhost'),
admin: {
auth: {
secret: env('ADMIN_JWT_SECRET', 'MY_JWT_SECRET'),
},
},
});
I am trying to configure a Social Sign In for Facebook in my react native mobile app using Cognito's hosted UI. My intention is to have any user that signs in with Facebook to have an enabled user in my Cognito User Pool.
However, when I click my "Login with Facebook" button and redirected to Cognito/Facebook's auth flow, it closes the embedded browser immediately and shows the following error in the logs:
[ERROR] 19:02.561 OAuth - Error handling auth response. [Error: invalid_client]
I have a manually configured aws backend with the following configuration:
export default awsConfig = {
Auth: {
"aws_project_region": "us-west-2",
identityPoolId: 'us-east-1:xxxxxx',
region: 'us-east-1',
userPoolId: 'us-east-xxxxx',
userPoolWebClientId: 'xxxxxx',
mandatorySignIn: false,
oauth: {
domain: "myapp.auth.us-east-1.amazoncognito.com",
scope: [
"email",
"openid",
],
redirectSignIn: "myapp://",
redirectSignOut: "myapp://",
responseType: "code",
urlOpener
},
federationTarget: "COGNITO_USER_POOLS"
}
}
This is my Facebook Login configuration:
And here is my react native code:
import React, { Component } from 'react';
import Amplify, { Auth, Hub } from 'aws-amplify';
import awsConfig from './aws-custom-exports';
const configObj = Amplify.configure(awsConfig);
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Button
} from 'react-native';
class App extends Component {
state = {
user: null,
customState: null
};
componentDidMount() {
Hub.listen("auth", ({ payload: { event, data } }) => {
switch (event) {
case "signIn":
this.setState({ user: data });
console.log("Sign in event recorded.")
break;
case "signOut":
this.setState({ user: null });
break;
case "customOAuthState":
this.setState({ customState: data });
console.log("Custom OAuth event recorded.")
default:
console.log("Other auth event: ", data)
}
})
Auth.currentAuthenticatedUser()
.then(user => this.setState({ user }))
.catch(() => console.log("Not signed in"));
}
render() {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<View style={styles.body}>
<Button onPress={() => {
Auth.federatedSignIn({provider: "Facebook"})
.then(data => {
console.log(data)
})
.catch(err => {
console.error(err)
})
}} title="Login with Facebook" />
</View>
</ScrollView>
</SafeAreaView>
</>
);
}
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
body: {
backgroundColor: Colors.white,
}
});
export default App;
My Info.plist file has the CFBundleURLSchemes set to myapp and have added the RTCLinking code snippets to my AppDelegate.m
I have done plenty of tests and research on this, but I simply cannot figure it out. I have a function that works perfectly fine when running locally (no errors), but fails when deployed as AWS lambda.
I created a simple example that recreates it:
URL LOCAL: http://localhost:3000/flagTest/visible (this works fine ✅)
URL DEPLOYED AS LAMBDA: https://www.publicfaq.com/flagTest/visible (the Toggle button doesn't work ❌)
FILE: /pages/flagTest/[tid].js (on a barebone NextJS installation)
import React from 'react'
class FlagTest extends React.Component {
static async getInitialProps({ query }) {
return { visible: query.tid }
}
constructor(){
super();
this.state = {
showFlag:false,
}
}
componentWillMount(){
this.setState({ showFlag: this.props.visible === 'visible' });
}
handleToggle =()=> {
this.setState({
showFlag:!this.state.showFlag
});
}
render() {
return (
<div>
<h1>Flag: {this.state.showFlag ? '🏁' : ''} </h1>
<button className='list_toggle' onClick={this.handleToggle}>
{this.state.showFlag ? 'Hide Flag': 'Show Flag'}
</button>
<hr/>
Props:
<pre>
{JSON.stringify(this.props, null, 2)}
</pre>
State:
<pre>
{JSON.stringify(this.state, null, 2)}
</pre>
</div>
);
}
}
export default FlagTest
Note: I do need to use getInitialProps because I'm planning to use it in a more complex case (API Fetching by id), didn't included it here because is not directly related with this problem.
This is my Serverless YML
service: A123-serverless
provider:
name: aws
runtime: nodejs8.10
stage: ${self:custom.secrets.NODE_ENV}
region: us-west-2
environment:
NODE_ENV: ${self:custom.secrets.NODE_ENV}
functions:
server:
handler: index.server
events:
- http: ANY /
- http: ANY /{proxy+}
plugins:
- serverless-apigw-binary
- serverless-domain-manager
custom:
secrets: ${file(secrets.json)}
apigwBinary:
types:
- '*/*'
customDomain:
domainName: ${self:custom.secrets.DOMAIN}
basePath: ''
stage: ${self:custom.secrets.NODE_ENV}
createRoute53Record: true
endpointType: 'regional'
Thanks!
I found the answer to my problem, posting it here, hopefully will help someone with the same problem:
The Problem was that I was using "query" to extract the 'id', It was working fine in local, but in the Server Side using Express you need to pass that as a parameter like this:
server.get("/q/:id", (req, res) => {
return app.render(req, res, "/q/_tid", { id: req.params.id });
});
Then on the React component you can catch it and use it getInitial Props as req.params.id
static async getInitialProps({ req }) {
myId = req.params.id
}
I am unable to deploy my ember application in Firebase. I can only see the welcome page of Firebase hosting:
You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!
I have installed the EmberFire add-on, as well as the Firebase tool.
My config file looks like this:
module.exports = function(environment) {
var ENV = {
modulePrefix: 'sample',
environment: environment,
rootURL: '/',
locationType: 'auto',
firebase : {
apiKey: 'xxxxxx',
authDomain: 'xxxxx',
databaseURL: 'xxxx',
storageBucket: 'xxxxx',
messagingSenderId: 'xxxxx'
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
ENV.APP.LOG_TRANSITIONS = true;
ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.
LOG_VIEW_LOOKUPS = true;
}
Firebase.json:
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
I have built the app and deployed using following commands:
ember build --prod
firebase login
firebase init
firebase deploy
Thanks in advance :-)
When you initialise your ember.js app with firebase init command for the first time, you will be prompted that
? File dist/index.html already exists. Overwrite? (y/N)
respond with No. Responding with yes will allow the default firebase hosting welcome page override your ember app index.html file, which is why you are still greeted with the firebase hosting welcome page.