Access route params in a single way react native - javascript

I am currently facing a problem with the authentication flow and the navigation file. Basicly I want to have the authentication logic inside my navigation file, so I can conditionaly say if I want to show the login or not.
Like this:
const { id: contextId } = useId()
const { token } = useToken()
const _id = contextId : getIdParam(contextId)
const globalParams = { initialParams: { _id } }
And then I use the _id to conditionally show or not the login. The problem with this implementation is, that I am using two ways to access the id param in the url:
ContextAPI (I set the id after login so it is available in that session)
getIdParam function, to access the id param via location.path, whenI try to reload a screen without passing in login.
Is there any way I can access params in the navigation file, I tried to use useRoute hook, but I am not allowed to use it outside of a screen.
Any help? Thanks

Related

Auth0 unable to get ID token / user metadata

I am currently working on adding Auth0 to a Vue.js/Node.js application and so far I have figured out how to allow users to register and log in (to /callback) and that seems to be working fine. However, I have manually added (will be automatic later on) some data to the user metadata section. I have the below code as a rule that is turned on. I can’t seem to get access to the data on the Vue.js end of things. What I’d like is to be able to get the user data and user metadata so I can store it in my front end.
Rule code
function (user, context, callback) {
const namespace = 'account_signup_type/';
const namespace2 = 'account_type';
context.idToken[namespace + 'is_new'] = (context.stats.loginsCount === 1);
context.idToken[namespace2] = user.account_type;
context.idToken.user = user;
callback(null, user, context);
}
Code I am trying in my Vue.js front end
getIdTokenClaims(o) {
return this.auth0Client.getIdTokenClaims(o);
}
Currently, this returns undefined
I ended up figuring it out, there was no namespace being created in the id_token which resulted in it not properly passing the data through to the Vue .js app. I added a namespace using a web address format with the domain extension cut off and it now works.

Display different navbar for logged user

I've created login/register in my app, and now i want to display different navbar based if user is logged.
I don't use redux for this project.
In App component, globally, i created state that i wanted to pass to childs, and then base on it, display different data, so i created something like this:
function App() {
const [loginStatus, setLoginStatus] = useState();
useEffect(() => {
if(!loginStatus) {
axios.get("http://localhost:5000/api/users/isUserAuth", {
headers: {
"x-access-token": localStorage.getItem("token")
}
}).then((response) => {
console.log(response);
setLoginStatus(true);
})
}}, [])
and then in my Navbar i created something like this:
<NavItem style={{display: loginStatus ? "block" : "none"}}>
This works, but it causes loginStatus to be loaded every page refresh, every route made, so when i go to different page when user is logged, it causes 0.5s delay before NavItem will appear, because it makes request to backend on every refresh.
How can i store information that user is logged in so it wouldn't have to make API calls on every page?
I think you can use localStorage to store user logged-in information.
You need to initialize state with the local storage token and check with that state
const [loginStatus, setLoginStatus] = useState(token)

How to get user's id from auth0 in React

I recently implemented user authentication in my react web app using Auth0. And I need to retrieve some information from user object. I did this so far:
cost { user, isAuthenticated } = useAuth0();
<p>{user.name}</p>
But I also want to get user's id, so I can reference them later in my backend. So I did this:
const { user, isAuthenticated } = useAuth0();
<p>{user.user_id}</p>
And when I go to the website I get undefined instead of the user's id.
Is it happening because I use dev-keys for my social connections, or maybe it has to be done differently?
Not sure if you are still searching for this problem, however I had a similar problem and found this as a solution:
const { user, isAuthenticated } = useAuth0();
<p>{user.sub}</p>
source: https://community.auth0.com/t/how-to-get-user-id-of-a-user-after-login-in-react-hook-useauth0/53309
It should be the "sub" key. Discord id is 18 characters long. The results prefix it with oauth2|discord|. Which you can truncate out with a function.
const { user, isAuthenticated } = useAuth0();
console.log(user.sub);
The results should be something like:
oauth2|discord|111111111111111111

Is there any way I can receive params from an URL in Next.JS after refreshing?

I'm working on an dynamic route with Next.JS that must be accessed directly from the address bar, not by a Next link. The problem is that when I either write or refresh the page, I don't receive any params.
Ex:
// URL: /ex/1
// File: pages/ex/[num].js
const router = useRouter()
// Access from a link
console.log(router.query) // {num: "1"}
// Access from address bar
console.log(router.query) // {}
I dont really know if there's any way to do what I want in Next.
I hope I've explained my problem well.

Ember - get target url of transition

I am creating an error hook in my Ember.js app to redirect you to the auth service if you are not allowed to view certain content (in other words, if the server returns a 401).
It looks like this:
Ember.Route = Ember.Route.extend({
error: function(error, transition){
if (error.status === 401) {
window.location.replace("https://auth.censored.co.za");
}
}
Our auth api works as follows: If you send it a parameter called target (which is a url), it will redirect you back to that target url after you've logged in.
So I want to somehow get the URL of the route the Ember app was trying to transition to.
Then my code will end up something like this
Ember.Route = Ember.Route.extend({
error: function(error, transition){
if (error.status === 401) {
var target = // Your answer here
window.location.replace("https://auth.censored.co.za?target=" + encodeURIComponent(target));
}
}
I came across a need for this too, and resorted to using some internal APIs. In my case, I wanted to reload the whole app so that if you're switching users there's not data left over from the other user. When I reload the app, I want to put the user at the URL they tried to transition to, but for which they had insufficient privileges. After they authenticate (and thus have the bearer token in localstorage) I wanted to use window.location.replace(url) to get a clean copy of the whole app with the user at the URL implied by the Ember Transition object. But the question was, how do I go from a Transition object to a URL? Here is my solution, which uses the generate method which is a private API of the router:
let paramsCount = 0;
let params = {};
let args = [transition.targetName];
// Iterate over route segments
for (let key1 in transition.params) {
if (transition.params.hasOwnProperty(key1)) {
let segment = transition.params[key1];
// Iterate over the params for the route segment.
for (let key2 in segment) {
if (segment.hasOwnProperty(key2)) {
if (segment[key2] != null) {
params[key2] = segment[key2];
paramsCount++;
}
}
}
}
}
if (paramsCount > 0) {
args.push(params);
}
let url = router.generate.apply(router, args);
You'll need to get the router somehow either with a container lookup or some other means. I got it by injecting the -routing service which is documented as an API that might be publically exposed in the future (used by link-to), and which happens to have the router as a property.
While messy, perhaps you might find this helpful.
I was able to use transition.intent.url to accomplish exactly this. I'm not sure if this is private or not -- relevant discussion: https://discuss.emberjs.com/t/getting-url-from-ember-router-transition-for-sso-login/7079/2.
After spending several hours searching for an answer to this question and using the Chrome debugger to try and reverse engineer the Ember 2.5 code, my conclusion is that what you are looking for is not possible at the present time.
For people who don't understand why someone wants to do this, the case arises when authentication (e.g the login page) is separated from the application. This is necessary if there is a requirement not to deliver any content (including the application itself) to the user if the user is not authenticated. In other words, the login page cannot be part of the application because the user is not allowed to access the application before logging in.
PS: I realize this is not a solution to the user's question and probably more suitable as a comment. However, I can't post comments.
Kevins answer is the most correct one, I came to a similar solution. Basically I found how the link-to component was populating the href attribute and used the same sort of code.
In your object inject -routing. I did so with:
'routing': Ember.inject.service('-routing'),
Then the code to generate the URL from the transition is as follows...
let routing = this.get('routing');
let params = Object.values(transition.params).filter(param => {
return Object.values(param).length;
});
let url = routing.generateURL(transition.targetName, params, transition.queryParams);

Categories

Resources