Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Implemented Auth functionality

Blaumause4727d8deac7
diff --git a/.env.example b/.env.example
new file mode 100644
index 000000000..99f8b1119
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,2 @@
+REACT_APP_API_URL=https://example.com/api/
+CHOKIDAR_USEPOLLING=true
\ No newline at end of file
diff --git a/package.json b/package.json
index 9d8abfba6..d1fa628b1 100644
--- a/package.json
+++ b/package.json
@@ -17,6 +17,7 @@
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"redux": "^4.0.5",
+ "redux-auth-wrapper": "^3.0.0",
"redux-saga": "^1.1.3",
"web-vitals": "^1.1.1"
},
diff --git a/src/App.js b/src/App.js
index 8eb22462d..38fbae7b3 100644
--- a/src/App.js
+++ b/src/App.js
@@ -1,6 +1,7 @@
-import React from 'react'
+import React, { useEffect } from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import routes from 'routes'
+import { useDispatch, useSelector } from 'react-redux'
import Header from 'components/Header'
import MainPage from 'pages/MainPage'
@@ -8,19 +9,54 @@ import SignUp from 'pages/Auth/Signup'
import SignIn from 'pages/Auth/Signin'
import ForgotPassword from 'pages/Auth/ForgotPassword'
import Dashboard from 'pages/Dashboard'
+import UserSettings from 'pages/UserSettings'
+import VerifyEmail from 'pages/Auth/VerifyEmail'
+
+import { isAuthenticated, notAuthenticated } from './hoc/protected'
+import { getAccessToken } from 'utils/accessToken'
+import { authMe } from './api'
+import { authActions } from "actions/auth"
+
+const ProtectedSignIn = notAuthenticated(SignIn)
+const ProtectedSignUp = notAuthenticated(SignUp)
+const ProtectedForgotPassword = notAuthenticated(ForgotPassword)
+const ProtectedDashboard = isAuthenticated(Dashboard)
+const ProtectedUserSettings = isAuthenticated(UserSettings)
+
+const App = () => {
+ const dispatch = useDispatch()
+ const { loading, authenticated } = useSelector(state => state.auth)
+ const { error } = useSelector(state => state.errors)
+ const accessToken = getAccessToken()
+
+ useEffect(() => {
+ (async () => {
+ if (accessToken) {
+ const me = await authMe()
+
+ dispatch(authActions.loginSuccess(me))
+ dispatch(authActions.finishLoading())
+ }
+ })()
+ }, [dispatch, accessToken])
-export default () => {
return (
- <>
- <Header />
- <Switch>
- <Route path={routes.signin} component={SignIn} exact />
- <Route path={routes.signup} component={SignUp} exact />
- <Route path={routes.recovery} component={ForgotPassword} exact />
- <Route path={routes.main} component={MainPage} exact />
- <Route path={routes.dashboard} component={Dashboard} exact />
- <Redirect to={routes.main} />
- </Switch>
- </>
+ (!accessToken || !loading) && (
+ <>
+ <Header authenticated={authenticated} />
+ <Switch>
+ <Route path={routes.main} component={MainPage} exact />
+ <Route path={routes.signin} component={ProtectedSignIn} exact />
+ <Route path={routes.signup} component={ProtectedSignUp} exact />
+ <Route path={routes.dashboard} component={ProtectedDashboard} exact />
+ <Route path={routes.user_settings} component={ProtectedUserSettings} exact />
+ <Route path={routes.verify} component={VerifyEmail} exact />
+ <Route path={routes.recovery} component={ProtectedForgotPassword} exact />
+ <Redirect to={routes.main} />
+ </Switch>
+ </>
+ )
)
-}
\ No newline at end of file
+}
+
+export default App
\ No newline at end of file
diff --git a/src/actions/auth/index.js b/src/actions/auth/index.js
index eaaeec6b6..02194c178 100644
--- a/src/actions/auth/index.js
+++ b/src/actions/auth/index.js
@@ -1,5 +1,105 @@
import { types } from './types'
-export const actions = {
-
-}
\ No newline at end of file
+export const authActions = {
+ // Synchronous
+ loginSuccess(user) {
+ return {
+ type: types.LOGIN_SUCCESSFUL,
+ payload: { user }
+ }
+ },
+
+ emailVerifySuccess() {
+ return {
+ type: types.EMAIL_VERIFY_SUCCESSFUL
+ }
+ },
+
+ signupSuccess(user) {
+ return {
+ type: types.SIGNUP_UP_SUCCESSFUL,
+ payload: { user }
+ }
+ },
+
+ updateProfileSuccess(user) {
+ return {
+ type: types.UPDATE_USER_PROFILE_SUCCESS,
+ payload: { user }
+ }
+ },
+
+ logout() {
+ localStorage.removeItem('access_token')
+ localStorage.removeItem('user_info')
+ document.cookie = 'email_confirm=false max-age=0 path=/'
+
+ return {
+ type: types.LOGOUT
+ }
+ },
+
+ clearErrors() {
+ return {
+ type: types.CLEAR_ERRORS
+ }
+ },
+
+ savePath(path) {
+ return {
+ type: types.SAVE_PATH,
+ payload: { path }
+ }
+ },
+
+ deleteAccountSuccess() {
+ localStorage.removeItem('access_token')
+ localStorage.removeItem('user_info')
+
+ return {
+ type: types.DELETE_ACCOUNT_SUCCESS
+ }
+ },
+
+ finishLoading() {
+ return {
+ type: types.FINISH_LOADING
+ }
+ },
+
+ // Asynchronous
+ loginAsync(credentials) {
+ return {
+ type: types.LOGIN_ASYNC,
+ payload: { credentials }
+ }
+ },
+
+ signupAsync(data, resetRecaptcha) {
+ return {
+ type: types.SIGNUP_ASYNC,
+ payload: { data, resetRecaptcha }
+ }
+ },
+
+ emailVerifyAsync(data, successfulCallback, errorCallback) {
+ return {
+ type: types.EMAIL_VERIFY_ASYNC,
+ payload: { data, successfulCallback, errorCallback }
+ }
+ },
+
+ updateUserProfileAsync(data, successfulCallback = () => {}) {
+ return {
+ type: types.UPDATE_USER_PROFILE_ASYNC,
+ payload: { data, successfulCallback }
+ }
+ },
+
+ deleteAccountAsync(errorCallback) {
+ return {
+ type: types.DELETE_ACCOUNT_ASYNC,
+ payload: { errorCallback }
+ }
+ }
+}
diff --git a/src/actions/auth/types.js b/src/actions/auth/types.js
index e69de29bb..fb9946f94 100644
--- a/src/actions/auth/types.js
+++ b/src/actions/auth/types.js
@@ -0,0 +1,19 @@
+export const types = {
+ // Synchronous
+ FINISH_LOADING: 'FINISH_LOADING',
+ LOGIN_SUCCESSFUL: 'LOGIN_SUCCESSFUL',
+ EMAIL_VERIFY_SUCCESSFUL: 'EMAIL_VERIFY_SUCCESSFUL',
+ EMAIL_VERIFY_FAILED: 'EMAIL_VERIFY_FAILED',
+ SIGNUP_UP_SUCCESSFUL: 'SIGNUP_UP_SUCCESSFUL',
+ UPDATE_USER_PROFILE_SUCCESS: 'UPDATE_USER_PROFILE_SUCCESS',
+ LOGOUT: 'LOGOUT',
+ SAVE_PATH: 'SAVE_PATH',
+ DELETE_ACCOUNT_SUCCESS: 'DELETE_ACCOUNT_SUCCESS',
+
+ // Asynchronous
+ LOGIN_ASYNC: 'LOGIN_ASYNC',
+ SIGNUP_ASYNC: 'SIGNUP_ASYNC',
+ EMAIL_VERIFY_ASYNC: 'EMAIL_VERIFY_ASYNC',
+ UPDATE_USER_PROFILE_ASYNC: 'UPDATE_USER_PROFILE_ASYNC',
+ DELETE_ACCOUNT_ASYNC: 'DELETE_ACCOUNT_ASYNC'
+}
diff --git a/src/actions/errors/index.js b/src/actions/errors/index.js
new file mode 100644
index 000000000..6c8b63702
--- /dev/null
+++ b/src/actions/errors/index.js
@@ -0,0 +1,52 @@
+import { types } from './types'
+
+export const errorsActions = {
+ // Authorisation
+ loginFailed(error) {
+ return {
+ type: types.LOGIN_FAILED,
+ payload: { error }
+ }
+ },
+
+ signupFailed(error) {
+ return {
+ type: types.SIGN_UP_FAILED,
+ payload: { error }
+ }
+ },
+
+ createNewPasswordFailed(error) {
+ return {
+ type: types.CREATE_NEW_PASSWORD_FAILED,
+ payload: { error }
+ }
+ },
+
+ updateProfileFailed(error) {
+ return {
+ type: types.UPDATE_USER_PROFILE_FAILED,
+ payload: { error }
+ }
+ },
+
+ canteensErrors(error) {
+ return {
+ type: types.CANTEENS_ERRORS,
+ payload: { error }
+ }
+ },
+
+ deleteAccountFailed(error) {
+ return {
+ type: types.DELETE_ACCOUNT_FAILED,
+ payload: { error }
+ }
+ },
+
+ clearErrors() {
+ return {
+ type: types.CLEAR_ERRORS
+ }
+ },
+}
diff --git a/src/actions/errors/types.js b/src/actions/errors/types.js
new file mode 100644
index 000000000..47d51cbf3
--- /dev/null
+++ b/src/actions/errors/types.js
@@ -0,0 +1,11 @@
+export const types = {
+ // Authorisation
+ LOGIN_FAILED: 'LOGIN_FAILED',
+ SIGN_UP_FAILED: 'SIGN_UP_FAILED',
+ UPDATE_USER_PROFILE_FAILED: 'UPDATE_USER_PROFILE_FAILED',
+ CREATE_NEW_PASSWORD_FAILED: 'CREATE_NEW_PASSWORD_FAILED',
+ DELETE_ACCOUNT_FAILED: 'DELETE_ACCOUNT_FAILED',
+
+ // Common
+ CLEAR_ERRORS: 'CLEAR_ERRORS'
+}
diff --git a/src/api/index.js b/src/api/index.js
new file mode 100644
index 000000000..7e670b5ca
--- /dev/null
+++ b/src/api/index.js
@@ -0,0 +1,116 @@
+import axios from 'axios'
+import { store } from 'store'
+import { authActions } from 'actions/auth'
+import { getAccessToken, removeAccessToken } from "utils/accessToken"
+
+const api = axios.create({
+ baseURL: process.env.REACT_APP_API_URL,
+})
+
+api.interceptors.request.use(
+ (config) => {
+ const token = getAccessToken()
+ if (token) {
+ config.headers['Authorization'] = `Bearer ${token}`
+ }
+ return config
+ },
+ (error) => {
+ return Promise.reject(error)
+ }
+)
+
+api.interceptors.response.use(
+ (response) => response,
+ (error) => {
+ if (error.response.data.statusCode === 401) {
+ removeAccessToken()
+ store.dispatch(authActions.logout())
+ }
+ return Promise.reject(error)
+ }
+)
+
+export const authMe = () =>
+ api
+ .get('/auth/me')
+ .then((response) => response.data)
+ .catch((error) => {
+ throw new Error(error.response.data.message)
+ })
+
+export const login = (credentials) =>
+ api
+ .post('/auth/login', credentials)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw new Error(error.response.data.message)
+ })
+
+export const signup = (data) =>
+ api
+ .post('/auth/register', data)
+ .then((response) => response.data)
+ .catch((error) => {
+ const errorsArray = error.response.data.message
+ if (Array.isArray(errorsArray)) {
+ throw errorsArray
+ }
+ throw new Error(errorsArray)
+ })
+
+export const deleteUser = () =>
+ api
+ .delete('/user')
+ .then((response) => response.data)
+ .catch((error) => {
+ throw new Error(JSON.stringify(error.response.data))
+ })
+
+export const changeUserDetails = (data) =>
+ api
+ .put('/user', data)
+ .then((response) => response.data)
+ .catch((error) => {
+ const errorsArray = error.response.data.message
+ if (Array.isArray(errorsArray)) {
+ throw errorsArray
+ }
+ throw new Error(errorsArray)
+ })
+
+export const forgotPassword = (email) =>
+ api
+ .post('/auth/user/reset-password', email)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw new Error(error.response.data.message)
+ })
+
+export const confirmEmail = () =>
+ api
+ .post('/user/confirm_email')
+ .then(response => response.data)
+ .catch(error => {
+ throw new Error(error.response.data.message)
+ })
+
+export const createNewPassword = (id, password) =>
+ api
+ .post(`/auth/password-reset/${id}`, password)
+ .then((response) => response.data)
+ .catch((error) => {
+ const errorsArray = error.response.data.message
+ if (Array.isArray(errorsArray)) {
+ throw errorsArray
+ }
+ throw new Error(errorsArray)
+ })
+
+export const verifyEmail = ({ path, id }) =>
+ api
+ .get(`/auth/${path}/${id}`)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw new Error(error.response.data.message)
+ })
\ No newline at end of file
diff --git a/src/components/Header/index.jsx b/src/components/Header/index.jsx
index 8a52f4735..dbbe8bacd 100644
--- a/src/components/Header/index.jsx
+++ b/src/components/Header/index.jsx
@@ -1,8 +1,11 @@
import React from 'react'
import { Link } from 'react-router-dom'
+import { useDispatch } from 'react-redux'
import routes from 'routes'
+import { authActions } from 'actions/auth'
-export default () => {
+const Header = ({ authenticated }) => {
+ const dispatch = useDispatch()
return (
<header className="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm">
@@ -18,7 +21,17 @@ export default () => {
<Link to="/" className="p-2 text-dark">FAQs</Link>
<Link to="/" className="p-2 text-dark">Docs</Link>
</nav>
- <Link to={routes.signup} className="btn btn-outline-primary">Get started</Link>
+ { authenticated
+ ? (
+ <>
+ <Link to={routes.user_settings} className="p-2 text-dark">You</Link>
+ <button className="p-2 text-dark btn btn-link" onClick={() => dispatch(authActions.logout())}>Exit</button>
+ </>
+ )
+ : <Link to={routes.signup} className="btn btn-outline-primary">Get started</Link>
+ }
</header>
)
-}
\ No newline at end of file
+}
+
+export default React.memo(Header)
\ No newline at end of file
diff --git a/src/hoc/protected.js b/src/hoc/protected.js
new file mode 100644
index 000000000..d2cb7f629
--- /dev/null
+++ b/src/hoc/protected.js
@@ -0,0 +1,20 @@
+import { connectedRouterRedirect } from 'redux-auth-wrapper/history4/redirect'
+import routes from 'routes'
+
+export const isAuthenticated = connectedRouterRedirect({
+ redirectPath: routes.signin,
+ authenticatedSelector: state => state.auth.authenticated,
+ wrapperDisplayName: 'userIsAuthenticated',
+ allowRedirectBack: false
+})
+
+export const notAuthenticated = connectedRouterRedirect({
+ redirectPath: (state) => {
+ const path = state.auth.redirectPath
+ return path || routes.dashboard
+ },
+
+ authenticatedSelector: state => !state.auth.authenticated,
+ wrapperDisplayName: 'userIsNotAuthenticated',
+ allowRedirectBack: false
+})
diff --git a/src/index.js b/src/index.js
index 8167d0087..65ffdc418 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,25 +1,22 @@
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
-// import { store } from 'store'
-// import { Provider } from 'react-redux'
+import { store } from 'store'
+import { Provider } from 'react-redux'
import './index.scss'
import 'bootstrap/dist/css/bootstrap.min.css'
import App from './App'
-import reportWebVitals from './reportWebVitals'
+// import reportWebVitals from './reportWebVitals'
ReactDOM.render(
<React.StrictMode>
- {/* <Provider store={store}> */}
+ <Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
- {/* </Provider> */}
+ </Provider>
</React.StrictMode>,
document.getElementById('root')
)
-// If you want to start measuring performance in your app, pass a function
-// to log results (for example: reportWebVitals(console.log))
-// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
-reportWebVitals()
\ No newline at end of file
+// reportWebVitals()
\ No newline at end of file
diff --git a/src/pages/Auth/ForgotPassword/ForgotPassword.jsx b/src/pages/Auth/ForgotPassword/ForgotPassword.jsx
index 71febcf32..c1af7eed0 100644
--- a/src/pages/Auth/ForgotPassword/ForgotPassword.jsx
+++ b/src/pages/Auth/ForgotPassword/ForgotPassword.jsx
@@ -59,7 +59,7 @@ export default ({ onSubmit }) => {
<Form.Control
type="email"
value={form.email}
- placeholder="[email protected]"
+ placeholder="[email protected]"
id="email"
className="form-control"
name="email"
@@ -72,15 +72,15 @@ export default ({ onSubmit }) => {
{errors.email}
</Form.Control.Feedback>
</Form.Group>
+ <div className="d-flex align-items-center mb-3">
+ <Link to={routes.signin} className="btn btn-link">
+ Sign in
+ </Link>
+ <button type="submit" className="btn btn-primary ml-auto">
+ Reset password
+ </button>
+ </div>
</Form>
- <div className="d-flex align-items-center mb-3">
- <Link to={routes.signin} className="btn btn-link">
- Sign in
- </Link>
- <button type="submit" className="btn btn-primary ml-auto">
- Reset password
- </button>
- </div>
</div>
)
}
\ No newline at end of file
diff --git a/src/pages/Auth/Signin/Signin.container.jsx b/src/pages/Auth/Signin/Signin.container.jsx
index 1ac2c5fae..c34b72483 100644
--- a/src/pages/Auth/Signin/Signin.container.jsx
+++ b/src/pages/Auth/Signin/Signin.container.jsx
@@ -1,8 +1,12 @@
import Signin from './Signin'
+import { useDispatch } from 'react-redux'
+import { authActions } from 'actions/auth'
export default () => {
+ const dispatch = useDispatch()
+
const onSubmit = data => {
- console.log(data)
+ dispatch(authActions.loginAsync(data))
}
return (
diff --git a/src/pages/Auth/Signin/Signin.jsx b/src/pages/Auth/Signin/Signin.jsx
index 0799106fa..af390e800 100644
--- a/src/pages/Auth/Signin/Signin.jsx
+++ b/src/pages/Auth/Signin/Signin.jsx
@@ -61,7 +61,7 @@ export default ({ onSubmit }) => {
<Form.Control
type="email"
value={form.email}
- placeholder="[email protected]"
+ placeholder="[email protected]"
id="email"
className="form-control"
name="email"
@@ -87,32 +87,32 @@ export default ({ onSubmit }) => {
required
/>
</Form.Group>
- </Form>
- <Form.Group className="custom-control custom-checkbox">
- <Form.Control
- type="checkbox"
- checked={form.keep_signedin}
- id="keep_signedin"
- className="custom-control-input"
- name="keep_signedin"
- onChange={handleInput}
- />
- <Form.Label htmlFor="keep_signedin" className="custom-control-label">
- Don't remember me.
+ <Form.Group className="custom-control custom-checkbox">
+ <Form.Control
+ type="checkbox"
+ checked={form.keep_signedin}
+ id="keep_signedin"
+ className="custom-control-input"
+ name="keep_signedin"
+ onChange={handleInput}
+ />
+ <Form.Label htmlFor="keep_signedin" className="custom-control-label">
+ Don't remember me.
</Form.Label>
- </Form.Group>
- <div className="d-flex align-items-center mb-3">
- <Link to={routes.reset_password} className="btn btn-link">
- Forgot password?
+ </Form.Group>
+ <div className="d-flex align-items-center mb-3">
+ <Link to={routes.reset_password} className="btn btn-link">
+ Forgot password?
</Link>
- <span> | </span>
- <Link to={routes.signup} className="btn btn-link">
- Sign up instead
+ <span> | </span>
+ <Link to={routes.signup} className="btn btn-link">
+ Sign up instead
</Link>
- <button type="submit" className="btn btn-primary ml-auto">
- Sign in
+ <button type="submit" className="btn btn-primary ml-auto">
+ Sign in
</button>
- </div>
+ </div>
+ </Form>
</div>
)
}
\ No newline at end of file
diff --git a/src/pages/Auth/Signup/Signup.container.jsx b/src/pages/Auth/Signup/Signup.container.jsx
index a07ba9621..dfd10548d 100644
--- a/src/pages/Auth/Signup/Signup.container.jsx
+++ b/src/pages/Auth/Signup/Signup.container.jsx
@@ -1,11 +1,13 @@
import Signup from './Signup'
-// import { useDispatch } from 'react-redux'
+import { useDispatch } from 'react-redux'
+import { authActions } from 'actions/auth'
export default () => {
- // const dispatch = useDispatch()
+ const dispatch = useDispatch()
const onSubmit = data => {
- console.log(data)
+ delete data.repeat
+ dispatch(authActions.signupAsync(data, () => {}))
}
return (
diff --git a/src/pages/Auth/Signup/Signup.jsx b/src/pages/Auth/Signup/Signup.jsx
index 7a58f516d..7abc5ec2a 100644
--- a/src/pages/Auth/Signup/Signup.jsx
+++ b/src/pages/Auth/Signup/Signup.jsx
@@ -75,7 +75,7 @@ export default ({ onSubmit }) => {
<Form.Control
type="email"
value={form.email}
- placeholder="[email protected]"
+ placeholder="[email protected]"
id="email"
className="form-control"
name="email"
@@ -142,28 +142,28 @@ export default ({ onSubmit }) => {
{errors.tos}
</Form.Control.Feedback>
</Form.Group>
- </Form>
- <Form.Group className="custom-control custom-checkbox">
- <Form.Control
- type="checkbox"
- checked={form.keep_signedin}
- id="keep_signedin"
- className="custom-control-input"
- name="keep_signedin"
- onChange={handleInput}
- />
- <Form.Label htmlFor="keep_signedin" className="custom-control-label">
- Don't remember me.
- </Form.Label>
- </Form.Group>
- <div className="d-flex align-items-center mb-3">
- <Link to={routes.signin} className="btn btn-link">
- Sign in instead
+ <Form.Group className="custom-control custom-checkbox">
+ <Form.Control
+ type="checkbox"
+ checked={form.keep_signedin}
+ id="keep_signedin"
+ className="custom-control-input"
+ name="keep_signedin"
+ onChange={handleInput}
+ />
+ <Form.Label htmlFor="keep_signedin" className="custom-control-label">
+ Don't remember me.
+ </Form.Label>
+ </Form.Group>
+ <div className="d-flex align-items-center mb-3">
+ <Link to={routes.signin} className="btn btn-link">
+ Sign in instead
</Link>
- <button type="submit" className="btn btn-primary ml-auto">
- Sign up
- </button>
- </div>
+ <button type="submit" className="btn btn-primary ml-auto">
+ Sign up
+ </button>
+ </div>
+ </Form>
</div>
)
}
\ No newline at end of file
diff --git a/src/pages/Auth/VerifyEmail/index.jsx b/src/pages/Auth/VerifyEmail/index.jsx
new file mode 100644
index 000000000..44c70b136
--- /dev/null
+++ b/src/pages/Auth/VerifyEmail/index.jsx
@@ -0,0 +1,44 @@
+import React, { useState, useEffect } from 'react'
+import { Link } from 'react-router-dom'
+import Spinner from 'react-bootstrap/Spinner'
+import { useDispatch } from 'react-redux'
+import { useParams } from 'react-router-dom'
+
+import routes from 'routes'
+import { authActions } from 'actions/auth'
+
+const VerifyEmail = () => {
+ const dispatch = useDispatch()
+ const { id } = useParams()
+ const [loading, setLoading] = useState(true)
+ const [error, setError] = useState('')
+
+ useEffect(() => {
+ setLoading(true)
+ const path = window.location.pathname.split('/')[1]
+
+ dispatch(authActions.emailVerifyAsync(
+ { path, id },
+ () => setLoading(false),
+ (error) => {
+ setError(error.message)
+ setLoading(false)
+ }))
+ }, [dispatch, id])
+
+ return (
+ <div className="container d-flex justify-content-center">
+ {loading
+ ? (
+ <Spinner animation="border" role="status">
+ <span className="sr-only">Loading...</span>
+ </Spinner>
+ )
+ : (
+ <p>{ error ? error : 'Your email has been successfully verified!' }</p>
+ )}
+ </div>
+ )
+}
+
+export default VerifyEmail
\ No newline at end of file
diff --git a/src/pages/UserSettings/UserSettings.container.jsx b/src/pages/UserSettings/UserSettings.container.jsx
new file mode 100644
index 000000000..e7c170448
--- /dev/null
+++ b/src/pages/UserSettings/UserSettings.container.jsx
@@ -0,0 +1,3 @@
+import UserSettings from './UserSettings'
+
+export default UserSettings
\ No newline at end of file
diff --git a/src/pages/UserSettings/UserSettings.jsx b/src/pages/UserSettings/UserSettings.jsx
new file mode 100644
index 000000000..84e214edc
--- /dev/null
+++ b/src/pages/UserSettings/UserSettings.jsx
@@ -0,0 +1,8 @@
+import React from 'react'
+
+export default () => {
+
+ return (
+ <h1>UserSettings page</h1>
+ )
+}
\ No newline at end of file
diff --git a/src/pages/UserSettings/index.jsx b/src/pages/UserSettings/index.jsx
index e69de29bb..6f7e983e1 100644
--- a/src/pages/UserSettings/index.jsx
+++ b/src/pages/UserSettings/index.jsx
@@ -0,0 +1,3 @@
+import UserSettings from './UserSettings.container'
+
+export default UserSettings
\ No newline at end of file
diff --git a/src/reducers/auth.js b/src/reducers/auth.js
index 2a6675d82..886afd461 100644
--- a/src/reducers/auth.js
+++ b/src/reducers/auth.js
@@ -9,8 +9,27 @@ const initialState = {
export default (state = initialState, { type, payload }) => {
switch (type) {
-
- default:
- return state
+ case types.SIGNUP_UP_SUCCESSFUL:
+ case types.LOGIN_SUCCESSFUL:
+ return { ...state, user: payload.user, authenticated: true }
+
+ case types.UPDATE_USER_PROFILE_SUCCESS:
+ return { ...state, user: payload.user }
+
+ case types.EMAIL_VERIFY_SUCCESSFUL:
+ return { ...state, user: { ...state.user, isActive: true }}
+
+ case types.SAVE_PATH:
+ return { ...state, redirectPath: payload.path }
+
+ case types.LOGOUT:
+ case types.DELETE_ACCOUNT_SUCCESS:
+ return { ...state, authenticated: false, user: null }
+
+ case types.FINISH_LOADING:
+ return { ...state, loading: false }
+
+ default:
+ return state
}
}
\ No newline at end of file
diff --git a/src/reducers/errors.js b/src/reducers/errors.js
new file mode 100644
index 000000000..6964c00c6
--- /dev/null
+++ b/src/reducers/errors.js
@@ -0,0 +1,22 @@
+import { types } from 'actions/errors/types'
+
+const initialState = {
+ error: null
+}
+
+export default (state = initialState, { type, payload }) => {
+ switch (type) {
+ case types.LOGIN_FAILED:
+ case types.SIGN_UP_FAILED:
+ case types.UPDATE_USER_PROFILE_FAILED:
+ case types.CREATE_NEW_PASSWORD_FAILED:
+ case types.DELETE_ACCOUNT_FAILED:
+ return { ...state, error: payload.error }
+
+ case types.CLEAR_ERRORS:
+ return { ...state, error: null }
+
+ default:
+ return state
+ }
+}
diff --git a/src/reducers/index.js b/src/reducers/index.js
index 4df645a17..40dd8c233 100644
--- a/src/reducers/index.js
+++ b/src/reducers/index.js
@@ -1,4 +1,5 @@
import { combineReducers } from 'redux'
import auth from './auth'
+import errors from './errors'
-export default combineReducers({ auth })
\ No newline at end of file
+export default combineReducers({ auth, errors })
\ No newline at end of file
diff --git a/src/routes.js b/src/routes.js
index 1ef8f3a4d..24f8c71ea 100644
--- a/src/routes.js
+++ b/src/routes.js
@@ -3,5 +3,7 @@ export default Object.freeze({
signup: '/signup',
reset_password: '/recovery',
main: '/',
- dashboard: '/dashboard'
+ dashboard: '/dashboard',
+ user_settings: '/settings',
+ verify: '/verify/:id',
})
\ No newline at end of file
diff --git a/src/sagas/.gitsave b/src/sagas/.gitsave
deleted file mode 100644
index e69de29bb..000000000
diff --git a/src/sagas/auth/watchers/index.js b/src/sagas/auth/watchers/index.js
new file mode 100644
index 000000000..ea45b757a
--- /dev/null
+++ b/src/sagas/auth/watchers/index.js
@@ -0,0 +1,31 @@
+import { takeLatest, all, call } from 'redux-saga/effects'
+import { types } from 'actions/auth/types'
+import signIn from 'sagas/auth/workers/signin'
+import signUp from 'sagas/auth/workers/signup'
+import verifyEmail from 'sagas/auth/workers/verifyEmail'
+import updateUserProfile from 'sagas/auth/workers/updateUserProfile'
+import deleteUserAccount from "sagas/auth/workers/deleteUserAccount"
+
+function* watchLogin() {
+ yield takeLatest(types.LOGIN_ASYNC, signIn)
+}
+
+function* watchVerifyEmail() {
+ yield takeLatest(types.EMAIL_VERIFY_ASYNC, verifyEmail)
+}
+
+function* watchSignup() {
+ yield takeLatest(types.SIGNUP_ASYNC, signUp)
+}
+
+function* watchUpdateUserProfile() {
+ yield takeLatest(types.UPDATE_USER_PROFILE_ASYNC, updateUserProfile)
+}
+
+function* watchDeleteUserProfile() {
+ yield takeLatest(types.DELETE_ACCOUNT_ASYNC, deleteUserAccount)
+}
+
+export default function* watchAuth() {
+ yield all([call(watchLogin), call(watchSignup), call(watchVerifyEmail), call(watchUpdateUserProfile), call(watchDeleteUserProfile)])
+}
diff --git a/src/sagas/auth/workers/deleteUserAccount.js b/src/sagas/auth/workers/deleteUserAccount.js
new file mode 100644
index 000000000..ab534c397
--- /dev/null
+++ b/src/sagas/auth/workers/deleteUserAccount.js
@@ -0,0 +1,14 @@
+import { call, put } from 'redux-saga/effects'
+import { authActions } from 'actions/auth'
+import { deleteUser } from 'api'
+
+export default function* ({ payload: { errorCallback } }) {
+ try {
+ yield call(deleteUser)
+ yield put(authActions.deleteAccountSuccess())
+ } catch (e) {
+ errorCallback(JSON.parse(e.message))
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/src/sagas/auth/workers/signin.js b/src/sagas/auth/workers/signin.js
new file mode 100644
index 000000000..3a569c48c
--- /dev/null
+++ b/src/sagas/auth/workers/signin.js
@@ -0,0 +1,18 @@
+import { call, put } from 'redux-saga/effects'
+import { authActions } from 'actions/auth'
+import { errorsActions } from 'actions/errors'
+import { setAccessToken } from 'utils/accessToken'
+import { login } from 'api'
+
+export default function* ({ payload: { credentials } }) {
+ try {
+ const response = yield call(login, credentials)
+
+ yield put(authActions.loginSuccess(response.user))
+ yield call(setAccessToken, JSON.stringify(response.access_token))
+ } catch (error) {
+ yield put(errorsActions.loginFailed(`serverErrors.${error.message}`))
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/src/sagas/auth/workers/signup.js b/src/sagas/auth/workers/signup.js
new file mode 100644
index 000000000..1c17c0a00
--- /dev/null
+++ b/src/sagas/auth/workers/signup.js
@@ -0,0 +1,19 @@
+import { call, put } from 'redux-saga/effects'
+import { authActions } from 'actions/auth'
+import { errorsActions } from 'actions/errors'
+import { setAccessToken } from "utils/accessToken"
+import { signup } from 'api'
+
+export default function* ({ payload: { data, resetRecaptcha } }) {
+ try {
+ const response = yield call(signup, data)
+
+ yield put(authActions.signupSuccess(response.user))
+ yield call(setAccessToken, JSON.stringify(response.access_token))
+ } catch (error) {
+ yield put(errorsActions.signupFailed(`serverErrors.${error.message || (typeof error === 'string' ? error : error[0])}`))
+ resetRecaptcha()
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/src/sagas/auth/workers/updateUserProfile.js b/src/sagas/auth/workers/updateUserProfile.js
new file mode 100644
index 000000000..b79da335c
--- /dev/null
+++ b/src/sagas/auth/workers/updateUserProfile.js
@@ -0,0 +1,17 @@
+import { call, put } from 'redux-saga/effects'
+import { authActions } from 'actions/auth'
+import { errorsActions } from 'actions/errors'
+import { changeUserDetails } from 'api'
+
+export default function* ({ payload: { data, successfulCallback } }) {
+ try {
+ const user = yield call(changeUserDetails, data)
+
+ yield put(authActions.updateProfileSuccess(user))
+ successfulCallback()
+ } catch (error) {
+ yield put(errorsActions.updateProfileFailed(error.message || (typeof error === 'string' ? error : error[0])))
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/src/sagas/auth/workers/verifyEmail.js b/src/sagas/auth/workers/verifyEmail.js
new file mode 100644
index 000000000..b82d3ed14
--- /dev/null
+++ b/src/sagas/auth/workers/verifyEmail.js
@@ -0,0 +1,15 @@
+import { call, put } from 'redux-saga/effects'
+import { authActions } from 'actions/auth'
+import { verifyEmail } from "api"
+
+export default function* ({ payload: { data, successfulCallback, errorCallback } }) {
+ try {
+ yield call(verifyEmail, data)
+ yield put(authActions.emailVerifySuccess())
+ successfulCallback()
+ } catch (error) {
+ errorCallback(error)
+ } finally {
+ yield put(authActions.finishLoading())
+ }
+}
diff --git a/src/sagas/index.js b/src/sagas/index.js
new file mode 100644
index 000000000..604e19101
--- /dev/null
+++ b/src/sagas/index.js
@@ -0,0 +1,6 @@
+import { all, call } from 'redux-saga/effects'
+import watchAuth from 'sagas/auth/watchers'
+
+export default function* rootSaga() {
+ yield all([call(watchAuth)])
+}
diff --git a/src/store/index.js b/src/store/index.js
index 3963162f1..5ef2eb182 100644
--- a/src/store/index.js
+++ b/src/store/index.js
@@ -1,14 +1,14 @@
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import root_reducer from 'reducers'
-// import root_saga from 'sagas'
+import root_saga from 'sagas'
-// const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
-// const sagaMiddleware = createSagaMiddleware()
+const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
+const sagaMiddleware = createSagaMiddleware()
export const store = createStore(
root_reducer,
- // composeEnhancers(applyMiddleware(sagaMiddleware))
+ composeEnhancers(applyMiddleware(sagaMiddleware))
)
-// sagaMiddleware.run(root_saga)
\ No newline at end of file
+sagaMiddleware.run(root_saga)
\ No newline at end of file
diff --git a/src/utils/accessToken.js b/src/utils/accessToken.js
new file mode 100644
index 000000000..851b7adc6
--- /dev/null
+++ b/src/utils/accessToken.js
@@ -0,0 +1,24 @@
+export const getAccessToken = () => {
+ const accessToken = localStorage.getItem('access_token')
+ let token = null
+
+ if (!accessToken) {
+ return null
+ }
+
+ try {
+ token = JSON.parse(accessToken)
+ } catch(e) {
+ console.error('Error while parsing access token: ' + e)
+ }
+
+ return token
+}
+
+export const setAccessToken = token => {
+ localStorage.setItem('access_token', token)
+}
+
+export const removeAccessToken = () => {
+ localStorage.removeItem('access_token')
+}
diff --git a/src/utils/cookie.js b/src/utils/cookie.js
new file mode 100644
index 000000000..44dca0e65
--- /dev/null
+++ b/src/utils/cookie.js
@@ -0,0 +1,8 @@
+export const getCookie = key => {
+ const match = document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)'))
+ if (match) return match[2]
+}
+
+export const setCookie = (key, value, maxAge = 3600) => {
+ document.cookie = `${key}=${value}; max-age=${maxAge}; path=/`
+}
\ No newline at end of file