Merge pull request #9 from sorrelbri/guest_account

Guest account
This commit is contained in:
Sorrel 2020-06-27 13:21:27 -07:00 committed by GitHub
commit dd0289439c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 240 additions and 107 deletions

View file

@ -51,3 +51,8 @@ table {
border-collapse: collapse; border-collapse: collapse;
border-spacing: 0; border-spacing: 0;
} }
button {
background: none;
border: none;
}

View file

@ -0,0 +1,34 @@
import React from "react";
import authServices from "../../../services/authServices";
const Guest = ({ dispatch }) => {
const handleClick = async (e) => {
e.preventDefault();
// dispatch to guest endpoint
const guestResponse = await authServices.guestService();
if (guestResponse.errors) {
const authError = guestResponse.errors[0].auth;
return dispatch({
type: "ERR",
message: "AUTH_ERROR",
body: { authError },
});
}
return dispatch({
type: "AUTH",
message: "GUEST",
body: guestResponse,
});
};
return (
<>
<button className="nav__section__button" onClick={handleClick}>
Continue As Guest
</button>
</>
);
};
export default Guest;

View file

@ -1,45 +1,49 @@
import React, { useState } from 'react'; import React, { useState } from "react";
import Login from '../Login/Login'; import Login from "../Login/Login";
import Signup from '../Signup/Signup'; import Signup from "../Signup/Signup";
import Guest from "../../Button/Guest/Guest";
const Auth = (props) => { const Auth = (props) => {
const [ showForm, setShowForm ] = useState('login') const [showForm, setShowForm] = useState("login");
const { state, dispatch } = props; const { state, dispatch } = props;
return ( return (
<> <>
<div <div
className="nav__section nav__section--auth" className="nav__section nav__section--auth"
onClick={()=>{setShowForm('login')}} onClick={() => {
setShowForm("login");
}}
> >
<p <p className="nav__section__label">Login</p>
className="nav__section__label"
>Login</p>
{ {showForm === "login" ? (
showForm === 'login' <Login dispatch={dispatch} state={state} />
? <Login dispatch={dispatch} state={state}/> ) : (
: <></> <></>
} )}
</div> </div>
<div <div
className="nav__section nav__section--auth" className="nav__section nav__section--auth"
onClick={()=>{setShowForm('signup')}} onClick={() => {
setShowForm("signup");
}}
> >
<p <p className="nav__section__label">Signup</p>
className="nav__section__label"
>Signup</p>
{ {showForm === "signup" ? (
showForm === 'signup' <Signup dispatch={dispatch} state={state} />
? <Signup dispatch={dispatch} state={state}/> ) : (
: <></> <></>
} )}
</div>
<div className="nav__section nav__section--auth">
<Guest dispatch={dispatch} />
</div> </div>
</> </>
); );
} };
export default Auth; export default Auth;

View file

@ -1,4 +1,5 @@
@import '../../../../public/stylesheets/partials/mixins'; @import '../../../../public/stylesheets/partials/mixins';
@import '../../../../public/stylesheets/partials/variables';
div.main-wrapper { div.main-wrapper {
display: flex; display: flex;
@ -33,4 +34,15 @@ div.main-wrapper {
height: 100%; height: 100%;
} }
} }
}
button {
color:map-get($colors, 'sidebar_link');
cursor: pointer;
font-family: inherit;
font-size: 110%;
font-weight: bold;
margin-bottom: .5em;
padding: 0;
text-decoration: none;
} }

View file

@ -1,29 +1,36 @@
import React from 'react'; import React from "react";
import { Link } from 'react-router-dom'; import { Link } from "react-router-dom";
import './NavBar.scss'; import "./NavBar.scss";
import Logo from '../../../components/Display/Logo/Logo'; import Logo from "../../../components/Display/Logo/Logo";
const NavBar = (props) => {
const NavBar = ({ state }) => {
return ( return (
<div className="NavBar" data-testid="NavBar"> <div className="NavBar" data-testid="NavBar">
<Link to="/home" > <Link to="/home">
<div className="NavBar__logo"><Logo /></div> <div className="NavBar__logo">
<Logo />
</div>
</Link> </Link>
<Link to="/home" > <Link to="/home">
<div className="NavBar__menu-item NavBar__home"><p className="--link">Find a Game</p></div> <div className="NavBar__menu-item NavBar__home">
<p className="--link">Find a Game</p>
</div>
</Link> </Link>
<Link to="/news"> <Link to="/news">
<div className="NavBar__menu-item NavBar__news"><p className="--link">News</p></div> <div className="NavBar__menu-item NavBar__news">
<p className="--link">News</p>
</div>
</Link> </Link>
<Link to="/account"> <Link to="/account">
<div className="NavBar__menu-item NavBar__account">{props.user ? props.user.username : <></>}</div> <div className="NavBar__menu-item NavBar__account">
{state.user.username ? state.user.username : <></>}
</div>
</Link> </Link>
</div> </div>
); );
} };
export default NavBar; export default NavBar;

View file

@ -1,20 +1,23 @@
export const authReducer = (state, action) => { export const authReducer = (state, action) => {
switch (action.message) { switch (action.message) {
case 'LOGIN': case "LOGIN":
return loginReducer(state, action);
case 'SIGNUP':
return loginReducer(state, action); return loginReducer(state, action);
case 'LOGOUT': case "SIGNUP":
return loginReducer(state, action);
case "GUEST":
return loginReducer(state, action);
case "LOGOUT":
return state; return state;
default: default:
return state; return state;
} }
} };
function loginReducer(state, action) { function loginReducer(state, action) {
const newUser = action.body; const newUser = action.body;
return {...state, user: newUser }; return { ...state, user: newUser };
} }

View file

@ -1,43 +1,58 @@
import config from '../config'; import config from "../config";
const authEndpoint = config.authAddress; const authEndpoint = config.authAddress;
const signupEndpoint = `${authEndpoint}/signup` const signupEndpoint = `${authEndpoint}/signup`;
const loginEndpoint = `${authEndpoint}/login` const loginEndpoint = `${authEndpoint}/login`;
const guestEndpoint = `${authEndpoint}/guest`;
var headers = new Headers(); var headers = new Headers();
headers.append('Content-Type', 'application/json'); headers.append("Content-Type", "application/json");
headers.append('Accept', 'application/json'); headers.append("Accept", "application/json");
headers.append('Sec-Fetch-Site', 'cross-site') headers.append("Sec-Fetch-Site", "cross-site");
const loginService = async(formData) => { const loginService = async (formData) => {
const response = await fetch(loginEndpoint, { const response = await fetch(loginEndpoint, {
method: 'POST', method: "POST",
credentials: 'include', credentials: "include",
body: JSON.stringify(formData), body: JSON.stringify(formData),
headers: headers headers: headers,
}) })
.then(res => res.text()) .then((res) => res.text())
.then(text => JSON.parse(text)) .then((text) => JSON.parse(text))
.catch(err => err); .catch((err) => err);
return response; return response;
} };
const signupService = async (formData) => { const signupService = async (formData) => {
const response = await fetch(signupEndpoint, { const response = await fetch(signupEndpoint, {
method: 'POST', method: "POST",
credentials: 'include', credentials: "include",
body: JSON.stringify(formData), body: JSON.stringify(formData),
headers: headers headers: headers,
}) })
.then(res => res.text()) .then((res) => res.text())
.then(text => JSON.parse(text)) .then((text) => JSON.parse(text))
.catch(err => err); .catch((err) => err);
return response; return response;
} };
const guestService = async () => {
const response = await fetch(guestEndpoint, {
method: "POST",
credentials: "include",
headers,
})
.then((res) => res.text())
.then((text) => JSON.parse(text))
.catch((err) => err);
return response;
};
export default { export default {
loginService, loginService,
signupService signupService,
} guestService,
};

View file

