Complete login, sign up, and member details

This commit is contained in:
Tanner Collin 2020-01-08 23:43:59 +00:00
parent 5526cf708b
commit d59d24ae65
15 changed files with 382 additions and 40 deletions

View File

@ -104,4 +104,6 @@ ENV/
# DB # DB
db.sqlite3 db.sqlite3
old_portal.sqlite3
old_models.py
migrations/ migrations/

View File

@ -1,3 +1,20 @@
from django.db import models from django.db import models
from django.contrib.auth.models import User
# Create your models here. from . import old_models
class Member(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT)
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
old_member_id = models.IntegerField(null=True, blank=True)
set_details = models.BooleanField(default=False)
preferred_name = models.CharField(max_length=32, blank=True)
phone = models.CharField(max_length=32, blank=True)
current_start_date = models.DateField(blank=True, null=True)
application_date = models.DateField(blank=True, null=True)
vetted_date = models.DateField(blank=True, null=True)
monthly_fees = models.IntegerField(blank=True, null=True)
emergency_contact_name = models.CharField(max_length=64, blank=True)
emergency_contact_phone = models.CharField(max_length=32, blank=True)

View File

@ -1,7 +1,70 @@
from django.contrib.auth.models import User, Group from django.contrib.auth.models import User, Group
from rest_framework import serializers from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_auth.registration.serializers import RegisterSerializer
from . import models, old_models
GRAB_FIELDS = [
'preferred_name',
'phone',
'current_start_date',
'application_date',
'vetted_date',
'monthly_fees',
'emergency_contact_name',
'emergency_contact_phone',
]
#custom_error = lambda x: ValidationError(dict(non_field_errors=x))
class UserSerializer(serializers.ModelSerializer): class UserSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ['id', 'username', 'email', 'groups'] fields = ['id', 'username', 'email', 'member']
depth = 1
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = models.Member
fields = '__all__'
read_only_fields = ['user', 'application_date', 'current_start_date', 'vetted_date', 'monthly_fees', 'old_member_id']
class AdminMemberSerializer(serializers.ModelSerializer):
class Meta:
model = models.Member
fields = '__all__'
read_only_fields = ['id', 'user']
class RegistrationSerializer(RegisterSerializer):
first_name = serializers.CharField(max_length=32)
last_name = serializers.CharField(max_length=32)
existing_member = serializers.ChoiceField(['true', 'false'])
def custom_signup(self, request, user):
data = request.data
old_member_id = None
old_member_fields = dict(preferred_name=data['first_name'])
if data['existing_member'] == 'true':
old_members = old_models.Members.objects.using('old_portal')
try:
old_member = old_members.get(email=data['email'])
except old_models.Members.DoesNotExist:
user.delete()
raise ValidationError(dict(email='Unable to find in old database.'))
old_member_id = old_member.id
for f in GRAB_FIELDS:
old_member_fields[f] = old_member.__dict__.get(f, None)
models.Member.objects.create(
user=user,
first_name=data['first_name'],
last_name=data['last_name'],
old_member_id=old_member_id,
**old_member_fields
)

View File

@ -1,8 +1,55 @@
from django.contrib.auth.models import User, Group from django.contrib.auth.models import User, Group
from rest_framework import viewsets from rest_framework import viewsets, views, permissions
from rest_framework.response import Response
from rest_auth.registration.views import RegisterView
from . import models, serializers from . import models, serializers
class AllowMetadata(permissions.BasePermission):
def has_permission(self, request, view):
return request.method in ['OPTIONS', 'HEAD']
class UserViewSet(viewsets.ModelViewSet): class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('-date_joined') queryset = User.objects.all().order_by('-date_joined')
serializer_class = serializers.UserSerializer serializer_class = serializers.UserSerializer
class MemberViewSet(viewsets.ModelViewSet):
permission_classes = [AllowMetadata | permissions.IsAuthenticated]
http_method_names = ['options', 'head', 'get', 'put', 'patch']
def get_queryset(self):
objects = models.Member.objects.all()
if self.request.user.is_staff:
return objects.order_by('id')
else:
return objects.filter(user=self.request.user)
def get_serializer_class(self):
if self.request.user.is_staff:
return serializers.AdminMemberSerializer
else:
return serializers.MemberSerializer
class MyUserView(views.APIView):
permission_classes = [AllowMetadata | permissions.IsAuthenticated]
def get(self, request):
serializer = serializers.UserSerializer(request.user)
return Response(serializer.data)
class RegistrationViewSet(RegisterView):
serializer_class = serializers.RegistrationSerializer
#def create(self, request):
# data = request.data.copy()
# data['username'] = '{}.{}'.format(
# data['first_name'],
# data['last_name']
# ).lower()
# request._full_data = data
# return super().create(request)

