Skip to content

Commit

Permalink
3.1.29-RELEASE
Browse files Browse the repository at this point in the history
  • Loading branch information
jonatanvicente committed Nov 19, 2024
2 parents 041b05b + edaff51 commit 3b5a2ab
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 89 deletions.
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,8 +1,9 @@
import {
type AfterContentChecked,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
type OnInit,
Output,
ViewChild,
inject
Expand All @@ -15,28 +16,38 @@ 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 { UserService } from 'src/app/services/user.service'
import { type SolutionResults } from 'src/app/models/solution-results.model'

@Component({
selector: 'app-challenge-info',
templateUrl: './challenge-info.component.html',
styleUrls: ['./challenge-info.component.scss'],
providers: [ChallengeService]
})
export class ChallengeInfoComponent implements AfterContentChecked {
export class ChallengeInfoComponent implements OnInit {
showStatement = true
isLogged: boolean = false
solutionSent: boolean = false
isUserSolution: boolean = true
challengeSolutions: any[] = []
resources: string = ''
params$!: Subscription
relatedChallengesData!: DataChallenge
relatedListOfChallenges: Challenge[] = []
challengeSubs$!: Subscription
challengeSolutions: SolutionResults[] = []
idLanguage: string = ''
userId!: string
private readonly challengeService = inject(ChallengeService)
private readonly authService = inject(AuthService)
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 @@ -54,42 +65,49 @@ export class ChallengeInfoComponent implements AfterContentChecked {

solutionsDummy = [{ solutionName: 'dummy1' }, { solutionName: 'dummy2' }]

showStatement = true
isLogged: boolean = false
solutionSent: boolean = false
resources: string = '' // TODO resources
params$!: Subscription
relatedChallengesData!: DataChallenge
relatedListOfChallenges: Challenge[] = []
challengeSubs$!: Subscription
// showStatement = true
// isLogged: boolean = false
// solutionSent: boolean = false
// resources: string = '' // TODO resources
// params$!: Subscription
// relatedChallengesData!: DataChallenge
// relatedListOfChallenges: Challenge[] = []
// challengeSubs$!: Subscription
isDropdownOpen: boolean = false

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.isLogged = this.userService.isUserLoggedIn()

this.loadRelatedChallenges(this.idChallenge)
this.solutionService.solutionSent$.subscribe((value) => {
this.solutionSent = value
})
}

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

if (
token !== null &&
refreshToken !== null &&
token !== '' &&
refreshToken !== ''
) {
this.isLogged = true
}
}
// ngAfterContentChecked (): void {
// const token = localStorage.getItem('authToken') // TODO
// const refreshToken = localStorage.getItem('refreshToken') // TODO

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

loadRelatedChallenges (id: string): void {
this.challengeSubs$ = this.relatedService
Expand Down Expand Up @@ -121,7 +139,7 @@ export class ChallengeInfoComponent implements AfterContentChecked {
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
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

0 comments on commit 3b5a2ab

Please sign in to comment.