Beispiel #1
0
def create_user():
    session = Session()
    new_user = User()
    new_user.fullname = flask.request.form["fullname"]
    new_user.name = flask.request.form["name"]
    new_user.password = flask.request.form["password"]
    session.add(new_user)
    session.commit()
    session.close()

    return flask.render_template("register.html",name = "completed")
Beispiel #2
0
    def index(self):
        user_query = User.gql("WHERE iwiw_id = :1", self.request.get('opensocial_owner_id'))
        user = user_query.get()
        if user == None:
            user = User()
            user.iwiw_id = self.request.get('opensocial_owner_id')
            user.put()

        sets = []
        for set in user.sets:
            sets.append({'key': str(set.key()),
                         'title': set.title, 
                         'description': set.description})
        return json.write(sets)
Beispiel #3
0
def register():
    from forms import register_form
    form = register_form(request.form)
    if request.method == 'POST' and form.validate():
        user = User()
        form.populate_obj(user)
        user.set_password(form.password.data)

        db.session.add(user)
        db.session.commit()

        login_user(user)
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
Beispiel #4
0
def is_valid_token(provider):
    """Validates the token for a specific provider.

    Args:
        provider: The provider for which we need to validate the token.

    Return:
        True if token is valid; False if not.
    """
    valid_token = True

    # Check local token validity.
    if provider == "local":
        user_id = User.verify_auth_token(login_session["access_token"],
                                         login_session["state"])
        if user_id is None:
            valid_token = False

    # Check facebook token validity.
    if provider == "facebook":
        url = "https://graph.facebook.com/v2.12/me?" \
            "access_token=%s" % login_session["access_token"]
        h = httplib2.Http()
        result = h.request(url, "GET")[1]
        data = json.loads(result)

        if "type" in data and data["type"] == "OAuthException":
            if "code" in data and data["code"] == 190:
                valid_token = False

    return valid_token
Beispiel #5
0
def create_user(login_session):
    """Creates and adds a new user to the database"""
    new_user = User(name=login_session['username'],
                    email=login_session['email'],
                    picture=login_session['picture'])
    SESSION.add(new_user)
    SESSION.commit()
    user = SESSION.query(User).filter_by(email=login_session['email']).one()
    return user.id_user
Beispiel #6
0
    def create(self):
        user_query = User.gql("WHERE iwiw_id = :1", self.request.get('opensocial_owner_id'))
        user = user_query.get()

        set = Set()
        set.description = self.request.get('description')
        set.title = self.request.get('title')
        set.owner = user
        return json.write({'key': str(set.put())})
Beispiel #7
0
def createUser(login_session):
    newUser = User(username=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()
    print "User created with id "
    print user.id
    return user.id
Beispiel #8
0
def create_user(password=None):
    """Creates a user and updates the database.

    Args:
        password: The user password to hash. ONLY used for local user login.

    Return:
        The new user's id.
    """
    newUser = User(name=login_session["username"],
                   email=login_session["email"],
                   picture=login_session["picture"])

    if login_session["provider"] == "local" and password is not None:
        newUser.hash_password(password)

    session.add(newUser)
    session.commit()
    return newUser.id
Beispiel #9
0
def create_db():
    """
    Backdoor to create the database
    :return:
    """
    if not User().username:
        # Create the database
        DB.create_all()
        DB.session.commit()  # Commit the changes
        DB.session.close()  # Close the database connection

    # Display a message on the home page
    flash(f'The database has been created successfully!')
    # Redirect to home page
    return redirect('/')
Beispiel #10
0
def add_user(first, last, user, hash_pass, email):
    """
    Add a new user into the user's database table

    :param
        - first     : *str* : user's first name
        - last      : *str* : user's last name
        - user      : *str* : user's preferred username
        - hash_pass : *str* : hashed password for the user's protection
        - email     : *str* : user's email address

    :return:
        Adds new user to the database user table
    """
    new_user = User(first=first, last=last, username=user,
                    password=hash_pass, email=email)
    DB.session.add(new_user)
    DB.session.commit()
    DB.session.close()
Beispiel #11
0
def google_auth():
    if request.args.get('state') != login_session['cur_state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data.decode("utf-8")
    try:
        # Specify the CLIENT_ID of the app that accesses the backend:
        idinfo = id_token.verify_oauth2_token(code, requests.Request(),
                                              CLIENT_ID)

        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise ValueError('Wrong issuer.')

        # ID token is valid.
        # Get the user's Google Account ID from the decoded token.
        userid = idinfo['sub']
    except ValueError:
        # Invalid token
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = code
    login_session['email'] = idinfo['email']

    # if the user id does not exist, make a new one
    user = (session.query(User).filter_by(email=idinfo['email']).first())
    if not user:
        newUser = User(name=idinfo["name"],
                       profile_pic=idinfo["picture"],
                       email=idinfo["email"])
        session.add(newUser)
        session.commit()
        user = (session.query(User).filter_by(email=idinfo['email']).first())
    login_session['g_user_id'] = userid
    login_session['user_id'] = user.id
    return 'You are now logged in'
Beispiel #12
0
#!/usr/bin/env python2
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db_model import Base, User, Category, Item
import datetime
from passlib.apps import custom_app_context as pwd_context

# Setup database.
engine = create_engine("postgresql://*****:*****@localhost/catalog")
Base.metadata.bind = engine
dbSession = sessionmaker(bind=engine)
session = dbSession()

# Create users.
user1 = User(name="luffy123",
             email="*****@*****.**",
             password_hash=pwd_context.encrypt("!@#$qwer"))
session.add(user1)
session.commit()

user2 = User(name="chopper123",
             email="*****@*****.**",
             password_hash=pwd_context.encrypt("!@#$qwer"))
session.add(user2)
session.commit()

# Create categories.
category1 = Category(category="Action", user_id=1)
session.add(category1)
session.commit()
Beispiel #13
0
def update_schedule(schedule):
    session = DBSession()
    try:
        session.query(Schedule).filter_by(date=schedule.date, user_id=schedule.user_id).update({"end_time": schedule.end_time, "modify": schedule.modify})
        session.commit()
    except Exception as e:
        error('error at update_schedule object')
        error('error info: %s' % str(e))
        session.rollback()
    finally:
        session.close()


if __name__ == '__main__':
    
    tuanlv = User(face_id='tuanlv', password='******', date_created = str(datetime.datetime.now()), level=1, fullname='Le Van Tuan', avatar= '/images/avatar/Tuanlv/0.jpg')
    insert_object(tuanlv)


    # s1 = Schedule(user_id=1, date=20181010, start='8:30:00', end='17:30:00', url_image='test', modify='17:30:00')
    # s2 = Schedule(user_id=1, date=20181011, start='8:30:00', end='17:30:00', url_image='test', modify='17:30:00')
    # s3 = Schedule(user_id=2, date=20181010, start='9:00:00', end='17:30:00', url_image='test', modify='17:30:00')
    # s4 = Schedule(user_id=2, date=20181011, start='9:30:00', end='17:30:00', url_image='test', modify='17:30:00')
    # s5 = Schedule(user_id=3, date=20181010, start='9:15:00', end='17:30:00', url_image='test', modify='17:30:00')
    # s6 = Schedule(user_id=3, date=20181011, start='10:00:00', end='17:30:00', url_image='test', modify='17:30:00')
    # insert_object(s1)
    # insert_object(s2)
    # insert_object(s3)
    # insert_object(s4)
    # insert_object(s5)
    # insert_object(s6)
def register():
    try:
        User.init_from_request(request.json)
    except Exception as error:
        return json_response(status_=404, error=str(error))
    return json_response(status_=200, message='Successfully registered')
Beispiel #15
0
def _user(session, name):
    obj = session.query(User).get(name)
    if obj is None:
        obj = User(name=name, clicks=0, events=0)
        session.add(obj)
    return obj
Beispiel #16
0
from db_model import User,Session

session = Session()

#INSERT
deneme = User()
deneme.fullname = "deneme-full"
deneme.name = "deneme-name"
deneme.password = "******"
session.add(deneme)
session.commit()

#WHERE
users = session.query(User).filter(User.id==2).first()
users.name = "degistirdim"

#DELETE
users = session.query(User).filter(User.id == 2).first()
session.delete(users)
session.commit()


#SELECT
print(session.query(User).all())


session.close()
Beispiel #17
0
import argparse
from db_session import insert_object, get_user_id
from db_model import User
import datetime
import os

FOLDER_CURR = os.path.dirname(os.path.abspath(__file__))
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--id", type=str, help="id of user")
ap.add_argument("-n", "--name", type=str, help="name of user")

args = vars(ap.parse_args())
id = args["id"]
name = args["name"]
records = get_user_id(name)
if len(records) > 0:
    print('user is exist!')
else:
    folder = os.path.join(FOLDER_CURR, '..', 'datasets')
    path = os.path.join(folder, name)
    avatar = '/images/avatar/{0}/0.jpg'.format(name)
    if not os.path.isdir(path):
        os.mkdir(path)
    user = User(face_id=id,
                password=id,
                date_created=str(datetime.datetime.now()),
                level=1,
                fullname=name,
                avatar=avatar)
    insert_object(user)
Beispiel #18
0
def store_user():
    user = u.User('Marc', 'MArc\@plus.com')
    SQLiteEngine.store_user(user)
Beispiel #19
0
def store_mosquito():
    user = u.User('Marc', 'MArc\@plus.com')
    mosquito = m.Mosquito(user, 'file', '')
    mosquito.label = 'Hello'
    print(mosquito)
    SQLiteEngine.store_mosquito(23, mosquito)
Beispiel #20
0
def addUser():
    session.add(User(id=1, username="******", email="*****@*****.**"))
    session.commit()
    print "User 1 added."
Beispiel #21
0
import random

from db import meta_engine
from db.db_config import session_make
from db_model import User, Manufacturer, Station, Asset, MeasurePoint

session = session_make(meta_engine)

admin = User(name="admin")
simens = Manufacturer(name="Simens", telephone="88835569")
hhht = Station(
    name="呼和浩特站", location="内蒙古", sharding_db_id=1, memo="N/A", telephone="89656985"
)
et = Station(
    name="鄂托克旗站", location="内蒙古", sharding_db_id=2, memo="N/A", telephone="89656985"
)
bt = Station(
    name="包头站", location="内蒙古", sharding_db_id=3, memo="N/A", telephone="89656985"
)

session.add_all([admin, simens, hhht, et, bt])
session.commit()

asset_list = []
stations = session.query(Station).all()
admin = session.query(User).one()

for station_id, units in enumerate([[1, 1], [2, 2], [3, 3]]):
    mp_id = 0
    for i in units:
        unit_name = "PumpUnit#" + str(random.randint(100, 999))