Fakultas Ilmu Komputer UI

Commit fa101c82 authored by Putu Agastya's avatar Putu Agastya
Browse files

[GREEN] Custom User model implemented.

parent 11ab869d
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class AuthenticationConfig(AppConfig):
name = 'authentication'
# Generated by Django 3.0.3 on 2020-04-06 18:50
import authentication.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('name', models.CharField(max_length=150)),
('is_admin', models.BooleanField(default=False)),
('is_contributor', models.BooleanField(default=False)),
('instansi', models.CharField(max_length=240)),
('nik', models.CharField(max_length=240)),
('alamat', models.CharField(max_length=240)),
('nomor_telpon', models.CharField(max_length=240)),
('email', models.EmailField(max_length=254, unique=True)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', authentication.models.CustomUserManager()),
],
),
]
# Generated by Django 3.0.3 on 2020-04-06 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(blank=True, default='', max_length=150),
),
]
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUserManager(UserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Create and save a user with the given email, and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_contributor(self, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_contributor', True)
extra_fields.setdefault('is_admin', False)
if extra_fields.get('is_contributor') is not True:
raise ValueError('Contributor must have is_contributor=True.')
if extra_fields.get('is_admin') is not False:
raise ValueError('contributor must have is_admin=False.')
return self._create_user(email, password, **extra_fields)
def create_admin(self, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_admin', True)
extra_fields.setdefault('is_contributor', False)
if extra_fields.get('is_admin') is not True:
raise ValueError('admin must have is_admin=True.')
if extra_fields.get('is_contributor') is not False:
raise ValueError('admin must have is_contributor=False.')
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_admin', True)
extra_fields.setdefault('is_contributor', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
if extra_fields.get('is_admin') is not True:
raise ValueError('Superuser must have is_admin=True.')
if extra_fields.get('is_contributor') is not True:
raise ValueError('Superuser must have is_contributor=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
email = models.EmailField(unique=True)
username = models.CharField(unique=False, blank=True, default='', max_length=150)
name = models.CharField(max_length=150)
is_admin = models.BooleanField(blank=False, default=False)
is_contributor = models.BooleanField(blank=False, default=False)
instansi = models.CharField(max_length=240)
nik = models.CharField(max_length=240)
alamat = models.CharField(max_length=240)
nomor_telpon = models.CharField(max_length=240)
objects = CustomUserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
\ No newline at end of file
from django.test import TestCase, Client
from django.urls import resolve
from authentication.models import User
class UserModelTest(TestCase):
def test_create_user(self):
self.assertRaises(ValueError, User.objects.create_user, )
user = User.objects.create_user(
email="alice@acme.com", password="acmeindustry").save()
self.assertEqual(User.objects.all().count(), 1)
def test_create_contributor(self):
self.assertRaises(ValueError, User.objects.create_contributor,
email="bob@acme.com", password="acmeindustry", is_admin=True)
self.assertRaises(ValueError, User.objects.create_contributor,
email="bob@acme.com", password="acmeindustry", is_contributor=False)
User.objects.create_contributor(
email="bob@acme.com", password="acmeindustry").save()
kontributor = User.objects.get(email="bob@acme.com")
self.assertTrue(kontributor.is_contributor)
self.assertFalse(kontributor.is_admin)
self.assertFalse(kontributor.is_superuser)
def test_create_admin(self):
self.assertRaises(ValueError, User.objects.create_admin,
email="carol@acme.com", password="acmeindustry", is_contributor=True)
self.assertRaises(ValueError, User.objects.create_admin,
email="carol@acme.com", password="acmeindustry", is_admin=False)
User.objects.create_admin(
email="carol@acme.com", password="acmeindustry").save()
admin = User.objects.get(email="carol@acme.com")
self.assertTrue(admin.is_admin)
self.assertFalse(admin.is_contributor)
self.assertFalse(admin.is_superuser)
def test_create_superuser(self):
self.assertRaises(ValueError, User.objects.create_superuser,
email="dan@acme.com", password="acmeindustry", is_contributor=False)
self.assertRaises(ValueError, User.objects.create_superuser,
email="dan@acme.com", password="acmeindustry", is_admin=False)
self.assertRaises(ValueError, User.objects.create_superuser,
email="dan@acme.com", password="acmeindustry", is_staff=False)
self.assertRaises(ValueError, User.objects.create_superuser,
email="dan@acme.com", password="acmeindustry", is_superuser=False)
User.objects.create_superuser(
email="dan@acme.com", password="acmeindustry").save()
superuser = User.objects.get(email="dan@acme.com")
self.assertTrue(superuser.is_admin)
self.assertTrue(superuser.is_contributor)
self.assertTrue(superuser.is_staff)
self.assertTrue(superuser.is_superuser)
from django.shortcuts import render
# Create your views here.
......@@ -40,7 +40,8 @@ INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
'authentication.apps.AuthenticationConfig',
'app.apps.AppConfig',
]
MIDDLEWARE = [
......@@ -110,6 +111,8 @@ STATICFILES_DIRS = (
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_USER_MODEL = 'authentication.User'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
......
Supports Markdown
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