user.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import REST from 'vuejs/api/rest-axios'
  2. // import JSONAPI from 'vuejs/api/json-axios'
  3. import MA from 'vuejs/api/ma-axios'
  4. import qs from 'querystring-es3'
  5. import materiauFlaglistGQL from 'vuejs/api/gql/materiauflaglist.fragment.gql'
  6. // import router from 'vuejs/route' // this is not working
  7. export default {
  8. namespaced: true,
  9. // router,
  10. // initial state
  11. state: {
  12. uid: null,
  13. // username: '',
  14. mail: '',
  15. name: null,
  16. csrf_token: null,
  17. logout_token: null,
  18. loginMessage: '',
  19. registerMessage: '',
  20. isloggedin: false,
  21. isAdmin: false,
  22. isAdherent: false,
  23. canSearch: false,
  24. hasDBAccess: false,
  25. roles: [],
  26. flagcolls: false,
  27. flagcollsLoadedItems: {},
  28. openedCollid: null
  29. },
  30. // getters
  31. getters: {},
  32. // mutations
  33. mutations: {
  34. SetCsrftoken (state, token) {
  35. console.log('SetCsrftoken', token)
  36. state.csrf_token = token
  37. },
  38. setToken (state, data) {
  39. console.log('setToken', data)
  40. state.uid = data.current_user.uid
  41. // state.username = data.username;
  42. state.mail = data.current_user.mail
  43. state.csrf_token = data.csrf_token
  44. // state.isloggedin = true
  45. state.logout_token = data.logout_token
  46. },
  47. setLoginMessage (state, message) {
  48. console.log('setLoginMessage', message)
  49. state.loginMessage = message
  50. },
  51. setRegisterMessage (state, message) {
  52. console.log('setRegisterMessage', message)
  53. state.registerMessage = message
  54. },
  55. setUid (state, uid) {
  56. state.uid = uid
  57. state.isloggedin = true
  58. },
  59. setUser (state, data) {
  60. state.mail = data.mail[0].value
  61. state.uuid = data.uuid[0].value
  62. state.name = data.name[0].value
  63. // with session_limit, only here we are certain that the user is logged
  64. state.isloggedin = true
  65. },
  66. setRoles (state, roles) {
  67. console.log('User setRoles', roles)
  68. state.roles = []
  69. for (let i = 0; i < roles.length; i++) {
  70. state.roles.push(roles[i].target_id)
  71. }
  72. // check if admin
  73. if (
  74. state.roles.indexOf('admin') !== -1 ||
  75. state.roles.indexOf('root') !== -1
  76. ) {
  77. // console.log('is admin')
  78. state.isAdmin = true
  79. }
  80. // check if has access to search
  81. if (state.roles.indexOf('adherent') !== -1 ||
  82. state.roles.indexOf('student') !== -1) {
  83. // console.log('is admin')
  84. state.canSearch = true
  85. state.isAdherent = true
  86. }
  87. if (state.isAdherent || state.isAdmin) {
  88. state.hasDBAccess = true
  89. }
  90. },
  91. // setName (state, name) {
  92. // console.log('setName', name)
  93. // state.name = name
  94. // },
  95. setLoggedOut (state) {
  96. console.log('setLoggedOut state', state)
  97. state.uid = null
  98. state.mail = ''
  99. state.csrf_token = null
  100. state.isloggedin = false
  101. state.logout_token = null
  102. state.asAdmin = false
  103. state.canSearch = false
  104. // if (state.isAdmin) {
  105. // // TODO: what if on a page where login is needed (as commerce checkout and cart)
  106. // window.location.reload(true)
  107. // } else {
  108. //
  109. // // return systematically to home page
  110. // this.$router.push({
  111. // name:`home`
  112. // // params: { alias:this.alias }
  113. // // query: { nid: this.item.nid }
  114. // // meta: { uuid:this.item.uuid },
  115. // })
  116. // }
  117. // redirect to home page in every case
  118. window.location = window.location.origin
  119. },
  120. setFlagColls (state, flagcolls) {
  121. console.log('User pre setFlagColls', state.flagcolls)
  122. state.flagcolls = flagcolls
  123. // console.log('User post setFlagColls', state.flagcolls)
  124. },
  125. openFlagColl (state, collid) {
  126. state.openedCollid = collid
  127. },
  128. closeFlagColl (state) {
  129. state.openedCollid = null
  130. },
  131. setLoadedCollItems (state, data) {
  132. console.log('setLoadedCollItems', data)
  133. // if no data, we are just calling the mutation to trigger the component update
  134. if (data) {
  135. state.flagcollsLoadedItems[data.collid] = data.items
  136. }
  137. }
  138. },
  139. // actions
  140. actions: {
  141. userRegister ({ dispatch, commit, state }, credentials) {
  142. return new Promise((resolve) => {
  143. REST.get('/session/token').then(({ token }) => {
  144. commit('SetCsrftoken', token)
  145. REST.post('/user/register?_format=json', credentials, {
  146. 'X-CSRF-Token': state.csrftoken,
  147. validateStatus: function (status) {
  148. return status >= 200 && status < 500
  149. }
  150. })
  151. .then((response) => {
  152. console.log('user REST registered', response)
  153. if (response.status === 200) {
  154. dispatch('userLogin', credentials).then(() => {
  155. resolve()
  156. })
  157. } else {
  158. let message = ''
  159. switch (response.status) {
  160. case 422:
  161. message = 'email is already registered'
  162. break
  163. default:
  164. message = response.data.message
  165. }
  166. commit('setRegisterMessage', message)
  167. }
  168. })
  169. .catch(error => {
  170. console.warn('Issue with register', error)
  171. Promise.reject(error)
  172. })
  173. })
  174. })
  175. },
  176. userLogin ({ dispatch, commit, state }, credentials) {
  177. return new Promise((resolve, reject) => {
  178. dispatch('getToken', credentials)
  179. // TODO: catch failed login
  180. .then((response) => {
  181. console.log('userLogin dispatch getToken response', response)
  182. if (response.status === 200) {
  183. commit('setToken', response.data)
  184. dispatch('getUser').then(userdata => {
  185. console.log('User Loggedin', state.isAdmin, state.isAdherent)
  186. // have to reload systematicly because of autologout library not loaded if not logged in the begining
  187. if (state.isAdmin) {
  188. window.location.reload()
  189. }
  190. if (state.isAdherent) {
  191. // router.push({
  192. // name: 'base'
  193. // })
  194. // // TODO: openCloseHamMenu(false)
  195. // dispatch('Common/openCloseHamMenu', false)
  196. window.location = '/base'
  197. }
  198. // else {
  199. // // * window.location.reload()
  200. // }
  201. resolve()
  202. })
  203. } else {
  204. commit('setLoginMessage', response.data.message)
  205. console.warn('Issue with getToken', response)
  206. console.log('user loggein failed')
  207. Promise.reject(new Error('user loggein failed'))
  208. }
  209. })
  210. .catch(error => {
  211. console.warn('Issue with Dispatch getToken', error)
  212. Promise.reject(error)
  213. })
  214. })
  215. },
  216. getToken ({ dispatch, commit, state }, credentials) {
  217. return REST.post('/user/login?_format=json',
  218. credentials,
  219. {
  220. validateStatus: function (status) {
  221. return status >= 200 && status < 500
  222. }
  223. })
  224. },
  225. getUser ({ dispatch, commit, state }) {
  226. return new Promise((resolve, reject) => {
  227. REST.get('/session/token').then(({ data }) => {
  228. console.log('csrftoken', data)
  229. commit('SetCsrftoken', data)
  230. console.log('state.csrf_token', state.csrf_token)
  231. const params = {
  232. token: state.csrf_token
  233. }
  234. REST.get(`/user/${state.uid}?_format=json`, params)
  235. .then(({ data }) => {
  236. console.log('user REST getUser data', data)
  237. console.log('roles', data.roles)
  238. // with session_limit, only here we are certain that the user is logged
  239. commit('setUser', data)
  240. if (data.roles) {
  241. commit('setRoles', data.roles)
  242. }
  243. // console.log('customer_profiles', data.customer_profiles.length)
  244. // if (data.customer_profiles.length) {
  245. // dispatch('getUserProfiles', data.customer_profiles[data.customer_profiles.length - 1].target_id)
  246. // }
  247. dispatch('getUserFlagColls')
  248. resolve()
  249. })
  250. .catch(error => {
  251. console.warn('Issue with getUser', error)
  252. Promise.reject(error)
  253. })
  254. })
  255. })
  256. },
  257. // getUserProfiles ({ dispatch, commit, state }, pid) {
  258. // const params = {
  259. // token: state.csrf_token
  260. // }
  261. // REST.get(`/profile/${pid}?_format=json`, params).then(({ data }) => {
  262. // console.log('profile', data)
  263. // if (data.address.length) {
  264. // commit('setName', `${data.address[0].given_name} ${data.address[0].family_name} `)
  265. // }
  266. // }).catch(error => {
  267. // console.warn('Issue with getUser', error)
  268. // Promise.reject(error)
  269. // })
  270. // },
  271. getUserFlagColls ({ dispatch, commit, state }) {
  272. // flags
  273. // REST.get('/flagging_collection/1?_format=json')
  274. // .then((data) => {
  275. // console.log('TEST FLAG REST data', data)
  276. // })
  277. // .catch(error => {
  278. // console.warn('Issue USER TEST FLAG REST', error)
  279. // Promise.reject(error)
  280. // })
  281. return MA.get('materio_flag/user_flagging_collections')
  282. .then(({ data }) => {
  283. console.log('user MA getFlags data', data)
  284. commit('setFlagColls', data)
  285. })
  286. .catch(error => {
  287. console.warn('Issue USER MA getFlags', error)
  288. Promise.reject(error)
  289. })
  290. },
  291. // https://drupal.stackexchange.com/questions/248539/cant-get-flagging-api-to-accept-post-request
  292. createFlagColl ({ dispatch, commit, state }, newCollectionName) {
  293. console.log('user createFlagColl', newCollectionName)
  294. return new Promise((resolve, reject) => {
  295. const params = {
  296. name: newCollectionName
  297. }
  298. MA.post('materio_flag/create_user_flagging_collection', params)
  299. .then(({ data }) => {
  300. console.log('user MA createFlagColl data', data)
  301. if (data.status) {
  302. dispatch('getUserFlagColls').then(() => {
  303. resolve(data)
  304. })
  305. }
  306. })
  307. .catch(error => {
  308. console.warn('Issue USER MA createFlag', error)
  309. reject(error)
  310. })
  311. })
  312. },
  313. deleteFlagColl ({ dispatch, commit, state }, flagcollid) {
  314. console.log('user deleteFlagColl', flagcollid)
  315. return new Promise((resolve, reject) => {
  316. const params = {
  317. flagcollid: flagcollid
  318. }
  319. MA.post('materio_flag/delete_user_flagging_collection', params)
  320. .then(({ data }) => {
  321. console.log('user MA deleteFlagColl data', data)
  322. dispatch('getUserFlagColls').then(() => {
  323. resolve()
  324. })
  325. })
  326. .catch(error => {
  327. console.warn('Issue USER MA createFlag', error)
  328. reject(error)
  329. })
  330. })
  331. },
  332. flagUnflag ({ dispatch, commit, state }, { action, id, collid }) {
  333. console.log('user flagUnflag', action, id, collid)
  334. return new Promise((resolve, reject) => {
  335. const params = {
  336. flagid: state.flagcolls[collid].flag_id,
  337. id: id,
  338. flagcollid: collid
  339. }
  340. return MA.post(`materio_flag/${action}`, params)
  341. .then(({ data }) => {
  342. console.log('user MA flag', data)
  343. // reload the fulllist of flagcolleciton
  344. dispatch('getUserFlagColls').then(() => {
  345. if (state.flagcolls[collid].items.length) {
  346. dispatch('loadMaterialsGQL', {
  347. ids: state.flagcolls[collid].items,
  348. gqlfragment: materiauFlaglistGQL,
  349. gqlFragmentfields: 'MateriauFlagListFields',
  350. callBack: 'loadMaterialsCallBack',
  351. callBackArgs: { collid: collid }
  352. }).then(() => {
  353. resolve()
  354. })
  355. // dispatch('loadMaterials', {
  356. // uuids: state.flagcolls[collid].items_uuids,
  357. // imgStyle: ['card_medium_half'],
  358. // callBack: 'loadMaterialsCallBack',
  359. // callBackArgs: { collid: collid }
  360. // }).then(() => {
  361. // resolve()
  362. // })
  363. } else {
  364. commit('setLoadedCollItems', { collid: collid, items: [] })
  365. resolve()
  366. }
  367. })
  368. })
  369. .catch(error => {
  370. console.warn('Issue USER MA flagUnflag', error)
  371. })
  372. })
  373. },
  374. openFlagColl ({ commit, dispatch, state }, collid) {
  375. console.log('user openFlagColl', collid)
  376. commit('openFlagColl', collid)
  377. if (state.flagcolls[collid].items.length) {
  378. if (typeof state.flagcollsLoadedItems[collid] === 'undefined') {
  379. console.log('loading flagcoll items', state.flagcolls[collid])
  380. // if no loadedItems, load them
  381. // loadMaterials is on mixins
  382. // https://github.com/huybuidac/vuex-extensions
  383. dispatch('loadMaterialsGQL', {
  384. ids: state.flagcolls[collid].items,
  385. gqlfragment: materiauFlaglistGQL,
  386. gqlFragmentfields: 'MateriauFlagListFields',
  387. callBack: 'loadMaterialsCallBack',
  388. callBackArgs: { collid: collid }
  389. })
  390. // dispatch('loadMaterials', {
  391. // uuids: state.flagcolls[collid].items_uuids,
  392. // imgStyle: ['card_medium_half'],
  393. // callBack: 'loadMaterialsCallBack',
  394. // callBackArgs: { collid: collid }
  395. // })
  396. } else {
  397. // call the mutation without data to only trigger the FlagCollection component update
  398. console.log('committing setLoadedCollItems without args')
  399. commit('setLoadedCollItems')
  400. }
  401. } else {
  402. commit('setLoadedCollItems', { collid: collid, items: [] })
  403. }
  404. },
  405. loadMaterialsCallBack ({ commit }, { items, callBackArgs }) {
  406. console.log('user loadMaterialsCallBack', items, callBackArgs)
  407. commit('setLoadedCollItems', { collid: callBackArgs.collid, items: items })
  408. },
  409. closeFlagColl ({ commit, dispatch }) {
  410. console.log('user closeFlagColl')
  411. commit('closeFlagColl')
  412. },
  413. userLogout ({ commit, state }) {
  414. const credentials = qs.stringify({
  415. token: state.csrf_token
  416. })
  417. REST.post('/user/logout', credentials)
  418. .then(resp => {
  419. console.log('userLogout resp', resp)
  420. commit('setLoggedOut')
  421. // window.location.reload(true) ???
  422. })
  423. .catch(error => {
  424. console.warn('Issue with logout', error)
  425. Promise.reject(error)
  426. })
  427. }
  428. }
  429. }