Exemplo n.º 1
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        access = 1
        if form.admin.data == True:  # given more access
            access = 2
        user = User(email=form.email.data,
                    name=form.name.data,
                    password=form.password.data,
                    access=access)
        db.session.add(user)
        db.session.commit()

        token = user.generateToken()
        subject = 'Please confirm your email'
        confirmURL = url_for('auth.confirm', token=token, _external=True)
        html = render_template('email/confirm.html',
                               user=user,
                               token=token,
                               confirmURL=confirmURL)
        sendEmail(user.email, subject, html)

        login_user(user)
        flash('A confirmation email has been sent to you by email.')
        return redirect(url_for('index'))
    return render_template('register.html', registrationForm=form)
Exemplo n.º 2
0
def users():
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("SELECT * FROM tbl_user")
        rows = cursor.fetchall()
        table = User(rows)
        table.border = True
        return render_template('users.html', table=table)
    except Exception as e:
        print(e)
    finally:
        cursor.close()
        conn.close()
Exemplo n.º 3
0
    def register(self):

        u = by_email(self.email)

        #si el usuario ya existe
        if u:
            self.response.out.write("User Already Exists")
        else:
            user = User(email=self.email,
                        hash_pw=hash_str(self.pass_up),
                        link_generated=self.confirmation_link)

            user.put()#guarda en la base de datos el usuario creado
            self.response.out.write("A confirmation email was sent to your account")
Exemplo n.º 4
0
def newUser():
    username = request.json.get('username')
    password = request.json.get('password')
    #checking validity of entered username
    if username is None or password is None:
        return "Username or password is Null"  # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        return "Username exists"
    user = User(username=username)
    user.hashPassword(password)
    #making changes in the Database
    db.session.add(user)
    db.session.commit()
    return "User Added Successfully"
Exemplo n.º 5
0
def signup():
    if not request.json:
        abort(400)
    email = request.json["email"]
    # check if account already exist
    from database import db_session
    from tables import User, Space
    alreadyUser = User.query.filter(User.email == email).first()
    if (alreadyUser != None):
        return jsonify({'id': '-1'})
    # Hash + salt password before storing it
    hashedPwd = bcrypt.generate_password_hash(request.json["password"])
    new_user = User(email=request.json["email"],
                    password=hashedPwd,
                    name=request.json["name"],
                    stringSpaces=",")
    db_session.add(new_user)
    db_session.commit()
    db_session.refresh(new_user)
    return jsonify({
        'id': (int)(new_user.id),
        'email': new_user.email,
        'name': new_user.name,
        'spaces': [],
        'token': encode_auth_token(new_user.id)
    })
Exemplo n.º 6
0
def register():
    # logout the user
    logout_user()

    form = RegisterForm()
    if form.validate_on_submit():

        # check if the email already exist
        if User.query.filter_by(email=form.email.data).first():
            flash("You've already signed up with that email, log in instead!")
            return redirect(url_for("login"))

        # make a new user
        new_user = User(
            email=form.email.data,
            password=generate_password_hash(form.password.data, method="pbkdf2:sha256", salt_length=8),
            name=form.name.data
        )
        db.session.add(new_user)
        db.session.commit()
        send_email(form.email.data, "Welcome to arsaiz.com!", f"Hello {form.name.data}!\nCheck my chat app at www.arsaiz.com/chat")

        # login the user immediately
        login_user(new_user)
        return redirect(url_for("get_all_posts"))

    return render_template("register.html", form=form, logged_in=current_user.is_authenticated, title="Register Arsa Izdihar Islam's Blog")
Exemplo n.º 7
0
 def add(self, name, lastname, patronymic, login, password, group):
     if isinstance(group, str) or isinstance(group, unicode):
         group = Manage.session.query(Group).filter(
             Group.name == group).first().id
     Manage.session.add(
         User(name, lastname, patronymic, login, password, group))
     self.commit()
Exemplo n.º 8
0
def ins_users(users, lname):
    league = session.query(League).filter_by(name=lname).first()
    for user in users:
        dname = user[0]
        tz = user[1]
        is_coach = user[2]
        is_admin = user[3]
        usr = User(username=user[0], timezone=user[1], league_id=league.id)
        session.add(usr)
        if user[2]:  # If is coach
            coach = Coach(discord_username=user[0], showdown_username=user[5])
            team = Team(league_id=league.id,
                        coach_username=user[0],
                        name=user[4])
            session.add(coach)
            session.add(team)
        if user[3]:  # If is admin
            admin = Administrator(username=user[0])
            session.add(admin)
        try:
            session.commit()
        except:
            session.rollback()
            return False
    return True
Exemplo n.º 9
0
 def post(self, name):  #Create user
     if not request.authorization:
         return "No credentials sent", BAD_REQUEST
     name = request.authorization.username
     password = request.authorization.password
     if not self._valid_password(password):
         return "Password needs to be longer than 5 characters", BAD_REQUEST
     if not self._valid_username(name):
         return "Username invalid", BAD_REQUEST
     if session.query(exists().where(User.username == name)).scalar():
         return "Username %s in use" % name, CONFLICT
     u = User(username=name)
     u.hash_password(password)
     session.add(u)
     session.commit()
     return self.get(name)
Exemplo n.º 10
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']).one()
    return user.id
Exemplo n.º 11
0
def registration():
    if session.get("user_id"):
        return redirect("/")
    form = RegistrationForm()
    if request.method == "POST":
        user = User()
        user.mail = form.mail.data
        user.password_hash = form.password.data
        user_ = User.query.filter_by(mail=user.mail).first()
        if user_:
            form.mail.errors.append(
                "Пользователь под такой почтой уже зарегистрирован")
        db.session.add(user)
        db.session.commit()
        return render_template("registration_success.html",
                               form=form,
                               mail=user.mail)
    return render_template("registration.html", form=form)
Exemplo n.º 12
0
def create(root, session):
    result = Element('result')

    for child in root:
        if child.tag == 'account':
            id = int(child.get('id'))
            balance = float(child.get('balance'))

            # search data base to see if there is this account, create or skip
            if session.query(User).filter_by(userid=id).first():
                # already exist, <error>
                # # print('acc already exist')
                error = SubElement(result, 'error', {'id': str(id)})
                error.text = 'This account already exist.'

            else:
                # print('creating acc')
                new_user = User(id, balance)
                session.add(new_user)
                session.commit()
                created = SubElement(result, 'created', {'id': str(id)})

        #add

        elif child.tag == 'symbol':
            sym = child.get('sym')
            for account in child.findall('account'):
                acc_id = int(account.get('id'))
                # print('account id is', acc_id)
                share = int(account.text)

                # if sym exist, add
                # else create

                position = session.query(Position).filter_by(
                    userid=acc_id, symbol=sym).first()
                if position is None:
                    # print('create position')
                    new_pos = Position(acc_id, sym, share)
                    session.add(new_pos)
                    session.commit()
                else:
                    # print('update position')
                    position.share += share
                    session.commit()
                created = SubElement(result, 'created', {
                    'sym': str(sym),
                    'id': str(acc_id)
                })

        else:
            error = SubElement(result, 'error')
            error.text = 'Invalid tag.'
    # print(result)
    res = str(et.tostring(result, encoding='utf8', method='xml'), 'utf-8')
    return str(len(res)) + '\r\n' + res
Exemplo n.º 13
0
 def Migrate(self):
     logging.debug("Migrate started")
     User().migrate(self.engine)
     Test().migrate(self.engine)
     Answer().migrate(self.engine)
     Question().migrate(self.engine)
     QuestionAnswer().migrate(self.engine)
     Trial().migrate(self.engine)
     TrialQuestion().migrate(self.engine)
     BlacklistToken().migrate(self.engine)
Exemplo n.º 14
0
 def Create(self):
     logging.debug("Create started")
     User().create(self.engine, self.meta)
     Test().create(self.engine, self.meta)
     Answer().create(self.engine, self.meta)
     Question().create(self.engine, self.meta)
     QuestionAnswer().create(self.engine, self.meta)
     Trial().create(self.engine, self.meta)
     TrialQuestion().create(self.engine, self.meta)
     BlacklistToken().create(self.engine, self.meta)
Exemplo n.º 15
0
 def add_user(self):
     uname = self.username.text()
     password = self.password.text()
     role = self.role.currentText()
     print(uname)
     print(password)
     print(role)
     user = User(uname, password, role)
     session.add(user)
     session.commit()
     self.statusBar().showMessage("User Saved Successfully")
Exemplo n.º 16
0
def signin():
    # GET method
    if request.method == "GET":
        return render_template("signin.html")
    # POST method
    elif request.method == "POST":
        # Check password
        form = request.form
        password = form.getlist("password")
        if (len(password) != 2) or (password[0] !=
                                    password[1]) or not password[0]:
            return render_template(
                "err.html",
                error="Error in password, check you entered it twice correctly"
            )
        else:
            password = password[0]

        #check first and second names
        first_name = form.get("first_name")
        second_name = form.get("second_name")
        if not first_name or not second_name:
            return render_template("err.html",
                                   error="Enter your first and second names")

        # Check username
        user_name = form.get("user_name")
        if not user_name:
            return render_template("err.html", error="Enter your username")
        elif user_name in user_names:
            return render_template(
                "err.html", user_name=f"{user_name} has already been picked")

        # Add user to the database
        user = User(first_name=first_name,
                    second_name=second_name,
                    user_name=user_name,
                    password=password)
        try:
            db.add(user)
            db.commit()
            users = db.query(Book).all()  # to debug
            return render_template('search.html')
        except:
            db.rollback()
            raise
            return render_template("err.html",
                                   error="SORRY something whent wrong")

    # Not GET nor POST methods
    else:
        return "Something went worg http method not suported"
Exemplo n.º 17
0
def add_user():
    username = request.form['username']
    if User.query.filter_by(username=username).first() is None:
        password = request.form['password']
        user_password_hash = pbkdf2_sha256.hash(password)
        user = User(username=username, password=user_password_hash)
        db.session.add(user)
        db.session.commit()
        login_user(user)
        flash('You were successfully signed up')

        return redirect(url_for("main"))
    else:
        flash('That username already exists')
        return render_template("add_user.html")
Exemplo n.º 18
0
def register():
    if request.method == 'POST':
        session = DBSession()
        email = request.form['useremail']
        username = request.form['username']
        password = request.form['userpassword']
        course = request.form['course']
        password = generate_password_hash(password)
        print(email)
        if session.query(User).filter(User.email == email).first():
            return render_template('register.html', msg='该邮箱已被注册!', current_time=current_time)
        else:
            adduser = User(password=password, username=username, email=email, course=course)
            session.add(adduser)
            session.commit()
            os.makedirs(os.getcwd() + '/static/files/{0}'.format(adduser.userid))
            session.close()

            return redirect(url_for('login'))
    else:
        return render_template('register.html', current_time=current_time)
Exemplo n.º 19
0
def success():
    if request.method == 'POST':
        username = request.form['username']
        if not username:
            return render_template("failure.html",
                                   error='Please enter a username')
        # Check if user is in db
        user = User.from_name(username)
        if not user:
            try:
                user_data = get_user_data(username)
                comments_data = get_comment_data(username)
            except HTTPError as err:
                if err.response.status_code == 404:
                    return render_template(
                        "failure.html",
                        error=f'User \'{username}\' does not exist')
                return render_template("failure.html",
                                       error='External API error')

            user = User(**user_data)
            user.comments = [
                Comment(**comment_data) for comment_data in comments_data
            ]
            user.prediction = pred_lean(user)

            db.session.add(user)

        user.searches += 1
        if not user.prediction:
            user.prediction = pred_lean(user)
        db.session.commit()

        return render_template(
            "success.html",
            stance_name=user.prediction.stance_name(),
            user=user.name,
            img=user.prediction.img(),
            h_fullstance=user.prediction.stance_name(axis='h_binary'),
            v_fullstance=user.prediction.stance_name(axis='v_binary'),
            h_confidence=f'{abs(user.prediction.h_pos):.0%}',
            v_confidence=f'{abs(user.prediction.v_pos):.0%}')

    elif request.method == 'GET':
        return redirect(url_for('index'))
