user.js 16 KB

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