Example #1
0
def doLogin():
    input = request.get_json()
    validate(instance=input, schema=schema)

    user = ClientAccount.query.filter_by(email=input["email"]).first()

    if user is None:
        return jsonify({"error": "email and password does not match"}), 400

    isValid = user.checkPassword(input["password"])

    if isValid is False:
        return jsonify({"error": "email and password does not match"}), 400

    Session.revokeAllToken(user.id)

    sessionId = generateUUID()
    accessToken = generateJWTToken(
        user.id,
        sessionId=sessionId,
        expire=datetime.datetime.utcnow() + datetime.timedelta(days=7),
        jwtSecret=current_app.config.get("JWT_SECRET_KEY"),
    )
    Session.createSession(userId=user.id, sessionId=sessionId)

    # return "OK"
    return jsonify({"accessToken": accessToken})
Example #2
0
 def login(self, user):
     session = Session(mail=user.mail,
                       expires=5 * 24 * 60 * 60)
     session.save()
     self.session_id = session.session_id
     self.app.current_user = user
     self.set_session()
def loaddb_sessions(filename):
    """ Populates the database with sessions and session-related relationships from a yml file. Requires loaddb_games and loaddb_users """
    sessions = yaml.safe_load(open(filename))

    # premier tour de boucle, creation des sessions et des timeslots
    dico_timeslots = dict()  # k=session_yml_id, v=timeslot_object
    dico_sessions = dict()  # k=session_yml_id, v=session_object
    for id, s in sessions.items():
        session_object = Session(nb_players_required=s["nb_players_required"],
                                 notifactions_sent=s["notifactions_sent"],
                                 confirmed=s["confirmed"],
                                 timeout=s["timeout"],
                                 archived=s["archived"])
        db.session.add(session_object)
        dico_sessions[id] = session_object

        timeslot = s["timeslot"]
        timeslot_object = TimeSlot(beginning=timeslot["beginning"],
                                   end=timeslot["end"],
                                   day=timeslot["day"])
        db.session.add(timeslot_object)
        dico_timeslots[id] = timeslot_object
    db.session.commit()

    # deuxieme tour de boucle, ajout des relations SessionXTimeslot, SessionXGame et SessionXUser
    for id, s in sessions.items():
        session_object = dico_sessions[id]
        session_object.timeslot_id = dico_timeslots[id].id
        load_relationship(s, 'session_id', session_object.id, 'games', Use,
                          Game.from_title, 'game_id', ['expected_time'],
                          'title')
        load_relationship(s, 'session_id', session_object.id, 'players', Play,
                          User.from_username, 'user_id', ['confirmed', 'won'],
                          'username')
    db.session.commit()
Example #4
0
def get_user_id(uuid):
    session = db.session.query(Session).filter_by(uuid=uuid).first()
    if session:
        user_id = session.email
        if user_id:
            return user_id
        else:
            return None
    else:
        user_id = get_user_id_ext(uuid=uuid)
        if user_id:
            try:
                session = db.session.query(Session).filter_by(
                    email=str(user_id)).first()
            except Exception as ex:
                print('ex: ' + ex)
            if session:
                session.uuid = uuid
                session = session.update_session()
            else:
                session = Session(username=user_id, uuid=uuid)
                session = session.save()
            return session.email
        else:
            return None
Example #5
0
 def __setitem__(self, key, value):
     pickled = self.encode(value)
     now = datetime.datetime.now()
     s = Session.get(key)
     if s:
         s.data = pickled
     else:
         s = Session(key, now, pickled)
         config.orm.add(s)
Example #6
0
def get_users():
    try:
        result = []
        sess = Session()
        user = sess.query(User).order_by(User.name).all()
        result = [a.to_dict() for a in user]
    except Exception as e:
        result = []
    return result
Example #7
0
def get_books():
    try:
        result = []
        sess = Session()
        book = sess.query(Book).order_by(Book.name).all()
        result = [a.to_dict() for a in book]
    except Exception as e:
        result = []
    return result
