Files
doneit-web/src/app/store/localstore.service.ts
T

66 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-07-18 18:56:53 +01:00
import { Injectable } from '@angular/core';
2021-07-18 20:20:30 +01:00
import { AES, enc, SHA1 } from 'crypto-js'
2021-07-18 18:56:53 +01:00
@Injectable({
providedIn: 'root'
})
export class LocalstoreService {
2021-09-02 12:37:21 +01:00
private prefix = 'v17-'
2021-07-18 18:56:53 +01:00
2021-07-18 20:52:14 +01:00
constructor() {
2021-07-30 11:45:18 +01:00
2021-07-18 20:52:14 +01:00
const key = SHA1('version').toString()
this.set(key, this.prefix)
}
2021-07-18 18:56:53 +01:00
2021-08-31 13:46:39 +01:00
getKey(keyName:string) {
2021-07-18 20:52:01 +01:00
return this.prefix + keyName
}
2021-07-18 20:52:14 +01:00
2021-08-31 13:46:39 +01:00
get( keyName:string, safe) {
2021-07-18 18:56:53 +01:00
2021-07-18 20:52:01 +01:00
keyName = this.getKey(keyName)
2021-07-18 20:20:30 +01:00
2021-07-30 11:45:18 +01:00
const ciphertext = localStorage.getItem(keyName)
2021-07-18 18:56:53 +01:00
2021-07-18 20:20:30 +01:00
const hashKey = SHA1(keyName).toString()
2021-07-18 18:56:53 +01:00
if(ciphertext) {
2021-07-18 20:20:30 +01:00
const bytes = AES.decrypt(ciphertext, hashKey)
var decryptedData = bytes.toString(enc.Utf8);
2021-07-18 20:52:01 +01:00
try {
return JSON.parse(decryptedData)
} catch {
return decryptedData;
2021-07-18 20:20:30 +01:00
}
2021-07-18 20:52:01 +01:00
2021-07-18 20:52:14 +01:00
} else {
return safe
2021-07-18 18:56:53 +01:00
}
}
2021-08-31 13:46:39 +01:00
set(keyName:string, value) {
2021-07-30 11:45:18 +01:00
2021-07-18 20:52:01 +01:00
keyName = this.getKey(keyName)
2021-07-18 18:56:53 +01:00
if(typeof(value) != 'string') {
value = JSON.stringify(value)
2021-07-18 20:20:30 +01:00
}
const hashKey = SHA1(keyName).toString()
2021-07-18 18:56:53 +01:00
const data = value
2021-07-18 20:20:30 +01:00
const encoded = AES.encrypt( data, hashKey).toString();
localStorage.setItem(keyName, encoded)
2021-07-18 18:56:53 +01:00
}
2021-08-31 13:46:39 +01:00
delete(keyName:string) {
2021-08-27 13:39:52 +01:00
keyName = this.getKey(keyName)
localStorage.removeItem(keyName)
}
2021-07-18 18:56:53 +01:00
}
2021-07-20 19:18:16 +01:00
2021-09-03 15:50:13 +01:00
export const localstoreService = new LocalstoreService()