user.js 15 KB

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