ducky/web

Paddy 2015-07-07 Parent:275a83e4c02e Child:13d27b50d79e

19:6b7037b4cbe7 Go to Latest

ducky/web/src/models/me.js

Update to hosted URL, use oauth-refresh in profiles. When syncing the profiles, use our oauth-refresh sync helper, so it won't fail because of an expired OAuth token. Also, update our URL to use the nginx-fronted URL.

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 })