Skip to content

Commit

Permalink
created dummy with fake JSON data
Browse files Browse the repository at this point in the history
  • Loading branch information
valerioprds committed Nov 6, 2023
1 parent 31593d9 commit bc482c4
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 75 deletions.
13 changes: 6 additions & 7 deletions src/app/models/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ export class User {
email: string;
password: string;
confirmPassword: string;
token?: string;
// specialization?: string;
// name?: string;
// accept?: boolean;
//token?: string;
//specialization?: string;
//name?: string;
//accept?: boolean;

constructor(
dni: string,
email: string,
password: string,
confirmPassword: string,
confirmPassword: string
// specialization: string,
// name: string,
// accept: boolean
Expand All @@ -24,6 +24,5 @@ export class User {
// this.specialization = specialization;
// this.name = name;
// this.accept = accept;

}
}
}
156 changes: 88 additions & 68 deletions src/app/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,52 +4,57 @@ import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { environment } from "src/environments/environment";
import { BehaviorSubject, Observable, catchError, map, throwError } from "rxjs";
import { User } from "../models/user.model";
import { Router } from '@angular/router';
import { Router } from "@angular/router";

@Injectable()
export class AuthService {
// newUser: User | undefined;
private userSubject: BehaviorSubject<User>;
public user: Observable<User>;
// newUser: User | undefined;
private userSubject: BehaviorSubject<User>;
public user: Observable<User>;

/**
* Gives us access to the Angular HTTP client so we can make requests to
* our Express app
*/
constructor(private http: HttpClient, private router: Router) {
this.userSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('user')!));
this.user = this.userSubject.asObservable();
}
/**
* Gives us access to the Angular HTTP client so we can make requests to
* our Express app
*/
constructor(private http: HttpClient, private router: Router) {
this.userSubject = new BehaviorSubject(
JSON.parse(localStorage.getItem("user")!)
);
this.user = this.userSubject.asObservable();
}

public get currentUser(): User {
return this.userSubject.value;
}
public get currentUser(): User {
return this.userSubject.value;
}

/**
* Passes the username and password that the user typed into the application
* and sends a POST request to our Express server login route, which will
* authenticate the credentials and return a JWT token if they are valid
*
* The `res` object (has our JWT in it) is passed to the setLocalStorage
* method below
*
* shareReplay() documentation - https://www.learnrxjs.io/operators/multicasting/sharereplay.html
*/
login(dni: string, password: string): Observable<User> {
return this.http
.post<User>(`${environment.BACKEND_ITA_WIKI_BASE_URL}${environment.BACKEND_LOGIN}`, { dni, password })
.pipe(
map((user) => {
console.log(user)
this.setLocalStorage(user);
return user;
})
);
}
/**
* Passes the username and password that the user typed into the application
* and sends a POST request to our Express server login route, which will
* authenticate the credentials and return a JWT token if they are valid
*
* The `res` object (has our JWT in it) is passed to the setLocalStorage
* method below
*
* shareReplay() documentation - https://www.learnrxjs.io/operators/multicasting/sharereplay.html
*/
login(dni: string, password: string): Observable<User> {
return this.http
.post<User>(
`${environment.BACKEND_ITA_WIKI_BASE_URL}${environment.BACKEND_LOGIN}`,
{ dni, password }
)
.pipe(
map((user) => {
console.log(user);
this.setLocalStorage(user);
return user;
})
);
}

register(user: User): Observable<void> {
// const userJSON = user
console.log('from auth service register', user)
register(user: User): Observable<void> {
// const userJSON = user
/* console.log('from auth service register', user)
return this.http
.post<void>(
`${environment.BACKEND_ITA_WIKI_BASE_URL}${environment.BACKEND_REGISTER}`,
Expand All @@ -65,40 +70,55 @@ export class AuthService {
// Handle error here (show an error message)
return throwError(error);
})
);
}
); */
console.log('from auth service register', user);

private setLocalStorage(authResult: any) {
// Takes the JWT expiresIn value and add that number of seconds
// to the current "moment" in time to get an expiry date
const expiresAt = moment().add(authResult.expiresIn, "second");
// Simular la solicitud con datos de un archivo dummy
return this.http
.post('../assets/dummy/user-register.json', user)
.pipe(
map((authResult: any) => {
this.setLocalStorage(authResult); // Llama a setLocalStorage con el resultado de autenticación
console.log('from auth service ', authResult);
}),
catchError((error: HttpErrorResponse) => {
// Maneja el error aquí (muestra un mensaje de error)
console.log('porque da error', error)
return throwError(error);
})
);
}

// Stores our JWT token and its expiry date in localStorage
localStorage.setItem("id_token", authResult.idToken);
localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()));
}
private setLocalStorage(authResult: any) {
// Takes the JWT expiresIn value and add that number of seconds
// to the current "moment" in time to get an expiry date
const expiresAt = moment().add(authResult.expiresIn, "second");

// By removing the token from localStorage, we have essentially "lost" our
// JWT in space and will need to re-authenticate with the Express app to get
// another one.
logout() {
localStorage.removeItem("id_token");
localStorage.removeItem("expires_at");
}
// Stores our JWT token and its expiry date in localStorage
localStorage.setItem("id_token", authResult.idToken);
localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()));
}

// Returns true as long as the current time is less than the expiry date
public isLoggedIn() {
return moment().isBefore(this.getExpiration());
}
// By removing the token from localStorage, we have essentially "lost" our
// JWT in space and will need to re-authenticate with the Express app to get
// another one.
logout() {
localStorage.removeItem("id_token");
localStorage.removeItem("expires_at");
}

isLoggedOut() {
return !this.isLoggedIn();
}
// Returns true as long as the current time is less than the expiry date
public isLoggedIn() {
return moment().isBefore(this.getExpiration());
}

getExpiration() {
const expiration = localStorage.getItem("expires_at");
const expiresAt = expiration != null ? JSON.parse(expiration) : "";
return moment(expiresAt);
}
isLoggedOut() {
return !this.isLoggedIn();
}

getExpiration() {
const expiration = localStorage.getItem("expires_at");
const expiresAt = expiration != null ? JSON.parse(expiration) : "";
return moment(expiresAt);
}
}
10 changes: 10 additions & 0 deletions src/assets/dummy/user-register.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"dni": "01875580E",
"email": "julia123@gmail.cat",
"password": "test123",
"confirmPassword": "test123",
"specialization": "cln1fjzif000008mdcsfq64c2",
"name": "olivia",
"role": "ADMIN",
"accept": true
}

0 comments on commit bc482c4

Please sign in to comment.