View File

@ -53,6 +53,7 @@ INSTALLED_APPS = [
'rest_auth', 'rest_auth',
'allauth', 'allauth',
'allauth.account', 'allauth.account',
'allauth.socialaccount', # to support user deletion
'rest_auth.registration', 'rest_auth.registration',
] ]
@ -94,6 +95,10 @@ DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'old_portal': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'old_portal.sqlite3'),
} }
} }
@ -209,3 +214,6 @@ LOGGING = {
} }
SITE_ID = 1 SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_USERNAME_MIN_LENGTH = 3

View File

@ -7,11 +7,15 @@ from .api import views
router = routers.DefaultRouter() router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet) router.register(r'users', views.UserViewSet)
router.register(r'members', views.MemberViewSet, basename='member')
#router.register(r'me', views.FullMemberView, basename='fullmember')
#router.register(r'registration', views.RegistrationViewSet, basename='register')
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path('', include(router.urls)),
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')), path('api-auth/', include('rest_framework.urls')),
url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')) url(r'^registration/', views.RegistrationViewSet.as_view(), name='rest_name_register'),
url(r'^me/', views.MyUserView.as_view(), name='fullmember'),
] ]

3
apiserver/gen_old_models.sh Executable file
View File

@ -0,0 +1,3 @@
#!/bin/bash
python manage.py inspectdb --database old_portal | sed 's/CharField/TextField/g' > apiserver/api/old_models.py

View File

