juice-shop

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

6
import { Injectable } from '@angular/core'
7
import { type Backup } from '../Models/backup.model'
8
import { CookieService } from 'ngx-cookie'
9
import { saveAs } from 'file-saver'
10
import { SnackBarHelperService } from './snack-bar-helper.service'
11
import { MatSnackBar } from '@angular/material/snack-bar'
12
import { forkJoin, from, of } from 'rxjs'
13
import { ChallengeService } from './challenge.service'
14

15
@Injectable({
16
  providedIn: 'root'
17
})
18
export class LocalBackupService {
19
  private readonly VERSION = 1
20

21
  constructor (private readonly cookieService: CookieService, private readonly challengeService: ChallengeService, private readonly snackBarHelperService: SnackBarHelperService, private readonly snackBar: MatSnackBar) { }
22

23
  save (fileName: string = 'owasp_juice_shop') {
24
    const backup: Backup = { version: this.VERSION }
25

26
    backup.banners = {
27
      welcomeBannerStatus: this.cookieService.get('welcomebanner_status') ? this.cookieService.get('welcomebanner_status') : undefined,
28
      cookieConsentStatus: this.cookieService.get('cookieconsent_status') ? this.cookieService.get('cookieconsent_status') : undefined
29
    }
30
    backup.language = this.cookieService.get('language') ? this.cookieService.get('language') : undefined
31

32
    const continueCode = this.challengeService.continueCode()
33
    const continueCodeFindIt = this.challengeService.continueCodeFindIt()
34
    const continueCodeFixIt = this.challengeService.continueCodeFixIt()
35
    forkJoin([continueCode, continueCodeFindIt, continueCodeFixIt]).subscribe(([continueCode, continueCodeFindIt, continueCodeFixIt]) => {
36
      backup.continueCode = continueCode
37
      backup.continueCodeFindIt = continueCodeFindIt
38
      backup.continueCodeFixIt = continueCodeFixIt
39
      const blob = new Blob([JSON.stringify(backup)], { type: 'text/plain;charset=utf-8' })
40
      saveAs(blob, `${fileName}-${new Date().toISOString().split('T')[0]}.json`)
41
    }, () => {
42
      console.log('Failed to retrieve continue code(s) for backup from server. Using cookie values as fallback.')
43
      backup.continueCode = this.cookieService.get('continueCode') ? this.cookieService.get('continueCode') : undefined
44
      backup.continueCodeFindIt = this.cookieService.get('continueCodeFindIt') ? this.cookieService.get('continueCodeFindIt') : undefined
45
      backup.continueCodeFixIt = this.cookieService.get('continueCodeFixIt') ? this.cookieService.get('continueCodeFixIt') : undefined
46
      const blob = new Blob([JSON.stringify(backup)], { type: 'text/plain;charset=utf-8' })
47
      saveAs(blob, `${fileName}-${new Date().toISOString().split('T')[0]}.json`)
48
    })
49
  }
50

51
  restore (backupFile: File) {
52
    return from(backupFile.text().then((backupData) => {
53
      const backup: Backup = JSON.parse(backupData)
54

55
      if (backup.version === this.VERSION) {
56
        this.restoreCookie('welcomebanner_status', backup.banners?.welcomeBannerStatus)
57
        this.restoreCookie('cookieconsent_status', backup.banners?.cookieConsentStatus)
58
        this.restoreCookie('language', backup.language)
59
        this.restoreCookie('continueCodeFindIt', backup.continueCodeFindIt)
60
        this.restoreCookie('continueCodeFixIt', backup.continueCodeFixIt)
61
        this.restoreCookie('continueCode', backup.continueCode)
62

63
        const snackBarRef = this.snackBar.open('Backup has been restored from ' + backupFile.name, 'Apply changes now', {
64
          duration: 10000
65
        })
66
        snackBarRef.onAction().subscribe(() => {
67
          const hackingProgress = backup.continueCode ? this.challengeService.restoreProgress(encodeURIComponent(backup.continueCode)) : of(true)
68
          const findItProgress = backup.continueCodeFindIt ? this.challengeService.restoreProgressFindIt(encodeURIComponent(backup.continueCodeFindIt)) : of(true)
69
          const fixItProgress = backup.continueCodeFixIt ? this.challengeService.restoreProgressFixIt(encodeURIComponent(backup.continueCodeFixIt)) : of(true)
70
          forkJoin([hackingProgress, findItProgress, fixItProgress]).subscribe(() => {
71
            location.reload()
72
          }, (err) => { console.log(err) })
73
        })
74
      } else {
75
        this.snackBarHelperService.open(`Version ${backup.version} is incompatible with expected version ${this.VERSION}`, 'errorBar')
76
      }
77
    }).catch((err: Error) => {
78
      this.snackBarHelperService.open(`Backup restore operation failed: ${err.message}`, 'errorBar')
79
    }))
80
  }
81

82
  private restoreCookie (cookieName: string, cookieValue: string) {
83
    if (cookieValue) {
84
      const expires = new Date()
85
      expires.setFullYear(expires.getFullYear() + 1)
86
      this.cookieService.put(cookieName, cookieValue, { expires })
87
    } else {
88
      this.cookieService.remove(cookieName)
89
    }
90
  }
91
}
92

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

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

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

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