· 9 years ago · Aug 24, 2016, 10:56 AM
1user = User.objects.get(username=username)
2
3AttributeError: Manager isn't available; 'auth.User' has been swapped for 'authentication.User'.
4
5from django.db import models
6from django.contrib.auth.models import AbstractBaseUser,
7 BaseUserManager, PermissionsMixin
8from django.utils import timezone
9from django.utils.translation import ugettext_lazy as _
10
11import uuid
12import base64
13
14
15class UserManager(BaseUserManager):
16 def create_user(self, username, email, name, password=None):
17 user = self.model(
18 username=username,
19 email=email,
20 name=name,
21 last_login=timezone.now()
22 ) # last_login is defined in AbstractBaseUser
23 user.set_password(password)
24 user.save(using=self._db)
25 return user
26
27 def create_superuser(self, username, password):
28 user = self.create_user(
29 username=username,
30 email=None,
31 name=username,
32 password=password
33 )
34 user.is_staff = True
35 user.is_superuser = True
36 user.save(using=self._db)
37 return user
38
39
40def generate_registration_code():
41 return "asd"
42
43
44class User(AbstractBaseUser, PermissionsMixin):
45 # This model should be created in the firest migration:
46 # https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#substituting-a-custom-user-model
47
48 # We use username, not email as primary user id, because OAuth
49 # implementation via python-social-auth requires this field to
50 # be present.
51 username = models.CharField(
52 verbose_name=_('username'),
53 max_length=255,
54 unique=True
55 )
56
57 email = models.EmailField(null=True, blank=True)
58
59 # name is a human-readable name used to refer to user e.g. "Martin Taylor"
60 # longest full name registered in guinness book is 744 letters-long
61 name = models.CharField(
62 verbose_name=_('name'),
63 max_length=1023,
64 null=True,
65 blank=True
66 )
67
68 # We don't need password and last_login fields, because they are
69 # already defined in AbstractBaseUser.
70
71 # is_active is a variable in AbstractBaseUser set to True, but we
72 # want a separate field for it.
73 is_active = models.BooleanField(
74 _('active'),
75 default=True,
76 help_text=_('Is this user account activated?')
77 )
78
79 is_staff = models.BooleanField(
80 _('staff status'),
81 default=False,
82 help_text=_('Is this user allowed to the admin page')
83 )
84
85 date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
86
87 code = models.CharField(
88 null=True,
89 blank=True,
90 default=generate_registration_code,
91 max_length=255,
92 help_text=_('''
93 Code to be sent via e-mail upon registration
94 or password recovery.
95 ''')
96 )
97
98 new_password = models.CharField(
99 null=True,
100 blank=True,
101 default="",
102 max_length=255,
103 help_text=_('''
104 If user is attempting to change password, this field stores new
105 password until user enters confirmation code.
106 ''')
107 )
108
109 objects = UserManager()
110
111 USERNAME_FIELD = 'username'
112 REQUIRED_FIELDS = []
113
114 class Meta:
115 verbose_name = _('user')
116 verbose_name_plural = _('users')
117
118 def __str__(self):
119 return self.username
120
121 def get_short_name(self):
122 return self.username
123
124 def get_full_name(self):
125 return self.username
126
127"""
128Django settings for simple_resserver_jwt project.
129
130Generated by 'django-admin startproject' using Django 1.10.
131
132For more information on this file, see
133https://docs.djangoproject.com/en/1.10/topics/settings/
134
135For the full list of settings and their values, see
136https://docs.djangoproject.com/en/1.10/ref/settings/
137"""
138
139import os
140import datetime
141
142# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
143BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
144
145
146# Quick-start development settings - unsuitable for production
147# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
148
149# SECURITY WARNING: keep the secret key used in production secret!
150SECRET_KEY = 'co0)lyiwbgi4wz#80gp&y++bga-+iqd8hxq5boiw3d$g(#!yl*'
151
152# SECURITY WARNING: don't run with debug turned on in production!
153DEBUG = True
154
155ALLOWED_HOSTS = []
156
157
158# Application definition
159
160INSTALLED_APPS = [
161 'django.contrib.admin',
162 'django.contrib.auth',
163 'django.contrib.contenttypes',
164 'django.contrib.sessions',
165 'django.contrib.messages',
166 'django.contrib.staticfiles',
167 'rest_framework',
168 'authentication',
169]
170
171MIDDLEWARE = [
172 'django.middleware.security.SecurityMiddleware',
173 'django.contrib.sessions.middleware.SessionMiddleware',
174 'django.middleware.common.CommonMiddleware',
175 'django.middleware.csrf.CsrfViewMiddleware',
176 'django.contrib.auth.middleware.AuthenticationMiddleware',
177 'django.contrib.messages.middleware.MessageMiddleware',
178 'django.middleware.clickjacking.XFrameOptionsMiddleware',
179]
180
181ROOT_URLCONF = 'simple_resserver_jwt.urls'
182
183TEMPLATES = [
184 {
185 'BACKEND': 'django.template.backends.django.DjangoTemplates',
186 'DIRS': [],
187 'APP_DIRS': True,
188 'OPTIONS': {
189 'context_processors': [
190 'django.template.context_processors.debug',
191 'django.template.context_processors.request',
192 'django.contrib.auth.context_processors.auth',
193 'django.contrib.messages.context_processors.messages',
194 ],
195 },
196 },
197]
198
199WSGI_APPLICATION = 'simple_resserver_jwt.wsgi.application'
200
201
202# Database
203# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
204
205DATABASES = {
206 'default': {
207 'ENGINE': 'django.db.backends.sqlite3',
208 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
209 }
210}
211
212AUTH_USER_MODEL = 'authentication.User'
213
214
215AUTHENTICATION_BACKENDS = ['authentication.backends.AuthBackend', ]
216
217
218REST_FRAMEWORK = {
219 'DEFAULT_PERMISSION_CLASSES': (
220 ),
221 'DEFAULT_AUTHENTICATION_CLASSES': (
222 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
223
224 )
225}
226
227from rest_framework_jwt.authentication import JSONWebTokenAuthentication
228
229
230with open('private') as f:
231 PRIVATE_KEY = f.readlines()
232
233with open('public') as f:
234 PUBLIC_KEY = f.readlines()
235
236JWT_AUTH = {
237 'JWT_ENCODE_HANDLER':
238 'authentication.utils.jwt_encode_handler',
239 'JWT_DECODE_HANDLER':
240 'authentication.utils.jwt_decode_handler',
241
242 # 'JWT_RESPONSE_PAYLOAD_HANDLER':
243 # 'authentication.utils.jwt_decode_handler',
244
245 'JWT_SECRET_KEY': PRIVATE_KEY,
246 'JWT_ALGORITHM': 'RS256',
247 'JWT_VERIFY': True,
248 'JWT_VERIFY_EXPIRATION': True,
249 'JWT_LEEWAY': 0,
250 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
251 'JWT_AUDIENCE': None,
252 'JWT_ISSUER': None,
253 'JWT_ALLOW_REFRESH': False,
254 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
255 'JWT_AUTH_HEADER_PREFIX': 'Bearer',
256}
257
258
259# Password validation
260# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
261
262AUTH_PASSWORD_VALIDATORS = [
263 {
264 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
265 },
266 {
267 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
268 },
269 {
270 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
271 },
272 {
273 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
274 },
275]
276
277
278# Internationalization
279# https://docs.djangoproject.com/en/1.10/topics/i18n/
280
281LANGUAGE_CODE = 'en-us'
282
283TIME_ZONE = 'UTC'
284
285USE_I18N = True
286
287USE_L10N = True
288
289USE_TZ = True
290
291
292# Static files (CSS, JavaScript, Images)
293# https://docs.djangoproject.com/en/1.10/howto/static-files/
294
295STATIC_URL = '/static/'