juice-shop

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

6
import { CookieService } from 'ngx-cookie'
7
import { WindowRefService } from '../Services/window-ref.service'
8
import { Router } from '@angular/router'
9
import { Component, NgZone, type OnInit } from '@angular/core'
10
import { UntypedFormControl, Validators } from '@angular/forms'
11
import { library } from '@fortawesome/fontawesome-svg-core'
12
import { UserService } from '../Services/user.service'
13
import { faEye, faEyeSlash, faKey } from '@fortawesome/free-solid-svg-icons'
14
import { faGoogle } from '@fortawesome/free-brands-svg-icons'
15
import { FormSubmitService } from '../Services/form-submit.service'
16
import { ConfigurationService } from '../Services/configuration.service'
17
import { BasketService } from '../Services/basket.service'
18

19
library.add(faKey, faEye, faEyeSlash, faGoogle)
20

21
const oauthProviderUrl = 'https://accounts.google.com/o/oauth2/v2/auth'
22

23
@Component({
24
  selector: 'app-login',
25
  templateUrl: './login.component.html',
26
  styleUrls: ['./login.component.scss']
27
})
28

29
export class LoginComponent implements OnInit {
30
  public emailControl = new UntypedFormControl('', [Validators.required])
31

32
  public passwordControl = new UntypedFormControl('', [Validators.required, Validators.minLength(1)])
33

34
  public hide = true
35
  public user: any
36
  public rememberMe: UntypedFormControl = new UntypedFormControl(false)
37
  public error: any
38
  public clientId = '1005568560502-6hm16lef8oh46hr2d98vf2ohlnj4nfhq.apps.googleusercontent.com'
39
  public oauthUnavailable: boolean = true
40
  public redirectUri: string = ''
41
  constructor (private readonly configurationService: ConfigurationService, private readonly userService: UserService, private readonly windowRefService: WindowRefService, private readonly cookieService: CookieService, private readonly router: Router, private readonly formSubmitService: FormSubmitService, private readonly basketService: BasketService, private readonly ngZone: NgZone) { }
42

43
  ngOnInit () {
44
    const email = localStorage.getItem('email')
45
    if (email) {
46
      this.user = {}
47
      this.user.email = email
48
      this.rememberMe.setValue(true)
49
    } else {
50
      this.rememberMe.setValue(false)
51
    }
52

53
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
54
    this.redirectUri = `${this.windowRefService.nativeWindow.location.protocol}//${this.windowRefService.nativeWindow.location.host}`
55
    this.configurationService.getApplicationConfiguration().subscribe((config) => {
56
      if (config?.application?.googleOauth) {
57
        this.clientId = config.application.googleOauth.clientId
58
        const authorizedRedirect = config.application.googleOauth.authorizedRedirects.find(r => r.uri === this.redirectUri)
59
        if (authorizedRedirect) {
60
          this.oauthUnavailable = false
61
          this.redirectUri = authorizedRedirect.proxy ? authorizedRedirect.proxy : authorizedRedirect.uri
62
        } else {
63
          this.oauthUnavailable = true
64
          console.log(this.redirectUri + ' is not an authorized redirect URI for this application.')
65
        }
66
      }
67
    }, (err) => { console.log(err) })
68

69
    this.formSubmitService.attachEnterKeyHandler('login-form', 'loginButton', () => { this.login() })
70
  }
71

72
  login () {
73
    this.user = {}
74
    this.user.email = this.emailControl.value
75
    this.user.password = this.passwordControl.value
76
    this.userService.login(this.user).subscribe((authentication: any) => {
77
      localStorage.setItem('token', authentication.token)
78
      const expires = new Date()
79
      expires.setHours(expires.getHours() + 8)
80
      this.cookieService.put('token', authentication.token, { expires })
81
      sessionStorage.setItem('bid', authentication.bid)
82
      this.basketService.updateNumberOfCartItems()
83
      this.userService.isLoggedIn.next(true)
84
      this.ngZone.run(async () => await this.router.navigate(['/search']))
85
    }, ({ error }) => {
86
      if (error.status && error.data && error.status === 'totp_token_required') {
87
        localStorage.setItem('totp_tmp_token', error.data.tmpToken)
88
        this.ngZone.run(async () => await this.router.navigate(['/2fa/enter']))
89
        return
90
      }
91
      localStorage.removeItem('token')
92
      this.cookieService.remove('token')
93
      sessionStorage.removeItem('bid')
94
      this.error = error
95
      this.userService.isLoggedIn.next(false)
96
      this.emailControl.markAsPristine()
97
      this.passwordControl.markAsPristine()
98
    })
99

100
    if (this.rememberMe.value) {
101
      localStorage.setItem('email', this.user.email)
102
    } else {
103
      localStorage.removeItem('email')
104
    }
105
  }
106

107
  googleLogin () {
108
    this.windowRefService.nativeWindow.location.replace(`${oauthProviderUrl}?client_id=${this.clientId}&response_type=token&scope=email&redirect_uri=${this.redirectUri}`)
109
  }
110
}
111

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

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

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

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