How to avoid/fix "Auth0Lock is not defined" exception - auth0

I am trying to use the Auth0 for social login but I keep getting an exception of an undefined reference.
This is the authentication service
import { Injectable } from '#angular/core';
import { tokenNotExpired } from 'angular2-jwt';
// Avoid name not found warnings
declare var Auth0Lock: any;
#Injectable()
export class AuthService {
// Configure Auth0
lock = new Auth0Lock('I have set the ID correctly here', 'and the domain as well', {});
constructor() {
// Add callback for lock `authenticated` event
this.lock.on("authenticated", (authResult) => {
localStorage.setItem('id_token', authResult.idToken);
});
}
public login() {
// Call the show method to display the widget.
this.lock.show();
};
public authenticated() {
// Check if there's an unexpired JWT
// This searches for an item in localStorage with key == 'id_token'
return tokenNotExpired();
};
public logout() {
// Remove token from localStorage
localStorage.removeItem('id_token');
};
}
I injected the services and configured providers. Everything is wired correctly, but it just won't find Auth0Lock even though defined.
Each time it reaches lock = new Auth0Lock('ID', 'DOMAIN', {}); it bombs out.

I replaced declare var Auth0Lock: any; with const Auth0Lock = require('auth0-lock').default; and that fixed the problem.

The accepted answer is good. I did get a Cannot find name 'require' error.
Rather than using 'declare const require', I imported like so:
import Auth0Lock from 'auth0-lock';

I needed to add to index.html:
<script src="https://cdn.auth0.com/js/lock/10.8/lock.min.js"></script>
via https://github.com/auth0/lock/issues/588

Related

NextJS consistently access request object for every page

I'm using express + passport + nextjs to set up an app that will perform authentication using OpenID Connect. The user data is stored on the request object using express-session which gives me req.user on every request as usual.
Now I want to pass the user information to the front-end so that I can use it for something, but there does not seem to be any consistent way to do this for all requests. I can use getServerSideProps for individual pages, but not for every page through either _document or _app. How can I set this up?
Here is my current _document.tsx
import Document, {
Head,
Main,
NextScript,
DocumentContext,
} from "next/document"
export default class Doc extends Document {
public static async getInitialProps(ctx: DocumentContext) {
const req: any = ctx.req
console.log("req/user", `${!!req}/${!!(req && req.user)}`)
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
user: req?.user || "no user",
}
}
public render() {
return (
<html>
<Head />
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
It appears to return a request object only during the very first request, not any subsequent refreshes of the page.
I've created a small repo that reproduces the issue here: https://github.com/rudfoss/next-server-custom-req
It seems ridiculous that there is no way to do this for all pages in an easy manner.
Edit: For reference this is my server.js. It is the only other relevant file in the repo
const express = require("express")
const next = require("next")
const dev = process.env.NODE_ENV !== "production"
const start = async () => {
console.log("booting...")
const server = express()
const app = next({ dev, dir: __dirname })
const handle = app.getRequestHandler()
await app.prepare()
server.use((req, res, next) => {
req.user = {
authenticated: false,
name: "John Doe",
}
next()
})
server.get("*", handle)
server.listen(3000, (err) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log("ready")
})
}
start().catch((error) => {
console.error(error)
process.exit(1)
})
It is recommended to do this via function components, as seen in the Next.js custom App docs:
// /pages/_app.tsx
import App, { AppProps, AppContext } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
MyApp.getInitialProps = async (appContext: AppContext) => {
// calls page's `getInitialProps` and fills `appProps.pageProps`
const appProps = await App.getInitialProps(appContext)
const req = appContext.ctx.req
return {
pageProps: {
...appProps.pageProps,
user: req?.user,
},
}
}
As in your answer, this will run on every request though so automatic static optimization will not be active.
Try a demo of changing pageProps in MyApp.getInitialProps (without usage of req.user) on the following CodeSandbox:
https://codesandbox.io/s/competent-thompson-l9r1u?file=/pages/_app.js
Turns out I can override getInitialProps on _app to make this work:
class MyApp extends App {
public static async getInitialProps({
ctx
}: AppContext): Promise<AppInitialProps> {
const req: any = ctx.req
return {
pageProps: {
user: req?.user
}
}
}
public render() {
//...
}
}
This will run on every request though so static optimization will not work, but in my case I need the information so I'm willing to accept the trade-off.
Edit: This answer also works, but it uses the "old" class-based component syntax which is no longer recommended. See answer from Karl for a more modern version using functional-component syntax.
I also had the similar problem where I had to fetch loggedIn user details from my Auth api. I solved it by wrapping my whole app inside a context provider, then using a set function for the initialState, which will remember if it was called before and fetch user details only once. Then in my each page, wherever I require these user details, I used the context to see if details are available and call the set function if details are not available. This way I think I achieved:
Only one request to fetch user details
Because it happens from the client side, TTFB is better
I can still take advantage of getStaticProps and getServerSideProps where it is required.

auth0 get profile information backside

I'm trying to get user profile information from Auth0. It works in the frontend with the pipe Async
<pre *ngIf="auth.userProfile$ | async as profile">
<code>{{ profile | json }}</code>
</pre>
But in the backend If I want to read the nickname and do something with it. I'm lost.
constructor(public auth: AuthService)
ngOnInit() {
if (this.auth.isAuthenticated$) {
const result = this.auth.userProfile$;
}
}
I know that my varibale "result" is an Observable.
But I'm new with this stuff of Observable. And I try to get the value.
If I use the debug console, I can see the value with this line :
this.auth.userProfile$.source.value.nickname
But If I wrote it in my code, I have this error: Typescript error: Property 'value' does not exist on type 'Observable'
ngOnInit() {
if (this.auth.isAuthenticated$) {
const result = this.auth.userProfile$;
console.log(this.auth.userProfile$.source.value.nickname); // error here
}
}
So someone can help me with this ?
thanks
You access data within an observable by subscribing to it (this is what the async pipe does under the hood).
Here's an example for how to subscribe to your observable:
// import { tap } from 'rxjs/operators';
// tap is one of many rxjs operators
// operators allow you to perform operations on data within observables
this.auth.userProfile$.pipe(
tap(profile => {
console.log(profile);
})
)
.subscribe(); // this is what allows you access the data within the observable
Observables: https://angular.io/guide/observables
RXJS Operators: https://rxjs-dev.firebaseapp.com/guide/operators
I finally find a solution:
in the class I enter this code:
export class getInfo implements OnInit {
private login_info: any;
ngOnInit() {
this.auth.getUser$().subscribe(val => {
this.login_info = val;
console.log('print info', val.nickname);
});
}
}
public useInfo(status: string) {
console.log('print info', this.login_info.nickname);
}
So In the useInfo method, I can use the information that I grabbed from the user profile.

Vuex-module-decorator, modifying state inside an action

Using the vuex-module-decorator I have a authenticate action that should mutate the state.
#Action
public authenticate(email: string, password: string): Promise<Principal> {
this.principal = null;
return authenticator
.authenticate(email, password)
.then(auth => {
const principal = new Principal(auth.username);
this.context.commit('setPrincipal', principal);
return principal;
})
.catch(error => {
this.context.commit('setError', error);
return error;
});
}
// mutations for error and principal
But this fail with the following message:
Unhandled promise rejection Error: "ERR_ACTION_ACCESS_UNDEFINED: Are you trying to access this.someMutation() or this.someGetter inside an #Action?
That works only in dynamic modules.
If not dynamic use this.context.commit("mutationName", payload) and this.context.getters["getterName"]
What I don't understand is that it works well with #MutationAction and async. However I miss the return type Promise<Principal>.
#MutationAction
public async authenticate(email: string, password: string) {
this.principal = null;
try {
const auth = await authenticator.authenticate(email, password);
return { principal: new Principal(auth.username), error: null };
} catch (ex) {
const error = ex as Error;
return { principal: null, error };
}
}
--
At this time I feel blocked and would like to have some help to implement an #Action that can mutate the state and return a specific type in a Promise.
Just add rawError option to the annotation so it becomes
#Action({rawError: true})
And it display error normally. this is because the the library "vuex-module-decorators" wrap error so by doing this you will able to get a RawError that you can work with
You can vote down this answer if you would like because it isn't answering the specific question being posed. Instead, I am going to suggest that if you are using typescript, then don't use vuex. I have spent the past month trying to learn vue /vuex and typescript. The one thing I am committed to is using typescript because I am a firm believer in the benefits of using typescript. I will never use raw javascript again.
If somebody would have told me to not use vuex from the beginning, I would have saved myself 3 of the past 4 weeks. So I am here to try and share that insight with others.
The key is Vue 3's new ref implementation. It is what really changes the game for vuex and typescript. It allows us to not have to rely on vuex to automatically wrap state in a reactive. Instead, we can do that ourselves with the ref construct in vue 3. Here is a small example from my app that uses ref and a typescript class where I was expecting to use vuex in the past.
NOTE1: the one thing you lose when using this approach is vuex dev tools.
NOTE2: I might be biased as I am ported 25,000 lines of typescript (with 7000 unit tests) from Knockout.js to Vue. Knockout.js was all about providing Observables (Vue's ref) and binding. Looking back, it was kind of ahead of its time, but it didn't get the following and support.
Ok, lets create a vuex module class that doesn't use vuex. Put this in appStore.ts. To simplify it will just include the user info and the id of the club the user is logged into. A user can switch clubs so there is an action to do that.
export class AppClass {
public loaded: Ref<boolean>;
public userId: Ref<number>;
public userFirstName: Ref<string>;
public userLastName: Ref<string>;
// Getters are computed if you want to use them in components
public userName: Ref<string>;
constructor() {
this.loaded = ref(false);
initializeFromServer()
.then(info: SomeTypeWithSettingsFromServer) => {
this.userId = ref(info.userId);
this.userFirstName = ref(info.userFirstName);
this.userLastName = ref(info.userLastName);
this.userName = computed<string>(() =>
return this.userFirstName.value + ' ' + this.userLastName.value;
}
}
.catch(/* do some error handling here */);
}
private initializeFromServer(): Promise<SomeTypeWithSettingsFromServer> {
return axios.get('url').then((response) => response.data);
}
// This is a getter that you don't need to be reactive
public fullName(): string {
return this.userFirstName.value + ' ' + this.userLastName.value;
}
public switchToClub(clubId: number): Promise<any> {
return axios.post('switch url')
.then((data: clubInfo) => {
// do some processing here
}
.catch(// do some error handling here);
}
}
export appModule = new AppClass();
Then when you want to access appModule anywhere, you end up doing this:
import { appModule } from 'AppStore';
...
if (appModule.loaded.value) {
const userName = appModule.fullName();
}
or in a compositionApi based component. This is what would replace mapActions etc.
<script lang="ts">
import { defineComponent } from '#vue/composition-api';
import { appModule } from '#/store/appStore';
import footer from './footer/footer.vue';
export default defineComponent({
name: 'App',
components: { sfooter: footer },
props: {},
setup() {
return { ...appModule }
}
});
</script>
and now you can use userId, userFirstName, userName etc in your template.
Hope that helps.
I just added the computed getter. I need to test if that is really needed. It might not be needed because you might be able to just reference fullName() in your template and since fullName() references the .value variables of the other refs, fullName might become a reference itself. But I have to check that out first.
I sugest this simple solution, work fine for me 👌:
// In SomeClassComponent.vue
import { getModule } from "vuex-module-decorators";
import YourModule from "#/store/YourModule";
someMethod() {
const moduleStore = getModule(YourModule, this.$store);
moduleStore.someAction();
}
If the action has parameters, put them.
Taken from: https://github.com/championswimmer/vuex-module-decorators/issues/86#issuecomment-464027359

How to instantiate an instance of a class that uses redux Connect

I have an API class that has various methods that communicate to a backend like "login, register, createPost" etc. I am connecting this class to a reducer. The reducer contains the state of the user info, which I want to be accessible in my Api class:
import axios from 'axios';
import React, { Component } from 'react';
import { connect } from 'react-redux';
#connect(state => ({
api: state.api,
}) )
export default class Api extends Component {
export const login = async({args}) => {
const url = this.props.api.url.concat('/login/');
const config = {
headers: {
'X-CSRFTOKEN': this.props.api.token
}
};
try {
const data = await axios.post(url, {"username": args.username, "password": args.password}, config);
this.props.api.key = data.data.token;
this.props.api.user = data.data.user;
return data;
} catch (e) {
throw e;
}
}
};
async createPost(args (content of the post)) {
try {
const url = this.props.api.url.concat('/post/PostList');
const Response = await axios.post(url, {...args}, !**this.props.api.key**! );
return Response;
} catch (e) {
throw e;
}
}
In the first method, I set the imported state.key and state.user (connected via redux) information, and I want to access that in the second method (this.props.api.key I surrounded by stars). I am trying to do it this way because I have a multitude of actions on different screens, and users have to pass their authentication information to the api method they're calling on top of whatever they're trying to do in order to be able to execute whatever respective action. I figure that it's easier to pass the user info in my Api class instead of importing the Api state into every different file I call the actions in.
The issue I'm running into is I can't instantiate a new object of api like
const api = new Api();
Because it gives me an error "cannot read property store of undefined," so I can't call the actions api.login(withArgs) in respective files, and if I make the methods static they won't have access to this.props.whatever
How do I instantiate a class that's connected to the global state of redux, or how can I access the info in that global state outside of my reducer file?
Since Api extends React.Component, why are you trying to instantiate the class yourself vs. letting React render it for you?
ReactDOM.render(<Api store={store} />)
or if you are not using JSX
ReactDOM.render(React.createElement(Api, { store })

Auth2 Object unidentified when trying to sign out (Angular2)

Good Day,
I am trying to sign out an auth2 client. This process was working fine before I upgraded my router to fit in with new RC requirements. Now it seems as if the auth2 object is cleared or lost along the way from signing in to signing out.
Here is my sign out tag:
<a role="button" (click)="signOut()" style="padding-left: 30px;">Log out</a>
it simply calls a signOut() function found in navbar.component.ts (See below)
signOut() {
var auth2 = this._navigationService.getAuth2();
auth2.signOut().then(function () {
});
console.log('User signed out.');
sessionStorage.clear();
localStorage.clear();
this.router.navigate(['Login'])
window.location.reload()
}
here is the navigationService code it is calling:
import { Injectable } from '#angular/core';
#Injectable()
export class NavigationService {
onEditMode:boolean;
auth2:any;
constructor() {
this.onEditMode=true;
}
getEditMode(){
return this.onEditMode;
}
setEditMode(editMode:boolean){
this.onEditMode=editMode;
}
setAuth2(auth2:any){
this.auth2=auth2;
}
getAuth2(){
return this.auth2;
}
}
Here is my login.component.ts which sets the auth2 object seen in navigationService.ts:
onGoogleLoginSuccess = (loggedInUser) => {
this.isLoading=true;
console.log(loggedInUser)
this._navigationService.setAuth2(gapi.auth2.getAuthInstance());
console.log("Google gapi" + gapi.auth2.getAuthInstance());
sessionStorage.setItem('gapi',gapi.auth2.getAuthInstance());
this._zone.run(() => {
this.userAuthToken = loggedInUser.hg.access_token;
this.userDisplayName = loggedInUser.getBasicProfile().getName();
var strClientID = document.getElementsByTagName('meta')['google-signin-client_id'].getAttribute('content')
this.objTrimbleAuthentication.ClientID = document.getElementsByTagName('meta')['google-signin-client_id'].getAttribute('content');
this.objTrimbleAuthentication.IDToken = loggedInUser.getAuthResponse().id_token;
this._trimbleAuthenticationService.sendAndVerify(this.objTrimbleAuthentication).subscribe(data=>{
if(data.tokenIsValid==true){
sessionStorage.setItem('S_USER_EMAIL',loggedInUser.getBasicProfile().getEmail());
sessionStorage.setItem('S_USER_NAME',loggedInUser.getBasicProfile().getName());
sessionStorage.setItem('S_ID_TOKEN',this.userAuthToken);
this.objExternalBindingModel.ExternalAccessToken=this.userAuthToken;
this.objExternalBindingModel.Provider="Google";
this.objExternalBindingModel.UserName = loggedInUser.getBasicProfile().getName();
this._LoginService.obtainLocalAccessToken(this.objExternalBindingModel).subscribe(data=>{
// console.log(data);
this.isLoading=false;
this._router.navigate(['/Home']);
sessionStorage.setItem("access_token",data.access_token);
},error=>{
console.log(error);
})
}else{
this.isLoading= false;
this.showModal('#trimbleAuthError');
}
}, error=>{
})
});
}
onGoogleLoginSuccess is called from login.component.html:
<div style="margin-left:8% !important" id="{{googleLoginButtonId}}"></div>
So this process was working fine until I update my router to use the latest Angular2 Release Candidate. I am out of ideas on what could possibly be causing the following error when I click the sign out button:
Error in component.html/navbar.component.html:12:33
ORIGINAL EXCEPTION: TypeError: Cannot read property 'signOut' of undefined
if you need any other information or components please ask I hope I have given enough information. As I said it was working so keep that in mind, please.
Update
Waiting for additional info ...
In the following code, auth2:any; is undeclared. Is setAuth2 called anywhere before signOut()?
import { Injectable } from '#angular/core';
#Injectable()
export class NavigationService {
onEditMode:boolean;
auth2:any;
constructor() {
this.onEditMode=true;
}
getEditMode(){
return this.onEditMode;
}
setEditMode(editMode:boolean){
this.onEditMode=editMode;
}
setAuth2(auth2:any){
this.auth2=auth2;
}
getAuth2(){
return this.auth2;
}
}
Base on limited information and code posted, my guess is a logical bug in the logout process.
In signOut(), the window.location.reload() reload the page at the current url, which also clear all variables/objects. However, after reload, your app properly try to do signout again (due to url?).
In your navbar.component, you may need to add more logic in ngInit() to handle the situation.
Or can your code work without window.location.reload()? It seems odd to use that with angular2, especially with routing.
Right, the solution i found to the above question was that signing out using localhost will not work. So i just used this block of code when deploying the website and keep it commented out when running the website on localhost.
this is my signOut() function found in navbar.component.ts:
signOut() {
//////////////////////////////////////// Uncomment block for live deployment //////////////////////////////
// var auth2 = gapi.auth2.getAuthInstance();
// auth2.signOut().then(function () {
// console.log('User signed out.');
// });
//////////////////////////////////////////////////////////////////////////////////////////////////////////
sessionStorage.clear();
localStorage.clear();
this.router.navigate(['/']);
window.location.reload();
}
although getAuthInstance gives an error when trying to run it in localhost, deploying the web application to a server seems to work fine.