Realm Object Server: Access Denied Error after successful login using Custom Authentication - realm

I am trying to setup a Realm Object Server for my company's mobile application. I have to use a custom authentication to allow users to access the database.
import { BasicServer } from 'realm-object-server'
import * as path from 'path'
import { AuthProvider } from './lib/auth'
const server = new BasicServer()
server.start({
dataPath: path.join(__dirname, '../data'),
address: '192.168.0.24',
authProviders: [new AuthProvider()]
})
.then(() => {
console.log(`Realm Object Server was started on ${server.address}`)
})
.catch(err => {
console.error(`Error starting Realm Object Server: ${err.message}`)
})
Here is the custom auth that I have to apply. The authentication will be done by another backend server.
import { post } from 'superagent'
import { auth, User, errors } from 'realm-object-server'
import { pick } from 'lodash';
export class AuthProvider extends auth.AuthProvider {
name = 'authprovider'
authenticateOrCreateUser(body: any): Promise<User> {
return post('https://XYZ/signin')
.send({
'email': body.user_info.email,
'password': body.user_info.password
})
.then((successResponseJSON: any) => {
return this.service.createOrUpdateUser(
successResponseJSON.body.id,
this.name, // this is the name of the provider,
false, // this is if the user should or should not be an admin
pick(successResponseJSON.body, ['id', 'email'])
)
})
.catch(err => {
throw new errors.realm.InvalidCredentials({ detail: err })
})
}
}
I have added code for custom authentication to the example for provided by realm to add data to the realm server. Here I am asking that the user be authenticated using 'authprovider'
var URL = "192.168.0.24:9080"
Realm.Sync.User.registerWithProvider(`http://${URL}`, {
provider: 'authprovider',
providerToken: null,
userInfo: {
email: username,
password: password
}
}).then(user => {
console.log('user', user, user.identity)
Realm.open({
sync: {
url: `realm://${URL}/abc`,
user: user
},
schema: [TickerSchema],
})
Even though the user is successfully authenticated, I am getting access denied error. I am not able to understand why.
user User {} 9ae6033cd9b55e3aca62a291af8726ea
Unhandled session token refresh error { Error: The path is invalid or current user has no access.
at new AuthError (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/errors.js:22:25)
at performFetch.then.then (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/user-methods.js:105:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
name: 'AuthError',
message: 'The path is invalid or current user has no access.',
stack: 'Error: The path is invalid or current user has no access.\n at new AuthError (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/errors.js:22:25)\n at performFetch.then.then (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/user-methods.js:105:29)\n at <anonymous>\n at process._tickCallback (internal/process/next_tick.js:188:7)',
type: 'https://realm.io/docs/object-server/problems/access-denied',
title: 'The path is invalid or current user has no access.',
status: 403,
code: 614 }

The realm url was incorrect: it should have been realm://${URL}/~/abc instead of realm://${URL}/abc

Related

Strapi athentication returns AxiosError: Request failed with status code 400

using Strapi with Next js. Trying to authenticate with following code
const authenticate = () => {
const paylaod = {data: {
identifier: email,
password: password
}}
console.log(paylaod)
axios.post(`http://localhost:1337/api/auth/local`, paylaod).then((res, err) => {
console.log(res, err)
console.log(res,err)
const { jwt, user } = res.data
window.localStorage.setItem('jwt', jwt)
window.localStorage.setItem('userData', JSON.stringify(user))
router.push({
pathname: '/calendar',
});
}).catch(err => {
console.log(err)
})
}
Response I'm getting is:
AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
Dug every possible answer in forums and Stackoverflow, but nothing helped.
User I'm using is not super admin, registered fresh one in Strapi admin.
this is how my middleware list looks like
export default [
'strapi::errors',
'strapi::security',
'strapi::cors',
'strapi::poweredBy',
'strapi::logger',
'strapi::query',
'strapi::body',
'strapi::session',
'strapi::favicon',
'strapi::public',
];
and here's my (scrappy) env
HOST='127.0.0.1'
PORT=1337
APP_KEYS="gfhgfhgfhg,hfghghgf"
API_TOKEN_SALT="adfasdfads"
ADMIN_JWT_SECRET="adfasdfasdf"
JWT_SECRET="sdasdadfasdf"

Ejabberd [warning] Unexpected info $gen_event

Warning message, that I'm trying to get rid off.
[warning] Unexpected info: {'$gen_event',
{xmlstreamstart,<<"stream:stream">>,
[{<<"xmlns:stream">>,
<<"http://etherx.jabber.org/streams">>},
{<<"xmlns">>,<<"jabber:client">>},
{<<"version">>,<<"1.0">>},
{<<"to">>,<<"example.com">>}]}}
My users connect via xmpp.js from example.com website
import { client } from '#xmpp/client';
const xmppClient = client({
service: "ejabberd-ws.example.com",
domain: "example.com",
credentials: async(auth) => {
try {
const res = await request('https://example.com/ejabberd/config');
const username = res.data['jid'];
const password = res.data['password'];
if (!password) {
console.error('Xmpp password is empty, null, false or undefined');
return this.xmpp.disconnect();
}
auth({ username, password });
} catch (e) {
return this.xmpp.disconnect();
}
}
});
It is ejabberd version 22.10
Do any of you guys know what exactly is causing this warning message?
I would like to get rid of it or at least understand what is causing it.

NextJS 12.2 middleware upgrade, return 401 basic auth

I'm trying to upgrade nextjs to v12.2+, which includes the change from using _middleware files on the page level to a global middleware file (https://nextjs.org/docs/messages/middleware-upgrade-guide). I've also read this guide that says I can no longer return a body in my middleware: https://nextjs.org/docs/messages/returning-response-body-in-middleware.
The problem I have now is that I want to show a Basic Auth prompt on specific pages, which was working in the old setup, but gives me the error "Middleware is returning a response body" in the new setup. I've tried to rewrite the code to use NextResponse.rewrite but that does not give me the basic auth prompt on the user's current page.
How would I rewrite this (old setup in /admin/_middleware.js):
import { NextResponse } from "next/server";
import checkBasicAuth from "#utils/middleware/checkBasicAuth";
export function middleware(req) {
if (
checkBasicAuth(req.headers.get("authorization"), {
username: process.env.AUTH_USERNAME,
password: process.env.AUTH_PASSWORD,
})
) {
return NextResponse.next();
}
return new Response("Authentication required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
});
}
to the new middleware setup (/src/middleware.js) so that the user does not get redirected, and gets the basic auth prompt when not logged in?
Found the answer myself, so for anyone stuck on the same problem, this is how I rewrote my old middleware:
import { NextResponse } from "next/server";
import checkBasicAuth from "#utils/middleware/checkBasicAuth";
export function middleware(request) {
if (
!checkBasicAuth(request.headers.get("authorization"), {
username: process.env.AUTH_USERNAME,
password: process.env.AUTH_PASSWORD,
})
) {
return NextResponse.rewrite(
`${request.nextUrl.protocol}//${request.nextUrl.host}/401`,
{
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
}
);
}
return NextResponse.next();
}
This will render but not redirect to the /401 error page, the custom header will make sure the basic auth dialog is shown to the user.

Next-auth prevent redirecting when credentials are incorrect [duplicate]

I'm using NextAuth.js for Next.js authentication. Login works fine, but the page is still reloading on wrong credentials. It doesn't show any error. I need to handle error to show some kind of toast message.
signIn("credentials", {
...values,
redirect: false,
})
.then(async () => {
await router.push("/dashboard");
})
.catch((e) => {
toast("Credentials do not match!", { type: "error" });
});
When passing redirect: false to its options, signIn will return a Promise that always resolves to an object with the following format.
{
error: string | undefined // Error code based on the type of error
status: number // HTTP status code
ok: boolean // `true` if the signin was successful
url: string | null // `null` if there was an error, otherwise URL to redirected to
}
You have to handle any errors inside the then block, as it won't throw an error.
signIn("credentials", { ...values, redirect: false })
.then(({ ok, error }) => {
if (ok) {
router.push("/dashboard");
} else {
console.log(error)
toast("Credentials do not match!", { type: "error" });
}
})

How to create user by Nativescript firebase plugin?

I'm using EddyVerbruggen's NativeScript firebase plugin - https://github.com/EddyVerbruggen/nativescript-plugin-firebase
Firebase has been configured properly. I ran the following code & it's working fine.
firebase.init(<any>{
persist: true, // Allow disk persistence. Default false.
url: config.apiUrl
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
But, when I'm trying to create user through email id & password by using following code
firebase.createUser({
email: 'eddyverbruggen#gmail.com',
password: 'firebase'
}).then(
function (result) {
// dialogs.alert({
// title: "User created",
// message: "userid: " + result.key,
// okButtonText: "Nice!"
// })
alert('User Created with user id - '+result.key);
},
function (errorMessage) {
// dialogs.alert({
// title: "No user created",
// message: errorMessage,
// okButtonText: "OK, got it"
// })
alert('No user created. Got error message insted - '+errorMessage);
}
)
I'm getting message from my console like this -
JS: --- auth state changed: com.google.android.gms.internal.zzadg#399fbe6
The main parent file is -
import {Injectable} from "#angular/core";
import {User} from "./user";
import {ConfigService} from "../config";
import firebase = require("nativescript-plugin-firebase");
#Injectable()
export class UserService {
register(user: User,config:ConfigService) {
alert("API url going to use is : "+config.apiUrl);
firebase.init(<any>{
persist: true, // Allow disk persistence. Default false.
url: config.apiUrl
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
firebase.createUser({
email: 'eddyverbruggen#gmail.com',
password: 'firebase'
}).then(
function (result) {
// dialogs.alert({
// title: "User created",
// message: "userid: " + result.key,
// okButtonText: "Nice!"
// })
alert('User Created with user id - '+result.key);
},
function (errorMessage) {
// dialogs.alert({
// title: "No user created",
// message: errorMessage,
// okButtonText: "OK, got it"
// })
alert('No user created. Got error message insted - '+errorMessage);
}
)
}
}
when in checking in my firebase app account user account also not reflecting.
I know, there is a small mistake, because of which it's not working. But, can't able to figure out what causing the problem.
-------Error Fixed-------
Whole time I was testign in an Emulator which has no Google Play Service installed. It required Google Play Service to work. Finally, when I tested this in my mobile device it's worked fine.

Resources