V
V
Vladimir Karpenko2017-09-04 18:01:13
Node.js
Vladimir Karpenko, 2017-09-04 18:01:13

React.JS/Redux authorization - what to do from the frontend?

I am doing an internship in an IT company as a front-end developer on React.js, I also use Redux in some places. The back end is written in Node.js + Express.js. Mongo is used as a database. Authorization is done using the session mechanism. I have a lot of questions: what do I need to do on the frontend to authorize a user, besides sending a login and password to the site, and then getting a response code to the request? How do I know if a user is currently logged in? The simplest way is desirable, because. little time left for the project. I don't understand Node.JS and Express.
So far, I just wrote this code for an authorization request:

$.post( "http://192.168.24.152:3000/login", userData)
  	  .done(function(data, textStatus, xhr) {
        sessionStorage.setItem('status','loggedIn')   			
  	  			if (sessionStorage.getItem('status') != null){
  	  				window.location.replace("/feed/ads");
  	  			}				   
      }	    
    )
    .fail(function(xhr) {
    	alert("Ошибка авторизации!");
    });
//А вот так проверяю, авторизован ли пользователь:
if (sessionStorage.getItem('status') != null))
    //пользователь авторизован
}
else{
    //ошибка авторизации
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrei Smirnov, 2017-09-04
@pinebit

Since you obviously don't know much about the subject, consider taking an off-the-shelf solution and integrating it properly. It will take a couple of hours, but the result will be better. In addition, in our era of integration, almost all tasks are somehow related to the skills of integrating one into another. It is unlikely that your company (if it is not some kind of Yandex) will write its authorization from scratch.
From what is easy and simple to integrate (and free): firebase. See examples here .

// зарегистрировать пользователя можно так (возвращает promise):
firebase.auth().createUserWithEmailAndPassword(email, password)
// залогиниться пользователь может так (возвращает promise)
firebase.auth().signInWithEmailAndPassword(email, password);
// ну и подписаться на событие успешной авторизации или потери сессии:
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
     // успешно авторизован, объект user содержит username и т.п.
     this.setState({
         ...this.state,
         user,
     });
  }
});

All. Create an account in firebase, add a new project and you're done.
There, even hosting will be free for your test application: just write `firebase deploy` in the console and your web-application will copy itself to the server.
The beauty! :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question