logout function refreshes the page but it's still logged in - javascript

I am following a course on Udemy, the instructor's side is using Angular 2 and I am trying to build the app using the latest version. The main problem I have, is that the logout function is accessed but because I have to refresh the page to display the login form again, for some reason, after the refresh, I see the login form but then it goes back to the part where I'm logged in.
Logout method on the back-end side:
#RequestMapping(value="/loggedOut", method=RequestMethod.POST)
public ResponseEntity logout(){
SecurityContextHolder.clearContext();
return new ResponseEntity("Logout Successfully!", HttpStatus.OK);
}
Logout function from my login service:
logOut() {
const url = 'http://localhost:8181/loggedOut';
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
'x-auth-token' : JSON.stringify(localStorage.getItem('xAuthToken')),
'Authorization' : basicHeader
});
return this.http.post(url, '', { headers, responseType: 'text'});
The button responsible for logging out:
logout() {
this.loginService.logOut().subscribe(
res => {
location.reload();
console.log("Logged out")
},
error => {
console.log(error)
}
);
Technically, it goes as follow: Logged in -> Login form -> Logged in
Logged in:
Log in form:
If I remove the reload method, I can see that the logout method is accessed and I get a 200 from the back-end.
Network tab before refreshing:
The server response before refreshing:

Try clearing out your localStorage when logging out:
localStorage.clear();
Basically, this removes any trace that the app left when logging in.

**Try This Approach **
logout() {
this.loginService.logOut().subscribe(
res => {
if(res) {
// clear localStorage
localStorage.clear();
//navigate to login component
this.router.navigate(['loginPagePathName']);
console.log("Logged out")
}
},
error => console.log(error));
}
We don't need to refresh the page
Note :- You can also clear the local storage whenever login component load into the browser simply put localStorage.clear() inside ngOnInit method of loginComponent

Related

Cookies not saved on mobile

I'm using next middleware to do protected routes and I'm using cookies to do the checking since you can use cookies on the server-side.
When a user logged in, I save the info on local storage(for all my frontend auth checks) and a cookie set to true if logged in(for server-side checking).
The issue is that when im on mobile, and a user logs in, the info is saved successfully. But if the user closes the browser(like safari) then opens it again and goes to the site, the user is still logged in but the Cookie doesnt seem to work(or is no longer there) but the localstorage still is there. Then this causes a case where the user is logged in but they cant access the logged in(protected) routes.
The following is my login in function
let loginUser = async (e) => {
e.preventDefault();
let response = await fetch(URL, {
method:'POST',
headers:{
'Content-Type': 'application/json'
},
body:JSON.stringify({'email':e.target.email.value, 'password':e.target.password.value})
})
if(response.ok){
let data = await response.json();
setAuthTokens(data);
localStorage.setItem("authTokens", JSON.stringify(data));
Cookies.set("auth", "true");
setUser(true);
setFailed(false);
router.push("/dashboard");
} else {
setFailed(true)
}
}
The following is my middleware
export default function middleware(req, event) {
let verify = req.cookies['auth']
const url = req.url
if (url.includes("/login") || url.includes("/signup")) {
if (verify) {
return NextResponse.redirect("some_url/dashboard");
}
}
if (url == "some_url" && verify) {
return NextResponse.redirect("some_url/dashboard");
}
if(url.includes("/dashboard")){
if(!verify){
return NextResponse.redirect("some_url/login");
}
}
}
This code may cause some security issues so I suggest you to set cookie from server also have an API for logout that clears cookie.
BTW if you don't set expire date in your cookie safari mobile will remove it.
You can do this by passing options to third argument of Cookies.set() .
It would be something like this:
Cookies.set('auth', 'true', { expires: 7 }); //expires 7 days from now

Redirect after logging in with $auth in nuxtjs

I'm having trouble redirecting my user when logging in with nuxt's default $auth configuration. Here's my problem:
Whenever I log in using the laravel/jwt provider, it redirects to my website home.
I have several points on the site where I need to open a modal with my login and I need to keep the user logged in on the same page he is on.
But I already tried to follow the documentation using the fake redirect flag and still I couldn't.
Is there any way to log in, if he is not on a specific page, such as the login page, he just refreshes instead of redirecting to the / route?
My usage:
async login() {
try {
this.loading(true)
await this.$auth.loginWith('laravelJWT', { data: this.form })
if (!this.redirectHome) {
this.$router.back()
this.$emit('is-logged')
}
} catch (error) {
this.loginError = true
} finally {
this.loading(false)
}
},
My resolution:
async login() {
await this.$auth
.loginWith('laravelJWT', { data: this.form })
.then(() => {
this.loading(true)
if (this.$route.name !== 'login') {
this.$router.go(this.$router.currentRoute)
}
this.$emit('is-logged')
})
.catch(() => {
this.loginError = true
})
.finally(() => {
this.loading(false)
})
},
use this.$auth.options.redirect = false before loginWith it will disable redirect.
when the promise resolved then you can call other api to refresh data or do whatever you want.

MSAL.js Twitter popup not redirecting after incorrect login attempt

I am using Azure MSAL library in a vanilla js application running in localhost and I step up with a problem in the login flow with Twitter.
I am using the loginPopup() approach and it seems to work fine. When I choose to sign in with Twitter it asks for my credentials and if I enter them right, the popup closes and the login works.
The problem is when I type the wrong credentials
It redirects me (inside the popup) to another Twitter page
Then if I enter the right credentials I get redirected to my page inside the popup window and it does not close itself. And on the original page, I am not logged in.
This the URL generated after the wrong redirect that stays in the popup and does not close itself.
https://localhost:3001/#state=asdasdasd...&client_info=asdasdasd....&code=asdasdasd...
This is my msalConfig:
export const msalConfig = {
auth: {
clientId: process.env.B2C_CLIENTID,
authority: process.env.B2C_AUTHORITY,
knownAuthorities: [process.env.B2C_KNOWN_AUTHORITIES],
redirectUri: process.env.B2C_REDIRECT_URL
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: false
}
};
And my login method:
constructor() {
this.account = null;
this.myMSALObj = new msal.PublicClientApplication(msalConfig);
this.myMSALObj.handleRedirectPromise()
.then((resp) => { this.handleResponse(resp); })
.catch(console.error);
}
loginWithTwitter() {
this.myMSALObj.loginPopup()
.then(response => {
utils.setSocialId(response.uniqueId);
utils.setSocialApplication(Constants.SOCIAL_APPLICATION.TWITTER);
const socialIdentity = {
email: response.idTokenClaims.emails[0],
name: response.idTokenClaims.name,
socialApplication: Constants.SOCIAL_APPLICATION.TWITTER,
userId: response.uniqueId
};
login.loginPlayerWithSocialIdentity(socialIdentity);
})
.catch(error => {
console.log(`Error signing in with Twitter: ${error}`);
});
}

not able to send request to express server using axios

I am building a chat application like whatsapp, & implementing the feature - when user clicks on any person's name, his chats appears, but can't able to send request to server when user clicks
Source code
There is div, when user will click on it, it will fetch data from server (onclick event handler) in Sidebar.js file -
{friends.map((e) => (
<div
onClick={getChatDetails}
key={e.friendName}
className='sidebar_chat_info'>
<Avatar />
<div>
<h2>{e.friendName}</h2>
<p>{getLastMessage()}</p>
</div>
</div>
))}
this is getChatDetails function in sidebar.js file
const getChatDetails = (e) => {
//console.log(e.target.textContent);
const Myfriend = e.target.textContent;
axios
.post('http://localhost:2000/message/get', { friend: Myfriend })
.then((response) => {
console.log(response);
})
.catch((error) => console.log(error));
};
At the server side , this is route in index.js file
Server is running on port 2000
app.post('/message/get', isloggedIn, async (req, res) => {
console.log('REQUESTED!');
try {
const conversation = await req.user.MyConversation.find(
(element) => element.friendName == req.body.friend
);
const messages = await conversationModel.findById(conversation.chats);
res.send(messages);
//await MessageModel.remove({})
} catch (error) {
res.status(500).send(error);
}
});
This is error on browser console , when I am clicking on div
But when I am sending request through postman, I am getting response
When I am sending request in other files (login.js), it's working there, don't know why it is not working only Sidebar.js file
The issue that you're having is that e in getChatDetails is undefined. The reason for this is is onclick does not pass an event object. In order to pass an event object to your sidebar function, you need to attach an event listener to it, which is a bit better than using onclick in most cases anyways (imo). Something like this:
const sidebar = document.getElementsByClassName('sidebar_chat_info')
for (let i = 0; i < sidebar.length; i++) {
sidebar[i].addEventListener('click', handleClick = e => {
//console.log(e.target.textContent);
const Myfriend = e.target.textContent;
axios
.post('http://localhost:2000/message/get', { friend: Myfriend })
.then((response) => {
console.log(response);
})
.catch((error) => console.log(error));
})
The middleware "isLoggedIn" causing issue. The problem was in my authentication part, when the user has been logged in then only he will see home page
index.js file at line 113
I added console.log and found that "NOT LOGGED IN " is displayed
function isloggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
console.log('NOT LOGGED IN !');
res.status(500).send('DENIED PERMISSION!');
}
}
I think it is happening because after logging in , I am redirecting to home page from
Login.js at line 59
history.push('/', { user: response.data });
const submitForm = async (e) => {
e.preventDefault();
axios
.post('http://localhost:2000/login', {
username: username,
password: password,
})
.then((response) => {
history.push('/', { user: response.data });
})
.catch((error) => setIsError(true));
//console.log(user.data); //user.data contains the details
//CALLING THE HOME PAGE AFTER SIGNUP & SENDING DETAILS OF CURRENT USER THERE !
//history.push('/', { user: user.data });
};
Maybe the request will be authenticated only from Login.js file, but I can't make other request from this file like getting chats details, sending message etc. I will have to go to home page . That's why I am redirecting to home page after logging in
On home page my request is not authenticated.
In postman all routes are working as I am not switching pages.
Login and logout routes are working as they are not taking in account "isLoggedIn"
Please suggest how to work with routes that needs authentication, like send message, gettingchats details?
PS - My request is even not authenticated from Login.js. After logging in, this time I didn't redirect to home page. I made request to route that needs authentication after logging in , it's still showing "NOT LOGGED IN" on server

How to use AsyncStorage in React-Native

I'm creating an Android App in React-Native.
This is my question:
I have basically 5 pages to manage the user:
1) Authentication ( in which I give the possibility to go to the Login or the SignUp)
2) Login Page
3) SignUp Page. In this page i set the value and then they are passed to the userPage.
4) User page. In this page I have the fetch to do a signup.
5) HomepageUser
In the User page I have the 2 function :
AsyncStorage.setItem
AsyncStorage.getItem
Like this
static async saveLoggedInUser(value) {
try {
await AsyncStorage.setItem("#loggedInUser", JSON.stringify(value));
} catch (error) {
console.log(error.message);
}
}
static async getUserLoggedIn() {
try {
return await AsyncStorage.getItem("#loggedInUser");
} catch (error) {
console.log(error.message);
return null;
}
}
Now My First page is the Authentication, how can I check if an user is already authenticated and then direct it to the HomepageUser??
Thanks you a lot!
On successful login you need to set user token in the Sign in page,
try {
await AsyncStorage.setItem('token', usertoken);
} catch (error) {
// Error saving data
}
Inside the componentDidMount method of your first page you need to check whether user token is set or not,
componentDidMount = async() =>{
try {
const value = await AsyncStorage.getItem('token');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
if token exist navigate to Home page or redirect to Sign in page.
There is an excellent documentation on Authentication flows with React navigation. You can check that if you are using React navigation for routing.
https://reactnavigation.org/docs/en/auth-flow.html

Categories

Resources