2020-04-14 02:05:44 -04:00
|
|
|
import React, { useState, useEffect } from "react";
|
2020-04-24 03:53:42 -04:00
|
|
|
import shortid from "shortid";
|
2020-04-14 02:05:44 -04:00
|
|
|
|
2020-04-26 03:59:46 -04:00
|
|
|
import { getRandomMonster } from "../helpers/monsters";
|
|
|
|
|
|
|
|
import db from "../database";
|
|
|
|
|
2020-04-14 02:05:44 -04:00
|
|
|
const AuthContext = React.createContext();
|
|
|
|
|
|
|
|
export function AuthProvider({ children }) {
|
|
|
|
const [password, setPassword] = useState(
|
|
|
|
sessionStorage.getItem("auth") || ""
|
|
|
|
);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
sessionStorage.setItem("auth", password);
|
|
|
|
}, [password]);
|
|
|
|
|
|
|
|
const [authenticationStatus, setAuthenticationStatus] = useState("unknown");
|
|
|
|
|
2020-04-24 03:53:42 -04:00
|
|
|
const [userId, setUserId] = useState();
|
|
|
|
useEffect(() => {
|
2020-04-26 03:59:46 -04:00
|
|
|
async function loadUserId() {
|
|
|
|
const storedUserId = await db.table("user").get("userId");
|
|
|
|
if (storedUserId) {
|
|
|
|
setUserId(storedUserId.value);
|
|
|
|
} else {
|
|
|
|
const id = shortid.generate();
|
|
|
|
setUserId(id);
|
|
|
|
db.table("user").add({ key: "userId", value: id });
|
|
|
|
}
|
2020-04-24 03:53:42 -04:00
|
|
|
}
|
2020-04-26 03:59:46 -04:00
|
|
|
|
|
|
|
loadUserId();
|
2020-04-24 03:53:42 -04:00
|
|
|
}, []);
|
|
|
|
|
2020-04-26 03:59:46 -04:00
|
|
|
const [nickname, setNickname] = useState("");
|
|
|
|
useEffect(() => {
|
|
|
|
async function loadNickname() {
|
|
|
|
const storedNickname = await db.table("user").get("nickname");
|
|
|
|
if (storedNickname) {
|
|
|
|
setNickname(storedNickname.value);
|
|
|
|
} else {
|
|
|
|
const name = getRandomMonster();
|
|
|
|
setNickname(name);
|
|
|
|
db.table("user").add({ key: "nickname", value: name });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
loadNickname();
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (nickname !== undefined) {
|
|
|
|
db.table("user").update("nickname", { value: nickname });
|
|
|
|
}
|
|
|
|
}, [nickname]);
|
|
|
|
|
2020-04-14 02:05:44 -04:00
|
|
|
const value = {
|
2020-04-24 03:53:42 -04:00
|
|
|
userId,
|
2020-04-26 03:59:46 -04:00
|
|
|
nickname,
|
|
|
|
setNickname,
|
2020-04-14 02:05:44 -04:00
|
|
|
password,
|
|
|
|
setPassword,
|
|
|
|
authenticationStatus,
|
|
|
|
setAuthenticationStatus,
|
|
|
|
};
|
|
|
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default AuthContext;
|