Flask Admin restrict access

I am learning Flask-Admin but I want to prevent users from going to the admin page. If you want to go to the admin page you must go to /a where admin_state becomes 2. But when I do it I get redirect again.Here is the code:

FLASK

from flask import Flask,redirect,url_for,render_template,request
from flask_sqlalchemy import SQLAlchemy
from flask_admin import BaseView,expose,Admin,AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_login import UserMixin,login_user,logout_user,login_required,LoginManager,current_user
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'abc'
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
admin_state = 1
class users(db.Model,UserMixin):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(200),unique=False,nullable=False)
    password = db.Column(db.String(200),unique=False,nullable=False)

db.create_all()

class AdminHome(AdminIndexView):
    def is_accessible(self):
        if admin_state == 2:
            return current_user.is_authenticated
    def inaccessible_callback(self,name,**kwargs):
        return redirect('/')
admin = Admin(app,name='Control',index_view=AdminHome())
@login_manager.user_loader
def user_loader(user_id):
    return users.query.get(int(user_id))

@app.route('/a')
def home():
    admin_state = 2
    return 'asd'
@app.route('/')
def home1():
    return 'asdasd'
if __name__ == '__main__':
    app.run(debug=True)

I can’t understand why the admin page doesn’t allow it.

Is there any way to do it?

Thanks.

How to enable / disable button in Oracle APEX based on other button

I am searching for this every where no one is able to help me.

Only this is the one hope left for me

Below is my scenario and components I have used

*  1 file browse button - To select file 
*  2 buttons 
     first  button 1 is for validating 
     second button 2 is for submitting 

Below is my GUI designed in Oracle APEX

GUI

Note :

On page load my submit button is disabled initially – it cannot be clicked.
On that submit button I have written PL/SQL code in backend as dynamic action

So my aim is to achieve step 3

Step 1 : I will choose file using file browse button

Step 2 : After selecting my file I will click VALIDATE button.

Once I click on validate button my dynamic action will get trigger which is written in JavaScript.

This Java script checks the file choosen is empty or not and return true or false

Sample code :

  if ( file is empty ) 
  {
    return false     
  }
  else
  {
    return true
  }
 

Step 3 : Once my Validate return true my Submit button should get enabled
and After its enabled and once I click on submit button my PL/SQL code should run

I ask every one over YouTube no one as respond me

Html To Base64 Html Upload Base64 From App Script Google Sheets

Gyuz.

I’m attempting to develop html code that accepts inputs on the page but stores the data in a spreadsheet using an app script. Everything works great, however when I use the SELECT tag to collect input for the gender fields, the output does not appear on the spreadsheet. All other fields do, but this one does not.

To double-check the code, I inserted select tag comments.

Forms.html


<!DOCTYPE html>
<html>

<head>
    <base target="_blank">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Registration</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materia