@ -21,3 +21,7 @@
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
# Editor
*.swp
*.swo

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,25 +1,31 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import './light.css'; import './light.css';
import Logo from './logo.svg'; import Logo from './logo.svg';
import { Container, Divider, Form, Grid, Header, Menu, Message } from 'semantic-ui-react'; import { Container, Divider, Form, Grid, Header, Icon, Menu, Message } from 'semantic-ui-react';
import { requester } from './utils.js'; import { requester } from './utils.js';
function LoginForm() { function LoginForm(props) {
const [input, setInput] = useState({}) const [input, setInput] = useState({});
const [error, setError] = useState({}) const [error, setError] = useState({});
const [loading, setLoading] = useState(false);
const handleChange = (e) => setInput({ const handleValues = (e, v) => setInput({
...input, ...input,
[e.currentTarget.name]: e.currentTarget.value [v.name]: v.value
}); });
const handleChange = (e) => handleValues(e, e.currentTarget);
const handleSubmit = (e) => { const handleSubmit = (e) => {
requester('/rest-auth/login/', 'POST', input) setLoading(true);
requester('/rest-auth/login/', 'POST', '', input)
.then(res => { .then(res => {
console.log(res); console.log(res);
setError({}); setError({});
props.setTokenCache(res.key);
}) })
.catch(err => { .catch(err => {
setLoading(false);
console.log(err); console.log(err);
setError(err.data); setError(err.data);
}); });
@ -27,6 +33,7 @@ function LoginForm() {
return ( return (
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
<Header size='medium'>Login to Spaceport</Header>
<Form.Input <Form.Input
label='Username' label='Username'
name='username' name='username'
@ -41,37 +48,95 @@ function LoginForm() {
onChange={handleChange} onChange={handleChange}
error={error.password} error={error.password}
/> />
<Form.Button error={error.non_field_errors}> <Form.Button loading={loading} error={error.non_field_errors}>
Login Login
</Form.Button> </Form.Button>
</Form> </Form>
); );
} }
function SignupForm() { function SignupForm(props) {
const [input, setInput] = useState({}) const [input, setInput] = useState({});
const [error, setError] = useState({});
const [loading, setLoading] = useState(false);
const handleChange = (e) => setInput({ const handleValues = (e, v) => setInput({
...input, ...input,
[e.currentTarget.name]: e.currentTarget.value [v.name]: v.value
}); });
const handleChange = (e) => handleValues(e, e.currentTarget);
const genUsername = () => (
input.first_name && input.last_name ?
(input.first_name + '.' + input.last_name).toLowerCase()
:
''
);
const handleSubmit = (e) => { const handleSubmit = (e) => {
console.log(input); setLoading(true);
} input.username = genUsername();
requester('/registration/', 'POST', '', input)
.then(res => {
console.log(res);
setError({});
props.setTokenCache(res.key);
})
.catch(err => {
setLoading(false);
console.log(err);
setError(err.data);
});
};
return ( return (
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
<Header size='medium'>Sign Up</Header>
<Form.Group widths='equal'> <Form.Group widths='equal'>
<Form.Input <Form.Input
label='First Name' label='First Name'
name='firstname' name='first_name'
onChange={handleChange} onChange={handleChange}
error={error.first_name}
/> />
<Form.Input <Form.Input
label='Last Name' label='Last Name'
name='lastname' name='last_name'
onChange={handleChange} onChange={handleChange}
error={error.last_name}
/>
</Form.Group>
<Form.Input
label='Username'
name='username'
value={genUsername()}
error={error.username}
/>
<Form.Input
label='Email'
name='email'
onChange={handleChange}
error={error.email}
/>
<Form.Group grouped>
<Form.Radio
label='I have an account on the old portal'
name='existing_member'
value={true}
checked={input.existing_member === true}
onChange={handleValues}
error={!!error.existing_member}
/>
<Form.Radio
label='I am new to Protospace'
name='existing_member'
value={false}
checked={input.existing_member === false}
onChange={handleValues}
error={!!error.existing_member}
/> />
</Form.Group> </Form.Group>
@ -80,30 +145,133 @@ function SignupForm() {
name='password1' name='password1'
type='password' type='password'
onChange={handleChange} onChange={handleChange}
error={error.password1}
/> />
<Form.Input <Form.Input
label='Confirm Password' label='Confirm Password'
name='password2' name='password2'
type='password' type='password'
onChange={handleChange} onChange={handleChange}
error={error.password2}
/>
<Form.Button loading={loading} error={error.non_field_errors}>
Sign Up
</Form.Button>
</Form>
);
}
function DetailsForm(props) {
const member = props.user.member;
const [input, setInput] = useState({
preferred_name: member.preferred_name,
phone: member.phone,
emergency_contact_name: member.emergency_contact_name,
emergency_contact_phone: member.emergency_contact_phone,
set_details: true,
});
const [error, setError] = useState({});
const [loading, setLoading] = useState(false);
const handleValues = (e, v) => setInput({
...input,
[v.name]: v.value
});
const handleChange = (e) => handleValues(e, e.currentTarget);
const handleSubmit = (e) => {
setLoading(true);
requester('/members/' + member.id + '/', 'PATCH', props.token, input)
.then(res => {
console.log(res);
setError({});
props.setUserCache({...props.user, member: res});
})
.catch(err => {
setLoading(false);
console.log(err);
setError(err.data);
});
};
return (
<Form onSubmit={handleSubmit}>
<Header size='medium'>Enter Details</Header>
<Form.Input
label='Preferred Name'
name='preferred_name'
onChange={handleChange}
value={input.preferred_name}
error={error.preferred_name}
/> />
<Form.Input <Form.Input
label='Email' label='Phone Number (999) 555-1234'
name='email' name='phone'
onChange={handleChange} onChange={handleChange}
value={input.phone}
error={error.phone}
/> />
<Form.Button>Sign Up</Form.Button> <Form.Input
label='Emergency Contact Name'
name='emergency_contact_name'
onChange={handleChange}
value={input.emergency_contact_name}
error={error.emergency_contact_name}
/>
<Form.Input
label='Emergency Contact Phone'
name='emergency_contact_phone'
onChange={handleChange}
value={input.emergency_contact_phone}
error={error.emergency_contact_phone}
/>
<Form.Button loading={loading} error={error.non_field_errors}>
Submit
</Form.Button>
</Form> </Form>
); );
} }
function App() { function App() {
const [token, setToken] = useState(localStorage.getItem('token', ''));
const [user, setUser] = useState(JSON.parse(localStorage.getItem('user', 'false')));
const setTokenCache = (x) => {
setToken(x);
localStorage.setItem('token', x);
}
const setUserCache = (x) => {
setUser(x);
localStorage.setItem('user', JSON.stringify(x));
}
useEffect(() => {
requester('/me/', 'GET', token)
.then(res => {
console.log(res);
setUserCache(res);
})
.catch(err => {
console.log(err);
setUser(false);
});
}, [token]);
const logout = () => {
setTokenCache('');
setUserCache(false);
}
return ( return (
<div> <div>
<Container> <Container>
<header className='header'> <div className='header'>
<img src={Logo} className='logo' /> <img src={Logo} className='logo' />
</header> </div>
</Container> </Container>
<Menu> <Menu>
@ -117,20 +285,33 @@ function App() {
<Menu.Item <Menu.Item
content='Contact' content='Contact'
/> />
{user && <Menu.Menu position='right'>
<Menu.Item
content='Logout'
onClick={logout}
/>
</Menu.Menu>}
</Container> </Container>
</Menu> </Menu>
<Container> <Container>
<Grid stackable padded columns={2}> <Grid stackable padded columns={2}>
<Grid.Column> <Grid.Column>
<Header size='medium'>Login to Spaceport</Header> {user ?
user.member.set_details ?
<LoginForm /> <p>yay welcome {user.member.first_name}</p>
:
<DetailsForm token={token} user={user} setUserCache={setUserCache} />
:
<div>
<LoginForm setTokenCache={setTokenCache} />
<Divider section horizontal>Or</Divider> <Divider section horizontal>Or</Divider>
<Header size='medium'>Sign Up</Header> <SignupForm setTokenCache={setTokenCache} />
<SignupForm /> </div>
}
</Grid.Column> </Grid.Column>
<Grid.Column> <Grid.Column>
<p>two</p> <p>two</p>

View File

@ -1,5 +1,11 @@
.header {
padding-top: 1.5rem;
margin-bottom: 1.5rem;
}
.header .logo { .header .logo {
max-width: 100%; max-width: 100%;
height: 2rem;
display: block; display: block;
margin: 1.5rem auto; margin: auto;
} }

View File

@ -8,23 +8,28 @@ if (process.env.NODE_ENV !== 'production') {
apiUrl = 'https://api.' + window.location.hostname; apiUrl = 'https://api.' + window.location.hostname;
} }
export const requester = (route, method, data) => { export const requester = (route, method, token, data) => {
var options; let options = {headers: {}};
if (token) {
options.headers.Authorization = 'Token ' + token;
}
if (method == 'GET') { if (method == 'GET') {
options = {}; // pass
} else if (method == 'POST') { } else if (['POST', 'PUT', 'PATCH'].includes(method)) {
const formData = new FormData(); const formData = new FormData();
Object.keys(data).forEach(key => Object.keys(data).forEach(key =>
formData.append(key, data[key]) formData.append(key, data[key])
); );
options = { options = {
method: 'POST', ...options,
method: method,
body: formData, body: formData,
}; };
} else { } else {
return 'Method not supported'; throw new Error('Method not supported');
} }
const customError = (data) => { const customError = (data) => {
@ -44,11 +49,13 @@ export const requester = (route, method, data) => {
const code = error.data.status; const code = error.data.status;
if (code == 413) { if (code == 413) {
throw customError({non_field_errors: ['File too big']}); throw customError({non_field_errors: ['File too big']});
} else if (code == 400) { } else if (code >= 400 && code < 500) {
return error.data.json() return error.data.json()
.then(result => { .then(result => {
throw customError(result); throw customError(result);
}); });
} else if (code >= 500 && code < 600) {
throw customError({non_field_errors: ['Server Error']});
} else { } else {
throw customError({non_field_errors: ['Network Error']}); throw customError({non_field_errors: ['Network Error']});
} }