I created a login page on my mobile app using a node js file to test the credentials. If the credentials are correct you get to the homepage, but It doesn’t remember the logged-in user, so every time you clean the RAM you have to login again.
I'm trying to save the token I get back from the backend in the device using @ionic/storage, but that's how far I can go on the logic and code. I don't really know what to do with the token. Some explaining of the logic could help a lot, or some code, or a link. I would really appreciate any help I can get!
I’m using Ionic Angular [5] and Capacitor.
My code if needed:
.ts file
senduserdata(){
var dataToSend = {
username:this.Username,
password:this.Password,
usertype:this.getSelectedSubject,
}
var url = 'http://localhost:3000/login';
this.http.post(url,{data:JSON.stringify(dataToSend)},{responseType: 'text'}).subscribe(
(data)=>{
let decoded = helper.decodeToken(data);
console.log('Decoded: ', decoded);
//the code to save it in storage
this.storage.set('loggedToken', decoded);
if(decoded.usertype === "Customer")
{
alert('Hello Customer')
}
else if(decoded.usertype === "Staff")
{
alert('Hello Staff')
}
}
)
}
node js file
//Login
app.post('/login', function (_req, res) {
var data = JSON.parse(_req.body.data);
var username = data.username;
var password = data.password;
var usertype = data.usertype;
mysqlConnection.connect(function () {
if(usertype ==="Customer"){
var query = "SELECT * from " + usertype + " Where Username = '" + username + "' And Password = '" + sha1(password) + "'";
}
else{
var query = "SELECT * from Staff Where Username = '" + username + "' And Password = '" + password + "'";
}
mysqlConnection.query(query, function (err, results, _fields) {
if (err) {
res.send(err);
}
else {
if (results.length > 0 && usertype === "Customer") {
if(results[0].Subscription === "True"){
passs = sha1(password)
const token = jwt.sign({username, passs, usertype}, 'my_secret_key_customer');
console.log(token);
res.send(token);
}
else{
console.log("Email not verified!");
res.send('Email not verified! Check your email for the verification email!');
}
}
else if (results.length > 0 && usertype === "Staff") {
passs = sha1(password)
const token1 = jwt.sign({username, passs, usertype}, 'my_secret_key_staff');
console.log(token1);
res.send(token1);
}
else {
console.log("The password or username is incorrect!");
res.send('The Password or Username is incorrect!');
}
}
})
})
});
you can use that decoded value that you saved in ionic storage as and 'id' of the user (you can read about JWT that is a way of doing this that is a standard) so you can use that value when making new requests to your node-js server so you can know which user is sending the request (it is the equivalent of been logged in on REST). you can also use the value to change which is the default page of the app when you are logged in (login page when not logged in and home page when logged in for example.)