Giter VIP home page Giter VIP logo

earthcomfy / drf-phone-email-auth Goto Github PK

View Code? Open in Web Editor NEW
27.0 27.0 8.0 14 KB

A Django boilerplate that provides a RESTful API interface for user registration and authentication using phone number and/or email.

Shell 1.04% Dockerfile 0.86% Python 98.10%
dj-rest-auth django django-authentication django-docker django-email-verification django-phone-verification django-rest-framework docker twilio

drf-phone-email-auth's Introduction

Hi ๐Ÿ‘‹, I'm Hana

  • I am interested in Backend web development
  • I am currently working as a Django developer
  • I am also a Software Engineering student at Bahir Dar University, Ethiopia
  • I write articles on DEV
  • You can find my latest resume here
  • You can reach me via Linkedin

Blog posts

Connect with me:

earthcomfy https://www.linkedin.com/in/hana-getnet-belay-323b91219/

Languages and Tools:

aws bash django docker express firebase git graphql java javascript linux mongodb mysql nginx nodejs pandas postgresql postman python react redis scikit_learn selenium sqlite tailwind

drf-phone-email-auth's People

Contributors

earthcomfy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

drf-phone-email-auth's Issues

RawPostDataException when posting raw json

The inbuilt djangorestframework form posts to the route 'api/user/register' fine, however, when you switch to raw json, for example:

  {
    "password1": "root.@qw",
    "password2": "root.@qw",
    "phone_number": "+254........7"
}

something you would do from a client, a user is created but an exception is raised before the otp message is sent, tried httpie client and got a status code _201 but no OTP got dispatched. As it is, can only post from the django form.

Admin page is broken

Admin page won't let super users to login, even though they're on the db with all necessary rights.

This fixed it for me:

AUTHENTICATION_BACKENDS = [
...
'django.contrib.auth.backends.ModelBackend',
...
]

added to config/settings.py

Make an endpoint to update the user.

I really liked your project! Can you please help me implement the update of the User, so that when the email changes, a confirmation comes to the mail, and when the phone changes, sms confirmation comes. Thanks in advance!
My models:

class CustomUser(AbstractUser):
APPLICANT = "Applicant"
EMPLOYER = "Employer"
ROLE_CHOICES = (
(APPLICANT, "Applicant"),
(EMPLOYER, "Employer"),
)
username = models.CharField(max_length=255, unique=True, blank=True, null=True)
email = models.EmailField(("email address"), unique=False, max_length=254, blank=True,null=True)
role = models.CharField(max_length=50, choices=ROLE_CHOICES)
avatar = models.ImageField(
("avatar"), upload_to="avatars/", null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
blocked_until = models.DateTimeField(null=True, blank=True)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = []

objects = UserManager()

def __str__(self):
    return self.email

def get_phone(self):
    try:
        phone = self.phone.phone_number
    except PhoneNumber.DoesNotExist:
        phone = None
    return phone

@property
def fullname(self):
    return f"{self.first_name} {self.last_name}"

class PhoneNumber(models.Model):
user = models.OneToOneField(CustomUser, related_name='phone', on_delete=models.CASCADE)
phone_number = PhoneNumberField(unique=True)
security_code = models.CharField(max_length=120)
is_verified = models.BooleanField(default=False)
sent = models.DateTimeField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
    ordering = ('-created_at', )

def __str__(self):
    return self.phone_number.as_e164

def generate_security_code(self):
    """
    Returns a unique random `security_code` for given `TOKEN_LENGTH` in the settings.
    Default token length = 6
    """
    token_length = getattr(base, "TOKEN_LENGTH", 6)
    return get_random_string(token_length, allowed_chars="0123456789")

def is_security_code_expired(self):
    expiration_date = self.sent + datetime.timedelta(
        minutes=base.TOKEN_EXPIRE_MINUTES
    )
    return expiration_date <= timezone.now()

def send_confirmation(self):
    twilio_account_sid = base.TWILIO_ACCOUNT_SID
    twilio_auth_token = base.TWILIO_AUTH_TOKEN
    twilio_phone_number = base.TWILIO_PHONE_NUMBER

    self.security_code = self.generate_security_code()

    # print(
    #     f'Sending security code {self.security_code} to phone {self.phone_number}')

    if all(
        [
            twilio_account_sid,
            twilio_auth_token,
            twilio_phone_number
        ]
    ):
        try:
            twilio_client = Client(
                twilio_account_sid, twilio_auth_token
            )
            twilio_client.messages.create(
                body=f'Your activation code is {self.security_code}',
                to=str(self.phone_number),
                from_=twilio_phone_number,
            )
            self.sent = timezone.now()
            self.save()
            return True
        except TwilioRestException as e:
            print(e)
    else:
        print("Twilio credentials are not set")

def check_verification(self, security_code):
    if (
        not self.is_security_code_expired() and
        security_code == self.security_code and
        self.is_verified == False
    ):
        self.is_verified = True
        self.save()
    else:
        raise NotAcceptable(
            _("Your security code is wrong, expired or this phone is verified before."))

    return self.is_verified

django.urls.exceptions.NoReverseMatch: Reverse for 'redirect' not found.

Hi, I am getting error django.urls.exceptions.NoReverseMatch: Reverse for 'redirect' not found. 'redirect' is not a valid view function or pattern name. when creating user.

class UserRegisterationAPIView(RegisterView):
    """
    Register new users using phone number or email and password.
    """
    serializer_class = UserRegisterSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

user = self.perform_create(serializer) this line of code causing the error.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.