コード例 #1
0
    def actionClicked(self):
        self._userID = self.txtUserID.toPlainText()
        self._username = self.txtUsername.toPlainText()
        self._password = self.txtPassword.toPlainText()
        self._role = self.cbRole.currentIndex()

        if self._username != '' and self._password != '':
            if self._ACTION == "ADD":
                msg = self.msgBox()
                if dbUser.getUserByUsername(self._username) is None:
                    dbUser.newUser(self._username, self._password, self._role)
                    msg.setText(f"New user '{self._username}' Added!")
                    self.clearForm()
                else:
                    msg.setText(f"USER ALREADY EXIST!")
                    msg.setIcon(QMessageBox.Warning)
            else:
                dbUser.updateUser(self._userID, self._username, self._password,
                                  self._role)
                msg = self.msgBox()
                msg.setText(
                    f"Update successful!\nUser with userID={self._userID} ")
                self.clearForm()
            msg.exec_()
        else:
            msg = self.msgBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setText("Please fill up the form!")
            msg.exec_()
コード例 #2
0
 def allowed_actions(user: User) -> List[Action]:
     ret = []
     if user.has_role(Role.APP_ADMINISTRATOR):
         # King of the world
         ret.extend([
             Action.CREATE_PROJECT, Action.ADMINISTRATE_APP,
             Action.ADMINISTRATE_USERS
         ])
     else:
         if user.has_role(Role.PROJECT_CREATOR):
             ret.append(Action.CREATE_PROJECT)
         if user.has_role(Role.USERS_ADMINISTRATOR):
             ret.append(Action.ADMINISTRATE_USERS)
     return ret
コード例 #3
0
def Login():

    if not session.get('username'):

        if request.method == 'POST':

            error = None
            email = request.form['email']
            account = request.form['account']
            if len(email) < 5:
                abort(400, 'The email address is too short')
            elif len(account) < 1:
                abort(400, 'No account number specified')
            response = User(email).login(account)
            if response == 1:
                flash("Logged In")
                session['username'] = email
                login_user = System().getUser(session.get('username'))
                return redirect('/home')
            error = 'Invalid login credentials'
            return render_template('login.html', error=error)
        return render_template('login.html')
    system = System()
    login_user = system.getUser(session.get('username'))
    return render_template('home.html', login_user=login_user)
コード例 #4
0
def Pin():

    if session.get('username'):

        system = System()
        pins = system.pins()
        login_user = system.getUser(session.get('username'))
        error = None

        if request.method == "POST":

            email = session.get('username')
            response = User(email).createPins()

            if type(response) is int:

                error = 'Error ' + str(response)
                return render_template('pin.html',
                                       login_user=login_user,
                                       error=error,
                                       pins=pins)
            else:

                error = response
                return render_template('pin.html',
                                       login_user=login_user,
                                       error=error,
                                       pins=pins)
        return render_template('pin.html',
                               login_user=login_user,
                               error=error,
                               pins=pins)

    return redirect(url_for("Index"))
コード例 #5
0
ファイル: main.py プロジェクト: Rhcsky/Rhcsky
def register():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        data = User.query.filter_by(username=username, email=email).first()

        if data:
            msg = 'Account already exists!'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address!'
        elif not re.match(r'[A-Za-z0-9]+', username):
            msg = 'Username must contain only characters and numbers!'
        elif not username or not password or not email:
            msg = 'Please fill out the form!'
        else:
            # Account doesnt exists and the form data is valid, now insert new account into accounts table
            msg = 'You have successfully registered!'
            user = User(username, email, password)
            db.session.add(user)
            db.session.commit()
            return render_template('index.html', msg=msg)
    elif request.method == 'POST':
        msg = 'Please fill out the form!'

    return render_template('register.html', msg=msg)
コード例 #6
0
def createUser(login_session):
    newUser = User(name=login_session['username'],
                   email=login_session['email'],
                   picture=login_session['picture'])
    session.add(newUser)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).first()
    return user.id
コード例 #7
0
ファイル: api.py プロジェクト: Pinsonbavard/myproject
def Register():

    error = None

    if not session.get('username'):

        if request.method == 'POST':

            firstname = request.form['firstname']
            lastname = request.form['lastname']
            email = request.form['email']
            number = request.form['number']

            if len(email) < 5:
                error = 'The email is invalid'
            elif len(firstname) < 1:
                error = 'The firstname cannot be empty'
            elif len(lastname) < 1:
                error = 'The lastname cannot be empty'
            else:
                db.session.commit(
                )  ###### commit to the database to refresh it
                system = System()
                account = system.account()

                response = User(email).register(firstname, lastname, email,
                                                account, number)
                if response == 1:
                    error = 'No record inserted, the email (' + email + ') already exist'

                else:

                    session['username'] = email
                    msg = Message(
                        "Registration successfull, your registration details ",
                        sender=app.config["DEFAULT_MAIL_SENDER"],
                        recipients=[email])
                    msg.html = render_template("reg-email.html",
                                               firstname=firstname,
                                               lastname=lastname,
                                               account=account,
                                               email=email)
                    thr = Thread(target=send_async_email_test, args=[app, msg])
                    thr.start()
                    flash("Logged In")
                    db.session.commit(
                    )  ####### commit to the database to refresh it
                    login_user = system.getUser(session.get('username'))
                    return redirect(url_for('Home'))
        return render_template('register.html', error=error)
    db.session.rollback(
    )  ################ commit to the database to refresh it
    system = System()
    login_user = system.getUser(session.get('username'))
    return redirect('/home')
コード例 #8
0
def delete_user(current_user, public_id):
    if not current_user.admin:
        return jsonify({'data': "You don't have permission for this action."})
    query = User.select().where(User.public_id == public_id).first()
    if not query:
        return jsonify({'data': 'No user found.'}), 404
    try:
        query.delete_instance()
    except Exception as e:
        return jsonify({'data': str(e)}), 401
    return jsonify({'data': 'The user has been successfully deleted!'}), 200
コード例 #9
0
def test_to_str():
    """ Just to ensure there is no type in __str__ methods """
    assert str(Acquisition()) is not None
    assert str(Process()) is not None
    assert str(Project()) is not None
    assert str(Sample()) is not None
    assert str(Task()) is not None
    assert str(Taxonomy()) is not None
    assert str(User()) is not None
    assert str(Role()) is not None
    assert str(ProjectPrivilege()) is not None
    assert str(ParticleProject()) is not None
コード例 #10
0
ファイル: api.py プロジェクト: Pinsonbavard/myproject
def user_create():

    if 'username' in session:
        system = System()
        login_user = system.getUser(session.get('username'))
        error = None

        if request.method == 'POST':

            firstname = request.form['firstname']
            lastname = request.form['lastname']
            email_cust = request.form['email_cust'] or None
            origin = request.form['number']

            if len(firstname) < 1:
                abort(400, 'Enter firstname')
            elif len(lastname) < 1:
                abort(400, 'Enter lastname')
            elif len(origin) < 1:
                abort(400, 'Enter phone number')

            email = session.get('username')
            response = User(email).createCustomer(firstname, lastname,
                                                  email_cust, origin)
            if response == 0:

                error = firstname + ' ' + lastname + ' is added Successfully'
                flash("Customer added Successfully")
                if email_cust is not None:

                    msg = Message(
                        "Registration successfull, your registration details ",
                        sender=app.config["DEFAULT_MAIL_SENDER"],
                        recipients=[email_cust])
                    msg.html = render_template("reg-email.html",
                                               firstname=firstname,
                                               lastname=lastname,
                                               email=email_cust)
                    thr = Thread(target=send_async_email_test, args=[app, msg])
                    thr.start()
                return render_template('user-create.html',
                                       login_user=login_user,
                                       error=error)

            if response == 1:

                error = origin + ' already exist, so no record created'
                return render_template('user-create.html',
                                       login_user=login_user,
                                       error=error)

        return render_template('user-create.html', login_user=login_user)
    return redirect('/')
コード例 #11
0
def destination_new(user_id):

    if session.get('username'):

        system = System()
        dids = system.available_dids()
        owns = system.owns()
        login_user = system.getUser(session.get('username'))
        user = system.getUserById(user_id)
        error = None
        if not user:
            return redirect('/customers')

        if request.method == 'POST':

            did = request.form['did']
            own = request.form['own']
            record = request.form['record']
            auth_gw = request.form['auth_gw']
            auth_did = request.form['auth_did']
            gateway = request.form['gateway']
            channel = request.form['channel']
            number = request.form['number']
            day = request.form['day']
            month = request.form['month']
            year = request.form['year']
            string_date = year + '-' + month + '-' + day + ' 12:00:00'
            end_date = datetime.datetime.strptime(string_date,
                                                  "%Y-%m-%d %H:%M:%S")
            email = session.get('username')
            response = User(email).destination_new(user_id, did, number,
                                                   record, auth_did, auth_gw,
                                                   gateway, channel, own,
                                                   end_date)
            if response == 0:

                error = "Destination created for origin "
            if response == 1:
                error = " Destination number already exist with origin "
            return render_template('destination-new.html',
                                   login_user=login_user,
                                   user=user,
                                   error=error,
                                   dids=dids,
                                   owns=owns)
        return render_template('destination-new.html',
                               login_user=login_user,
                               user=user,
                               error=error,
                               dids=dids,
                               owns=owns)

    return redirect('/')
コード例 #12
0
ファイル: Auth.py プロジェクト: arzh/CS253
	def post(self):
		self.resetErrors()
		rawName = self.request.get("username")
		if rawName and User.get_by(property_name = "name", value = rawName):
			self.userData.set_false()
			self.userData.errorMsg = "Username already taken"
		else:
			self.userData.is_valid(rawName)
		
		#logging.info("username is: %s", self.userError)

		rawPassword = self.request.get("password")
		rawVerify = self.request.get("verify")
		passwordsMatch = rawPassword == rawVerify

		if rawPassword and passwordsMatch:
			self.passData.is_valid(rawPassword)
		else:
			self.passData.set_false()
			self.passData.errorMsg = "Passwords do not match"

		#logging.info("password is: %s", self.passwordError)

		rawEmail = self.request.get("email")
		if rawEmail:
			self.emailData.is_valid(rawEmail)

		#logging.info("email is: %s", self.emailError)

		if not self.userData.isValid or not self.passData.isValid or not self.emailData.isValid:
			#logging.info("somethings gone wrong! userData:"+str(self.userData.isValid)+" passData: "+str(self.passData.isValid)+" emailData: "+str(self.emailData.isValid))
			self.renderSignup()
		else:
			#logging.info("it worked!")
			newUser = User.generate_new(rawName, rawPassword, rawEmail)
			newUser.put()
			self.login(newUser)
			self.redirect("/")
コード例 #13
0
ファイル: Auth.py プロジェクト: arzh/CS253
	def post(self):
		self.reset()

		name = self.request.get("username")
		u = User.get_by("name", name)
		if not u:
			self.userData.set_false()
		else:
			pw = self.request.get("password")	
			if not u.check_password(pw):
				self.passData.set_false()

		if not self.userData.isValid or not self.passData.isValid:
			self.renderPage()
		else:
			self.login(u)
			self.redirect("/")
コード例 #14
0
    def Login(self):
        import connector
        import DB.User as dbUser

        self.txtUsername.setStyleSheet(
            "#txtUsername{background-color:rgba(255,255,255,.8);}")
        self.txtPassword.setStyleSheet(
            "#txtPassword{background-color:rgba(255,255,255,.8);}")
        username = self.txtUsername.toPlainText()
        password = self.txtPassword.toPlainText()
        if username == '':
            self.txtUsername.setPlaceholderText('PLEASE ENTER A USERNAME')
            self.txtUsername.setStyleSheet(
                "#txtUsername{background-color:rgba(255,112,80,.7);}")
            self.txtUsername.setFocus()
        elif password == '':
            self.txtPassword.setPlaceholderText('PLEASE ENTER A PASSWORD')
            self.txtPassword.setStyleSheet(
                "#txtPassword{background-color:rgba(255,112,80,.7);}")
            self.txtUsername.setFocus()
        else:
            exist = dbUser.checkExistingUser(username, password)
            if not exist:
                msg = QMessageBox()
                msg.setWindowTitle("Sanction Management System - Login Failed")
                msg.setText(
                    "INVALID CREDENTIALS!\nPlease Enter correct Username and Password!"
                )
                msg.setIcon(QMessageBox.Warning)
                msg.setStandardButtons(QMessageBox.Ok)
                msg.setDefaultButton(QMessageBox.Ok)
                msg.exec_()
                self.clearPassword()
            else:
                _userID = exist[0]
                _userRole = exist[3]
                if (_userRole == 0):

                    self.frmADMIN = QtWidgets.QMainWindow()
                    self.admin = Ui_wndwAdmin(self.wndwLogin, _userID)
                    self.admin.setupUi(self.frmADMIN)
                    self.frmADMIN.show()
                    self.wndwLogin.hide()

                    self.clearPassword()
コード例 #15
0
ファイル: api.py プロジェクト: Pinsonbavard/myproject
def countries():
    if 'username' in session:

        system = System()
        countries = system.countries()
        login_user = system.getUser(session.get('username'))
        error = None
        if request.method == 'POST':

            country = request.form['country']
            region = request.form['region']

            if len(country) < 1:
                abort(400, 'No country entered')
            elif len(region) < 1:
                abort(400, 'No region selected')

            email = session.get('username')
            response = User(email).createCountry(region, country)
            if response == 0:
                error = country + ' added to region ' + region + ', refresh browser to see update'
                flash("Country added Successfully")
                countries = system.countries()
                return render_template('country.html',
                                       login_user=login_user,
                                       error=error,
                                       countries=countries)
            if response == 506:

                abort(
                    400,
                    'No data insertion was made, please check Internet connectivity'
                )
            if response == 1:
                error = country + ' already exist'
                return render_template('country.html',
                                       login_user=login_user,
                                       error=error,
                                       countries=countries)
        return render_template('country.html',
                               login_user=login_user,
                               error=error,
                               countries=countries)

    return redirect(url_for("Index"))
コード例 #16
0
    def decorated(*args, **kwargs):

        token = request.cookies.get('auth', default='', type=str)
        if not token:
            # return jsonify({'data': 'The auth token is missing.'}), 401
            return redirect('/'), 302
        try:
            tokenDecoded = jwt.decode(token,
                                      Settings.secret_key,
                                      algorithms='HS256')
        except jwt.exceptions.ExpiredSignatureError:
            # return jsonify({'data': 'The auth token has expired.'}), 401
            return redirect('/'), 302
        except:
            # return jsonify({'data': "The auth token is invalid"}), 401
            return redirect('/'), 302
        current_user = User.select().where(
            User.public_id == tokenDecoded['public_id']).first()
        return func(current_user, *args, **kwargs)
コード例 #17
0
ファイル: api.py プロジェクト: Pinsonbavard/myproject
def Login():

    if not 'username' in session:

        #db.session.commit() ####### commit to the database to refresh it

        if request.method == 'POST':

            error = None
            email = request.form['email']
            account = request.form['account']
            if len(email) < 5:
                abort(400, 'The email address is too short')
            elif len(account) < 1:
                abort(400, 'No account number specified')
            response = User(email).login(account)
            if response == 1:
                session['username'] = email
                db.session.commit(
                )  ####### commit to the database to refresh it
                system = System()
                username = session.get('username')
                login_user = system.getUser(username)
                session.permanent = True

                return redirect('/home')
            elif response == 2:
                error = 'Database server is sleeping... Please try again to wake it up'
            elif response == 0:
                error = 'Invalid login credentials'
            else:
                abort(
                    400,
                    'Something unusual happened, please check Internet connectivity'
                )
            return render_template('login.html', error=error)
        return render_template('login.html')
    db.session.commit()  ####### commit to the database to refresh it
    system = System()
    username = session.get('username')
    login_user = system.getUser(username)
    return redirect('/home')
コード例 #18
0
ファイル: Rights.py プロジェクト: ecotaxa/ecotaxa_back
 def highest_right_on(user: User, prj_id: int) -> str:
     """
         Return the highest right for this user onto this project.
     """
     # Check
     if user.has_role(Role.APP_ADMINISTRATOR):
         # King of the world
         return ProjectPrivilegeBO.MANAGE
     else:
         a_priv: ProjectPrivilege
         # Collect privileges for user on project
         rights_on_proj = {
             a_priv.privilege
             for a_priv in user.privs_on_projects if a_priv.projid == prj_id
         }
         if ProjectPrivilegeBO.MANAGE in rights_on_proj:
             return ProjectPrivilegeBO.MANAGE
         elif ProjectPrivilegeBO.ANNOTATE in rights_on_proj:
             return ProjectPrivilegeBO.ANNOTATE
         elif ProjectPrivilegeBO.VIEW in rights_on_proj:
             return ProjectPrivilegeBO.VIEW
     return ""
コード例 #19
0
def Did():

    if session.get('username'):

        system = System()
        login_user = system.getUser(session.get('username'))
        pins = system.pins()
        countries = system.countries()
        dids = system.dids()
        error = None

        if request.method == 'POST':

            file = request.files['did_file']

            if not file:

                phone = request.form['phone']
                cost = request.form['cost']
                country = request.form['country']
                capacity = request.form['capacity']
                provider = request.form['provider']
                mode = request.form['mode']
                pin = request.form['pin']

                if len(phone) < 1:

                    abort(400, 'The phone number is invalid')
                elif len(cost) < 1:
                    abort(400, 'Invalid cost specified')
                elif len(country) < 1:
                    abort(400, 'Invalid country code')
                elif len(capacity) < 1:
                    abort(400, 'Please select capacity')
                elif len(provider) < 1:
                    abort(400, 'Please select provider')
                elif len(mode) < 1:
                    abort(400, 'Please select mode')
                elif len(pin) < 1:
                    abort(400, 'Please select pin')

                email = session.get('username')
                response = User(email).createDid(phone, provider, cost,
                                                 country, capacity, mode, pin)

                if response == 0:

                    flash('DID Successfully created')
                    error = 'DID Successfully created with pin ' + pin
                    return render_template('did.html',
                                           login_user=login_user,
                                           error=error,
                                           dids=dids,
                                           pins=pins,
                                           countries=countries)

                elif response == 1:

                    abort(400, 'DID %s already exist' % (phone))
                else:
                    abort(400, 'DID is not created')

            if System().allowed_file(file.filename):

                filename = secure_filename(file.filename)

                try:

                    file.save(
                        os.path.join(app.config['UPLOAD_FOLDER'], filename))
                    fileUrl = os.path.abspath(app.config['UPLOAD_FOLDER'] +
                                              filename)
                    #fileUrl = path(app.config['UPLOAD_FOLDER']+filename).abspath()

                    error = 'File uploaded : Path -> ' + fileUrl
                    data_list_dids = System().readCSV(fileUrl)
                    insert_dids = System().insertDids(data_list_dids)

                    error = str(
                        insert_dids) + ' DIDs has been uploaded and saved'

                except:

                    error = 'File not uploaded Successfully'

            else:

                error = 'File format is not allowed'

            return render_template('did.html',
                                   login_user=login_user,
                                   error=error,
                                   did_file=file,
                                   dids=dids,
                                   pins=pins,
                                   countries=countries)

        return render_template('did.html',
                               login_user=login_user,
                               error=error,
                               pins=pins,
                               dids=dids,
                               countries=countries)

    return redirect(url_for("Index"))
コード例 #20
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from DB import Theater, Base, MovieName, User

# connect with DB

engine = create_engine('postgresql://*****:*****@localhost/catalog')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

# Create User
user1 = User(name="admin", email="*****@*****.**")
session.add(user1)
session.commit()
# create random theater number 1
theater1 = Theater(name="Test Theater", user_id="1")
session.add(theater1)
session.commit()

# Create movie names for funny theater
movieName1 = MovieName(
    name="Free State of Jones",
    description="A disillusioned Confederate army deserter returns to "
    " Mississippi and leads a militia of fellow deserters "
    " and women in an uprising "
    "against the corrupt local Confederate government.",
    price="10",
    theater=theater1,
    user_id="1")
session.add(movieName1)
コード例 #21
0
import sys
from DB import db, User
from Security import password

if 'y' != input('Tämä tuohoaa tietokannan, oletko varma? [y/n]'):
    sys.exit()


db.drop_all()
db.create_all()

u = User()
u.username = '******'
u.password_hash = password.hash('swat')
u.email = '*****@*****.**'
u.admin = True

db.session.add(u)
db.session.commit()
コード例 #22
0
ファイル: Base.py プロジェクト: arzh/CS253
	def cached_user(self):
		uid = self.get_cookie('user_id')
		if uid:
			return User.get_by_id(int(uid))
		else:
			return None
コード例 #23
0
from DB import Bill, User, db
from Security.password import hash

from datetime import datetime, timedelta

for i in range(100):
    bill = Bill(submitter="Loers The {}".format(i),
                description="Kaljaa {}".format(i),
                iban="DE79850503003100180568",
                date=datetime.now() + timedelta(days=-i),
                receipts=[])
    db.session.add(bill)

uns = ['Rahis', 'Puhis', 'IE', 'Äbäj']

for un in uns:
    user = User(username=un, password_hash=hash(un), admin=False)

db.session.commit()
コード例 #24
0
ファイル: Project.py プロジェクト: ecotaxa/ecotaxa_back
    def projects_for_user(session: Session, user: User,
                          for_managing: bool = False,
                          not_granted: bool = False,
                          title_filter: str = '',
                          instrument_filter: str = '',
                          filter_subset: bool = False) -> List[ProjectIDT]:
        """
        :param session:
        :param user: The user for which the list is needed.
        :param for_managing: If set, list the projects that the user can manage.
        :param not_granted: If set, list (only) the projects on which given user has no right, so user can
                                request access to them.
        :param title_filter: If set, filter out the projects with title not matching the required string,
                                or if set to a number, filter out the projects of which ID does not match.
        :param instrument_filter: If set, filter out the projects which do not have given instrument in at least
                                     one sample.
        :param filter_subset: If set, filter out any project of which title contains 'subset'.
        :return: The project IDs
        """
        sql_params: Dict[str, Any] = {"user_id": user.id}

        # Default query: all projects, eventually with first manager information
        # noinspection SqlResolve
        sql = """SELECT p.projid
                       FROM projects p
                       LEFT JOIN ( """ + ProjectPrivilegeBO.first_manager_by_project() + """ ) fpm 
                         ON fpm.projid = p.projid """
        if not_granted:
            # Add the projects for which no entry is found in ProjectPrivilege
            sql += """
                       LEFT JOIN projectspriv pp ON p.projid = pp.projid AND pp.member = :user_id
                      WHERE pp.member is null """
            if for_managing:
                sql += " AND False "
        else:
            if not user.has_role(Role.APP_ADMINISTRATOR):
                # Not an admin, so restrict to projects which current user can work on, or view
                sql += """
                            JOIN projectspriv pp 
                              ON p.projid = pp.projid 
                             AND pp.member = :user_id """
                if for_managing:
                    sql += """
                             AND pp.privilege = '%s' """ % ProjectPrivilegeBO.MANAGE
            sql += " WHERE 1 = 1 "

        if title_filter != '':
            sql += """ 
                        AND ( title ILIKE '%%'|| :title ||'%%'
                              OR TO_CHAR(p.projid,'999999') LIKE '%%'|| :title ) """
            sql_params["title"] = title_filter

        if instrument_filter != '':
            sql += """
                         AND p.projid IN (SELECT DISTINCT sam.projid FROM samples sam, acquisitions acq
                                           WHERE acq.acq_sample_id = sam.sampleid
                                             AND acq.instrument ILIKE '%%'|| :instrum ||'%%' ) """
            sql_params["instrum"] = instrument_filter

        if filter_subset:
            sql += """
                         AND NOT title ILIKE '%%subset%%'  """

        with CodeTimer("Projects query:", logger):
            res: Result = session.execute(text(sql), sql_params)
            # single-element tuple :( DBAPI
            ret = [an_id for an_id, in res.fetchall()]
        return ret  # type:ignore
コード例 #25
0
ファイル: api.py プロジェクト: Pinsonbavard/myproject
def Own():

    if 'username' in session:

        db.session.commit()  ###### commit to the database
        system = System()
        login_user = system.getUser(session.get('username'))
        dids = system.dids()
        owns = system.owns()
        error = None

        if request.method == 'POST':

            file = request.files['own_file']

            if not file:

                sim = request.form['sim']
                did = request.form['did']

                if len(sim) < 1:
                    abort(400, 'Please enter a SIM number')
                elif len(did) < 1:
                    abort(400, 'Please select a did')

                email = session.get('username')
                response = User(email).createSim(sim, did)
                if response == 0:
                    flash('OWN Successfully created')
                    error = 'OWN Successfully created with did ' + did
                    owns = system.owns()
                    return redirect('/own')

                elif response == 1:
                    abort(400, 'OWN %s already exist with SIM ' % (sim))

                elif response == 506:
                    abort(400, 'Error:' + response + ', Data insertion error')

            if System().allowed_file(file.filename):

                filename = secure_filename(file.filename)

                try:

                    file.save(
                        os.path.join(app.config['UPLOAD_FOLDER'], filename))
                    fileUrl = os.path.abspath(app.config['UPLOAD_FOLDER'] +
                                              filename)
                    #fileUrl = path(app.config['UPLOAD_FOLDER']+filename).abspath()

                    error = 'File uploaded : Path -> ' + fileUrl
                    data_list_owns = system.readCSV(fileUrl)
                    insert_owns = system.insertOwns(data_list_owns)

                    error = error = str(
                        insert_owns['insertnum']
                    ) + ' Owns has been uploaded in total of ' + str(
                        insert_owns['total'])
                    #error =  data_list_owns

                except:

                    error = 'File not uploaded Successfully'

            else:

                error = 'File format is not allowed'
            owns = system.owns()
            return render_template('own.html',
                                   login_user=login_user,
                                   error=error,
                                   own_file=file,
                                   owns=owns)

        db.session.commit()  ###### commit to the database
        dids = system.dids()
        owns = system.owns()
        return render_template('own.html',
                               login_user=login_user,
                               error=error,
                               dids=dids,
                               owns=owns)

    return redirect(url_for("Index"))
コード例 #26
0
from DB import User, Blog
from Module0 import app
from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'

db = SQLAlchemy(app=app)

currentUser = User(name='Anh',
                   email='*****@*****.**',
                   phoneNumber='123456789',
                   employment='CEO')
db.session.add(currentUser)
コード例 #27
0
ファイル: api.py プロジェクト: Pinsonbavard/myproject
def Did():

    if 'username' in session:

        db.session.commit()  ###### commit to the database
        system = System()
        login_user = system.getUser(session.get('username'))
        pins = system.available_pins()
        countries = system.countries()
        dids = system.dids()
        count_available_dids = system.count_available_dids()

        error = None

        if request.method == 'POST':

            file = request.files['did_file']

            if not file:

                phone = request.form['phone']
                cost = request.form['cost']
                country = request.form['country']
                capacity = request.form['capacity']
                provider = request.form['provider']
                mode = request.form['mode']
                pin = request.form['pin']

                if len(phone) < 1:

                    abort(400, 'The phone number is invalid')
                elif len(cost) < 1:
                    abort(400, 'Invalid cost specified')
                elif len(country) < 1:
                    abort(400, 'Invalid country code')
                elif len(capacity) < 1:
                    abort(400, 'Please select capacity')
                elif len(provider) < 1:
                    abort(400, 'Please select provider')
                elif len(mode) < 1:
                    abort(400, 'Please select mode')
                elif mode == 'PIN-DIALING' and len(pin) < 1:
                    abort(400, 'Please select pin')
                elif mode == 'DIRECT-DIALING':
                    pin = None

                email = session.get('username')
                response = User(email).createDid(phone, provider, cost,
                                                 country, capacity, mode, pin)

                if response == 0:

                    flash('DID Successfully created')
                    dids = system.dids()
                    pins = system.available_pins()
                    error = 'DID Successfully created  ' + phone
                    #return render_template('did.html', login_user=login_user, error=error, dids=dids, pins=pins, countries=countries)
                    return redirect('/did')
                elif response == 1:

                    abort(400, 'DID %s already exist' % (phone))

                elif response == 506:

                    abort(
                        400,
                        'A technical error occured, this has to do with the application program the mode for the pin in the (PIN) table'
                    )

                else:
                    abort(400, 'DID is not created')

            if System().allowed_file(file.filename):

                filename = secure_filename(file.filename)

                try:

                    file.save(
                        os.path.join(app.config['UPLOAD_FOLDER'], filename))
                    fileUrl = os.path.abspath(app.config['UPLOAD_FOLDER'] +
                                              filename)
                    #fileUrl = path(app.config['UPLOAD_FOLDER']+filename).abspath()

                    error = 'File uploaded : Path -> ' + fileUrl
                    data_list_dids = System().readCSV(fileUrl)
                    insert_dids = System().insertDids(data_list_dids)

                    error = str(
                        insert_dids['insertnum']
                    ) + ' DIDs has been uploaded in total of ' + str(
                        insert_dids['total'])

                except:

                    error = 'File not uploaded Successfully'

            else:

                error = 'File format is not allowed'
            ###### After the browsers refresh when uploading from a file
            dids = system.dids()
            pins = system.available_pins()
            count_available_dids = system.count_available_dids()
            return render_template('did.html',
                                   login_user=login_user,
                                   countdids=count_available_dids,
                                   error=error,
                                   did_file=file,
                                   dids=dids,
                                   pins=pins,
                                   countries=countries)
        ###### When the browser is using other method apart from GET
        db.session.rollback()
        dids = system.dids()
        pins = system.available_pins()
        count_available_dids = system.count_available_dids()
        return render_template('did.html',
                               login_user=login_user,
                               countdids=count_available_dids,
                               error=error,
                               pins=pins,
                               dids=dids,
                               countries=countries)

    return redirect(url_for("Index"))