Example #8
0
def get_user(user_id):
    try:
        sess = Session()
        user = sess.query(User).get(user_id)
        if not user:
            result = []
        else:
            result = [user.to_dict()]
    except Exception as e:
        result = []
    return result
Example #9
0
def registerHouse():
    get_lang(request)
    #generate form data
    form = RegisterForm(request.form)
    if request.method == 'POST':
        #store form data
        address = form.address.data
        city = form.city.data
        state = form.state.data
        zip = form.zip.data

        #generate lat/long from address
        results = Geocoder.geocode(address)
        result = results[0].coordinates
        lat = result[0]
        long = result[1]

        #create new db session
        sess = Session()

        #get user id for database relations
        account_id = session['id']

        #create new home: A new home is identified by street. city, zip, state, lat/long
        new_home = Home(account_id=account_id,
                        street_address=address,
                        city=city,
                        state=state,
                        zip_code=zip,
                        latitude=lat,
                        longitude=long)

        #Does the address already exist
        match = sess.query(Home.street_address)\
              .filter(Home.street_address==address)\
              .all()

        #If the address is unique the home is added
        if not match:
            print(f'Added: {new_home}')
            #add entry to database for home
            sess.add(new_home)

            #save changes
            sess.commit()

        #the address is not unique
        else:
            #error message
            flash("Address already registered")

            #return to registration page
            return render_template('registerHouse.html', form=form)

        #close connection
        sess.close()
        return redirect(url_for('dashboard'))
    return render_template('registerHouse.html', form=form)
Example #10
0
def set_server_session():
    from app.models import Session
    server_session = None
    if ('uuid' not in session):
        server_session = Session.new_session()
        session['uuid'] = server_session.uuid
    else:
        server_session = Session.by_uuid(session['uuid'])
        if (server_session is None):
            server_session = Session.new_session()
            session['uuid'] = server_session.uuid
    db.session.commit()
    g.server_session = server_session
Example #11
0
def index(request):
    user = request.user
    if user.is_authenticated:
        if request.method == 'POST':
            time = request.POST.get('time', '')
            duration = timedelta(minutes=float(time))
            session = Session(duration=duration, date=date.today(), user=user)
            session.save()
            return HttpResponseRedirect(reverse('index'))
        else:
            return render(request, 'app/index.html', {'navbar': 'index'})
    else:
        return render(request, 'app/index.html', {'navbar': 'index'})
Example #12
0
def session():
    session = Session()

    # We want the session be flushed and commited after each instance
    # to not violate FK constraints in DB
    def add_all(self, instances):
        for instance in instances:
            self.add(instance)
            self.flush()
            self.expunge(instance)

    # Override the originial add_all for this session
    session.add_all = add_all.__get__(session, Session)
    return session
Example #13
0
def logout(request):
    try:
        data = json.loads(request.body.decode('utf-8'))
    except json.JSONDecodeError:
        return JsonResponse({'error': 'MALFORMED_REQUEST'},
                            HTTPStatus.BAD_REQUEST)
        key = data['key']
    try:
        key = data['key']
    except KeyError:
        return JsonResponse({'error': 'INVALID_DATA'},
                            HTTPStatus.UNPROCESSABLE_ENTITY)

    Session.delete_with_key(key)
    return JsonResponse({})
Example #14
0
def send_emails(transactions):
	session = Session()
	for transaction in transactions:
		user = session.query(User) \
			.filter(User.id == transaction.user_id)

		email = user[0].email

		sg = sendgrid.SendGridClient(os.environ.get('SENDGRID_USERNAME'), os.environ.get("SENDGRID_PASSWORD"))
		message = sendgrid.Mail()
		message.add_to(email)
		message.set_from("*****@*****.**")
		message.set_subject("ayyyy lmao")
		message.set_html("yoooooooooooooooo")
		sg.send(message)
