Пример #1
0
def register(request):
    serializer = RegisterSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.save()
    return Response({
        "message":
        "User Created Successfully.  Now perform Login to get your token",
    })
Пример #2
0
    def post(self, request, *args, **kwargs):
        serializer = RegisterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(self.get_response_data(user),
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Пример #3
0
 def post(self, request):
     serializer = RegisterSerializer(data=request.data)
     data = {}
     if serializer.is_valid():
         person = serializer.save()
         data['response'] = ['success']
     else:
         data = serializer.errors
     return Response(data)
Пример #4
0
    def create(self, request):
        serializer = RegisterSerializer(data=request.GET)

        if serializer.is_valid():
            user = serializer.create(serializer.data)
            user_serializer = UserSerializer(user)

            return Response({'user': user_serializer.data})

        return Response({'errors': serializer.errors},
                        status=status.HTTP_404_NOT_FOUND)
Пример #5
0
def register(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        username = data['email'].split('@')[0]
        data['username'] = username

        serializer = RegisterSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            Response = {
                "id": serializer.data['id'],
                "token": serializer.data['token']
            }
            return JsonResponse(Response)
        return HttpResponse(status=404)
Пример #6
0
    def post(self, request):
        # Save our code and return the serialized data.
        serializer = RegisterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.save()

        # Get the newly created user from the registration.
        authenticated_user = data['user']

        # Get our web application authorization.
        application = Application.objects.filter(
            name=settings.MIKAID_RESOURCE_SERVER_NAME).first()

        # Generate our access token which does not have a time limit.
        aware_dt = timezone.now()
        expires_dt = aware_dt.replace(aware_dt.year + 1776)
        access_token, created = AccessToken.objects.update_or_create(
            application=application,
            user=authenticated_user,
            defaults={
                'user': authenticated_user,
                'application': application,
                'expires': expires_dt,
                'token': generate_token(),
                'scope': 'read,write,introspection'
            },
            scope='read,write,introspection')

        # Return our new token.
        return Response(
            data={
                # --- REQUIRED --- #
                'token': str(access_token),
                'scope': access_token.scope,

                # --- OPTIONAL --- #
                "client_id": access_token.user.id,
                "email": access_token.user.email,
                # "exp": int(format(access_token.expires, 'U'))
                "exp": access_token.expires,
            },
            status=status.HTTP_201_CREATED)
Пример #7
0
    def create(self, request, format=None):
        serializer = RegisterSerializer(data=request.data)

        if not serializer.is_valid():
            return Response(
                InvalidPost("Invalid or Incorrect data on the post request.",
                            1).display_invalid_exception())

        [email, password] = [item for item in serializer.data.values()]

        # Checking if the email is already registered.
        if User.objects.filter(email=email):
            return Response(
                get_json_response("false", {}, {
                    "code":
                    2,
                    "message":
                    "Invalid or Incorrect credentials. Email already registered."
                }))

        # Checking if the password is strong
        if not len(password) > 5:
            return Response(
                get_json_response("false", {}, {
                    "code":
                    3,
                    "message":
                    "Invalid or Incorrect credentials. Weak credentials."
                }))

        [hashed_password, token_id
         ] = [generate_hash(password),
              generate_token(email, password)]
        User.objects.get_or_create(email=email,
                                   password=hashed_password,
                                   token_id=token_id)
        return Response(
            get_json_response("true", {
                "email": email,
                "token_id": token_id
            }, {}))
Пример #8
0
def user_register(request):
    """用户注册"""
    data = request.data
    print(data)
    serializer = RegisterSerializer(data=data)
    serializer.is_valid(raise_exception=True)
    # 获取验证码
    tel = serializer.validated_data['tel']
    tel_code = request.data.get('tel_code')
    if tel_code == caches['default'].get(f'{tel}_time'):
        # 验证码失效
        caches['default'].delete_pattern(f'{tel}_time')
        with atomic():
            user = User()
            user.password = to_md5_hex(serializer.validated_data['password'])
            user.tel = serializer.validated_data['tel']
            user.username = serializer.validated_data['username']
            user.user_image = DefaultImagePath
            user.save()
        return DefaultResponse(*REGISTER_SUCCESS)
    return DefaultResponse(*CACHE_ERROR)
Пример #9
0
def registration(request):
    if request.method == 'POST':
        user_data = request.data
        serializer = RegisterSerializer(data=user_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_201_CREATED)
Пример #10
0
 def post(self, request, *args, **kwargs):
     serializer = self.serializer_class(data=request.data,
                                        context={'request': request})
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     register_serializer = RegisterSerializer(user)
     token, created = Token.objects.get_or_create(user=user)
     return Response({
         'token': token.key,
         'user_id': user.pk,
         'email': user.email,
         'user_data': register_serializer.data,
     })
Пример #11
0
class CustomRegisterView(RegisterView):
    successfully_create_response = openapi.Response(
        description="Registration",
        schema=RegisterSerializer(help_text='custom register serializer'),
    )

    @swagger_auto_schema(
        operation_description="Creates new user in database",
        request_body=RegisterSerializer(help_text='custom register serializer'),
        responses={
            status.HTTP_201_CREATED: successfully_create_response
        }
    )
    def post(self, request, *args, **kwargs):
        serializer = RegisterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(self.get_response_data(user),
                        status=status.HTTP_201_CREATED,
                        headers=headers)
Пример #12
0
 def post(self, request):
     serializer = RegisterSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return response.Response(
         status=status.HTTP_201_CREATED,
         data=serializer.data,
     )
    def registration(self, request, pk=None):
        """
            Function will fetch the login credentials and either log the user in
            or return error. To call this function, use this URL:
            --------------------------------------------
            /api/registers/0/registration/?format=json
            --------------------------------------------
        """
        # ALGORITHM: Attempt to decode the data the way iOS encoded it
        #            else we have to just attempt to decode the data raw.
        try:
            for data in request.data:
                json_arr = json.loads(data)
                serializer = RegisterSerializer(data=json_arr)  # iOS Version
        except Exception as e:
            serializer = RegisterSerializer(
                data=request.data)  # Mobile Version

        if serializer.is_valid():
            username = serializer.data['username'].lower()
            email = serializer.data['email']
            password = serializer.data['password']
            first_name = serializer.data['first_name']
            last_name = serializer.data['last_name']

            # Validate to ensure the user is not using an email which is banned in
            # our system for whatever reason.
            banned_domains = BannedDomain.objects.all()
            for banned_domain in banned_domains:
                if email.count(banned_domain.name) > 0:
                    return Response({
                        'status': 'failure',
                        'errors': {
                            'email':
                            'this emal domain is not accepted by our system'
                        }
                    })

            # Validate to ensure the email has not been taken by another user.
            try:
                user = User.objects.get(email=email)
                return Response({
                    'status': 'failed',
                    'errors': {
                        'email': 'has already been taken by another user.'
                    }
                })
            except User.DoesNotExist:
                pass

            # Create our new user
            try:
                user = User.objects.create_user(
                    username,
                    email,
                    password,
                )
                user.first_name = serializer.data['first_name']
                user.last_name = serializer.data['last_name']
                # user.is_active = False;  # Need email verification to change status.
                user.save()

                return Response({ # Return success message.
                    'status': 'success',
                    'errors': [],
                    'user_id': user.id,
                })
            except Exception as e:
                return Response({
                    'status': 'failure',
                    'errors': {
                        'Unknown':
                        'An unknown error occured, failed registering user.'
                    }
                })
        else:
            return Response({
                'status': 'failed',
                'errors': str(serializer.errors),
            })
Пример #14
0
    def registration(self, request, pk=None):
        """
            Function will fetch the login credentials and either log the user in
            or return error. To call this function, use this URL:
            --------------------------------------------
            /api/registers/0/registration/?format=json
            --------------------------------------------
        """
        # ALGORITHM: Attempt to decode the data the way iOS encoded it
        #            else we have to just attempt to decode the data raw.
        try:
            for data in request.data:
                json_arr = json.loads( data )
                serializer = RegisterSerializer(data=json_arr) # iOS Version
        except Exception as e:
            serializer = RegisterSerializer(data=request.data) # Mobile Version
        
        if serializer.is_valid():
            username = serializer.data['username'].lower()
            email = serializer.data['email']
            password = serializer.data['password']
            first_name = serializer.data['first_name']
            last_name = serializer.data['last_name']
        
            # Validate to ensure the user is not using an email which is banned in
            # our system for whatever reason.
            banned_domains = BannedDomain.objects.all()
            for banned_domain in banned_domains:
                if email.count(banned_domain.name) > 0:
                    return Response({
                        'status' : 'failure',
                        'errors' : {'email':'this emal domain is not accepted by our system'}
                    })

            # Validate to ensure the email has not been taken by another user.
            try:
                user = User.objects.get(email=email)
                return Response({
                    'status': 'failed',
                    'errors': {'email':'has already been taken by another user.'}
                })
            except User.DoesNotExist:
                pass

            # Create our new user
            try:
                user = User.objects.create_user(
                    username,
                    email,
                    password,
                )
                user.first_name = serializer.data['first_name']
                user.last_name = serializer.data['last_name']
                # user.is_active = False;  # Need email verification to change status.
                user.save()

                return Response({ # Return success message.
                    'status': 'success',
                    'errors': [],
                    'user_id': user.id,
                })
            except Exception as e:
                return Response({
                    'status' : 'failure',
                    'errors' : {'Unknown':'An unknown error occured, failed registering user.'}
                })
        else:
            return Response({
                'status': 'failed',
                'errors': str(serializer.errors),
            })
Пример #15
0
 def post(self, request, format=None):
     serializer = RegisterSerializer(data=request.data)
     if serializer.is_valid():
         token = serializer.save()
         return Response({'token': token}, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)