MayoMayn
BestDev
- Oct 18, 2016
- 1,423
- 683
Well, I saw some folks on here who wanted to get some knowledge about JavaScript from scratch.
I wrote two components for my Electron app, and I then decided just to release them as a separate thread so that other people can enjoy this.
It uses the CryptoJS module by Google for encrypting and decrypting the local storage items.
Auth.js
Session.js
Simple usage:
I wrote two components for my Electron app, and I then decided just to release them as a separate thread so that other people can enjoy this.
It uses the CryptoJS module by Google for encrypting and decrypting the local storage items.
Auth.js
PHP:
import CryptoJS from 'crypto-js'
//const CryptoJS = require('crypto-js')
export default class Auth {
/**
* Encrypt a string, object or array
*/
static encrypt(value) {
// if the value is an object, stringify it so it can be properly encrypted
if(typeof value === 'object')
value = JSON.stringify(value)
// encrypted the value using aes
let enc = CryptoJS.AES.encrypt(value, 'devbest') // < secret key
// incase you want to use the encrypted value it gets returned
return enc.toString()
}
/**
* Decrypt a string, object or array
*/
static decrypt(value) {
// decrypts the specified value
let bytes = CryptoJS.AES.decrypt(value, 'devbest'), // < secret key
bytesToStr = bytes.toString(CryptoJS.enc.Utf8) // since it returns an object, we're only supposed to receive the decrypted part
// if the decrypted value is an object, parse it using json
return (typeof bytesToStr === 'object') ? JSON.parse(bytesToStr) : bytesToStr
}
}
Session.js
PHP:
import Auth from './auth'
// const Auth = require('./auth')
export default class Session {
// writes an object to the local storage
static write(obj) {
for(let key in obj) {
// encrypt the value using the auth class
obj[key] = Auth.encrypt(obj[key])
// write the encrypted value to the local storage
localStorage.setItem(key, obj[key])
}
// return object incase you want to use it
return obj
}
// reads a value from the storage
static read(key) {
// decrypt the local storage item using our decrypt method
return Auth.decrypt(localStorage.getItem(key))
}
// checks if several or one item exists in our local storage
static exists(arr) {
for(let key in arr) {
// checks if it exists
let exists = (localStorage.getItem(arr[key]) !== null)
if(!exists) return false
}
return true
}
// remove item in our local storage
static remove(arr) {
for(let key in arr) {
localStorage.removeItem(arr[key])
}
}
}
Simple usage:
PHP:
Session.write({
username: 'Sentinel',
bitch: 'Pettyjohn'
})
if(Session.exists(['username', 'bitch']) {
console.log(Session.read('username'))
// outputs Sentinel
}
Last edited: