Using MongoDb Realm authentication within a React app - mongodb

I am learning MongoDb Realm from the documentation and following the examples given. My code to login is
const loginEmailPassword = async (email, password) => {
const app = Realm.App.getApp(APP_ID)
const credentials = Realm.Credentials.emailPassword(email, password)
try {
// Authenticate the user
const user = await app.logIn(credentials)
return true
} catch (err) {
console.error('Failed to log in', err)
}
return false
}
If the credentials match a current user all is good, if the don't it doesn't throw an error but generates the following in the console:
POST https://eu-west-1.aws.stitch.mongodb.com/api/client/v2.0/app/<"my Realm App ID">/auth/providers/local-userpass/login 401
Failed to log in Error: Request failed (POST https://eu-west-1.aws.stitch.mongodb.com/api/client/v2.0/app/<"my Realm App ID">/auth/providers/local-userpass/login): invalid username/password (status 401)
Can anyone please help me understand what is going on?

Related

Sveltekit + Supabase Keycloak Authenticate Error

I use sveltekit, supabase with Keycloak. When I attempt to login, it redirects to keycloak authentication page. After I enter username and password, it returns url like this:
http://localhost:5173/?error=server_error&error_description=Unable+to+exchange+external+code%3A+7cfe164c-1fad-48e2-98a9-c59c0d80d43a.96a435ef-b0a3-45da-85fc-8557377a2cdf.a1e9662f-8901-4944-9490-a0674ba33776
I entered correct Client Secret and Realm URL, and it redirect to my realm correctly.
But it occurs error: Unable to Exchange External Code
I use signInwithKeycloak function to login
async function signInWithKeycloak() {
const { data, error } = await supabaseClient.auth.signInWithOAuth({
provider: 'keycloak',
options: {
scopes: 'openid',
},
})
}

Correctly handling authentication handshake during socket connection

I am trying to figure out if following is secure and correct way of handling user authentication with websockets when using socket.io. My understanding is that we only need to verify authentication (jwt token) during socket connection and can assume that all subsequent events are authenticated?
I essentially made this middleware to verify jwt token once during connect event and then set user details on socket.
socketIo.use((socket, next) => {
socket.on('connect', async () => {
try {
const { authToken } = socket.handshake.auth
const user = await verifyUserToken(authToken)
socket.user = {
uid: user.uid
}
next()
} catch {
next(new Error(SocketError.UNAUTHORIZED))
}
})
})
Is this correct and secure, or do I need to verify token on every event call?

Why isn't my Firebase app connecting to Google Secret Manager?

I can't figure out why I keep getting the error: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
firebase login from my command line returns that I am already logged in and
I have configured my-app#appspot.gserviceaccount.com to be a Secret Manager Secret Accessor in the GCP IAM admin dashboard within the same project.
Here's the code I'm using:
const { SecretManagerServiceClient } = require("#google-cloud/secret-manager");
const client = new SecretManagerServiceClient();
const gcpSecretsLoader = async (secretName: string) => {
try {
const secret = await client.accessSecretVersion({
name: `projects/my-app/secrets/${secretName}/versions/latest`,
});
const payload = secret.payload.data.toString("utf8");
console.info(`Payload: ${payload}`);
} catch (err) {
console.log(err);
}
};
gcpSecretsLoader("CLIENT_ID"); // CLIENT_ID matched a secret name within the secret manager

how to reset password of users whose email is not verified in loopback?

So I ran into this issue.
I have a user who has emailedVerified as false.
So, when I try to reset password for that user as follows it gives me user unverified error.
Person.resetPassword({
email: email
}, function (err) {
if (err) return res.status(422).send(err);
});
So if user has emailVerified as false I created a token for the user with token data as follows:
const tokenData = {
ttl: 900,
scopes: ['reset-password'],
};
user.createAccessToken(tokenData, req, function (err, token) {
//email link with token
});
Now when I try to change password with following request.
/api/people/reset-password?access_token=generated-token and data message as {newPassword: “newPassword”}
I’m getting Access Denied for POST /api/people/reset-password?access_token=token
--Context scopes of Person.setPassword()
This happening only for generated token (either for verified user or non-verified user). If verified user request for password-change its successful which is done by following code.
Person.resetPassword({
email: email
}, function (err) {
if (err) return res.status(422).send(err);
});
I have following settings in person model, which i removed, but still it says access denied.
"restrictResetPasswordTokenScope": true,
"emailVerificationRequired": true,
I found this code in loopback/common/models/user.js:
User.resetPassword = function(options, cb) {
...
if (UserModel.settings.emailVerificationRequired && !user.emailVerified) {
err = new Error(g.f('Email has not been verified'));
err.statusCode = 401;
err.code = 'RESET_FAILED_EMAIL_NOT_VERIFIED';
return cb(err);
}
...
}
Looks like email verification validation only depends on the emailVerificationRequired setting. The value should be false if you want to enable reset password for not verified users:
"emailVerificationRequired": false, // The deletion of this property should also work as I don't see a default value in user.json
If it will not help, I suggest just debug the method above. I think it should be easy to find the problem, when you know the place to search.

Firebase Facebook authentication : Malformed or expired auth credential

I'm working on a react native ios app using facebook authentication and firebase.
I created my facebook app, copied the secret keys to my firebase facebook auth mode, but when i'm trying to sign in with facebook credential using firebase I'm getting this error : The supplied auth credential is malformed or has expired.
I had a look at this issue : FB login - Firebase.Auth() Error: The supplied auth credential is malformed or has expired which is the quite similar to mine, but the answer didn't help me because my keys are the same in my facebook app configuration than in my firebase facebook auth mode.
Here is the code i'm using when the facebook auth button is pressed :
facebookLogin = () => {
LoginManager.logInWithPermissions(['public_profile', 'email'])
.then(
(result) => {
if (result.isCancelled) {
Alert.alert('Whoops!', 'You cancelled the sign in.');
} else {
AccessToken.getCurrentAccessToken()
.then((data) => {
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
console.log(credential);
firebase.auth().signInWithCredential(credential)
.then(() => this.props.navigation.replace('Home'))
.catch((error) => {
console.log(error.message);
this.setState({ errorMessage: error.message })
});
});
}
},
(error) => {
Alert.alert('Sign in error', error);
},
);
};
I hope you guys can help me, maybe I mistook when I configured my facebook app.
Thank you in advance.
turns out Facebook Graph API is not supported by firebase yet check this out
the reason why Graph API is not supported