lize.min.css">
    <style>
        body {
            color: #fff;
            background: #232526;
            background: -webkit-linear-gradient(to left, #414345, #232526);
            background: linear-gradient(to left, #414345, #232526);
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            -o-user-select: none;
            user-select: none;

        }

        .disclaimer {
            width: 480px;
            color: #646464;
            margin: 20px auto;
            padding: 0 16px;
            text-align: center;
            font: 400 12px Roboto, Helvetica, Arial, sansserif
        }

        .disclaimer a {
            color: #009688
        }

        #credit {
            display: none
        }
    </style>
</head>

<body>
    <form class="main" id="form" novalidate="novalidate" style="max-width: 480px;margin: 40px auto;">
        <div id="forminner">
            <div class="row">
                <div class="col s12">
                    <h5 class="center-align teal-text">Registration</h5>
                    <p class="disclaimer">Fill up all fields.</p>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s12">
                    <input id="name" type="text" name="Name" class="validate" required="" aria-required="true"
                        placeholder="Enter Your Name">
                    <label for="name" style="display: none;">Name</label>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s12">
                    <input id="email" type="email" name="Email" class="validate" required="" aria-required="true"
                        placeholder="Enter Your Email">
                    <label for="email" style="display: none;">Email Address</label>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s12">
                    <input id="tel" type="tel" name="Tel" class="validate" required="" aria-required="true"
                        placeholder="Enter Your Mobile Number">
                    <label for="tel" style="display: none;">Mobile Number</label>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s12">
                    <input id="gender" name="gender" type="text" class="validate" required="" aria-required="true"
                        placeholder="Enter Your Gender" maxlength="6">
                </div>
            </div>
            <div class="row">
                <div class="input-field col s12">
                    <input id="jd" name="jd" type="text" class="validate" required="" aria-required="true"
                        placeholder="Enter Your Intrested Field">
                </div>
            </div>

            <!-- Select Tag -->

            <div class="row">
                <div class="input-field col s12">
                    <select id="position" name="position" style="display: block;"> 
                        <option value="" disabled selected>Position</option>
                        <option value="Head">Head</option>
                        <option value="Assistant">Assistant</option>
                        <option value="Secretary">Secretary</option>
                        <option value="Others">Others</option>
                        </select>                        
                </div>
            </div>

            <div class="row">
                <div class="file-field input-field col s12">
                    <div class="btn">
                        <span>Resume</span>
                        <input id="files" type="file">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" placeholder="Upload Your Resume Here">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s6">
                    <button class="waves-effect waves-light btn submit-btn" type="submit"
                        onclick="submitForm(); return false;">Submit</button>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s12" id="progress">
                </div>
            </div>
        </div>
        <div id="success" style="display:none">
            <h5 class="left-align teal-text" style="color: #fff;">File Uploaded</h5>
            <p style="color: #fff;">Your file has been successfully uploaded.</p>
            <p class="center-align"><a class="btn btn-large" onclick="restartForm()">Restart</a></p>
        </div>
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materializ e.min.js"></script>
    <script>
        var file, reader = new FileReader();
        reader.onloadend = function (e) {
            if (e.target.error != null) {
                showError("File " + file.name + " could not be read.");
                return;
            } else {
                google.script.run
                    .withSuccessHandler(showSuccess)
                    .uploadFileToGoogleDrive(e.target.result, file.name, $('input#name').val(), $('input#email').val(), $('input#gender').val(), $('input#tel').val(), $('input#jd').val(), $('input#position').val());
            }
        };
        function showSuccess(e) {
            if (e === "OK") {
                $('#forminner').hide(); $('#success').show();
            } else {
                showError(e);
            }
        }
        function restartForm() {
            $('#form').trigger("reset"); $('#forminner').show(); $('#success').hide(); $('#progress').html("");
        }
        function submitForm() {
            var files = $('#files')[0].files;
            if (files.length === 0) {
                showError("Please select a file to upload");
                return;
            }
            file = files[0];
            if (file.size > 1024 * 1024 * 5) {
                showError("The file size should be < 5 MB. ");
                return;
            }
            showMessage("Uploading file ...");
            reader.readAsDataURL(file);
        }
        function showError(e) {
            $('#progress').addClass('red-text').html(e);
        }
        function showMessage(e) {
            $('#progress').removeClass('red-text').html(e);
        }
        $(document).ready(function () {
            $('select').material_select();
        });
    </script>
</body>

</html>

Code.gs

// 1. Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
// 2. Run > setup
//
// 3. Publish > Deploy as web app
// - enter Project Version name and click 'Save New Version'
// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
// 4. Copy the 'Current web app URL' and post this in your form/script action
//
// 5. Insert column names on your destination sheet matching the
//parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new
//property service
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('forms.html').setTitle("SIPP Registrations");
// return HtmlService.createHtmlOutputFromFile('forms.html').setFaviconUrl("");
}
function uploadFileToGoogleDrive(data, file, name, email, gender, tel, jd, position) {
try {
var dropbox = "Received Files";
//var folder, folders = DriveApp.getFoldersByName(dropbox);
var folder=DriveApp.getFolderById('1JkR_IgA0sQWj4mROqozAbvWpN6GrUdjP');
/*
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
*/
/* Credit: www.labnol.org/awesome */
var contentType = data.substring(5,data.indexOf(';')), bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)), blob = Utilities.newBlob(bytes, contentType, file),
file = folder.createFolder([name, email].join(" ")).createFile(blob),
filelink=file.getUrl() ;
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("15OLJTZm-M_nTuh15TKpbymJWbXhZY6xgjCnpn0NNFJQ"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with
//header_row in GET/POST data
var headRow = 1;
var headers = sheet.getRange(1, 1, 1,
sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a'Timestamp' column
row.push(new Date());
} else if (headers[i] == "name"){
row.push(name);
} else if (headers[i] == "email"){
row.push(email);
} else if (headers[i] == "gender"){
row.push(gender);
} else if (headers[i] == "tel"){
row.push(tel);
} else if (headers[i] == "jd"){
row.push(jd); 
} else if (headers[i] == "filelink"){
row.push(filelink);
} else if (headers[i] == "position"){
row.push(position);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
//return ContentService
// .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
// .setMimeType(ContentService.MimeType.JSON);
return "OK";
} catch (f) {
return f.toString();
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet(); SCRIPT_PROP.setProperty("15OLJTZm-M_nTuh15TKpbymJWbXhZY6xgjCnpn0NNFJQ", doc.getId());
}

Here is the code I used; everything works except the slecect tag; could you kindly assist me?

Here’s The Output See Position Field Is Blank No Input

Render HTML of embed-deployed Component

I want to integrate my react app to a 3rd party app which enables me to put a script that appends the elements into the html.

But it appears that it is not that straightforward in react. The script does not append the elements so my custom component does not appear on the page.

This is what I am trying to do ( but not a gist ):

function Snippet){
    
    return (
        <Wrapper>
            <h1> Snippet 1</h1>
            <script src="https://gist.github.com/xxxx/e4208e452e32e353b6076944c80a1058.js"></script>
        </Wrapper>
    )
}

Is there a way to do this with just react?

Why getBoundingClientRect returns null when pointing to a negative coordinate position in svg?

The trick part might be the viewBox="-50 0 150 100". But I really need to get the negative coordinates.

Please take a look at the demo below:

$('svg').click(function(e){
  const { farthestViewportElement: svgRoot } = e.target;
  const dim = svgRoot.getBoundingClientRect();
  const x = e.clientX - dim.left;
  const y = e.clientY - dim.top;
  $('#cord-track').val(`x: ${x}, y: ${y}`);
})
svg {border:1px dashed blue}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>When you click mouse in the red rect, it works perfectly</p>
<p>When you click mouse in the left blank zone, it throws an error, so that I can't trace my x and y values. How do I fix it?</p>
<svg width="100px" id="test" viewBox="-50 0 150 100">
<rect x="0" y="0" width="100" height="100" fill="red">
</svg>
<input id="cord-track" />

What is static site generation?

I know that static site generation idea, The question here is, if SSG gets fetched data at build time, in my next app I used an event handler to get some data according to the search keyword, and it works, How.

This is my code:
Below is the code for the Input component in the next weather app and I use handleSubmit event handler, It gets weather data from an API endpoint.

import React, { useState } from "react";
import PropTypes from "prop-types";
import axios from "axios";