Example #15
0
def update_book(book_id, **data):
    try:
        sess = Session()
        book = sess.query(Book).get(book_id)
        if not book:
            result = False
        else:
            book.name = data['name']
            book.author = data['author']
            book.description = data['description']
            sess.commit()
            result = True
    except Exception as err:
        result = False
    return result
Example #16
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        child_id = form.child_id.data
        proctor_id = form.proctor_id.data

        # Check if the child is in the database - if they are not, then add
        # them. We might want to change this behavior later so that if they are
        # not in the database, we do not allow them to log in.
        if Child.query.filter_by(id=child_id).first() is None:
            child = Child(id=child_id)
            db.session.add(child)
            db.session.commit()

        # Check if the proctor is in the database - if they are not, then add
        # them. We might want to change this behavior later so that if they are
        # not in the database, we do not allow them to log in.
        if Proctor.query.filter_by(id=proctor_id).first() is None:
            proctor = Proctor(id=proctor_id)
            db.session.add(proctor)
            db.session.commit()

        session_db_entry = Session(child_id=child_id, proctor_id=proctor_id)
        db.session.add(session_db_entry)
        db.session.commit()

        child = Child.query.filter_by(id=form.child_id.data).first()
        if child is None:
            print("Invalid child_id or password")
            return redirect(url_for("routes.login"))

        login_user(child)
        return redirect(url_for("routes.index"))

    return render_template("login.html", title="Sign In", form=form)
Example #17
0
 def to_json(self):
     json = super().to_json()
     if not isinstance(self.qs, list):
         qoods_qs = Session.query(
             metadata.tables['goods']).filter_by(store_id=self.id).all()
         json['goods'] = GoodsSerializer(qoods_qs).to_json()
     return json
Example #18
0
def v1_fblogin():
    try:
        check_params(request, ['token'])
    except StandardError as e:
        return respond(str(e), code=400), 400

    token = str(request.form['token'])

    # Create the username
    fb_url = "https://graph.facebook.com/v2.8/me?fields=id&access_token={}"
    r = requests.get(fb_url.format(token))
    data = r.json()

    if r.status_code != 200:
        return respond("Server failure", code=r.status_code), 500

    fb_username = "******".format(r.json()['id'])
    user = User.query.filter(User.username == fb_username).first()

    ## Create if does not exist
    if user == None:
        user = User(fb_username, "")
        db.session.add(user)
        db.session.commit()

    # Create a session
    session = Session(hexlify(urandom(50)), user)
    try:
        db.session.add(session)
        db.session.commit()
    except:
        db.session.rollback()
        return respond("Internal server error has occured", code=101), 500

    return respond("SUCCESS", data={'session': session.session})
Example #19
0
def find_books(search_text):
    try:
        result = []
        sess = Session()
        # books = sess.query(Book).filter(Book.name.contains(search_text)).order_by(Book.name).all()
        # result = [a.to_dict() for a in books]
        # %' or 1=1 or '%
        query = "SELECT * FROM book WHERE name like '%" + search_text + "%'"
        print(query)
        books = sess.execute(query)
        result = [{column: value
                   for column, value in rowproxy.items()}
                  for rowproxy in books]
    except Exception as e:
        result = []
    return result
Example #20
0
def create_session():
    """Create a new Session"""
    app = Application.query.filter_by(id=request.json['app']).first()
    questionnaire = Questionnaire.query.filter_by(
        id=request.json['questionnaire']).first()
    expected_emotions = request.json['expected_emotions']

    # validate application type
    if not app:
        return {'status': 'error', 'message': 'Invalid application.'}, 400

    new_session = Session(app=app,
                          expected_emotions=expected_emotions,
                          questionnaire=questionnaire)

    db.session.add(new_session)
    db.session.commit()

    result = session_schema.dump(new_session).data

    return jsonify({
        'status':
        'success',
        'message':
        'Created new session for application with id of {}.'.format(
            request.json['app']),
        'data':
        result
    }), 201
