ember-simple-auth + oauth2 : session lost on refresh - oauth-2.0

I read that session restore is supposed to work out of the box, but it doesn't for me, and I can't find what I did wrong.
authenticators/oauth2.js :
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default OAuth2PasswordGrant.extend({
serverTokenEndpoint: '/oauth/token'
});
routes/application.js :
import Route from '#ember/routing/route';
import { inject as service } from '#ember/service';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Route.extend(ApplicationRouteMixin, {
currentUser: service(),
beforeModel() {
return this._loadCurrentUser();
},
sessionAuthenticated() {
this._super(...arguments);
this._loadCurrentUser();
},
_loadCurrentUser() {
return this.get('currentUser').load().catch(() => this.get('session').invalidate());
}
});
services/current-user.js :
import Service from '#ember/service';
import { inject as service } from '#ember/service';
import RSVP from 'rsvp';
export default Service.extend({
session: service('session'),
store: service(),
load() {
if (this.get('session.isAuthenticated')) {
return this.get('store').queryRecord('user', { me: true }).then((user) => {
this.set('user', user);
});
} else {
return RSVP.resolve();
}
}
});

The simple way is to implement the restore method or you just overwrite restore() with your custom authenticator. Hope that's helpful.
you can also refer the link
https://github.com/simplabs/ember-simple-auth#implementing-a-custom-authenticator
This show the options how you can make it.
I will also provide you the example:
// app/authenticators/yours.js
restore() {
return new RSVP.Promise(res, rej){
return resolve(data);
}
}
This will store your session if you have already login

Related

react native google sign in - cannot press next, forgot email, or create account

image of simulator
unable to press the forgot email, create account or next button. When I press them there is no action, it stays on that same signin page. help, privacy and terms work.
wrote the function in the googlesignin.tsx file
import React, { Component } from 'react'
import { Button } from 'react-native'
import {
GoogleSignin,
statusCodes,
} from '#react-native-google-signin/google-signin';
export class GoogleSign extends Component {
constructor(props) {
super(props);
this.state = {
userInfo: null,
};
}
render() {
return(
<Button title={'Sign in with Google'} onPress={async () => {
GoogleSignin.configure({
iosClientId: '552669576534-ninopsfqvitpk59v9kt42mn0r2e4o37h.apps.googleusercontent.com',
webClientId: '552669576534-vpmbo9vbodnaeqghnjai6d0fhcl2enhc.apps.googleusercontent.com',
offlineAccess: true,
});
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
this.setState({userInfo});
console.log(userInfo);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
// user cancelled the login flow
} else if (error.code === statusCodes.IN_PROGRESS) {
// operation (e.g. sign in) is in progress already
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
} else {
// some other error happened
}
}
}}/>
);
}
}
I also have added my inverse url to the workspace.
Please refer this doc, you might have missed to configure signIn which is mandatory
import { GoogleSignin } from '#react-native-google-signin/google-signin';
GoogleSignin.configure();

In NestJS, param annotation is not working with controller

I am working on a simple project using NestJS.
I came here to ask for help because there was a problem while I was working on the project separating the controller and the service.
I am going to get the path value of the Get method from the controller and hand it over to the service.
In this process, the controller was set up as follows.
import { Controller, Get, Param, Post, Query } from '#nestjs/common';
import { AppService } from 'src/app.service.ts'
#Controller('app')
export class AppController {
constructor(private readonly appService: AppService) {}
#Get(':vendor/art/:artId')
findOneByVenderAndUid(
#Param('vender') vender: string,
#Param('artId') artId: string,
) {
return this.appService.findOneByVenderAndUid(vender, artId);
}
}
In addition, the global pipeline was set in main.ts as follows.
import { ValidationPipe } from '#nestjs/common';
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
await app.listen(3000);
}
bootstrap();
However, when I output the path value received from the service to the console, it appeared as undefined and could not be used.
Is there anything wrong with the part that I implemented?
Typo in the #Param(). The string passed to the annotation must mat ch the string used in the url. In this case :vendor does not match #Param('vender')

Nestjs - There is no matching event handler defined in the remote service

I'm trying to handle the message published on topic test_ack from online MQTT broker using microservices. But I'm getting the error.
There is no matching event handler defined in the remote service.
My Code:
main.ts
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '#nestjs/common/enums/transport.enum';
var url = 'mqtt://test.mosquitto.org';
async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.MQTT,
options: {
url: url
}
});
await app.listenAsync();
}
bootstrap();
app.controller.ts
import { Controller } from '#nestjs/common';
import { MessagePattern } from '#nestjs/microservices';
#Controller()
export class AppController {
constructor() {}
#MessagePattern('test')
ackMessageTestData(data:unknown) {
console.log(data.toString());
return 'Message Received';
}
}
As I don't have edit permission, I will post it as a new answer. As mentioned in the above answer. We have to use #EventPattern('test_ack').
The published message should be in format {data: 'Your message'} and should be serialized before publishing as mentioned here.
client.publish('test_ack', JSON.stringify({data: 'test data'})).

How to fix subscribe not exist in type void

I am new to angular 7 and didn't find any proper answer for similar questions posted.
I am getting Property 'subscribe' does not exist on type 'void' in angular-cli. I tried importing subscribe from rxjs but didn't find that library.
The problem is in the UpdateRecord Function!
product.component.ts code:
the code bellow is exist in compoent.ts of product
import { Component, OnInit } from '#angular/core';
import { ProductService } from 'src/app/shared/product.service';
import { NgForm } from '#angular/forms';
import { ToastrService } from 'ngx-toastr';
import { filter, map } from 'rxjs/operators';
#Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
constructor(private service : ProductService, private toastr : ToastrService) { }
ngOnInit() {
this.resetForm();
}
resetForm(form?: NgForm) {
if (form != null)
form.resetForm();
this.service.formData = {
ProductID: null,
ProductName: '',
ProductDescription: '',
Price: 0.00,
Image: '',
Qte: null
}
}
onSubmit(form: NgForm) {
if (form.value.ProductID == null)
this.insertRecord(form);
else
this.updateRecord(form);
}
insertRecord(form: NgForm) {
this.service.postProduct(form.value).subscribe(res => {
this.toastr.success('Inserted successfully', 'Product. Register');
this.resetForm(form);
this.service.refreshList();
});
}
updateRecord(form: NgForm) {
this.service.putProduct(form.value).subscribe(res => {
this.toastr.success('Updated successfully', 'Product. Update');
this.resetForm(form);
this.service.refreshList();
});
}
}
product.service.ts code :
the code bellow is exist in service file related to product
import { Injectable } from '#angular/core';
import { Product } from './product.model';
import { HttpClient } from "#angular/common/http";
#Injectable({
providedIn: 'root'
})
export class ProductService {
formData : Product
list : Product[]
readonly rootURL= 'http://localhost:50369/api'
constructor(private http : HttpClient) { }
postProduct(formData : Product){
return this.http.post(this.rootURL+'/Product', formData);
}
refreshList(){
return this.http.get(this.rootURL+'/Product')
.toPromise().then(res => this.list = res as Product[]);
}
putProduct(formData : Product){
this.http.put(this.rootURL+'/Product/'+formData.ProductID,FormData);
}
}
Thanks in advance,
I missed return :
So in putProduct function in product.service.ts is updated to be :
putProduct(formData : Product){
return this.http.put(this.rootURL+'/Product/'+formData.ProductID,FormData);
}
And it's working now!
Your HttpClient.put function seems to be incorrectly used (you are passing the class as parameter when you should be passing the object).
Look for the function updateHero() in this StackBlitz example.
/** PUT: update the hero on the server. Returns the updated hero upon success. */
updateHero (hero: Hero): Observable<Hero> {
httpOptions.headers =
httpOptions.headers.set('Authorization', 'my-new-auth-token');
return this.http.put<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('updateHero', hero))
);
}

Cannot read AsyncStorage value on React Native app startup

I am using React Native with Redux. The following code is used to create the Redux store, and uses AsyncStorage to check if the user is logged in by checking the presence of an authToken.
import {createStore} from 'redux';
import {persistStore} from 'redux-persist';
async function getAuthToken() {
return await AsyncStorage.getItem('authToken');
}
export function createStore(onCompletion:() => void):any {
...
const store = createStore(
reducer,
{
auth: {
authenticated: !!getAuthToken()
}
},
enhancer);
persistStore(store, {
storage: AsyncStorage,
},
onCompletion);
}
The creation of the store:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
store: createStore(...),
};
}
render() {
return (
<Provider store={this.state.store}>
<AppNavigator />
</Provider>
);
}
}
The authToken value get correctly set once the user logs in, and is removed once the user logs out. But the authToken does not get persisted after the app is relaunched. The first call to getAuthToken always returns this junk value from AsyncStorage:
{ _45: 0, _81: 0, _65: null, _54: null }
Why could this be happening?
Now you're returning a promise from AsyncStorage, you need to return the token value. Try:
async function getAuthToken() {
return await AsyncStorage.getItem('authToken').then((token) => token);
}
With hooks you useEffect
import AsyncStorage from '#react-native-async-storage/async-storage';
import { useState, useEffect } from 'react';
export function App() {
const [token, setToken] = useState<string>();
useEffect(()=>{
(async function() {
setToken(await AsyncStorage.getItem());
await SplashScreen.hideAsync();
})();
},[]);
if (token) {
return (<View><Text>{token}</Text></View>);
} else {
return null;
}
}

Resources