user.js 13 KB

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