Example #21
0
    def update(self, **data):
        """
        update
        :param data:
        :return:
        """
        # 基于 id 的更新
        cid = data.pop('id', -1)
        with Session() as ss:
            if cid > 0:
                query = ss.query(
                    self.table).filter(self.table.id == cid).first()
                if query:
                    self.modify_raw(query, data)
                    ss.add(query)
                    ss.commit()
                    return 200, query.id
                return 404, u'id无法关联信息'

            # 基于其他唯一且不为空的key更新
            keys = self.get_unique_key()
            for key in keys:
                name = data.pop(key, None)
                if name:
                    query = ss.query(self.table).filter(
                        self.table.__dict__[key] == name).first()
                    if query:
                        self.modify_raw(query, data)
                        ss.add(query)
                        ss.commit()
                        return 200, query.id
            return 404, u'没有匹配到任何行'
Example #22
0
def login():
    if request.method == 'POST':
        if current_user.is_active:
            print('Error, user is active!')
            return json.dumps({'errmsg': '用户已登陆'})
        #获取post来的数据
        json_data = json.loads(request.data)
        user = User.query.filter_by(id=json_data['id']).first()
        if user is None or not user.check_password(json_data['password']):
            print('username or password isn\'t correct!')
            return json.dumps({'errmsg': '用户名或密码错误'})
        login_user(user)

        #建立session数据库
        se = Session.query.filter_by(uid=user.id).first()
        if se == None:
            se = Session(uid=user.id)
            db.session.add(se)
            db.session.commit()
            print('Create a new session {}'.format(se.sid))
        else:
            print('Resume Session {}'.format(se.sid))

        print('login user {}!'.format(user))
        data = json.dumps(user, default=UserToJson, sort_keys=False)

        #生成返回的resp,增加session的选项
        resp = make_response()
        resp.headers['session_id'] = str(se.sid)
        resp.data = data
        return resp
    return json.dumps({'errmsg': '没有使用POST请求'})
Example #23
0
def authentication(data):
    try:
        sess = Session()
        # password = sha512(data['passwd'].encode('utf-8')).hexdigest()
        password = data['passwd']
        user = sess.query(User).filter(User.name == data['name'],
                                       User.password == password).first()
        if not user:
            result = {'status': False, 'data': []}
        else:
            result = {'status': True, 'data': [user.to_dict()]}

    except Exception as e:
        result = {'status': False, 'message': str(e)}

    return result
Example #24
0
def create_with_campaign(id):
    form = SessionForm()
    form.submit.label.text = "Create Session"
    form.participants.choices = gen_participant_choices()

    campaign = Campaign.query.filter_by(id=id).first_or_404()

    if not current_user.is_dm_of(campaign):
        del form.dm_notes

    if form.validate_on_submit():
        participants = Character.query.filter(Character.id.in_(form.participants.data)).all()

        dm_notes = None
        if current_user.is_dm_of(campaign):
            dm_notes = form.dm_notes.data

        new_session = Session(title=form.title.data, campaign_id=form.campaign.data, summary=form.summary.data, dm_notes=dm_notes, date=form.date.data, participants=participants)

        db.session.add(new_session)
        db.session.commit()

        flash("Session was created.", "success")
        return redirect(url_for("session.view", id=new_session.id))
    elif request.method == "GET":
        participants = []

        for p in campaign.default_participants:
            participants.append(p.id)

        form.participants.data = participants

        form.campaign.data = id

    return render_template("session/create.html", form=form, campaign=campaign, title=page_title("Add Session"))
