def add(self): user_email = utils.authenticate_user(self, self.request.url) if not user_email: return self.response.headers['Content-Type'] = "application/json" self.response.headers['Access-Control-Allow-Origin'] = '*' try: expense_acc = ExpenseAccount() response = expense_acc.add( user_email=user_email, account_id=str(uuid.uuid4()), type=self.request.get("type", None), title=self.request.get("title", None), balance=float(self.request.get("balance", None)), ) self.response.out.write( json.dumps({ 'success': True, 'error': [], 'response': response })) except Exception as e: self.response.out.write( json.dumps({ 'success': False, 'error': e.message, 'response': None })) logging.error(traceback.format_exc())
def user_login(request): """ **User Login** Login an existing user. Used for authenticating the user. > POST * Requires following fields of users in JSON format: 1. `email` - String 2. `password` - String * Returns user profile data on successful login. * Also returns Authentication token to be used by frontend for further communication with backend. * On failure it returns appropriate HTTP status and message in JSON response. * Possible HTTP status codes and JSON response: * `HTTP_200_OK` on successful login. * `HTTP_401_UNAUTHORIZED` for failed login attempt. { "message": "Invalid username or password" } * `HTTP_500_INTERNAL_SERVER_ERROR` - Internal server error. * `HTTP_404_NOT_FOUND` - When user is not found. { "message": "User with specified email does not exist." } :param request: """ try: email = request.data['email'] password = request.data['password'] except KeyError: return Response(messages.REQUIRED_EMAIL_AND_PASSWORD, status=status.HTTP_400_BAD_REQUEST) try: # response = validations_utils.login_user_existence_validation(email) user = authenticate( email=email, password=password) # Validates credentials of user. except ValidationException: return Response(messages.INVALID_EMAIL_OR_PASSWORD, status=status.HTTP_401_UNAUTHORIZED) try: login_user = utils.authenticate_user( user, request.data) # Authorizes the user and returns appropriate data. except ValidationException as e: # Generic exception return Response(e.errors, status=e.status) return Response(login_user, status=status.HTTP_200_OK)
def suggestions(request): code = request.GET.get('code', '') token = authenticate_user(code) client_address = request.META.get('HTTP_X_FORWARDED_FOR') ip = client_address.split(',')[0] print(ip) #client_address = request.META.get('HTTP_X_REAL_IP') url = 'https://api.ipdata.co/' + ip sublist = get_authenticated_user_data(token) payload = { "api-key": "54a69eabf71ca58daea3ca176740cedda9c99acd0c6ebe5e239b1696" } response = requests.get(url, params=payload) response_json = response.json() context = {} if response.status_code == 200: city = response_json["city"] country = response_json["country_name"] context["country"] = country context["city"] = city print(response_json) context["sublist"] = sublist return render_to_response('SubSuggest_Final.html', context)
def fetch_all(self): user_email = utils.authenticate_user(self, self.request.url) if not user_email: return self.response.headers['Content-Type'] = "application/json" self.response.headers['Access-Control-Allow-Origin'] = '*' try: user_transactions = ExpenseTransaction.get(user_email=user_email) response = [] for transaction in user_transactions: response.append( ExpenseTransaction.get_json_object(transaction)) self.response.out.write( json.dumps({ 'success': True, 'error': [], 'response': response })) except Exception as e: self.response.out.write( json.dumps({ 'success': False, 'error': e.message, 'response': None })) logging.error(traceback.format_exc())
def update(self): try: if self.request.method == 'GET' and "X-AppEngine-Cron" in self.request.headers: taskqueue.add( method='POST', queue_name='default', url='/data_collector/binance_market/update', ) else: update = False if self.request.method == 'POST' and "X-AppEngine-QueueName" in self.request.headers: update = True else: user = utils.authenticate_user(self, self.request.url, ['*****@*****.**']) if user: update = True if update: start_time = time.time() while True: if time.time() - start_time > 9 * 60: break try: BinanceMarket().update() except: logging.error(traceback.format_exc()) time.sleep(2) time.sleep(5) except: logging.error(traceback.format_exc())
def post(self): user_email = utils.authenticate_user(self, self.request.url) if not user_email: return xslx_file_html = self.request.get('file', '') xslx_file = StringIO.StringIO(xslx_file_html) wb = openpyxl.load_workbook(filename=xslx_file, read_only=True) print wb.get_sheet_names()
def get(self): user_email = utils.authenticate_user(self, self.request.url) if not user_email: return page = utils.template("upload.html", "ExcelReader/templates") template_values = { "upload_label": "Excel File (.xslx): ", "accept": ".xlsx" } self.response.out.write(template.render(page, template_values))
def authenticate_user(self, user="", password=""): if user == "": self.setUser(param.params.myuid) return True if utils.authenticate_user(user, password): self.setUser(user) self.utimer.start(10 * 60000) # Ten minutes! return True else: QtGui.QMessageBox.critical(None, "Error", "Invalid Password", QtGui.QMessageBox.Ok) return False
def jda_login(request): ctx = {"msg": ""} if request.user.id: return HttpResponseRedirect("/home/") login_form = LoginForm() if request.POST: login_form = LoginForm(request.POST) if login_form.is_valid(): try: success = authenticate_user(request, request.POST["username"], request.POST["password"]) except Exception as e: success = False if success: return HttpResponseRedirect("/home/") ctx["login_form"] = login_form return render_to_response("login.html", ctx, context_instance=RequestContext(request))
def login_user(request): if request.method == "GET": return HttpResponseNotFound( "The page you are asking for does not exist") if request.method == 'POST': try: if len(request.POST) != 0: username = request.POST['username'].strip() password = request.POST['password'].strip() else: return HttpResponse("Did not find form data in body", status=500) if username is None or password is None: return HttpResponseForbidden( "Please provide a valid name/username/password") if len(username) < 4: return HttpResponseForbidden( "The username must be atleast 4 characters") if len(password) < 6: return HttpResponseForbidden( "The password be atleast 6 character") if " " in password or " " in username: return HttpResponseForbidden( "The username/password is not correct") user = authenticate_user(username=username, password=password) if user is None: return HttpResponseForbidden( "The username/password is not correct") token = generate_token(user.uuid) res = json.dumps({"AUTH_TOKEN": token, "NAME": user.name}) return HttpResponse(res, content_type='application/json', status=200) except Exception, e: print e return HttpResponseForbidden( "The request cannot be completed as %s" % e)
async def login_for_access_token( form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)): """ **IMPORTANT!!**\n Instead of **username** use **email** address!! """ user = authenticate_user(form_data.username, form_data.password, db) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Incorrect email or password', headers={'WWW-Authenticate': "Bearer"}, ) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token(data={'sub': user.email}, expires_delta=access_token_expires) return {'access_token': access_token, 'token_type': 'bearer'}
def login_properties(): session.permanent = True form = LoginForm() context = {'form': form} if request.method == 'POST': if form.validate_on_submit(): username = request.form.get('username') password = request.form.get('password') authenticated = authenticate_user(username, password) context['error'] = 'Succesfully logged in!' if not authenticated: context['error'] = 'Invalid credentials!' else: redirect('/edit') return render_template('login.html', **context)
def add(self): user_email = utils.authenticate_user(self, self.request.url) if not user_email: return self.response.headers['Content-Type'] = "application/json" self.response.headers['Access-Control-Allow-Origin'] = '*' try: expense_trx = ExpenseTransaction() response = expense_trx.add( user_email=user_email, account_id=self.request.get("account_id", None), transaction_id=str(uuid.uuid4()), type=self.request.get("type", None), title=self.request.get("title", None), amount=float(self.request.get("amount", None)), tag=self.request.get("tag", None), month=int( self.request.get("month", datetime.datetime.now().month)), year=int(self.request.get("year", datetime.datetime.now().year)), ) self.response.out.write( json.dumps({ 'success': True, 'error': [], 'response': response })) except Exception as e: self.response.out.write( json.dumps({ 'success': False, 'error': e.message, 'response': None })) logging.error(traceback.format_exc())
def update(self): try: if self.request.method == 'GET' and "X-AppEngine-Cron" in self.request.headers: taskqueue.add( method='POST', queue_name='default', url='/data_collector/crypto_news/update', ) else: update = False if self.request.method == 'POST' and "X-AppEngine-QueueName" in self.request.headers: update = True else: user = utils.authenticate_user(self, self.request.url, ['*****@*****.**']) if user: update = True if update: CryptoNews().update() except: logging.error(traceback.format_exc())