@ -1,15 +1,16 @@
const { validationResult } = require('express-validator'); const { validationResult } = require("express-validator");
const userQueries = require('../data/queries/user'); const userQueries = require("../data/queries/user");
const { hashPassword, compareHash } = require('../services/bcrypt'); const { hashPassword, compareHash } = require("../services/bcrypt");
const signToken = require('../services/signToken'); const signToken = require("../services/signToken");
const guestServices = require("../services/guestServices");
const checkValidationErrors = (req, res) => { const checkValidationErrors = (req, res) => {
const errors = validationResult(req); const errors = validationResult(req);
if (!errors.isEmpty()) { if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() }); return res.status(422).json({ errors: errors.array() });
} }
} };
const signup = async (req, res, next) => { const signup = async (req, res, next) => {
checkValidationErrors(req, res); checkValidationErrors(req, res);
@ -20,51 +21,68 @@ const signup = async (req, res, next) => {
const hashedPassword = await hashPassword(user.password); const hashedPassword = await hashPassword(user.password);
const secureUser = { ...user, password: hashedPassword }; const secureUser = { ...user, password: hashedPassword };
if (existingUser.length) { if (existingUser.length) {
return res.status(409).json({errors: [{auth: 'User already exists!'}]}) return res
.status(409)
.json({ errors: [{ auth: "User already exists!" }] });
} }
const newUser = await userQueries.insertUser(secureUser); const newUser = await userQueries.insertUser(secureUser);
signToken(res, newUser) signToken(res, newUser);
res.status(201).json({...newUser}); res.status(201).json({ ...newUser });
} } catch (err) {
catch (err) {
res.status(500).json(err); res.status(500).json(err);
} }
} };
const login = async (req, res, next) => { const login = async (req, res, next) => {
checkValidationErrors(req, res); checkValidationErrors(req, res);
const user = req.body; const user = req.body;
try { try {
const queryResults = await userQueries.findUserByNameOrEmail(user); const queryResults = await userQueries.findUserByNameOrEmail(user);
const savedUser = queryResults[0] || null; const savedUser = queryResults[0] || null;
if (!savedUser) { if (!savedUser) {
return res.status(401).send({errors: 'bad credentials'}); return res.status(401).send({ errors: "bad credentials" });
} }
const hashedPassword = savedUser.password; const hashedPassword = savedUser.password;
const passwordMatch = await compareHash(user.password, hashedPassword); const passwordMatch = await compareHash(user.password, hashedPassword);
if (!passwordMatch) { if (!passwordMatch) {
return res.status(401).send({errors: 'bad credentials'}); return res.status(401).send({ errors: "bad credentials" });
} }
const authorizedUser = {...savedUser}; const authorizedUser = { ...savedUser };
delete authorizedUser.password; delete authorizedUser.password;
signToken(res, authorizedUser); signToken(res, authorizedUser);
res.send({...authorizedUser}).status(200); res.send({ ...authorizedUser }).status(200);
} catch (e) {
res.status(500).send({ errors: e });
} }
};
catch (err) {
res.status(500).send({errors: err}); const guest = async (req, res, next) => {
try {
// username generator returns `Guest-${num}`
const { username, password } = guestServices.generateGuest();
// generateGuestUser();
const email = null;
// id generator returns `
const id = null;
const user = { username, email, id, password };
signToken(res, user);
delete user.password;
res.send(user);
} catch (e) {
console.log(e);
res.status(500).send({ errors: e });
} }
} };
module.exports = { module.exports = {
signup, signup,
login login,
} guest,
};

View file

@ -1,10 +1,20 @@
const express = require('express'); const express = require("express");
const router = express.Router(); const router = express.Router();
const app = require('../server'); const app = require("../server");
const authController = require('../controllers/auth'); const authController = require("../controllers/auth");
const { signupValidationRules, loginValidationRules, validate } = require('../middleware/userValidator'); const {
signupValidationRules,
loginValidationRules,
validate,
} = require("../middleware/userValidator");
router.post('/signup', signupValidationRules(), validate, authController.signup); router.post(
router.post('/login', loginValidationRules(), validate, authController.login); "/signup",
signupValidationRules(),
validate,
authController.signup
);
router.post("/login", loginValidationRules(), validate, authController.login);
router.post("/guest", authController.guest);
module.exports = router; module.exports = router;

View file

@ -0,0 +1,25 @@
const generateRandomPassword = () => {
const minLength = 8,
maxLength = 16,
minUTF = 33,
maxUTF = 126;
const randomize = (min, max) => Math.floor(Math.random() * (max - min) + min);
return Array(randomize(minLength, maxLength))
.fill(0)
.map(() => String.fromCharCode(randomize(minUTF, maxUTF)))
.join("");
};
const guestService = {
currentGuest: 0,
generateGuest() {
// generate unique username
const username = `Guest-${String(this.currentGuest++).padStart(6, 0)}`;
// generate random "password"
// this exists solely to add extra randomness to signed token and is not validated
const password = generateRandomPassword();
return { username, password };
},
};
module.exports = guestService;