user.js 14 KB

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