def get(self, request): """ Get the list of users for Admin purpose :param request: :return: """ user = request.user nick_name = request.GET.get('nick_name', None) mobile = request.GET.get('mobile', None) email = request.GET.get('email', None) unique_id = request.GET.get('unique_id', None) if user.is_superuser: user_data = UserModelQueries.get_all_user_profile() elif mobile: user_data = UserModelQueries.get_user_profile_by_mobile() elif email: user_data = UserModelQueries.get_user_profile_by_email() elif unique_id: user_data = UserModelQueries.get_user_profile_by_unique_id() elif nick_name: user_data = UserModelQueries.get_user_profile_by_nick_name() else: return StandardHttpResponse.bad_rsp([], 'Invalid Search.') paginator = Paginator(user_data, 30) page = request.GET.get('page', 1) try: user_data = paginator.page(page) except PageNotAnInteger: return StandardHttpResponse.bad_rsp([], 'Not a valid Page Number.') except EmptyPage: return StandardHttpResponse.rsp_200([], 'No User Found') serializer = GetUserProfileSerializer(instance=user_data, many=True) return StandardHttpResponse.rsp_200(serializer.data, 'User fetched Successfully.')
def login(request): """ Authenticate user. :param request: :return: """ try: json_body = json.loads(request.body) request._body = urllib.parse.urlencode(json_body) json_body['redirect_uri'] = REDIRECT_URL request._post = json_body except Exception as e: return StandardHttpResponse.bad_rsp([], e.__str__()) view = TokenView.as_view() username = json_body["username"] if "username" in json_body else False password = json_body["password"] if "password" in json_body else False if not username or not password: return StandardHttpResponse.login_bad_rsp([], 'Credentials missing') user = authenticate(username=username, password=password) if not user: return StandardHttpResponse.login_bad_rsp([], 'Wrong credentials') application_token = get_application_token() if not application_token: return StandardHttpResponse.bad_rsp( [], 'Application is not ready. Please contact Admin.') delete_other_token(user.id) request.META["HTTP_AUTHORIZATION"] = "Basic " + application_token.decode() request.META["CONTENT_TYPE"] = "application/x-www-form-urlencoded" return StandardHttpResponse.login_rsp(json.loads(view(request).content), 'User Logged-In Successfully.')
def post(self, request): """ API to resend the OTP to mobile :param request: :return: """ user = request.user request_data = request.data if not type(request_data) == dict: return StandardHttpResponse.bad_rsp([], 'Bad data') if not self.validate_request_data(request_data): return StandardHttpResponse.bad_rsp([], 'Missing data fields') result, response = MobileOtpService.resend_otp(request_data['otp_ref']) if not result: return StandardHttpResponse.bad_rsp([], response) user_profile_obj = UserModelQueries.get_user_profile_by_user_id( user.id) if not response.mobile.__str__() == user_profile_obj.mobile.__str__(): return StandardHttpResponse.bad_rsp([], 'Invalid Data') response_data = [{'otp_ref': response.otp_ref}] return StandardHttpResponse.rsp_200( response_data, 'An OTP Sent to {} to reset the password'.format( response.mobile.__str__()))
def get(self, request): """ :param request: :return: """ nick_name = request.GET.get("nick_name", None) if not nick_name: return StandardHttpResponse.bad_rsp([], 'Missing Data') response = UserModelQueries.get_user_profile_by_nick_name(nick_name) if response: return StandardHttpResponse.bad_rsp([], 'NickName already taken.') return StandardHttpResponse.rsp_200([], 'NickName available.')
def get(self, request): """ To get the profile details :param request: :return: """ user = request.user user_obj = UserModelQueries.get_user_profile_by_user_id(user.id) serializer = GetUserProfileSerializer(instance=user_obj) return StandardHttpResponse.rsp_200(serializer.data, 'Profile fetched Successfully.')
def _validate(request, *args, **kwargs): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != 'Token'.lower().encode(): msg = _( 'Invalid token. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) if len(auth) == 1: msg = _('Invalid token. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _( 'Invalid token. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: token = auth[1].decode() except UnicodeError: msg = _( 'Invalid token header. Token string should not contain invalid characters.' ) raise exceptions.AuthenticationFailed(msg) try: access_token = AccessToken.objects.get(token=token) if access_token.is_expired(): request.authenticators = False raise exceptions.AuthenticationFailed('Invalid token.') except AccessToken.DoesNotExist: request.authenticators = False raise exceptions.AuthenticationFailed('Invalid token.') token = access_token.user if not token: raise exceptions.AuthenticationFailed('Invalid token.') perm = False if len(_scopes) > 0 else True if token.is_superuser: perm = True elif token.permission_string: permissions = _(token.permission_string).split(',') for val in _scopes: # The list will be OR if type(val) == tuple: for z in val: if z in permissions: perm = True else: if val in permissions: perm = True else: perm = False if perm: return view_func(request, *args, **kwargs) return StandardHttpResponse.rsp_401([], 'You are not authorized.')
def post(request): """ To logout a user means to expire the oauth token :param request: :return: """ logout(request) token = request.token token_obj = AccessToken.objects.get(token=token) token_obj.expires = datetime.now(utc) token_obj.save() return StandardHttpResponse.rsp_200([], 'Logout Successfully.')
def post(self, request): """ Api to send the link on mail for forget password :param request: :return: """ request_data = request.data if 'mobile' not in request_data or not request_data['mobile']: return StandardHttpResponse.bad_rsp([], 'Invalid Data.') email = None mobile = None if '@' in request_data['mobile']: email = request_data['mobile'] else: mobile = request_data['mobile'] if mobile: user_profile_obj = UserModelQueries.get_user_profile_by_mobile( mobile) if not user_profile_obj: return StandardHttpResponse.bad_rsp( [], 'Mobile is yet not registered or not verified.') else: user_profile_obj = UserModelQueries.get_user_profile_by_email( email) if not user_profile_obj: return StandardHttpResponse.bad_rsp( [], 'Looks like You haven\'t registered yet. Please Registered.' ) result, response = MobileOtpService.create_otp(user_profile_obj.mobile, 'ForgetPassword') if not result: return StandardHttpResponse.bad_rsp([], response) # TODO: Code to send the otp to mobile SentOTP.send_otp_to_email(email, response['otp'], 'Forget Password') response_data = {'otp_ref': response['otp_ref']} return StandardHttpResponse.rsp_200( response_data, 'An OTP Sent to {} to reset the password'.format( user_profile_obj.mobile.__str__()))
def post(self, request): """ Api to send an otp to mobile to verify it :param request: :return: """ current_time = datetime.now(utc) request_data = request.data.copy() user = request.user if not type(request_data) == dict: return StandardHttpResponse.bad_rsp([], 'Bad data') if not self.validate_request_data(request_data): return StandardHttpResponse.bad_rsp([], 'Missing data fields') result, response = MobileOtpService.validate_otp( otp=request_data['otp'], otp_ref=request_data['otp_ref'], o_type='MobileVerification', current_time=current_time) if not result: return StandardHttpResponse.bad_rsp([], response) if not response.mobile == request_data['mobile']: return StandardHttpResponse.bad_rsp([], 'Invalid Data') user_profile_obj = UserModelQueries.get_user_profile_by_user_id( user.id) if not user_profile_obj.mobile.__str__() == request_data['mobile']: return StandardHttpResponse.bad_rsp([], 'Invalid Data') user_profile_obj.mobile_verified = True user_profile_obj.is_active = True user_profile_obj.save() return StandardHttpResponse.rsp_200([], 'Mobile Verified.')
def post(self, request): original_request_data = request.data.copy() user = request.user if not type(original_request_data) == dict: return StandardHttpResponse.bad_rsp([], 'Bad data') if not self.validate_request_data(original_request_data): return StandardHttpResponse.bad_rsp([], 'Missing data fields') if not original_request_data['new_password'] == original_request_data['confirm_new_password']: return StandardHttpResponse.bad_rsp([], 'Password and Confirm Password not matched.') old_password = original_request_data['old_password'] user_obj = UserModelQueries.get_user_by_id(user.id) authenticated_user = authenticate(username=user_obj.username, password=old_password) if not authenticated_user: return StandardHttpResponse.login_bad_rsp([], 'Old Password not matched') user_obj.set_password(original_request_data['new_password']) user_obj.save() return StandardHttpResponse.rsp_200([], 'Password Changed Successfully.')
def post(self, request): """ To edit the user profile :param request: :return: """ request_data = request.data.copy() if not type(request_data) == dict: return StandardHttpResponse.bad_rsp([], 'Bad data') user = request.user user_profile_obj = UserModelQueries.get_user_profile_by_user_id(user.id) if 'nick_name' in request_data: response = UserModelQueries.get_user_profile_by_nick_name(request_data['nick_name']) if response and not response.user_id == user.id: return StandardHttpResponse.bad_rsp([], 'Nick Name already taken.') if 'dob' in request_data: result, dob1 = ValidationClass.validate_dob(request_data['dob']) if not result: return StandardHttpResponse.bad_rsp([], dob1) request_data['dob'] = dob1 serializer = UpdateUserProfileSerializer(instance=user_profile_obj, data=request_data, partial=True) if serializer.is_valid(): serializer.save() if 'first_name' in request_data or 'last_name' in request_data: user_obj = UserModelQueries.get_user_by_id(user.id) if 'first_name' in request_data and request_data['first_name']: user_obj.first_name = request_data['first_name'] if 'last_name' in request_data and request_data['last_name']: user_obj.last_name = request_data['last_name'] user_obj.save() # -------This is extra query load on database because of Android demand--- user_profile_obj = UserModelQueries.get_user_profile_by_user_id(user.id) response_data = GetUserProfileSerializer(instance=user_profile_obj).data # ------------------------------------------------------------------------ return StandardHttpResponse.rsp_200(response_data, 'User Profile Updated Successfully') return StandardHttpResponse.bad_rsp([], serializer.errors)
def PasswordResetViaOTP(request): """ TO reset the password for a user via otp :param request: :return: """ current_time = datetime.now(utc) request_data = json.loads(request.body) if not type(request_data) == dict: return StandardHttpResponse.login_bad_rsp([], 'Bad data') if not PasswordResetUtils().validate_request_data(request_data): return StandardHttpResponse.login_bad_rsp([], 'Missing data fields') if not request_data['password'] == request_data['confirm_password']: return StandardHttpResponse.login_bad_rsp([], 'Password Not Matched') result, response = MobileOtpService.validate_otp( otp=request_data['otp'], otp_ref=request_data['otp_ref'], o_type='ForgetPassword', current_time=current_time, return_obj=True) if not result: return StandardHttpResponse.login_bad_rsp([], response) if not response.mobile: return StandardHttpResponse.login_bad_rsp( [], 'Invalid request. Please contact Admin.') user_profile_obj = UserModelQueries.get_user_profile_by_mobile( response.mobile) if not user_profile_obj: return StandardHttpResponse.login_bad_rsp([], 'Mobile not registered') user_obj = UserModelQueries.get_user_by_id(user_profile_obj.user_id) response.delete() user_obj.set_password(request_data['password']) user_obj.save() json_body = dict() json_body['username'] = user_obj.username json_body['password'] = request_data['password'] json_body['grant_type'] = 'password' request._body = urllib.urlencode(json_body) json_body['redirect_uri'] = REDIRECT_URL request._post = json_body view = TokenView.as_view() request.META[ "HTTP_AUTHORIZATION"] = "Basic YlVhOFBCTTFCQTFGb3JPUlp5RVB0RmFBSUJZOGNhUWF5N2hTbTE4dDpla25ENkVzenlJZEZMeUM1RmhqSFlnUnVuMlk2alpqMTN0Mll1ZzZhVWNJc0ZYYk9VMnNyWDRjRmJLQkpwMnpVVVRZNnV6U0U5V3AyN3JJTmNPZ09FWmVDVlB4NXVEWXV0ZHBFMHhVcEROTTBGUlluRERMQzlTTnNNN3RRZUhEbA==" request.META["CONTENT_TYPE"] = "application/x-www-form-urlencoded" return StandardHttpResponse.login_rsp(json.loads(view(request).content), 'User Logged-In Successfully.')
def post(self, request): """ To create a user :param request: :return: """ request_data = request.data.copy() if not type(request_data) == dict: return StandardHttpResponse.bad_rsp([], 'Bad data') if not self.validate_request_data(request_data): return StandardHttpResponse.bad_rsp([], 'Missing data fields') name_arr = request_data['name'].split(' ') if len(name_arr) > 1: last_name = name_arr[-1:][0] name_arr.remove(last_name) first_name = '' for i in name_arr: if i: first_name = first_name + ' ' + i first_name = first_name.lstrip() else: first_name = request_data['name'] last_name = '' result, user_response = UserUtils.create_user(first_name=first_name, last_name=last_name, username=first_name, password=request_data['password']) if not result: return StandardHttpResponse.bad_rsp([], user_response) blood_group = dob = None if 'blood_group' in request_data and request_data['blood_group']: blood_group = request_data['blood_group'] if 'dob' in request_data and request_data['dob']: dob = request_data['dob'] result, user_profile_response = UserUtils.create_user_profile(user=user_response, blood_group=blood_group, dob=dob) if not result: user_response.delete() return StandardHttpResponse.bad_rsp([], user_profile_response) data = {"username": first_name, "password": request_data['password'], "grant_type": "password"} response = requests.post(API_DOMAIN + '/v1/login/', json=data) if response.status_code == 200: data = json.loads(response.text) return StandardHttpResponse.rsp_201(data['success'], 'User Created Successfully.') else: return StandardHttpResponse.rsp_200([], 'User Created Successfully.')
def post(self, request): """ To sent the otp on mobile for various purpose :param request: :return: """ request_data = request.data.copy() user = request.user if not type(request_data) == dict: return StandardHttpResponse.bad_rsp([], 'Bad data') if not self.validate_request_data(request_data): return StandardHttpResponse.bad_rsp([], 'Missing data fields') mobile = request_data['mobile'] user_profile = UserModelQueries.get_user_profile_by_mobile( mobile=mobile, mobile_verified=True) if user_profile: if user_profile.user.id == request.user.id: return StandardHttpResponse.bad_rsp( [], 'Same Mobile number already registered with you.') else: return StandardHttpResponse.bad_rsp( [], 'Mobile already registered.') user_profile_obj = UserModelQueries.get_user_profile_by_user_id( user.id) user_profile_obj.mobile = mobile user_profile_obj.is_active = False user_profile_obj.mobile_verified = False user_profile_obj.save() result, response = MobileOtpService.create_otp( mobile, o_type=request_data['otp_type'], created_by=user.id) if result: resp = [{'otp_ref': response['otp_ref'], 'mobile': mobile}] return StandardHttpResponse.rsp_200( resp, 'An OTP sent to your Mobile. Please Verify it.') return StandardHttpResponse.bad_rsp([], response)