ducky/web

Paddy 2015-06-30 Parent:b9d0efb44eaa Child:13d27b50d79e

14:275a83e4c02e Go to Latest

ducky/web/src/models/me.js

Persist session data to localStorage. Create a helper library that figures out whether to write to chrome.storage.local or window.localStorage, and unifies their two APIs. Update the Me model to use the getOrFetch method for the profiles collection when retrieving the user's profile. This, unfortunately, makes it an async call (because we may need to fetch data from the server), so we can no longer have it be a derived property, which is a shame. It instead must just be the me.profile() function. Separate out the logic to determine when an access token expires, and turn it into the tokenExpires function. Fill the writeToCache placeholder with the logic to store the current session in either window.localStorage or chrome.storage.local, whichever is the more appropriate, using the helper library. Create the load helper function that will attempt to read session data from localStorage or chrome.storage.local, whichever the library decides is available, and updates the session based on it. Implement the logout function, which just uses the helper library to remove the session data from window.localStorage or chrome.storage.local. We should also be resetting the app.me variable, however. Create a debouncedWriteToCache function that will only write to the cache once every 250 ms, to avoid rushes on the cache. When instantiating our app.me variable, load it in from localStorage or chrome.storage.local if we can. Also, listen for changes to app.me, and persist them to chrome.storage.local or localStorage.

History
paddy@0 1 import Model from 'ampersand-model'
paddy@0 2 import Sync from 'ampersand-sync'
paddy@0 3 import qs from 'qs'
paddy@0 4 import config from '../config'
paddy@0 5 import isObject from 'lodash.isobject'
paddy@2 6 import jwtDecode from 'jwt-decode'
paddy@14 7 import localStore from '../helpers/local-storage'
paddy@14 8 import debounce from 'lodash.debounce'
paddy@0 9
paddy@0 10 export default Model.extend({
paddy@0 11 url: config.urlBase + '/token',
paddy@0 12 ajaxConfig: {
paddy@0 13 headers: {
paddy@0 14 'Content-Type': 'application/x-www-form-urlencoded',
paddy@0 15 'Authorization': 'Basic ' + btoa(config.clientID + ':' + config.clientSecret),
paddy@0 16 }
paddy@0 17 },
paddy@0 18
paddy@0 19 props: {
paddy@0 20 access_token: 'string',
paddy@0 21 refresh_token: 'string',
paddy@0 22 expires_in: 'int',
paddy@0 23 token_created: 'date',
paddy@2 24 profileID: 'string',
paddy@0 25 },
paddy@0 26
paddy@14 27 profile() {
paddy@14 28 return new Promise((resolve, reject) => {
paddy@14 29 app.profiles.getOrFetch(this.profileID, (err, model) => {
paddy@14 30 if (err) {
paddy@14 31 reject(err)
paddy@14 32 } else {
paddy@14 33 resolve(model)
paddy@14 34 }
paddy@14 35 })
paddy@14 36 })
paddy@14 37 },
paddy@14 38
paddy@0 39 derived: {
paddy@0 40 loggedIn () {
paddy@0 41 return !!this.access_token
paddy@0 42 },
paddy@14 43 tokenExpires () {
paddy@14 44 let d = this.token_created
paddy@14 45 d.setSeconds(d.getSeconds() + this.expires_in)
paddy@14 46 return d
paddy@14 47 },
paddy@0 48 needsRefresh () {
paddy@14 49 return !!this.refresh_token && (new Date() >= this.tokenExpires)
paddy@0 50 },
paddy@14 51 },
paddy@14 52
paddy@14 53 initialize() {
paddy@14 54 this.debouncedWriteToCache = debounce(this.writeToCache, 250)
paddy@0 55 },
paddy@0 56
paddy@0 57 login (email, password) {
paddy@0 58 let options = {
paddy@0 59 data: qs.stringify({
paddy@0 60 'username': email,
paddy@0 61 'password': password,
paddy@0 62 'grant_type': 'password',
paddy@0 63 }),
paddy@0 64 }
paddy@0 65 let moc = this
paddy@0 66 options.success = function(resp) {
paddy@0 67 if (!resp.access_token) {
paddy@0 68 return false
paddy@0 69 }
paddy@0 70 let serverAttrs = moc.parse(resp, options)
paddy@0 71 serverAttrs.token_created = new Date()
paddy@0 72 if (options.wait) serverAttrs = assign({}, serverAttrs)
paddy@0 73 if (isObject(serverAttrs) && !moc.set(serverAttrs, options)) {
paddy@0 74 return false
paddy@0 75 }
paddy@2 76 const token = jwtDecode(moc.access_token)
paddy@2 77 moc.profileID = token.sub
paddy@0 78 moc.trigger('sync', moc, resp, options)
paddy@0 79 }
paddy@0 80 options.error = function(resp) {
paddy@0 81 moc.trigger('error', moc, resp, options)
paddy@0 82 }
paddy@0 83 let sync = Sync('create', moc, options)
paddy@0 84 },
paddy@0 85
paddy@0 86 writeToCache () {
paddy@14 87 const data = JSON.stringify(this)
paddy@14 88 localStore.set('me', data)
paddy@14 89 },
paddy@14 90
paddy@14 91 load () {
paddy@14 92 let moc = this
paddy@14 93 localStore.get('me').catch((err) => {
paddy@14 94 console.error(err)
paddy@14 95 }).then((resp) => {
paddy@14 96 if (resp) {
paddy@14 97 const loaded = this.parse(JSON.parse(resp))
paddy@14 98 moc.set(loaded, {silent: true})
paddy@14 99 }
paddy@14 100 })
paddy@14 101 return this
paddy@0 102 },
paddy@0 103
paddy@0 104 logout () {
paddy@14 105 localStore.remove('me')
paddy@0 106 },
paddy@0 107
paddy@0 108 })