Next Auth email credential without default signIn page - next.js

Is there a solution to use credential email - password from backend
without the default authentication page provided from Next/auth?
I must use Modal instead of full-page authentication
I follow the doc:"https://next-auth.js.org/providers/credentials" but when I use the SignIn from nextAuth it generates a signIn Page

Add your own custom login page if any and/or a sign-in button that uses a function that is provided by NextAuth. See below how it is done.
Custom Login Page
In your api/auth/[...nextauth].js file add this option.
export default NextAuth({
...
pages: {
signIn: '/login',
},
});
NextAuth Sign In Function
signIn('credentials', {
redirect: false,
callbackUrl: '/',
username: ...,
password: ...,
})

Related

Firebase Persisting Auth with Stack Navigator

Attempting to let Firebase persist authentication within the app.js of React Native by doing the following:
There is a sign in page that envokes auth() sign in via Firebase, which works fine, and redirects to the home page via navigation.replace("Home"); however, once the app is closed and relaunched on the emulator, it redirects back to sign in.
This is seemingly what the App.js looks like, I assume that the AuthStateChanged would be prevalent as depicted below, however, user is not accessed in App.js as it is established in SignIn.js, when the Firebase credentials are sent, but I assume it would be similar to this layout?
const App = () => {
var initialRoute = null
React.useEffect(() => {
const unsubscribe = auth().onAuthStateChanged(user => {
if(user) {
initialRoute = "Home"
}
else {
initialRoute = "SignIn"
}
})
return unsubscribe
}, []);
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false,
}}
initialRouteName={initialRoute}
>
The reason it needs to affect the initial route, and not just redirect anyone who reopens to the home page, is because after registration, there are extra steps included that adjust the database, such as location mapping and etc., therefore, the redirection has to occur within the initial route.
Thanks for your assistance.
This is not how you build a navigation flow with react-navigation. But that's no problem since theres a guide here on the official react-navigation side on how to do that: https://reactnavigation.org/docs/auth-flow/
Fixed by setting two different returns within App.js, one for if the user is authenticated with Firebase that sets the initialRoute to "Home", and one for else that sets it to "SignUp", seems to work fine.

React Native - How to persist a Firebase authenticated user session from react-native app to a (react-native-webview) webview component?

I have a react-native app which uses Firebase (with "#react-native-firebase/auth": "^6.0.1").
In the app there is one Webview (with "react-native-webview": "^7.5.2").
The user logs in, then I have access to its jwt by using:
auth().currentUser.getIdTokenResult()
.then(jwtToken => {
console.log('jwtToken: ', jwtToken.token);
})
Now I need the user to open the Webview and still being connected because the webview points to my firebase hosting page.
<WebView
source={{
uri: 'my-firebase-hosting-url',
headers: {
Authorization: jwtToken,
},
}}
renderLoading={this.renderLoadingView}
startInLoadingState={true}
sharedCookiesEnabled={true}
thirdPartyCookiesEnabled={true}
domStorageEnabled={true}
ref={ref => {
this.webview = ref;
}}
/>
On the server side, I have setup express and cookie-session.
The user doesn't seems to be logged in the webview: on the server side, when I console.log(req.session) it shows an empty object {}.
I've tried multiple options but nothing seems to work in iOS (not tried on Android yet)
What am I missing? Are there extra steps on the frontend/backend? (I am still new to programming)
Thank you for your help.
I finally solved it and hope it will help others:
Design your state
state = {
shouldRenderWebview: false,
authorization: ''
...
In your constructor, get a refreshed token from firebase
auth()
.currentUser.getIdTokenResult()
.then(result => {
this.setState({
authorization: result.token,
shouldRenderWebview: true,
});
})
Design your main component to either show a loading view (while it's getting the token) or render the webview
Your webview (and add 'Bearer' to the code)
const Authorization = 'Bearer ' + this.state.authorization;
<WebView
source={{
uri: this.state.urlToGo,
headers: {
Authorization,
},
}}
....
In your backend, check if the authentication code is valid
firebase.auth().verifyIdToken(req.headers.authorization.substr(7));
Then do your stuff depending on the result.

How to get currentUser on first load in firebase-auth without requesting

I'm using firebase authentication, and my navbar is depend on if user is logged in or not. When i load the website, if user not logged out before, he should still stay as logged in.But, Firebase onAuthStateChanged listener returns user after 100-300ms, so my navbar can't decide if user is logged in or not.So, navbar shows login and signup button for 300ms, then firebase returns user, and navbar shows dashboard and logout button.
I'm using vue, I've tried saving UID and username on localstorage, but i'm concerning about security. what if someone manually changed localstorage data? Also, user may logged out, but stay logged in my manually setting localStorage.setItem('user', ....)
Navbar.vue
<div v-if="user.uid" class="flex row space-b">
// userpic, photo, logout button
</div>
<div v-else>
// login and signup button
</div>
vuex
state: {
user: {
uid: null,
photoURL: null,
username: null,
},
},
I tried not to mount Vue instance until onAuthStateChanged listener returns something, but this can't be a good solution, hence i'm rendering website nearly 300ms late.
Anyway, i saved it in cookie. when website loads, if cookie is exists i render navbar as if user logged in, and then double check after firebase listener returns
This is caused because beforeEach is getting executed before firebase has fully finished initialization.
You can use onAuthStateChanged observer to make sure the vue app is initialized only after the firebase is fully initialized.
One way to fix it is to wrap the vue initialization code in main.js(new Vue( ... )) with onAuthStateChanged like this:
let app;
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
console.log("user", user);
if (!app) {
new Vue({
router,
vuetify: new Vuetify(options.Vuetify),
render: (h) => h(App),
}).$mount("#app");
}
});
for version 7 firebase you can check this repo file
https://github.com/ErikCH/FirebaseTokenFrontend/blob/master/src/main.js

How to register user without admin in ROS?

Now I'm verification ROS2.0 with NodeJS
But I don't know How to register user without admin in ROS2.0 from NodeJS.
How to do it ?
Anyone can register a user, so you can just following the guidelines here: https://realm.io/docs/javascript/latest/#users
Realm.Sync.User.register('http://my.realm-auth-server.com:9080', 'username', 'p#s$w0rd', (error, user) => { /* ... */ });

How do I login a user with Meteor

I've added accounts-password and useraccounts:unstyled
I've included the signin template in my footer.html -
{{#if showSignIn}}
{{> atForm state="signIn"}}
{{/if}}
I'm hard coding the creation of users as the app starts up -
import { Accounts } from 'meteor/accounts-base'
if (!Acounts.findUserByEmail('aidan#gmail.com')) {
Accounts.createUser({
username: 'Aidan',
email: 'aidan#gmail.com',
password: 'securePassword'
});
}
It's just that I can't work out how to actually log my user in. I've tried simply entering the password and email address into the form. That doesn't work (the form error says 'Login Forbidden').
I've tried adding the following line (to the same file as my account creation code) -
accountsServer.validateLoginAttempt(()=>{return true;});
Unsurprisingly that doesn't do anything.
I've tried add a submit event into my footer.js file -
Template.footer.events({
'submit form'(event) {
console.log('submitted');
const email = document.getElementById('at-field-email').value;
const password = document.getElementById('at-field-password').value;
Meteor.loginWithPassword(email, password);
},
});
I can see that the event is firing, but when I try Meteor.user() in the console I still get null.
There's typo in if (!Acounts.findUserByEmail('aidan#gmail.com')) (it should have been Accounts). The user isn't being created.
To get a super simple functional login with a single hard coded user -
Add the accounts-password package and the ui user accounts package.
> meteor add accounts-password
> meteor add useraccouts:unstyled
The accounts-password package handles the actual logging in. The user accounts:unstyled packages provides a set of templates for accounts management.
Then add the login form to a template.
<template name="templateWithLogin">
{{> atForm state="signIn"}}
</template>
Lastly create a user (e.g. in /server/main.js).
import { Accounts } from 'meteor/accounts-base';
if (!Accounts.findUserByEmail('user#gmail.com')) {
Accounts.createUser({
username: 'User',
email: 'user#gmail.com',
password: 'securePassword'
});
}
This should be everything needed to get a functional login form. There's loads of tutorials online for creating additional functionality. The main documentation is here.
you can use {{>loginButtons}} to get the ui and {{#if currentUser }} for the functionality.

Resources