juice-shop

Форк
0
/
navbar.component.ts 
220 строк · 7.6 Кб
1
/*
2
 * Copyright (c) 2014-2024 Bjoern Kimminich & the OWASP Juice Shop contributors.
3
 * SPDX-License-Identifier: MIT
4
 */
5

6
import { environment } from '../../environments/environment'
7
import { ChallengeService } from '../Services/challenge.service'
8
import { UserService } from '../Services/user.service'
9
import { AdministrationService } from '../Services/administration.service'
10
import { ConfigurationService } from '../Services/configuration.service'
11
import { Component, EventEmitter, NgZone, type OnInit, Output } from '@angular/core'
12
import { CookieService } from 'ngx-cookie'
13
import { TranslateService } from '@ngx-translate/core'
14
import { Router } from '@angular/router'
15
import { SocketIoService } from '../Services/socket-io.service'
16
import { LanguagesService } from '../Services/languages.service'
17
import { MatSnackBar } from '@angular/material/snack-bar'
18
import { BasketService } from '../Services/basket.service'
19

20
import {
21
  faBomb,
22
  faComment,
23
  faInfoCircle,
24
  faLanguage,
25
  faMapMarker,
26
  faRecycle,
27
  faSearch,
28
  faShoppingCart,
29
  faSignInAlt,
30
  faSignOutAlt,
31
  faThermometerEmpty,
32
  faThermometerFull,
33
  faThermometerHalf,
34
  faThermometerQuarter,
35
  faThermometerThreeQuarters,
36
  faTrophy,
37
  faUserCircle,
38
  faUserSecret
39
} from '@fortawesome/free-solid-svg-icons'
40
import { faComments } from '@fortawesome/free-regular-svg-icons'
41
import { faGithub } from '@fortawesome/free-brands-svg-icons'
42
import { library } from '@fortawesome/fontawesome-svg-core'
43
import { LoginGuard } from '../app.guard'
44
import { roles } from '../roles'
45

46
library.add(faLanguage, faSearch, faSignInAlt, faSignOutAlt, faComment, faBomb, faTrophy, faInfoCircle, faShoppingCart, faUserSecret, faRecycle, faMapMarker, faUserCircle, faGithub, faComments, faThermometerEmpty, faThermometerQuarter, faThermometerHalf, faThermometerThreeQuarters, faThermometerFull)
47

48
@Component({
49
  selector: 'app-navbar',
50
  templateUrl: './navbar.component.html',
51
  styleUrls: ['./navbar.component.scss']
52
})
53
export class NavbarComponent implements OnInit {
54
  public userEmail: string = ''
55
  public languages: any = []
56
  public selectedLanguage: string = 'placeholder'
57
  public version: string = ''
58
  public applicationName: string = 'OWASP Juice Shop'
59
  public showGitHubLink: boolean = true
60
  public logoSrc: string = 'assets/public/images/JuiceShop_Logo.png'
61
  public scoreBoardVisible: boolean = false
62
  public shortKeyLang: string = 'placeholder'
63
  public itemTotal = 0
64

65
  @Output() public sidenavToggle = new EventEmitter()
66

67
  constructor (private readonly administrationService: AdministrationService, private readonly challengeService: ChallengeService,
68
    private readonly configurationService: ConfigurationService, private readonly userService: UserService, private readonly ngZone: NgZone,
69
    private readonly cookieService: CookieService, private readonly router: Router, private readonly translate: TranslateService,
70
    private readonly io: SocketIoService, private readonly langService: LanguagesService, private readonly loginGuard: LoginGuard,
71
    private readonly snackBar: MatSnackBar, private readonly basketService: BasketService) { }
72

73
  ngOnInit () {
74
    this.getLanguages()
75
    this.basketService.getItemTotal().subscribe(x => (this.itemTotal = x))
76
    this.administrationService.getApplicationVersion().subscribe((version: any) => {
77
      if (version) {
78
        // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
79
        this.version = `v${version}`
80
      }
81
    }, (err) => { console.log(err) })
82

83
    this.configurationService.getApplicationConfiguration().subscribe((config: any) => {
84
      if (config?.application?.name) {
85
        this.applicationName = config.application.name
86
      }
87
      if (config?.application) {
88
        this.showGitHubLink = config.application.showGitHubLinks
89
      }
90

91
      if (config?.application?.logo) {
92
        let logo: string = config.application.logo
93

94
        if (logo.substring(0, 4) === 'http') {
95
          logo = decodeURIComponent(logo.substring(logo.lastIndexOf('/') + 1))
96
        }
97
        this.logoSrc = 'assets/public/images/' + logo
98
      }
99
    }, (err) => { console.log(err) })
100

101
    if (localStorage.getItem('token')) {
102
      this.getUserDetails()
103
    } else {
104
      this.userEmail = ''
105
    }
106

107
    this.userService.getLoggedInState().subscribe((isLoggedIn) => {
108
      if (isLoggedIn) {
109
        this.getUserDetails()
110
      } else {
111
        this.userEmail = ''
112
      }
113
    })
114

115
    this.getScoreBoardStatus()
116

117
    this.ngZone.runOutsideAngular(() => {
118
      this.io.socket().on('challenge solved', (challenge) => {
119
        if (challenge.key === 'scoreBoardChallenge') {
120
          this.scoreBoardVisible = true
121
        }
122
      })
123
    })
124
  }
125

126
  checkLanguage () {
127
    if (this.cookieService.get('language')) {
128
      const langKey = this.cookieService.get('language')
129
      this.translate.use(langKey)
130
      this.selectedLanguage = this.languages.find((y: { key: string }) => y.key === langKey)
131
      this.shortKeyLang = this.languages.find((y: { key: string }) => y.key === langKey).shortKey
132
    } else {
133
      this.changeLanguage('en')
134
      this.selectedLanguage = this.languages.find((y: { key: string }) => y.key === 'en')
135
      this.shortKeyLang = this.languages.find((y: { key: string }) => y.key === 'en').shortKey
136
    }
137
  }
138

139
  search (value: string) {
140
    if (value) {
141
      const queryParams = { queryParams: { q: value } }
142
      this.ngZone.run(async () => await this.router.navigate(['/search'], queryParams))
143
    } else {
144
      this.ngZone.run(async () => await this.router.navigate(['/search']))
145
    }
146
  }
147

148
  getUserDetails () {
149
    this.userService.whoAmI().subscribe((user: any) => {
150
      this.userEmail = user.email
151
    }, (err) => { console.log(err) })
152
  }
153

154
  isLoggedIn () {
155
    return localStorage.getItem('token')
156
  }
157

158
  logout () {
159
    this.userService.saveLastLoginIp().subscribe((user: any) => { this.noop() }, (err) => { console.log(err) })
160
    localStorage.removeItem('token')
161
    this.cookieService.remove('token')
162
    sessionStorage.removeItem('bid')
163
    sessionStorage.removeItem('itemTotal')
164
    this.userService.isLoggedIn.next(false)
165
    this.ngZone.run(async () => await this.router.navigate(['/']))
166
  }
167

168
  changeLanguage (langKey: string) {
169
    this.translate.use(langKey)
170
    const expires = new Date()
171
    expires.setFullYear(expires.getFullYear() + 1)
172
    this.cookieService.put('language', langKey, { expires })
173
    if (this.languages.find((y: { key: string }) => y.key === langKey)) {
174
      const language = this.languages.find((y: { key: string }) => y.key === langKey)
175
      this.shortKeyLang = language.shortKey
176
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
177
      const snackBarRef = this.snackBar.open(`Language has been changed to ${language.lang}`, 'Force page reload', {
178
        duration: 5000
179
      })
180
      snackBarRef.onAction().subscribe(() => {
181
        location.reload()
182
      })
183
    }
184
  }
185

186
  getScoreBoardStatus () {
187
    this.challengeService.find({ name: 'Score Board' }).subscribe((challenges: any) => {
188
      this.ngZone.run(() => {
189
        this.scoreBoardVisible = challenges[0].solved
190
      })
191
    }, (err) => { console.log(err) })
192
  }
193

194
  goToProfilePage () {
195
    window.location.replace(environment.hostServer + '/profile')
196
  }
197

198
  goToDataErasurePage () {
199
    window.location.replace(environment.hostServer + '/dataerasure')
200
  }
201

202
  onToggleSidenav = () => {
203
    this.sidenavToggle.emit()
204
  }
205

206
  // eslint-disable-next-line no-empty,@typescript-eslint/no-empty-function
207
  noop () { }
208

209
  getLanguages () {
210
    this.langService.getLanguages().subscribe((res) => {
211
      this.languages = res
212
      this.checkLanguage()
213
    })
214
  }
215

216
  isAccounting () {
217
    const payload = this.loginGuard.tokenDecode()
218
    return payload?.data && payload.data.role === roles.accounting
219
  }
220
}
221

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.