Advertisement
Guest User

Untitled

a guest
Nov 30th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. var React = require('react')
  2.  
  3. var loginPage = React.createClass({
  4.  
  5. getInitialState: function () {
  6. return {
  7. token: null,
  8. user: null,
  9. badLogin: null
  10. }
  11. },
  12.  
  13. submitCredentials: function (user) {
  14. if (user.username !== undefined && user.password !== undefined) {
  15. this.login({
  16. username: user.username,
  17. password: user.password
  18. }, () => {
  19. this.setState({ badLogin: true });
  20. })
  21. }
  22. },
  23.  
  24. login: function (user, callback) {
  25. fetch(API_URL, {
  26. method: 'POST',
  27. headers: {
  28. 'Accept': 'application/json',
  29. 'Content-Type': 'application/json'
  30. },
  31. body: JSON.stringify(user)
  32. }).then((response) => {
  33. return response.json()
  34. }).then((response) => {
  35. if (response.token && response.user) {
  36. localStorage.setItem(('login', JSON.stringify([{'token': response.token}, {'userId': response.user.id}]))
  37. } else {
  38. if (callback) { callback() }
  39. }
  40. }).done()
  41. },
  42.  
  43. componentWillMount: function () {
  44. var token;
  45. var data = JSON.parse(localStorage.getItem('login'))
  46.  
  47. if (data[0]) {
  48. token = data[0]
  49. this.getUser(data[1])
  50. .then((user) => {
  51. return user
  52. })
  53. .then((user) => {
  54. this.setState({
  55. user: user,
  56. token: token
  57. })
  58. })
  59. }
  60. },
  61.  
  62. getUser: function (userId) {
  63. return fetch(PROFILE_URL + userId, {
  64. method: 'GET',
  65. headers: {
  66. 'Accept': 'application/json',
  67. 'Content-Type': 'application/json'
  68. }
  69. })
  70. },
  71.  
  72. logout: function () {
  73. fetch(LOGOUT_URL, {
  74. method: 'GET'
  75. }).then(function () {
  76. localStorage.removeItem('login')
  77. })
  78. },
  79.  
  80. render: function () {
  81. if (!this.state.token) {
  82. return (
  83. <MyForm />
  84. )
  85. } else {
  86. return (
  87. <Profile />
  88. );
  89. }
  90. }
  91.  
  92. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement