Skip to content

Commit

Permalink
Developing Auth Features: added User to Global Scope & mechanism to log
Browse files Browse the repository at this point in the history
  • Loading branch information
jonatanvicente committed Jan 29, 2024
1 parent 41d3d61 commit 1134904
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 126 deletions.
23 changes: 7 additions & 16 deletions src/app/interceptors/jwt-interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,19 @@ const TOKEN = environment.BACKEND_TOKEN;
})
export class JwtInterceptor implements HttpInterceptor {


constructor(private router: Router,
private authService: AuthService) { }
private authService: AuthService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

console.log('***************************INTERCEPTOR');



/* const currentUser = this.authService.currentUser;
const isLoggedIn = currentUser && currentUser.token;
const isApiUrl = request.url.startsWith(environment.BACKEND_ITA_SSO_BASE_URL);*/
const currentUser = this.authService.currentUser;

/* console.log(currentUser);
console.log(isLoggedIn);
console.log(isApiUrl);*/
console.log("~~~~~~~~~~~"+JSON.stringify(currentUser));

/* if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: { Authorization: `Bearer ${currentUser.token}` }
});
}*/
this.authService.user.subscribe((user) => {
console.log("#########"+JSON.stringify(user));
});

return next.handle(request);
}
Expand Down
28 changes: 12 additions & 16 deletions src/app/models/user.model.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
export class User {
dni: string;
email: string;
password: string;
confirmPassword: string;
token?: string;
idUser: string;
dni?: string;
email?: string;
password?: string;
confirmPassword?: string;
itineraryId?: string;
name?: string;
accept?: boolean;

constructor(
dni: string,
email: string,
password: string,
confirmPassword: string,
itineraryId?: string,
// name: string,
// accept: boolean
idUser: string,
dni?: string,
email?: string,
password?: string,
confirmPassword?: string,
itineraryId?: string
) {
this.idUser = idUser;
this.dni = dni;
this.email = email;
this.password = password;
this.confirmPassword = confirmPassword;
this.itineraryId = itineraryId;
// this.name = name;
// this.accept = accept;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class RegisterModalComponent {

register() {
console.log("Valores del formulario:", this.registerForm.value);
if (this.registerForm.valid) {
/* if (this.registerForm.valid) {
const user = new User(
this.registerForm.get("dni")?.value ?? "", // Usa '' como valor predeterminado
this.registerForm.get("email")?.value ?? "", // Usa '' como valor predeterminado
Expand All @@ -41,16 +41,16 @@ export class RegisterModalComponent {
// Agrega el itineraryId desde environment
user.itineraryId = environment.ITINERARY_ID;
console.log('from register-modal********', user)
console.log('from register-modal********', user)*/
/* this.authService.register(user).subscribe({
next: (userData) => {console.log('userData ' , userData)},
error: (errorData) => {
console.error("Error during registration", errorData);
this.registerError = errorData.error || 'Error en el registro'; // Accede a la propiedad error de HttpErrorResponse
},
});*/
}
});
}*/
this.closeModal();
}
closeModal() {
Expand Down
114 changes: 24 additions & 90 deletions src/app/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,113 +17,47 @@ import { Router } from "@angular/router";
@Injectable()
export class AuthService {

/* private userSubject: BehaviorSubject<User>;
public user: Observable<User>;*/
private readonly anonym: string = "anonym";
private userSubject: BehaviorSubject<User>;
public user: Observable<User>;

constructor(private http: HttpClient, private router: Router) {
//this.userSubject = new BehaviorSubject(JSON.parse(localStorage.getItem("user")!));

//console.log("*******"+JSON.stringify(this.userSubject));
//this.user = this.userSubject.asObservable();
this.userSubject = new BehaviorSubject(JSON.parse(localStorage.getItem("user")!));
this.user = this.userSubject.asObservable();
}

/*public get currentUser(): User {
/**
* Creates a new anonymous user if there is no user in the local storage.
*/
public get currentUser(): User {
if(this.userSubject.value===null) {
this.userSubject.next(new User(this.anonym));
localStorage.setItem("user", JSON.stringify(this.userSubject.value));
}
return this.userSubject.value;
}

public login(dni: string, password: string): Observable<User> {
return this.http.post<User>(
`${environment.BACKEND_ITA_SSO_BASE_URL}${environment.BACKEND_SSO_LOGIN}`,
{ dni, password }
)
.pipe(
map((user) => {
this.setLocalStorage(user);
return user;
}),
catchError((error: HttpErrorResponse) => {
return throwError(error);
})
);
}
/**
* Register a user and log in with the new user. Set new user as current user.
*/
public register(dni: string, email:string, password: string, confirmPassword:string){

public register(user: User): Observable<void> {
user.itineraryId = environment.ITINERARY_ID;

return this.http.post<void>(`${environment.BACKEND_ITA_SSO_BASE_URL}${environment.BACKEND_SSO_REGISTER}`,
user
)
.pipe(
tap((authResult: any) => {
if (authResult) {
this.setLocalStorage(authResult);
} else {
}
}),
catchError((error: HttpErrorResponse) => {
return throwError(error);
})
);
}

private setLocalStorage(authResult: any) {
if (authResult) {
const expiresAt = add(new Date(), { seconds: 5 });
localStorage.setItem("authToken", authResult.authToken);
localStorage.setItem("refreshToken", authResult.refreshToken);
localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()));
} else {
throw new Error("Invalid authentication result: no data found");
}
this.isLoggedIn();
/**
* Log in with a user. Set user as current user.
*/
public login(dni: string, password: string) {

}


public logout() {
localStorage.removeItem("user");
localStorage.removeItem("authToken");
localStorage.removeItem("refreshToken");
localStorage.removeItem("expires_at");
}

public isLoggedIn(): Observable<boolean> {
const token = localStorage.getItem("authToken") ?? "";
const refreshToken = localStorage.getItem("refreshToken");
if (!token && !refreshToken) {
return of(false);
}
if (token && refreshToken) {
}
return this.validateTokenOnServer(token);
}
private validateTokenOnServer(token: string): Observable<boolean> {
return this.http
.post<boolean>(
"https://dev.sso.itawiki.eurecatacademy.org/api/v1/tokens/validate",
{ token }
)
.pipe(
map((isValid) => {
if (!isValid) {
this.logout();
}
return isValid;
}),
catchError((error) => {
this.logout();
return of(false);
})
);
}
public isLoggedOut() {
return !this.isLoggedIn();
}
public getExpiration() {
const expiration = localStorage.getItem("expires_at");
return expiration != null ? JSON.parse(expiration) : null;
}*/
}

0 comments on commit 1134904

Please sign in to comment.