Código de classe Helper (Vue
AppStroage.js
class AppStroage{
storeToken(token) {
localStorage.setItem('token', token);
}
storeUser(user){
localStorage.setItem('user', user)
}
store(token,user){
this.storeToken(token)
this.storeUser(user)
}
getToken(){
localStorage.getItem('token')
}
getUser(){
localStorage.getItem('user')
}
clear(){
localStorage.removeItem('token')
localStorage.removeItem('user')
}
}
export default AppStroage = new AppStroage();
Token.js
class Token{
isValid(token){
const payload = this.payload(token);
if(payload){
return payload.iss == "http://localhost:8000/api/auth/login" || "http://localhost:8000/api/auth/register" ? true : false;
}
return false;
}
payload(token){
const payload = token.split('.')[1];
return this.decode(payload)
}
decode(payload){
console.log(payload);
return JSON.parse(atob(payload));
}
}
export default Token = new Token();
App.js
import AppStroage from "./AppStroage"
import Token from "./Token"
class User {
responseAfterLogin(res) {
const access_token = res.data.access_token
const username = res.data.name
console.log(username)
console.log(access_token)
if (Token.isValid(access_token)) {
AppStroage.store(access_token, username);
}
}
hasToken() {
const storeToken = localStorage.getItem("token");
if (storeToken) {
return Token.isValid(storeToken) ? true : false;
}
return false;
}
logedIn() {
return this.hasToken();
}
logedOut() {
AppStroage.clear();
window.location = '/';
}
name() {
if (this.logedIn) {
return localStorage.getItem("user");
}
}
id() {
if (this.logedIn) {
const payload = Token.payload(localStorage.getItem("token"));
return payload.sub;
}
}
}
export default User = new User();
YellowSnowman85