Example #25
0
def user_register(data):
    try:
        username = data.get('username')
        password = data.get('password')
        language = data.get('language')
        status = data.get('status')
        if is_user_exist(username):
            return generate_username_taken_response(username)
        salt = generate_uuid()
        hash_pwd = get_hash_password(salt, password)
        user = User(username=username,
                    hash_pwd=hash_pwd,
                    salt=salt,
                    language=language,
                    status=status)
        if user:
            temp_uuid = generate_uuid()
            session = Session(username=user.username, uuid=temp_uuid)
            user.save(session)
            return generate_registration_success_response(temp_uuid)
        else:
            raise Exception('Failed to create user')
    except Exception as exe:
        print('user user registration failed')
        if hasattr(exe, 'message'):
            print(exe.message)
        else:
            print(exe)
        return generate_registration_failed_response(exe)
Example #26
0
def get_user_id_remotely(data):
    key = data.get('key')
    url = 'https://veryimportantlot.com/gallery3d/api/auth?key=' + key
    response = requests.get(url)
    user_id = response.text
    if user_id and user_id != '0':
        temp_uuid = generate_uuid()
        session_old = db.session.query(Session).filter_by(email=user_id)
        if session_old:
            session_old.delete()
        session = Session(user_id, temp_uuid)
        if session:
            session.save()
        return generate_login_success_response(temp_uuid)
    else:
        return generate_login_failed_response()
Example #27
0
    def __init__(self):

        # Grid initialization
        super(EditSessionsGrid, self).__init__(Session, Session.all())

        # Creation of a customized date field to view the session's date
        self.append(create_date_field("formatted_atime", "atime", DT_FORMAT))

        # Creation of a customized field to view the session's data
        self.append(
            Field(
                name="formatted_data",
                value=lambda model: "{%s}"
                % ",".join(
                    [
                        "%s:%s" % (k, v)
                        for k, v in config.session_manager.session_handler.store.decode(model.data).items()
                        if k != "session_id"
                    ]
                ),
            )
        )

        # Grid configuration
        inc = [
            FORMATTED_ATIME_READONLY(self.formatted_atime),
            FORMATTED_DATA_READONLY(self.formatted_data),
            SESSION_ID_READONLY(self.session_id),
        ]

        self.configure(include=inc)
Example #28
0
    def __init__(self):

        # Grid initialization
        super(EditSessionsGrid, self).__init__(Session, Session.all())

        # Creation of a customized date field to view the session's date
        self.append(create_date_field("formatted_atime", "atime", DT_FORMAT))

        # Creation of a customized field to view the session's data
        self.append(
            Field(name="formatted_data",
                  value=lambda model: "{%s}" % ",".join([
                      "%s:%s" % (k, v) for k, v in config.session_manager.
                      session_handler.store.decode(model.data).items()
                      if k != "session_id"
                  ])))

        # Grid configuration
        inc = [
            FORMATTED_ATIME_READONLY(self.formatted_atime),
            FORMATTED_DATA_READONLY(self.formatted_data),
            SESSION_ID_READONLY(self.session_id)
        ]

        self.configure(include=inc)
Example #29
0
    def _wechatLoginByJSCode(self, app_name, code):
        if app_name == 'drawingboard':
            appid = config.WECHAT_LITEAPP_APPID
            appsecret = config.WECHAT_LITEAPP_SECRET
        elif app_name == 'eyes':
            appid = config.WECHAT_LITEAPP_EYES_APPID
            appsecret = config.WECHAT_LITEAPP_EYES_SECRET
        else:
            appid = ''
            appsecret = ''
        result = requests.get(
            config.WECHAT_LOGIN_BY_JSCODE_URL, {
                'appid': appid,
                'secret': appsecret,
                'js_code': code,
                'grant_type': 'authorization_code'
            }).json()

        openid = result.get('openid', '')
        if not openid:
            return None, None
        account = Account.get_or_create_by_liteapp_openid(app_name, openid)
        session = Session.update_or_create_session(
            account.id, result.get('session_key', ''),
            result.get('expires_in', 0) - config.SAFE_LOGIN_BUFFER)

        return account, session
