Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature#462 #467

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, Input, inject } from '@angular/core'
import { ChangeDetectorRef, Component, Input, inject } from '@angular/core'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { SendSolutionModalComponent } from './../../../modals/send-solution-modal/send-solution-modal.component'
import { RestrictedModalComponent } from './../../../modals/restricted-modal/restricted-modal.component'
Expand All @@ -20,6 +20,7 @@ export class ChallengeHeaderComponent {
private readonly router = inject(Router)
private readonly translate = inject(TranslateService)
private readonly userService = inject(UserService)
private readonly cdr = inject(ChangeDetectorRef)

@Input() title = ''
@Input() creation_date!: Date
Expand All @@ -37,7 +38,12 @@ export class ChallengeHeaderComponent {
this.challenge_title = this.title
this.challenge_date = this.creation_date
this.challenge_level = this.level
this.isLogged = this.userService.isUserLoggedIn()

this.userService.userLoggedIn$.subscribe((loggedIn) => {
this.isLogged = loggedIn
// Forza il rilevamento delle modifiche se necessario
this.cdr.detectChanges()
})

this.solutionService.solutionSent$.subscribe((value) => {
this.solutionSent = value
Expand All @@ -58,7 +64,7 @@ export class ChallengeHeaderComponent {
size: 'lg'
})
} else {
this.solutionService.sendSolution('') // Puedes pasar la solución como argumento si es necesario
this.openSendSolutionModal()
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {
type AfterContentChecked,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
type OnInit,
Output,
ViewChild,
inject,
type OnInit
inject
} from '@angular/core'
import { type ChallengeDetails } from 'src/app/models/challenge-details.model'
import { type Example } from 'src/app/models/challenge-example.model'
Expand All @@ -16,21 +16,21 @@ import { type Subscription } from 'rxjs'
import { DataChallenge } from '../../../../models/data-challenge.model'
import { type Challenge } from '../../../../models/challenge.model'
import { NgbModal, type NgbNav } from '@ng-bootstrap/ng-bootstrap'
import { AuthService } from 'src/app/services/auth.service'
import { SolutionService } from 'src/app/services/solution.service'
import { SendSolutionModalComponent } from 'src/app/modules/modals/send-solution-modal/send-solution-modal.component'
import { RestrictedModalComponent } from 'src/app/modules/modals/restricted-modal/restricted-modal.component'
import { RelatedService } from '../../../../services/related.service'
import { type SolutionResults } from 'src/app/models/solution-results.model'
import { UserService } from 'src/app/services/user.service'
// import { UserService } from 'src/app/services/user.service'

@Component({
selector: 'app-challenge-info',
templateUrl: './challenge-info.component.html',
styleUrls: ['./challenge-info.component.scss'],
providers: [ChallengeService]
})
export class ChallengeInfoComponent
implements AfterContentChecked, OnInit {
export class ChallengeInfoComponent implements OnInit {
showStatement = true
isLogged: boolean = false
solutionSent: boolean = false
Expand All @@ -43,12 +43,12 @@ implements AfterContentChecked, OnInit {
challengeSolutions: SolutionResults[] = []
idLanguage: string = ''
userId!: string

private readonly authService = inject(AuthService)
private readonly challengeService = inject(ChallengeService)
private readonly userService = inject(UserService)
private readonly solutionService = inject(SolutionService)
private readonly modalService = inject(NgbModal)
private readonly relatedService = inject(RelatedService)
private readonly userService = inject(UserService)
private readonly cdr = inject(ChangeDetectorRef)

@ViewChild('nav') nav!: NgbNav

Expand All @@ -75,29 +75,36 @@ implements AfterContentChecked, OnInit {
// challengeSubs$!: Subscription

async ngOnInit (): Promise<void> {
// Sottoscrizione allo stato di login
this.userService.userLoggedIn$.subscribe((loggedIn) => {
this.isLogged = loggedIn
console.log('ChallengeInfoComponent: isLogged updated to', this.isLogged)
this.cdr.detectChanges() // Forza il rilevamento delle modifiche
})

// Sottoscrizione allo stato delle soluzioni
this.solutionService.solutionSent$.subscribe((value) => {
this.isUserSolution = !value
this.solutionSent = value
this.solutionSent = value
})

this.isLogged = this.userService.isUserLoggedIn()

this.loadRelatedChallenges(this.idChallenge)
}

ngAfterContentChecked (): void {
const token = localStorage.getItem('authToken') // TODO
const refreshToken = localStorage.getItem('refreshToken') // TODO00000000
// ngAfterContentChecked (): void {
// const token = localStorage.getItem('authToken') // TODO
// const refreshToken = localStorage.getItem('refreshToken') // TODO

if (
token !== null &&
refreshToken !== null &&
token !== '' &&
refreshToken !== ''
) {
this.isLogged = true
}
}
// if (
// token !== null &&
// refreshToken !== null &&
// token !== '' &&
// refreshToken !== ''
// ) {
// this.isLogged = true
// }
// }

loadRelatedChallenges (id: string): void {
this.challengeSubs$ = this.relatedService
Expand Down Expand Up @@ -129,15 +136,7 @@ implements AfterContentChecked, OnInit {
size: 'lg'
})
} else {
this.solutionService.sendSolution('') // Puedes pasar la solución como argumento si es necesario
this.openSendSolutionModal()
}
}

loadSolutions (idChallenge: string, idLanguage: string): void {
this.solutionService
.getAllChallengeSolutions(idChallenge, idLanguage)
.subscribe((data) => {
this.challengeSolutions = data.results
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { of } from 'rxjs'

import { LoginModalComponent } from './login-modal.component'
import { TranslateModule, TranslateService } from '@ngx-translate/core'
import { HttpClientTestingModule } from '@angular/common/http/testing'

describe('LoginModalComponent', () => {
let component: LoginModalComponent
Expand All @@ -31,7 +32,7 @@ describe('LoginModalComponent', () => {

await TestBed.configureTestingModule({
declarations: [LoginModalComponent],
imports: [FormsModule, ReactiveFormsModule, NgbModule, TranslateModule.forRoot()],
imports: [FormsModule, ReactiveFormsModule, NgbModule, TranslateModule.forRoot(), HttpClientTestingModule],
providers: [
FormBuilder,
{ provide: AuthService, useValue: authServiceMock },
Expand Down
15 changes: 12 additions & 3 deletions src/app/modules/modals/login-modal/login-modal.component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, inject } from '@angular/core'
import { Component, inject, NgZone } from '@angular/core'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { RegisterModalComponent } from '../register-modal/register-modal.component'
import { FormBuilder, Validators } from '@angular/forms'
Expand All @@ -8,6 +8,7 @@ import { type User } from 'src/app/models/user.model'
import { environment } from 'src/environments/environment'
import { TranslateService } from '@ngx-translate/core'
import { isValidDni, isValidInput, getInputError } from '../../../helpers/form-validator.helper'
import { UserService } from 'src/app/services/user.service'

@Component({
selector: 'app-login-modal',
Expand All @@ -18,8 +19,10 @@ export class LoginModalComponent {
private readonly modalService = inject(NgbModal)
private readonly formBuilder = inject(FormBuilder)
private readonly authService = inject(AuthService)
private readonly userService = inject(UserService)
private readonly router = inject(Router)
private readonly translate = inject(TranslateService)
private readonly ngZone = inject(NgZone)

loginError: string = ''

Expand All @@ -41,9 +44,15 @@ export class LoginModalComponent {

try {
const res = await this.authService.login(user)
this.openSuccessfulLoginModal(res)
this.ngZone.run(() => {
console.log('LoginModalComponent: Login successful')
this.userService.login()
this.openSuccessfulLoginModal(res)
})
} catch (err) {
this.notifyErrorLogin(err)
this.ngZone.run(() => {
this.notifyErrorLogin(err)
})
}
}
};
Expand Down
27 changes: 0 additions & 27 deletions src/app/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,3 @@
// import { add } from 'date-fns'
// import { AbstractType, Injectable } from '@angular/core'
// import { catchError, map, of, tap, throwError } from 'rxjs'
// import { ResolveEnd} from '@angular/router'
// import { fakeAsync } from '@angular/core/testing'
// import { BlobOptions } from 'buffer'
// import { error } from 'console'

import { HttpClient } from '@angular/common/http'
import { environment } from '../../environments/environment'
import { BehaviorSubject, type Observable, firstValueFrom } from 'rxjs'
Expand Down Expand Up @@ -228,23 +220,4 @@ export class AuthService {
})
})
}

/* Check if the user is Logged in */
// TODO: Desarrollar una vez validados los tokens. Por ahora, se usa solo cookie.service.
// public isUserLoggedIn (): boolean {
// const authToken = this.cookieService.get('authToken')
// if (authToken !== null && authToken !== undefined && authToken !== '') {
// console.log('is logged: true')
// return true
// }

// const refreshToken = this.cookieService.get('refreshToken')
// if (refreshToken !== null && refreshToken !== undefined && refreshToken !== '') {
// console.log('is logged: true')
// return true
// }

// console.log('is logged: false')
// return false
// }
}
53 changes: 28 additions & 25 deletions src/app/services/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,58 @@
import { Inject, Injectable } from '@angular/core'
import { AuthService } from './auth.service'
// import { type User } from '../models/user.model'
import { SolutionService } from './solution.service'
import { CookieService } from 'ngx-cookie-service'
import { BehaviorSubject, type Observable } from 'rxjs'

@Injectable({
providedIn: 'root'
})
export class UserService {
public userRegistered: boolean = false
public userLoggedIn: boolean = false
public userSentASolution: boolean = false
public userLoggedIn$: Observable<boolean>

// BehaviorSubject para estado de login
private readonly userLoggedInSubject: BehaviorSubject<boolean>

constructor (
@Inject(AuthService) private readonly authService: AuthService,
@Inject(CookieService) private readonly cookieService: CookieService,
@Inject(SolutionService) private readonly solutionService: SolutionService
) {}
) {
// Inicializa el BehaviorSubject con el estado de login
const isLoggedIn = this.checkLoginStatus()
this.userLoggedInSubject = new BehaviorSubject<boolean>(isLoggedIn)
this.userLoggedIn$ = this.userLoggedInSubject.asObservable()
}

public isUserLoggedIn (): boolean {
// metodo para verificar el estado de login
private checkLoginStatus (): boolean {
const authToken = this.cookieService.get('authToken')
if (authToken !== null && authToken !== undefined && authToken !== '') {
this.userLoggedIn = true
console.log(`userLoggedIn: ${this.userLoggedIn}`)
return true
}

const refreshToken = this.cookieService.get('refreshToken')
if (refreshToken !== null && refreshToken !== undefined && refreshToken !== '') {
this.userLoggedIn = true
console.log(`userLoggedIn: ${this.userLoggedIn}`)
return true
}

console.log(`userLoggedIn: ${this.userLoggedIn}`)
return false
return (authToken !== null && authToken !== undefined && authToken !== '') || (refreshToken !== null && refreshToken !== undefined && refreshToken !== '')
}

// public async login (user: User): Promise<void> {
// await this.authService.login(user)
// this.userLoggedIn = true
// console.log(`userLoggedIn: ${this.userLoggedIn}`)
// }
// metodo para actualizar el estado de login
public updateLoginStatus (isLoggedIn: boolean): void {
console.log('UserService.updateLoginStatus() called with:', isLoggedIn)
this.userLoggedInSubject.next(isLoggedIn)
}

// llamado después del login
public login (): void {
this.updateLoginStatus(true)
}

// llamado después del logout
public logout (): void {
console.log('UserService.login() called')
this.authService.logout()
this.userLoggedIn = false
this.updateLoginStatus(false)
this.userSentASolution = false
console.log(`userLoggedIn: ${this.userLoggedIn}`)
}

// metodo para monitorear el estado de la solución
public monitorSolutionState (): void {
this.solutionService.solutionSent$.subscribe((solutionSent) => {
this.userSentASolution = solutionSent
Expand Down