from app import db
from tables import User
from passlib.hash import pbkdf2_sha256

username = input("Username:"******"Password:"******"Truck Owner(y/n):")
if truck_owner == "y":
    truck_id = input("Truck ID:")

if User.query.filter_by(username=username).first() is None:
    password_hash = pbkdf2_sha256.hash(password)
    if truck_owner == "y":
        user = User(username=username,
                    password=password_hash,
                    rank="truck",
                    owner_truck_id=truck_id)
    else:
        user = User(username=username, password=password_hash, rank="admin")
    db.session.add(user)
    db.session.commit()
Exemplo n.º 21
0
def add_employee(email):
    user = User(email=email)
    session.add(user)
    session.commit()
    session.add(Employee(user_id=user.id))
    session.commit()
Exemplo n.º 22
0
def create_user(make_new_user=True):
    if request.method == 'OPTIONS':
        return handle_preflight()
    
    req = request.get_json()
    
    u_id = None
    if make_new_user == True:
        u_id = hp.read_user_id(req['u_id'])
        if len(u_id) == 0:
            return USER_ADD_FAILED
        
    p_id = req['p_id']
    
    if len(p_id) == 0:
        if make_new_user == True:
            return USER_ADD_FAILED
        return MEDICINE_ADD_FAILED
    
    meds = req['med_names']
    dosages = req['dosages']
    
    if len(meds) == 0 or len(dosages) == 0:
        if make_new_user == True:
            return USER_ADD_FAILED
        return MEDICINE_ADD_FAILED
    
    cur_session = Session()
    m_ids = [hp.keygen(cur_session, Medication, Medication.med_id) for i in range(len(meds))]
    d_ids = [hp.keygen(cur_session, Dosage, Dosage.dosage_id) for i in range(len(dosages))]
    
    if u_id is None:
        cur_user = cur_session.query(User).filter(User.patient_id == p_id).first()
        if cur_user is None:
            cur_session.close()
            return MEDICINE_ADD_FAILED
        u_id = cur_user.user_id
    cur_meds = [Medication(user_id=u_id, med_id=m_ids[i], 
                           med_name=meds[i], 
                           dosage_id=d_ids[i],
                           validation_date=(datetime.now()-timedelta(days=1)).isoformat()) for i in range(len(meds))]
    cur_dosages = [Dosage(dosage_id=d_ids[i], 
                          days=hp.stringify(dosages[i]['days']), 
                          times=hp.stringify(dosages[i]['times'])
                          ) for i in range(len(dosages))]
    
    if make_new_user == True:
        cur_user = User(user_id=u_id, patient_id=p_id)
        prev_user = cur_session.query(User).filter(
                    User.user_id == cur_user.user_id).first()
    
        if prev_user is not None:
            cur_session.close()
            return USER_ALREADY_EXISTS
    
        cur_session.add(cur_user)
        
    cur_session.add_all(cur_meds)
    cur_session.add_all(cur_dosages)
    cur_session.commit()
    cur_session.close()
    if make_new_user == True:
        return USER_ADD_SUCCESS
    return MEDICINE_ADD_SUCCESS
Exemplo n.º 23
0
 def make_user(self, data, **kwargs):
     return User(**data)
Exemplo n.º 24
0
def by_email(email):
    u = User.all().filter("email =", email).get()
    return u
Exemplo n.º 25
0
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tables import Base
from tables import User

engine = create_engine('sqlite:///test.db', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')
session.add(ed_user)

session.commit()
session.close()
Exemplo n.º 26
0
def by_lg(link):
    u = User.all().filter("link_generated =", link).get()
    return u
Exemplo n.º 27
0
from tables import Session, User, Event

session = Session()

user1 = User(email='*****@*****.**', username='******', password='******')
user2 = User(email='*****@*****.**', username='******', password='******')
user3 = User(email='*****@*****.**', username='******', password='******')

event1 = Event(name='Event1',
               description='Description1',
               event_date='2020-12-11',
               organizer=user1,
               users=[user2, user3])
event2 = Event(name='Event2',
               description='Description2',
               event_date='2020-12-12',
               organizer=user2,
               users=[user1, user3])
event3 = Event(name='Event3',
               description='Description3',
               event_date='2020-12-13',
               organizer=user1)

session.add(event1)
session.add(event2)
session.add(event3)
session.add(user1)
session.add(user2)
session.add(user3)

session.commit()
Exemplo n.º 28
0
api_url = "http://www.bnefoodtrucks.com.au/api/1/trucks"

db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)