Example #30
0
def student_addcourse():
    dept = Department.query.filter_by(staff_id=current_user.id).scalar()
    if (dept):
        department_code = Department.query.filter_by(
            staff_id=current_user.id).first()

    course_id = request.json['course_id']
    session_id = Session.get_current()
    courseform = Courseform.query.filter_by(student_id=current_user.id,
                                            session_id=session_id).first()

    course = Course.query.get(course_id)
    unit = course.unit
    old_unit = courseform.total_units
    courseform.total_units = unit + old_unit
    db.session.commit()

    offering = Offering(courseform_id=courseform.id, course_id=course_id)
    exists = Offering.query.filter_by(courseform_id=courseform.id,
                                      course_id=course_id).scalar()
    if not exists:
        offering.save()

        data = {"message": "success"}
    else:
        data = {"message": "Course already exists"}

    return jsonify(data)
Example #31
0
 def post(self):
     session = Session(status='Started',
                       startDate=datetime.datetime.now(),
                       company_id=api.payload['companyId'],
                       user_id=api.payload['userId'])
     db.session.add(session)
     db.session.commit()
     return session_schema.jsonify(session)
Example #32
0
 def logout(self):
     self.app.log('Logout user: %s.' % self.app.current_user)
     self.app.current_user = None
     session = Session.get(Session.session_id == self.session_id)
     session.active = False
     session.save()
     self.session_id = None
     response.delete_cookie(self.key)
Example #33
0
def add_game(session_id):
    """
    Render the session template on the /session route
    """
    session = Session.from_id(session_id)
    return render_template('add_player.html',
                           stylesheet='session',
                           session=session)
Example #34
0
 def logout(self):
     self.app.log('Logout user: %s.' % self.app.current_user)
     self.app.current_user = None
     session = Session.get(Session.session_id == self.session_id)
     session.active = False
     session.save()
     self.session_id = None
     response.delete_cookie(self.key)
Example #35
0
 def __setitem__(self, key, value):
     pickled = self.encode(value)
     now = datetime.datetime.now()
     s = Session.get(key)
     if s :
         s.data = pickled
     else:
         s = Session(key, now, pickled)
         config.orm.add(s)
Example #36
0
 def load_user(self):
     if self.session_id is not None:
         self.app.log(self.session_id)
         session = Session.get(Session.session_id == self.session_id)
         if session.active:
             self.app.current_user = User.get(User.mail == session.mail)
         else:
             self.app.current_user = None
             self.session_id = None
     else:
         self.app.current_user = None
Example #37
0
def cron_update_db():
	session = Session()
	items = session.query(Item).all()

	for item in items:
		url = item.url
		response = get_amazon_price(url)
		currentPrice = response.get("price", None)

		if currentPrice:
			if currentPrice <= item.price:
				transactions = session.query(Transaction) \
					.filter(Transaction.requested_price >= currentPrice) \
					.all()

				send_emails(transactions)
			item.price = currentPrice


	session.commit()
Example #38
0
 def save_news(self, news):
     session = Session()
     q = session.query(News)
     for n in news:
         published = n['published_parsed']
         date = datetime.date(published[0], published[1], published[2])
         link = n['link']
         title = n['title']
         existing_news = q.filter(News.link == link).all()
         if not existing_news:
             news = News(date=date, title=title, summary=n['summary'],
                         link=link)
             session.add(news)
     session.commit()
Example #39
0
 def __delitem__(self, key):
     s = Session.get(key)
     config.orm.delete(s)
 def tearDown(self):
     Session.rollback()
Example #41
0
 def __getitem__(self, key):
     
     now = datetime.datetime.now()
     s = Session.get(key)
     s.atime = now
     return self.decode(s.data)
Example #42
0
 def __contains__(self, key):
     s = Session.get(key)
     return s and not s in config.orm.deleted
Example #43
0
 def get_unpublished(self):
     q = Session().query(News)
     return q.filter(News.published.is_(False)).order_by(News.date).all()
Example #44
0
 def test_all(self):
     all_sessions = Session.all()
     self.assertEqual(len(all_sessions), 1)