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