function Input({ onInput }) {
  const [inputText, setInputText] = useState();
  const [placeholder, setPlaceholder] = useState("أخل اسم البلد أو المنطقة...");

  return (
    <form className="hstack gap-3" onSubmit={handleSubmit}>
      <input
        type="text"
        className="form-control me-auto"
        placeholder={placeholder}
        value={inputText || ""}
        onChange={handleInput}
        onFocus={handleFocus}
        onBlur={handleBlur}
      />
      <button type="submit">ابحث</button>

      <style jsx>{`
        input {
          height: 50px;
          border-radius: 10px;
          color: var(--input-color);
          font-weight: 500;
          font-size: 1.1em;
          direction: rtl;
        }
        input:focus-visible {
          color: var(--input-color);
          font-weight: 500;
          font-size: 1.1em;
        }
        input:focus {
          box-shadow: 0 0 0 0.25rem var(--input-shadow-color);
        }
        input::placeholder {
          color: var(--input-placeholder-color);
          font-weight: 500;
          opacity: 0.7;
        }
        button {
          padding: 0.60em 1.3em;
          background-color: var(--search-btn-background-color);
          color: #fff;
          font-weight: 500;
          border: 5px solid var(--search-btn-border-color);
          background-color: var(--search-btn-background-color);
          border-radius: 12px;
          transition: 0.5s;
        }
        button:hover {
          color: #fff;
          background-color: var(--btn-hover-color);
        }
        button:focus {
          box-shadow: 0 0 0 0.25rem var(--search-btn-shadow-color);
        }
      `}</style>
    </form>
  );

  function handleFocus() {
    setPlaceholder("");
  }

  function handleBlur() {
    setPlaceholder("أخل اسم البلد أو المنطقة...");
  }

  function handleInput(event) {
    setInputText(event.target.value);
  }

  function handleSubmit(event) {
    event.preventDefault();
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/weather?q=${inputText}&units=metric&appid=5a60c3e5c70d9f4ad304b2b115b3bf72&lang=ar`
      )
      .then((response) => {
        onInput(response.data);
      })
      .catch((error) => {
        console.log(error);
        onInput(0);
      });

    setInputText("");
  }
}

Input.propTypes = {
  onInput: PropTypes.func.isRequired,
};

export default Input;

Using async when two requests have to be made and response from the first is needed in the other request

I have a async function like this:

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()
  }

  try {

    const results = await axios.get(`https://a-domain.com/url/path`);
    const info = results.data;

    const docRef = await addDoc(collection(db, "name_of_collec"), info);
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }

  next();
};

Here, response from the first request is required in the second request. But according to my knowledge since I am making asynchronous requests, the two requests should be made at the same time.

What I cannot understand:

  • So, how it is possible that there is no error occurring?
  • How is it that, sometimes the no document is added to Firestore? Like it is skipped somehow…

Context info:

  • I am using Express.js and Node.js to make a backend
  • I am using axios to make the first request and the second one is adding a document to Firestore.
  • Firestore is a noSQL database inside Google’s Firebase.

Weather App using react always return null

I am trying to create a WeatherApp using React and OpenWeathermap API as beginner project. After fetching the data from the API, I am not able to return any component as it always returns null from the conditional statement.

import React, {useEffect, useState } from "react";


 export default function App(){

 const API_KEY = somekey; 

 const [lat, setLat] = useState([]);
 const [long, setLong] = useState([]);
 const [data, setData] = useState([]);

 useEffect(() => {
   const fetchData = async () => {

     navigator.geolocation.getCurrentPosition(function (position) {
       console.log(position.coords.latitude);
       setLat([position.coords.latitude]); //sets latitude
       setLong([position.coords.longitude]); //sets longitude
     });
     await fetch(
       `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&exclude=hourly,minutely&units=metric&appid=${API_KEY}`
     )
       .then((res) => res.json())
       .then((result) => {
         setData([result]);
         console.log(data);
       });
   };
   fetchData();
 }, [lat, long]);

  return (
    <div className="App">
      {(typeof data.main !== 'undefined') ? (
        <h1>{data.name}</h1>  //doesnt execute
      ) :null}
    </div>
  );
}

The project is based on this example:https://www.freecodecamp.org/news/learn-react-by-building-a-weather-app/

RSA encryption between Node js and Web

TDLR I’m working on a node js server that uses the Crypto module to create a public and private RSA key. I need to be able to export the public key so my React app can communicate with the node server. The problem is that react uses a different module. I’m able to encrypt the message from React but when it gets to the server it’s either a mess of bits or the server outputs a padding error.

I’ve been trying to get it to work but the node js server keeps telling me the padding is wrong. I tried different combinations of paddings but it still had the same error.

Ps, They communicate through a WebSocket channel.

Error:

function: 'RSA_padding_check_PKCS1_OAEP_mgf1',
  reason: 'oaep decoding error',
  code: 'ERR_OSSL_RSA_OAEP_DECODING_ERROR'

Node Server code

const { publicKey, privateKey } = generateKeyPairSync('rsa', {
                modulusLength: 4096,
                publicKeyEncoding: {
                    type: 'spki',
                    format: 'pem'
                },
                privateKeyEncoding: {
                    type: 'pkcs8',
                    format: 'pem',
                    cipher: 'aes-256-cbc',
                    passphrase: 'Bob'
                }
            })
            this.rsa = privateKey.toString('hex')
            this.rsap = publicKey.toString('hex')
...
var decryptodata = crypto.privateDecrypt({
            'key': this.rsa,
            passphrase: 'Bob',
            'padding': crypto.constants.RSA_PKCS1_OAEP_PADDING
        },
            Buffer.from(data, "base64")
        )
        return decryptodata.toString()

Subtle code

var publicKey =`HAS THE PUBLIC KEY AS A STRING`
const pemHeader = "-----BEGIN PUBLIC KEY-----";
const pemFooter = "------END PUBLIC KEY-----";
const kBase64Digits ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function atob(input) {
                            // The implementation here has not been performance optimized in any way and
                            // should not be.
                            // Refs: https://github.com/nodejs/node/pull/38433#issuecomment-828426932
                            input = `${input}`;
                            var result = ``
                            for (let n = 0; n < input.length; n++) {
                                if (kBase64Digits.includes(input[n])) result += input[n];
                                
                            }
                            return Buffer.from(result, 'base64').toString('latin1');
                        }
const pemContents = publicKey.substring(pemHeader.length, publicKey.length - pemFooter.length);
const binaryDerString = atob(pemContents);
const binaryDer = str2ab(binaryDerString);
this.publicKey = await window.crypto.subtle.importKey(
                            "spki",
                            binaryDer,
                            {
                                name: "RSA-OAEP",
                                hash: "SHA-256"
                            },
                            true,
                            ["encrypt"]
                        )


...

const enc = new TextEncoder()
var msg = await window.crypto.subtle.encrypt({
            name: "RSA-OAEP"
        }, this.publicKey, enc.encode(message)
        );
        function ab2str(buf) {
            return String.fromCharCode.apply(null, new Uint8Array(buf));
        }
        const encryptedBase64 = window.btoa(ab2str(msg));
        console.log(encryptedBase64.replace(/(.{64})/g, "$1n"));

Calling callback function inside for loop doesn’t work

I am trying to run a callback function inside a for loop, but I am finding issues in executing the callback function. Seems like the function gets executed after the for loop is completed. For example if for loop has 2 iteration, then the function is executed only after the two for loop iteration is executed. Hence the execution of function is always done after the last iteration of for for loop. I am trying it really hard and have spend almost a day today looking at examples and have finally have used the closures as per the example provided in example in below link but still not getting the accurate result.
https://www.geekabyte.io/2013/04/callback-functions-in-loops-in.html

Below is the code that I am using :

            let promoList = [];
            for(i = 0; i< availablePromoCount; i++){

              promoObj = {};
              promoObj.maxUsesUser = getAvailablePromoResults[i].MaxUsesUser //getAvailablePromoResults is a list coming from another function not shown here

              promoObj.promoCode = getAvailablePromoResults[i].PromoCode; // available promo code for this iteration

              promoList.push(promoObj);

              (function(clsn){
              
                  searchUserUsedPromo(userId, promoList[clsn].promoCode, (error, searchUserUsedPromoResults) => {
                    if (error) {
                      console.log(error);
                      return res.status(500).json({
                        success: 0,
                        message: "Some other error",
                        error: error,
                      });
                    }
                    cosnole.log("Iteration of function is ", clsn);  // always iteration is last iteration and displays same and last iteration of i
                    
                    console.log("Searched promo code is ", promoList[clsn].promoCode);
                    timesUsed = searchUserUsedPromoResults.length;
                    console.log("Times Used", timesUsed);
                    console.log("Max uses user", promoList[i].maxUsesUser);

                  });
              
              })(i)

              count++;
              if(getAvailablePromoResults.length == count){
              
                return res.status(200).json({
                  success: 1,
                  availablePromoList: availablePromoList,
                });

              }
            }