Commit bdb603ea authored by David Haynes's avatar David Haynes 🙆

Add page template for auth checking

- ping the api to check for status before rendering
- render children if true, else hit the auth wall
parent ce7a5548
Pipeline #3813 passed with stage
in 1 minute and 37 seconds
import React from "react";
import * as Yup from "yup";
import { Formik, Field, Form, ErrorMessage } from "formik";
import { Formik, Field, Form as FormikForm, ErrorMessage } from "formik";
import { GetCSRFToken } from "../../Utils";
import { SingleDatePicker } from "react-dates";
import moment from "moment";
import { Form, FormGroup, Button, Card, CardBody, CardTitle } from "reactstrap";
const DebugCreateYup = Yup.object().shape({
destination: Yup.string()
......@@ -21,70 +22,85 @@ class DebugCreate extends React.Component {
constructor(props) {
super(props);
this.state = {
focused: false,
date: null
focused: false
};
}
render() {
return (
<div>
<Formik
initialValues={{
destination: "",
short: "",
expires: moment(new Date())
}}
validationSchema={DebugCreateYup}
onSubmit={(values, { setSubmitting }) => {
const newValues = {
destination: values.destination,
short: values.short,
date_expires: values.expires.format()
};
console.log(newValues);
fetch("/api/golinks/", {
method: "post",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": GetCSRFToken()
},
body: JSON.stringify(newValues)
})
.then(response => console.log(response))
.then(setSubmitting(false));
}}
render={({ values, isSubmitting, setFieldValue }) => (
<Form>
{"Destination: "}
<Field
name="destination"
placeholder="https://longwebsitelink.com"
/>
<ErrorMessage name="destination" component="div" />
<br />
{"Short: "}
<Field name="short" />
<ErrorMessage name="short" />
<br />
{"Expires: "}
<SingleDatePicker
date={values["expires"]} // momentPropTypes.momentObj or null
onDateChange={date => setFieldValue("expires", date)} // PropTypes.func.isRequired
focused={this.state.focused} // PropTypes.bool
onFocusChange={({ focused }) => this.setState({ focused })} // PropTypes.func.isRequired
id="expires" // PropTypes.string.isRequired,
/>
<ErrorMessage name="expires" />
<br />
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
/>
</div>
<Card>
<CardBody>
<CardTitle>Create</CardTitle>
<Formik
initialValues={{
destination: "",
short: "",
expires: moment(new Date())
}}
validationSchema={DebugCreateYup}
onSubmit={(values, { setSubmitting }) => {
const newValues = {
destination: values.destination,
short: values.short,
date_expires: values.expires.format()
};
console.log(newValues);
fetch("/api/golinks/", {
method: "post",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": GetCSRFToken()
},
body: JSON.stringify(newValues)
})
.then(response => console.log(response))
.then(setSubmitting(false));
}}
render={({ values, isSubmitting, setFieldValue }) => (
<Form>
<FormikForm>
<FormGroup>
{"Destination: "}
<Field
className="form-control"
name="destination"
placeholder="https://longwebsitelink.com"
/>
<ErrorMessage name="destination" component="div" />
</FormGroup>
<FormGroup>
{"Short: "}
<Field className="form-control" name="short" />
<ErrorMessage name="short" />
</FormGroup>
<FormGroup>
{"Expires: "}
<br />
<SingleDatePicker
date={values["expires"]} // momentPropTypes.momentObj or null
onDateChange={date => setFieldValue("expires", date)} // PropTypes.func.isRequired
focused={this.state.focused} // PropTypes.bool
onFocusChange={({ focused }) =>
this.setState({ focused })
} // PropTypes.func.isRequired
id="expires" // PropTypes.string.isRequired,
/>
<ErrorMessage name="expires" />
</FormGroup>
<Button
type="submit"
disabled={isSubmitting}
outline
color="primary"
>
Submit
</Button>
</FormikForm>
</Form>
)}
/>
</CardBody>
</Card>
);
}
}
......
import React from "react";
import {
PageTemplate,
AuthedPageTemplate,
DebugRead,
DebugCreate,
DebugDelete,
......@@ -15,21 +15,18 @@ class DebugCRUD extends React.Component {
render() {
return (
<PageTemplate>
<div>
<h3>Create</h3>
<DebugCreate />
<AuthedPageTemplate>
<DebugCreate />
<h3>Read</h3>
<DebugRead />
<h3>Read</h3>
<DebugRead />
<h3>Update</h3>
<DebugUpdate />
<h3>Update</h3>
<DebugUpdate />
<h3>Delete</h3>
<DebugDelete />
</div>
</PageTemplate>
<h3>Delete</h3>
<DebugDelete />
</AuthedPageTemplate>
);
}
}
......
import React from "react";
import { Container } from "reactstrap";
class AuthedPageTemplate extends React.Component {
constructor(props) {
super(props);
this.state = { isLoggedIn: null, loaded: false };
}
componentDidMount() {
fetch("/auth/status/", {
headers: {
"Content-Type": "application/json"
}
})
.then(r => r.json())
.then(res =>
this.setState({
isLoggedIn: res.is_authenticated,
loaded: true
})
);
}
render() {
const { isLoggedIn, loaded } = this.state;
return (
<div>
{loaded ? (
<div>
{isLoggedIn ? (
<Container>{this.props.children}</Container>
) : (
<h1>You're not authed!</h1>
)}
</div>
) : (
<div />
)}
</div>
);
}
}
export default AuthedPageTemplate;
import PageTemplate from "./PageTemplate";
import AuthedPageTemplate from "./AuthedPageTemplate";
export { PageTemplate };
export { PageTemplate, AuthedPageTemplate };
......@@ -7,7 +7,7 @@ import {
} from "./Molecules";
import { NavBar } from "./Organisms";
import { HomePage, AboutPage, DhaynesPage, DebugCRUD } from "./Pages";
import { PageTemplate } from "./Templates";
import { PageTemplate, AuthedPageTemplate } from "./Templates";
export {
//Molecules
......@@ -24,5 +24,6 @@ export {
DhaynesPage,
DebugCRUD,
//Templates
PageTemplate
PageTemplate,
AuthedPageTemplate
};
......@@ -10,7 +10,7 @@ from rest_framework.authentication import TokenAuthentication, SessionAuthentica
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.authtoken.views import ObtainAuthToken
from .serializers import URLSerializer
......@@ -60,17 +60,12 @@ class CustomAuthToken(ObtainAuthToken):
class GetSessionInfo(APIView):
"""Handy endpoint to return current user session status & information to the frontend."""
authentication_classes = (SessionAuthentication,)
permission_classes = (IsAuthenticated,)
permission_classes = (AllowAny,)
def get(self, request, *args, **kwargs):
token, created = Token.objects.get_or_create(user=request.user)
session_info = {
"username": request.user.username,
# "full_name": f"{request.user.get_full_name}",
"last_login": request.user.last_login,
"is_authenticated": request.user.is_authenticated,
"token": token.key,
}
return Response(session_info)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment