Skip to content

Commit

Permalink
Fix auth store
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaron-9900 committed Feb 23, 2021
1 parent fdb4253 commit ca9be41
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 34 deletions.
42 changes: 20 additions & 22 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { RootStoreProvider } from "./models/root-store/root-store-context"
import { setupRootStore } from "./models/root-store/setup-root-store"
import { BrowserRouter as Router, Switch, Route } from "react-router-dom"
import { Spin } from "antd"
const Home = React.lazy(() => import("./screens/home"))
const Login = React.lazy(() => import("./screens/login"))
const Register = React.lazy(() => import("./screens/register"))
import Home from "./screens/home"
import Login from "./screens/login"
import Register from "./screens/register"

const App = observer(function App() {
const [rootStore, setRootStore] = useState<RootStore | null>(null)
Expand All @@ -19,25 +19,23 @@ const App = observer(function App() {
}, [])
if (!rootStore) return null
return (
<div className="App">
<RootStoreProvider value={rootStore}>
<Suspense fallback={<Spin size="large" style={{ color: "red" }} />}>
<Router>
<Switch>
<Route exact path="/">
<Home></Home>
</Route>
<Route path="/login">
<Login></Login>
</Route>
<Route path="/register">
<Register></Register>
</Route>
</Switch>
</Router>
</Suspense>
</RootStoreProvider>
</div>
<RootStoreProvider value={rootStore}>
<div className="App">
<Router>
<Switch>
<Route exact path="/">
<Home></Home>
</Route>
<Route path="/login">
<Login></Login>
</Route>
<Route path="/register">
<Register></Register>
</Route>
</Switch>
</Router>
</div>
</RootStoreProvider>
)
})

Expand Down
4 changes: 4 additions & 0 deletions src/models/auth-model/auth-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export const AuthModel = types
.model("AuthModel")
.props({
loading: false,
username: "",
id: 0,
})
.extend(withEnvironment)
.actions((self) => {
Expand All @@ -14,6 +16,8 @@ export const AuthModel = types
try {
const resp = yield self.environment.api.login(email, password)
self.loading = false
self.username = resp.response.username
self.id = resp.response.id
return resp
} catch (err) {
self.loading = false
Expand Down
2 changes: 1 addition & 1 deletion src/models/root-store/root-store-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ export const RootStoreProvider = RootStoreContext.Provider
* `const { someStore, someOtherStore } = useStores()`,
* or less likely: `const rootStore = useStores()`
*/
export const useStores = () => useContext(RootStoreContext)
export const useStores = (): RootStore => useContext(RootStoreContext)
21 changes: 18 additions & 3 deletions src/models/root-store/setup-root-store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { RootStoreModel } from "./root-store"
import { RootStore, RootStoreModel } from "./root-store"
import { Environment } from "../environment"
import { onSnapshot } from "mobx-state-tree"

/**
* The key we'll be saving our state as within async storage.
Expand All @@ -18,12 +19,26 @@ export async function createEnvironment() {
return env
}

const ROOT_STATE_STORAGE_KEY = "root"

/**
* Setup the root state.
*/
export async function setupRootStore() {
let rootStore: RootStore

// prepare the environment that will be associated with the RootStore.
const env = await createEnvironment()
const rootStore = RootStoreModel.create({}, env)
if (localStorage.getItem(ROOT_STATE_STORAGE_KEY) !== null) {
const data = JSON.parse(localStorage.getItem(ROOT_STATE_STORAGE_KEY) as string)
rootStore = RootStoreModel.create(data, env)
} else {
rootStore = RootStoreModel.create({}, env)
}
// track changes & save to storage
onSnapshot(rootStore, (snapshot) =>
localStorage.setItem(ROOT_STATE_STORAGE_KEY, JSON.stringify(snapshot)),
)

return rootStore
}
export {}
12 changes: 10 additions & 2 deletions src/screens/home.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Avatar, List, Typography } from "antd"
import { Avatar, List, PageHeader, Typography } from "antd"
import { observer } from "mobx-react-lite"
import React, { ReactElement, useEffect } from "react"
import { CenteredBody } from "../components"
Expand All @@ -16,13 +16,21 @@ const StyledBody = styled(CenteredBody)`
margin-right: 100px;
margin-left: 100px;
`
const StyledHeader = styled(PageHeader)`
width: 100vw;
text-align: right;
position: relative;
top: 0;
`
const Home = observer(function Home(props): ReactElement {
const { proposalsStore } = useStores()
const { proposalsStore, authStore } = useStores()
useEffect(() => {
proposalsStore.getProposals(0, 30)
}, [])
console.log(authStore.username)
return (
<StyledBody>
<StyledHeader title={authStore.username} subTitle="Welcome" />
<StyledList>
{proposalsStore.proposals.map((e) => {
return (
Expand Down
10 changes: 8 additions & 2 deletions src/screens/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useStores } from "../models/root-store/root-store-context"
import { parseError } from "../services/error-parser"
import { Typography } from "antd"
import { observer } from "mobx-react-lite"
import { Link } from "react-router-dom"
import { Link, Redirect } from "react-router-dom"

const { Text, Link: AntdLink } = Typography

Expand Down Expand Up @@ -43,13 +43,19 @@ const StyledTextWrapper = styled.div`
const Login = observer(function Login(): ReactElement {
const { authStore } = useStores()
const [err, setErr] = useState<string | false>(false)
const [isLogged, setLogged] = useState<boolean>(false)
const onFinish = async (value) => {
try {
const resp = await authStore.login(value.email, value.password)
await authStore.login(value.email, value.password)
setLogged(true)
} catch (e) {
console.log(e)
setErr(parseError(e))
}
}
if (isLogged) {
return <Redirect to="/"></Redirect>
}
return (
<CenteredBody>
<StyledForm
Expand Down
10 changes: 10 additions & 0 deletions src/services/api-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,13 @@ export function parseProposals(proposalsList): ProposalsModelStore {
}
})
}

export function parseAuth(auth) {
console.log(auth)
return {
accessToken: auth.access_token,
refreshToken: auth.refresh_token,
username: auth.user.name,
id: auth.user.id,
}
}
10 changes: 9 additions & 1 deletion src/services/api-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@ import { ProposalsModelStore } from "../models/proposals-model/proposals-model-s
import { GeneralApiProblem } from "./api-problem"

export type GetUsersResult =
| { kind: "ok"; tokens: { accessToken: string; refreshToken: string } }
| {
kind: "ok"
response: {
accessToken: string
refreshToken: string
username: string
id: number
}
}
| GeneralApiProblem
export type PostRegister = { kind: "ok"; username: string } | GeneralApiProblem
export type GetProposals = { kind: "ok"; proposals: ProposalsModelStore } | GeneralApiProblem
9 changes: 6 additions & 3 deletions src/services/api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import apisauce, { ApiResponse, ApisauceInstance } from "apisauce"
import Cookies from "universal-cookie/es6"
import { ProposalsModelStore } from "../models/proposals-model/proposals-model-store"
import { parseProposals } from "./api-helpers"
import { parseAuth, parseProposals } from "./api-helpers"
import { getGeneralApiProblem } from "./api-problem"
import { GetProposals, GetUsersResult, PostRegister } from "./api-types"
import { ApiConfig, API_CONFIG } from "./apiconfig"
Expand Down Expand Up @@ -38,9 +38,12 @@ export class Api {
}
try {
const { access_token: accessToken, refresh_token: refreshToken } = response.data
this.client.headers["Access-Token"] = accessToken
this.client.headers["Authorization"] = "Bearer " + accessToken
this.cookies.set("refresh", refreshToken)
return { kind: "ok", tokens: { accessToken: accessToken, refreshToken: refreshToken } }
return {
kind: "ok",
response: parseAuth(response.data),
}
} catch {
return { kind: "bad-data" }
}
Expand Down

0 comments on commit ca9be41

Please sign in to comment.