from tables import User, Trucks, Votes, Comments

if path.exists('database/food_truck.sqlite'):
    db.create_all()
    while not path.exists('database/food_truck.sqlite'):
        time.sleep(3)

if User.query.filter_by(username='******').first() is None:
    password_hash = pbkdf2_sha256.hash("admin")
    admin = User(username='******', password=password_hash, rank="admin")
    db.session.add(admin)
    db.session.commit()
# END SETUP


# Required by Flask_login to set up its functionality
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


# Retrieves all the data from the api and transfers it to JSON variable
# Then deletes all data in table to then put the new up to data into the table
def api_data_database():
    data = requests.get(api_url)
Exemplo n.º 29
0
nonexist_file = 'nonexist.csv'

with open(nonexist_file) as f:
    reader = csv.reader(f)
    nonexist = {row[0] for row in reader}

with open(data_file) as f:
    reader = csv.reader(f)
    usernames = {row[2]: row[3] for row in reader if row[2] not in nonexist}
    total = len(usernames)

nonexist_new = set() # Buffer-Like construction that we use to write non-existent users to csv
for i, (username, stance_name) in enumerate(usernames.items()):
    if stance_name == 'libright2':
        stance_name = 'libright'
    if stance_name != 'None' and not User.from_name(username):
        try:
            user_data = get_user_data(username)
            comments_data = get_comment_data(username)
        except HTTPError as e:
            print(f'{username:<24} | HTTPError {e.response.status_code} thrown')
            if e.response.status_code in [404, 403]:
                nonexist_new.add(username)
            continue

        user = User(**user_data)
        user.comments = [Comment(**comment_data) for comment_data in comments_data]
        user.stance = Stance.from_str(username, stance_name)
        db.session.add(user)
        db.session.commit()
Exemplo n.º 30
0
from tables import Session, User, Event

session = Session()

user1 = User(
    email='*****@*****.**',
    username='******',
    password='******'
)
user2 = User(
    email='*****@*****.**',
    username='******',
    password='******'
)
user3 = User(
    email='*****@*****.**',
    username='******',
    password='******'
)

event1 = Event(name='Event1',
               description='Description1',
               event_date='2020-12-11',
               organizer=user1,
               users=[user2, user3])
event2 = Event(name='Event2',
               description='Description2',
               event_date='2020-12-12',
               organizer=user2,
               users=[user1, user3])
event3 = Event(name='Event3',
Exemplo n.º 31
0
if __name__ == '__main__':
    from tables import Comment, User, db
    from collections import defaultdict

    comment_groups = Comment.query.with_entities(Comment.author, Comment.subreddit, db.func.count(Comment.subreddit))\
                            .group_by(Comment.author, Comment.subreddit)\
                            .all()

    subreddit_counts = defaultdict(dict)
    for author, subreddit, count in comment_groups:
        subreddit_counts[author][subreddit] = count

    features, labels = [], []
    for author, subs in subreddit_counts.items():
        user = User.from_name(author)
        if user and user.stance:
            features.append(subs)
            labels.append((user.stance.v_pos, user.stance.h_pos))

    labels = np.array(labels)
    features = pd.Series(features)

    splitter = StratifiedShuffleSplit(n_splits=1,
                                      test_size=0.2,
                                      random_state=42)
    for train_index, test_index in splitter.split(features, labels):
        X_train, y_train = features[train_index], labels[train_index]
        X_test, y_test = features[test_index], labels[test_index]

    if not args.noval:
Exemplo n.º 32
0
def add_customer(email, name, phone):
    user = User(email=email)
    session.add(user)
    session.commit()
    session.add(Customer(user_id=user.id, name=name, phone=phone))
    session.commit()