def dispatch_request(self):
        users = UserModel.query()
        user_create_form = UserForm()

        if user_create_form.is_submitted():
            user = UserModel(
                name=user_create_form.name.data,
                gender="",
                uuid="",
                bluetooth="",
                facebook_id="",
                photo_url="",
                facebook_token="",
                gps="",
                experience_education="",
                experience_hometown="",
                experience_work="",
                experience_tagged_place="",
                interest_music="",
                interest_book="",
                installed_apps="",
                vibrate_status=False,
                matched_with=None
            )
            try:
                user.put()
                user_id = user.key.id()
                return redirect(url_for('admin_list_users'))
            except CapabilityDisabledError:
                flash(u'App Engine Datastore is currently in read-only mode.', 'info')
                return redirect(url_for('admin_list_users'))
        return render_template('list_users.html', users=users, form=user_create_form)
Exemplo n.º 2
0
def create_app(config_file):
    # load config
    app.config.from_pyfile(config_file)

    from views.backgrounds import load_backgrounds
    load_backgrounds(app)

    # setup db
    from database import db
    db.init_app(app)

    # setup login
    login_manager.init_app(app)

    # login_manager.setup_app(app)

    from monkey.views import index_view, login_view

    for bp in [login_view, index_view]:
        app.register_blueprint(bp)

    # init all
    with app.app_context():
        db.create_all()
        import api

        api.start_api([UserModel])
        UserModel.initialize()

    return app
    def new_user(self, fb_id, email=u'*****@*****.**'):

        ## creating new user
        user = UserModel(fb_id=fb_id, email=email)
        user.save()

        ## creating new album
        self._create_new_album(user)

        return user
Exemplo n.º 4
0
 def checkOrSaveUserModel(userModel):
     # Use key_name attribute to get and create Model, otherwise, it maybe create two same Models.
     userModel = UserModel.get_by_key_name(username)
     if userModel:
         errorMessages['occupiedUsername'] = '******' % username
     else:
         # Save new user with key_name attribute to make sure only one model will be inserted concurrently.
         # import time
         # time.sleep(5)
         userModel = UserModel(key_name = username, username = username, email = email, password = password, ip = ip)
         userModel.put()
Exemplo n.º 5
0
def main():
    if len(sys.argv) != 3:
        usage()
        sys.exit(0)

    new_user = UserModel()
    new_user.username = sys.argv[1]
    new_user.set_password(sys.argv[2])
    new_user.admin = True

    db.session.add(new_user)
    db.session.commit()
    def dispatch_request(self):
        res = {}
        info = request.json
        #return json.dumps(info)
        try:
            #facebook_id = info["FacebookID"]
            # existed_user = UserModel.query().filter("facebook_id = ", facebook_id)
            # if existed_user:
            #     res["status"] = "fail"
            #     res["error"] = "UserExisted"
            #     return json.dumps(res)

            fb_info = info["FBinfo"]
            tagged_places = [p["place"]["location"]["city"] for p in fb_info["tagged_places"]["data"]] if fb_info["tagged_places"] else []
            tagged_places = list(set(tagged_places))
            installed_app = []
            apps_cat = {"Tools":0, "Music & Audio":0, "Finance":0, "Communication":0}
            for app in info["app"]["apps"]:
                if app["category"] in apps_cat:
                    installed_app.append(app["title"])
                    apps_cat[app["category"]] += 1
            user = UserModel(
                name=fb_info["name"],
                gender=fb_info["gender"],
                uuid="",
                bluetooth="",
                facebook_id=info["FacebookID"],
                photo_url=info["photo URL"],
                facebook_token=info["AccessToken"],
                gps="",
                experience_education="[" + ",".join([s["school"]["name"] for s in fb_info["education"]]) + "]",
                experience_hometown="" if "name" not in fb_info["hometown"] else fb_info["hometown"]["name"],
                experience_work="[" + ",".join([w["employer"]["name"] for w in fb_info["work"]]) + "]",
                experience_tagged_place=",".join(tagged_places),
                interest_music="[" + ",".join([m["name"] for m in fb_info["music"]["data"]]) + "]",
                interest_book="[" + ",".join([b["name"] for b in fb_info["books"]["data"]]) + "]",
                #installed_apps=json.dumps(apps),
                installed_apps=json.dumps(installed_app),
                apps_category=json.dumps(apps_cat),
                vibrate_status=False,
                matched_with=None
            )
            user.put()
            user_id = user.key.id()
            res["user_id"] = user_id
            res["status"] = "succeed"
            return json.dumps(res)
        except Exception as e:
            res["status"] = "fail"
            res["error"] = e.message
            return json.dumps(res)
Exemplo n.º 7
0
 def _enqueueUsersTest(self, assertMethod):
     redisMock = Mock()
     redisMock.sadd = Mock(side_effect=lambda k, v:0 if v == 'test_user2' else 1)
     userBuff = []
     redisMock.rpush = Mock()
     
     param1 = []
     for i in range(0, 3):
         user = UserModel()
         user.name = 'test_user%s' % i
         param1.append(user)
     target = RedisContext(RedisModuleMock(redisMock))
     target.enqueueUsers(param1)
     
     assertMethod(redisMock)
Exemplo n.º 8
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('old_password', help = 'This field cannot be blank', required = True)
     parser.add_argument('new_password', help = 'This field cannot be blank', required = True)
     data = parser.parse_args()
     user = UserModel.find_by_username(get_jwt_identity())
     if len(data['new_password']) <= 7:
         return {'message': 'Password has to be at least 8 chars long', 'success': False}
     elif UserModel.verify_hash(data['old_password'], user.password):
         try:
             UserModel.update_pw(user.username, UserModel.generate_hash(data['new_password']))
             return {'success': True}
         except:
             return {'success': False, 'message': 'Something went wrong'}
     else:
         return {'message': 'Wrong password', 'success': False}
Exemplo n.º 9
0
 def get(self):
     data = parser.parse_args()
     get_all = data.get("get_all")
     username = data["username"]
     user_id = UserModel.find_by_username(username).id
     return (LabeledDatasetModel.get_unlabeled(user_id)
             if not get_all else LabeledDatasetModel.get_all())
Exemplo n.º 10
0
    def dispatch_request(self, filters):
        filters = filters.split(',')
        registered_users = UserModel.query().order(UserModel.user_last_name)
        households = list(set([x.user_household for x in registered_users]))

        if 'children' in filters:
            filters.remove('children')
            registered_users = filter(lambda x: x.user_is_adult == False,
                                      registered_users)
        elif 'adults' in filters:
            filters.remove('adults')
            registered_users = filter(lambda x: x.user_is_adult == True,
                                      registered_users)

        filtered_users = []
        if not filters:
            filtered_users = registered_users
        else:
            for user in registered_users:
                if user.user_household in filters:
                    filtered_users.append(user)

        form = UserForm()

        return render_template('list_users.html',
                               users=filtered_users,
                               form=form,
                               auth=session.get('user', {}),
                               is_admin=users.is_current_user_admin(),
                               households=households)
Exemplo n.º 11
0
    def post(self):
        # db, cursor = self.db_init()
        arg = parser.parse_args()
        user = {
            'name': arg['name'],
            'gender': arg['gender'] or 0,
            'birth': arg['birth'] or "1900-01-01",
            'note': arg['note'] or None,
        }

        # sql = """
        #     INSERT INTO `api`.`users` (`name`, `gender`, `birth`, `note`) VALUES ('{}', '{}', '{}', '{}');
        # """.format(user['name'], user['gender'], user['birth'], user['note'])

        response = {}
        status_code = 200

        try:
            new_user = UserModel(name=user['name'],
                                 gender=user['gender'],
                                 birth=user['birth'],
                                 note=user['note'])
            db.session.add(new_user)
            db.session.commit()
            # cursor.execute(sql)
            response['msg'] = 'success'
        except:
            status_code = 400
            traceback.print_exc()
            response['msg'] = 'failed'

        # db.commit()
        # db.close()
        return make_response(jsonify(response), status_code)
Exemplo n.º 12
0
    def post(self):
        data = parser_b.parse_args()
        
        if UserModel.find_by_username(data['username']):
            if UserAccountInfoModel.find_by_username(data['username']):
                return {'message': 'User {} already has a spreadsheet'.format(data['username'])}

            new_accountinfo = UserAccountInfoModel(
                username = data['username'],
                spreadsheet = data['spreadsheet'],
                spreadsheet_target = data['spreadsheet_target']
            )

            try:
                new_accountinfo.save_to_db()
                return {
                    'message': 'Spreadsheet {} was added'.format(new_accountinfo.username),
                    'spreadsheet': new_accountinfo.spreadsheet,
                    'spreadsheet_target': new_accountinfo.spreadsheet_target
                    }
            except:
                return {'message': 'Something went wrong'}, 500
        
        else:
            return {'message': 'This user doesnt exist'}
Exemplo n.º 13
0
def login():
	form = LoginForm()
	if form.validate_on_submit():
		user = UserModel.find_by_eid(form.eid.data)
		if user is not None and user.check_password(form.password.data):
			return render_template('base.html')
	return render_template('login.html', form = form)
Exemplo n.º 14
0
    def post(self):
        data = self.token_parser.parse_args()
        current_user_id = get_jwt_identity()

        logged_in = current_user_id is not None

        denied = []
        tokens = {}
        for app_id in data['ids']:
            denied.append(app_id)

        if logged_in:
            current_user = UserModel.find_by_id(current_user_id)
            if not current_user:
                return {'message': 'Invalid token'}, 401

            for app_id in denied:
                if Purchase.find_purchase(current_user_id, app_id):
                    denied.remove(app_id)
                    tokens[app_id] = jwt.encode(
                        {
                            'sub': 'users/%d' % current_user_id,
                            'prefixes': [app_id],
                            'exp': datetime.utcnow() + longRepoTokenLifetime,
                            'name': 'auth.py',
                        },
                        repo_secret,
                        algorithm='HS256').decode('utf-8')

        return {'denied': denied, 'tokens': tokens}
Exemplo n.º 15
0
def init():
    user = UserModel(name="Selina Joey",
                     username="******",
                     url="https://www.facebook.com/selina.joey",
                     profile="origin")
    dbhelper = DBHelper()
    dbhelper.save_user(user=user)
Exemplo n.º 16
0
    def post(self):
        user_dict = get_jwt_identity()
        user = UserModel.find_by_username(user_dict['username'])
        item_id = purchase_parser.parse_args()['id']
        item = ShopItemModel.find_item_by_id(item_id)
        if item:
            new_transaction = TransactionModel(
                sender_id=user.id,
                receiver_id=0,
                amount=item.price,
                date=datetime.datetime.now(),
                transaction_type='Purchase'
            )

            if user.current_balance < item.price:
                return {'message': 'Not enough money'}, 400

            try:
                item.purchase_item(user)
                user.change_balance(user.current_balance - item.price)
                new_transaction.save_to_db()
                return {'message': 'You have successfully bought {}'.format(item.name)}, 200
            except:
                return {'message': 'Something went wrong'}, 500
        return {'message': 'Item not found'}, 400
Exemplo n.º 17
0
    def patch(self, args):
        current_user = get_jwt_identity()
        logged_user = UserModel.find_by_username(current_user)

        if not args.get('menu_id'):
            return {'message': 'menu_id is required.'}, 400

        db_result = MenuModel.get_by_owner_and_id(menu_id=args.get('menu_id'),
                                                  owner=logged_user)

        if db_result:
            try:
                db_result.name = args.get('name')
                db_result.menu_type = args.get('menu_type')
                db_result.coffee_option = args.get('coffee_option')
                db_result.taste_level = args.get('taste_level')
                db_result.water_level = args.get('water_level')
                db_result.foam_level = args.get('foam_level')
                db_result.grind_size = args.get('grind_size')
                db_result.save_to_db()
                return {'message': 'menu update successfully.'}
            except (Exception, ):
                logger.exception('Menu update failed.')
                return {'message': 'Something went wrong'}, 500
        else:
            return {'message': 'menu item not found.'}, 404
Exemplo n.º 18
0
    def post(self):
        data = request.get_json()
        promoter = promoter_schema.load(data)
        #get current user
        current_user = get_jwt_identity()
        user = UserModel.find_by_username(current_user)

        #do not process request if a promoter with that name already exists
        if PromoterModel.find_by_name(promoter.data['name']):
            return {
                'message':
                'Promoter {} already exists'.format(promoter.data['name'])
            }

        #do not process request if this user already has an associated promoter
        if user.promoter_name:
            return {
                'message': 'You are already associated with a promoter account'
            }

        new_promoter = PromoterModel(name=promoter.data['name'])

        new_promoter.users.append(user)

        try:
            new_promoter.save_to_db()
            ret = promoter_schema.dump(new_promoter)
            return ret.data
        except:
            return {'message': 'Something went wrong'}, 500
Exemplo n.º 19
0
    def post(self):
        parser.add_argument('usrId', help='usrId missing', required=True)
        parser.add_argument('pwd', help='pwd missing', required=True)
        parser.add_argument('noTel', help='noTel missing', required=True)
        parser.add_argument('correo', help='correo missing', required=True)
        data = parser.parse_args()
        current_user = UserModel.find_by_username(data['usrId'])
        if (not current_user):
            return {'message': 'Wrong credentials'}
        if (current_user.verify_hash(data['pwd'], current_user.pwd)):
            current_user.noTel = data['noTel']
            current_user.correo = data['correo']
            current_user.save_to_db()
            jsonUser = {
                'usrId': current_user.usrId,
                'nomUsr': current_user.nomUsr,
                'noTel': current_user.noTel,
                'correo': current_user.correo,
                'rfcTutor': current_user.rfcTutor,
                'fechaAlta': current_user.fechaAlta,
                'idTipoUsr': current_user.idTipoUsr
            }
            access_token = create_access_token(identity=jsonUser)
            #access_token = create_access_token(identity=data['usrId'])
            refresh_token = create_refresh_token(identity=jsonUser)
            return {
                'message': 'logged in as {} '.format(current_user.usrId),
                'access_token': access_token,
                'refresh_token': refresh_token
            }

        else:
            return {'message': 'Wrong credentials'}
Exemplo n.º 20
0
    def delete(self):
        return UserModel.delete_all()


#class UserLogoutAccess(Resource):
#    @jwt_required
#    def post(self):
#        jti = get_raw_jwt()['jti']
#        try:
#            revoked_token = RevokedTokenModel(jti=jti)
#            revoked_token.add()
#            return {'message': 'Access token has been revoked'}
#        except:
#            return {'message': 'Something went wrong'}, 500

#class UserLogoutRefresh(Resource):
#    @jwt_refresh_token_required
#    def post(self):
#        jti = get_raw_jwt()['jti']
#        try:
#            revoked_token = RevokedTokenModel(jti=jti)
#            revoked_token.add()
#            return {'message': 'Refresh token has been revoked'}
#        except:
#            return {'message': 'Something went wrong'}, 500
Exemplo n.º 21
0
def signup_view(request):
    if request.method == 'POST':
        signup_form =SignUpForm(request.POST)
        if signup_form.is_valid():
            username = signup_form.cleaned_data['username']
            name= signup_form.cleaned_data['name']
            email= signup_form.cleaned_data['email']
            password = signup_form.cleaned_data['password']
            user = UserModel(name=name, password =make_password(password),email =email,username= username)
            user.save()
            return render(request, 'success.html')

    else:
        signup_form= SignUpForm()

    return render(request,'index.html',{'signup_form':signup_form})
Exemplo n.º 22
0
def initial_set():
    identity = get_raw_jwt()['identity']
    print(identity)
    data = None
    files = request.files
    if 'image' not in files:
        print("File not in request.file")
        return redirect(request.url)
    file = files['image']
    user = UserModel.find_by_username(identity)
    if file:
        try:
            img = Image.open(file)
            img.save(
                os.path.join(app.config['UPLOAD_FOLDER'] + identity + '/',
                             'initial.jpg'))
            data = initialize(
                os.path.join(app.config['UPLOAD_FOLDER'] + identity + '/',
                             'initial.jpg'), identity)

        except Exception as e:
            print(e)
            print(traceback.format_exc())
            return {'message': 'Error in initialization'}, 500

        try:
            user.normalPosture = json.dumps(data)
        except Exception as e:
            print(e)
            print(traceback.format_exc())
            return {'message': 'Failure'}, 500
        finally:
            user.save_to_db()
            return {'message': 'Success'}, 200
Exemplo n.º 23
0
def login():
	login_form = LoginForm()
	username = session.get('username')

	context = {
		'login_form': login_form,
		'username': username
	}

	if current_user is True:
		return redirect(url_for('dashboard'))

	if login_form.validate_on_submit():
		username = login_form.username.data
		password = login_form.password.data

		user_doc = get_user(username)

		if user_doc.to_dict() is not None:
			password_from_db = user_doc.to_dict()['password']

			if password == password_from_db:
				user_data = UserData(username, password)
				user = UserModel(user_data)

				login_user(user)
				flash('Login success')

				return redirect(url_for('dashboard'))
			else:
				flash('Information does not match')
		else:
			flash('User does not exist')

	return render_template('login.html', **context)
Exemplo n.º 24
0
def sendReport():
    identity = get_raw_jwt()['identity']
    user = UserModel.find_by_username(identity)
    postures = PostureModel.find_by_userid(user.id)
    result = [0, 0, 0, 0]  # normal, FHP, scoliosis, slouch
    level = [1, 1, 1, 1]
    for posture in postures:
        jsonData = json.loads(posture.postureData)
        MFP = int(jsonData['MFP'])
        result[MFP] += 1

    for idx, count in enumerate(result):
        if idx == 0:
            continue
        if count > 20:
            level[idx] = 2
        if count > 50:
            level[idx] = 3

    return {
        'message': "Success",
        "Normal": str(result[0]),
        "FHP": str(result[1]),
        "Scoliosis": str(result[2]),
        "Slouch": str(result[3]),
        "FHPLevel": str(level[1]),
        "SlouchLevel": str(level[3]),
        "ScoliosisLevel": str(level[2])
    }, 200
Exemplo n.º 25
0
    def dispatch_request(self, user_id):
        users = UserModel.query().order(UserModel.user_last_name)
        user = filter(lambda x: x.key.id()==user_id, users)[0]
        households = list(set([x.user_household for x in users]))

        #user = UserModel.get_by_id(user_id)

        form = UserForm(obj=user)
        if request.method == "POST":
            if form.validate_on_submit():
                user.user_first_name = form.data.get('user_first_name')
                user.user_last_name = form.data.get('user_last_name')
                user.user_email = form.data.get('user_email')
                user.user_phone = phonenumbers.format_number(
                    phonenumbers.parse(form.data.get('user_phone'), region='US'),
                    phonenumbers.PhoneNumberFormat.E164
                )
                user.user_admin = form.data.get('user_admin')
                user.user_household = form.data.get('user_household')
                user.user_house_manager = form.data.get('user_house_manager')
                user.user_is_adult = form.data.get('user_is_adult')
                user.user_is_managed = form.data.get('user_is_managed')
                user.put()
                flash(u'User %s successfully saved.' % user_id, 'success')
                return redirect(url_for('list_users'))
        return render_template(
            'edit_user.html',
            user=user,
            form=form,
            auth=session.get('user', {}),
            households=households
        )
Exemplo n.º 26
0
 def put(self, user_id):
     data = parser.parse_args()
     current_user = get_jwt_identity()
     if current_user == int(user_id):
         return UserModel.edit_user(data, user_id)
     else:
         return {'message': 'Something went wrong!'}
Exemplo n.º 27
0
class UserHandler(BaseHandler):
  def __init__(self, application, request, **kwargs):
    self._users = UserModel()
    super(UserHandler, self).__init__(application, request, **kwargs)

  def get(self):
    if self.current_user:
      return self.redirect('/')
    return self.render('login.html')

  def post(self):
    account = self.get_body_argument("usrn", None)
    passwd = self.get_body_argument("pswd", None)
    if not account or not passwd:
      return self.render('result.html', message = {
                                                    u"error": 1,
                                                    u"content": u"请输入用户名和密码"
                                                  }, redirect = '/login')
    user_id = self._users.login(account, passwd)
    if not user_id:
      return self.render('result.html', message = {
                                                    u"error": 2,
                                                    u"content": u"用户名或密码错误"
                                                  }, redirect = '/login')
    self.set_current_user(user_id)
    return self.render('result.html', message = {
                                                  u"error": 0,
                                                  u"content": u"登录成功"
                                                }, redirect = '/')
Exemplo n.º 28
0
 def test_login_failed(self):
     usr = UserModel(
         username = self.first_user.username,
         password = random_string(7)
     )
     response_body = UserApi.login_user(usr).json()
     self.check_error(response_body, "Login failed")
Exemplo n.º 29
0
 def mutate(root, info, input):
     user = UserModel(input)
     # ok = graphene.Boolean()
     db_session.add(user)
     db_session.commit()
     
     return CreateUser(user=user)        
Exemplo n.º 30
0
    def get(self):
        current_user = get_jwt_identity()
        logged_user = UserModel.find_by_username(current_user)

        db_result = OrderModel.find_valid_by_user(logged_user)

        result = list()
        for item in db_result:
            menu_list = list()
            for menu in item.menus:
                menu_list.append({
                    'menu_id': menu.menu.id,
                    'menu_name': menu.menu.name,
                    'taste_level': menu.menu.taste_level,
                    'water_level': menu.menu.water_level,
                    'foam_level': menu.menu.foam_level,
                    'grind_size': menu.menu.grind_size,
                    'menu_type': menu.menu.menu_type,
                    'coffee_option': menu.menu.coffee_option,
                    'counts': menu.counts
                })
            result.append({
                'order_id':
                item.id,
                'order_contents':
                menu_list,
                'order_date':
                item.create_date.strftime("%Y-%m-%d %H:%M:%S")
            })

        return result
Exemplo n.º 31
0
    def post(self):
        data = parser.parse_args()
        current_user = UserModel.find_by_email(data['email'])
        if not current_user:
            return {
                'message': "Email {} doesn't exist".format(data['email'])
            }, 401

        # Verify user is active
        if not current_user.active:
            return {
                'message': "Email {} is not yet verified".format(data['email'])
            }, 401

        # If the password matches, generate and send the token
        if current_user.verify_password(data['password']):
            access_token = create_access_token(identity=data['email'])
            refresh_token = create_refresh_token(identity=data['email'])
            return {
                'message': 'Logged in as {}'.format(current_user.email),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        else:
            return {'message': "Wrong credentials"}, 401
Exemplo n.º 32
0
    def get(self):

        user = UserModel.find_by_username(email=get_jwt_identity())
        results = []
        company = CompanyModel.find_by_id(id=user.id_company)
        if (company == None):
            return {'data': []}
        else:
            #return jsonify(json_list = questions)
            return {
                "id": company.id,
                "sector": company.sector,
                "subsector": company.subsector,
                "commercial_name": company.commercial_name,
                "fiscal_name": company.fiscal_name,
                "nif": company.nif,
                "number_survey": company.number_survey,
                "duplication_survey": company.duplication_survey,
                "name_surname": company.name_surname,
                "telephone_number": company.telephone_number,
                "description": company.description,
                "comarca": company.comarca,
                "territori_leader": company.territori_leader,
                "number_workers": company.number_workers
            }
Exemplo n.º 33
0
def init():
    user = UserModel(name="Lawrence Moore",
                     username="******",
                     url="https://www.facebook.com/lawrence.moore.94",
                     profile="origin")
    dbhelper = DBHelper()
    dbhelper.save_user(user=user)
Exemplo n.º 34
0
 def get(self):
     user = UserModel.find_by_username(email=get_jwt_identity())
     results = []
     company = CompanyModel.find_by_id(id=user.id_company)
     items = SurveyCompanyModel.find_by_company_id(
         id_company=user.id_company)
     if (len(items) == 0):
         return {'data': []}
     else:
         #return jsonify(json_list = questions)
         for item in items:
             results.append({
                 "id":
                 item.id,
                 "id_survey":
                 item.id_survey,
                 "name_survey":
                 item.name_survey,
                 "id_company":
                 item.id_company,
                 "status":
                 item.status,
                 "score":
                 item.score,
                 "last_modified":
                 item.last_date.strftime('%m/%d/%Y %H:%M'),
                 "version":
                 item.version
             })
         return results
Exemplo n.º 35
0
def authorize():
    try:
        t = Token(request.args.get('code'), request.args.get('redirect_uri'),
                  os.environ['SLACK_CLIENT_ID'],
                  os.environ['SLACK_CLIENT_SECRET'])
    except KeyError:
        session['error'] = 'Missing required params during authorization!'
        return redirect(url_for('failed'))

    try:
        response = t.generate_token()
        if not response:
            return redirect(url_for('unavailable'))

        um = UserModel.query.filter_by(user_id=response['user_id']).first()
        if not um:
            db.session.add(
                UserModel(user_id=response['user_id'],
                          token=response['access_token']))
        else:
            um.token = response['access_token']
        db.session.commit()
        session['current_user'] = response['user_id']
        return redirect(url_for('setup'))
    except KeyError:
        if 'error' in response:
            session['error'] = response['error']
Exemplo n.º 36
0
    def post(self):
        data = loginParser.parse_args()
        current_user = UserModel.find_by_username(data['username'])
        if not current_user:
            return {'message': 'User {} doesn\'t exist'.format(data['username'])}

        if UserModel.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity = data['username'])
            refresh_token = create_refresh_token(identity = data['username'])
            return {
            'message': 'Logged in as {}'.format(current_user.username),
            'access_token': access_token,
            'refresh_token': refresh_token,
            }
        else:
            return {'message': 'Wrong credentials'}
Exemplo n.º 37
0
    def put(self, event_id):
        data = request.get_json()
        if data == None:
            return {"sucess": "false"}
        event = EventModel.get(event_id)
        new_data = {}
        if 'status' in data:
            new_data['status'] = data['status']

        event.update(**new_data, updated_at=datetime.now())
        res = event.to_dict()
        if event.status == 'real_fire':
            loc = event.location.split(",")
            for i in UserModel.telephones(loc[0], loc[1]):
                print(i)
                send_sms(i, 'Warning Fire near location. Caution is advised.')
            for i in authorities_telephones:
                send_sms(
                    i,
                    'Warning wildfire detected. Emergency response is advised.'
                )
        if event.status == 'panic_accept':
            send_sms(
                fire_man_phone, 'Emergency Assistance needed at ' +
                'https://www.google.com/maps/@' + event.location + ',15z')
            send_sms(victim, 'Assistance is on your way!!')
        res['id'] = event.meta.id

        return res
Exemplo n.º 38
0
    def post(self):
        data = parser.parse_args()
        current_user = UserModel.find_by_username(data['username'])

        if not current_user:
            return {'message': 'User {} does not exists'.format(data['username'])}
        if not UserModel.verify_hash(data['password'], current_user.password):
            return {'message': 'wrong credentials'}
        
        ## 여기서 만들자
        access_token = create_access_token(identity=data['username'])
        refresh_token = create_refresh_token(identity=data['username'])
        
        return {'message': 'Loged in as {}'.format(data['username']),
                'access_token': access_token,
                'refresh_token': refresh_token}
 def dispatch_request(self, user_id, speech_percent):
     user = UserModel.get_by_id(int(user_id))
     user.speech_percent = float(speech_percent)
     user.put()
     u_dict = user.to_dict()
     u_dict["user_id"] = user.key.id()
     del u_dict["timestamp"]
     return json.dumps(u_dict)
    def dispatch_request(self, user_id, other_id, grading):
        if grading == "0":
            grading = str(random.randrange(0,5))
        else:
            grading = str(random.randrange(5,10))
        user = UserModel.get_by_id(int(user_id))
        other = UserModel.get_by_id(int(other_id))
        sim = user.cal_sim(other)
        features = json.loads(user.features)
        grade_his = json.loads(user.grades)
        sim_in_feature = [sim[i] for i in features]
        sim_str = str(sim_in_feature)
        if sim_str in grade_his:
            grade_his[sim_str] = grading
        else:
            if len(grade_his) > 15:
                del(grade_his[grade_his.keys()[0]])
            grade_his[sim_str] =  grading
        user.grades = json.dumps(grade_his)

        if len(grade_his) >= 3:
            import numpy as np
            x = []
            y = []
            for key, value in grade_his.items():
                x.append(json.loads(key))
                y.append(int(value))
            xMat = np.mat(x)
            yMat = np.mat(y).T
            xTx = xMat.T * xMat
            if np.linalg.det(xTx) == 0.0:
                #user.put()
                return "canot do inverse" + json.dumps(user.grades)

            weights_learnt_matrix = xTx.I*(xMat.T*yMat)
            weights_learnt = [a[0] for a in weights_learnt_matrix.tolist()]
            weights = [0] * 7
            for i in range(len(weights_learnt)):
                weights[features[i]] = weights_learnt[i]
            user.weights = json.dumps(weights)

        user.put()
        u_dict = user.to_dict()
        u_dict["user_id"] = user.key.id()
        del u_dict["timestamp"]
        return json.dumps(u_dict)
 def dispatch_request(self, user_id, willing):
     user = UserModel.get_by_id(int(user_id))
     user.willing = int(willing)
     user.put()
     u_dict = user.to_dict()
     u_dict["user_id"] = user.key.id()
     del u_dict["timestamp"]
     return json.dumps(u_dict)
Exemplo n.º 42
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = UserModel.query(UserModel.username==username, UserModel.password==password).get()
        if user and user.role == ROLES['EXHIBITOR']:
            result = flask_login.login_user(user)
    return redirect(url_for('exhibitor.index'))
Exemplo n.º 43
0
 def deleteUser(self, meta, username):
     userModel = UserModel.gql('where username = :1', username).get()
     
     @transactional
     def deleteUserModel(userModel):
         if userModel:
             userModel.delete()
             
     deleteUserModel(userModel)
Exemplo n.º 44
0
    def getFollowingUser(self, userName):
        result = []
        cursor = 0
        while True:
            r = self._apiClient.friendships.friends.get(screen_name=userName, cursor=cursor, count=200)
            if len(r.users) == 0:
                break
            for user in r.users:
                userModel = UserModel()
                userModel.id = user.id
                userModel.name = user.screen_name
                result.append(userModel)
            if r.next_cursor == 0:
                break
            else:
                cursor = r.next_cursor

        return result
 def dispatch_request(self, user_id):
     user = UserModel.get_by_id(int(user_id))
     if request.method == "POST":
         try:
             user.key.delete()
             flash(u'User %s successfully deleted.' % user_id, 'success')
             return redirect(url_for('admin_list_users'))
         except CapabilityDisabledError:
             flash(u'App Engine Datastore is currently in read-only mode.', 'info')
             return redirect(url_for('admin_list_users'))
Exemplo n.º 46
0
 def test(self, meta):
     userModels = UserModel.all()
     # userModel = UserModel.all().get()
     # userModels = UserModel.all().fetch(10)
     
     @transactional
     def testUserModel(userModel):
         pass
     
     testUserModel(userModels)
 def dispatch_request(self, user_id):
     user = UserModel.get_by_id(user_id)
     form = UserForm(obj=user)
     if request.method == "POST":
         if form.validate_on_submit():
             user.name = form.data.get('name')
             user.put()
             flash(u'Example %s successfully saved.' % user_id, 'success')
             return redirect(url_for('list_examples'))
     return render_template('edit_user.html', user=user, form=form)
Exemplo n.º 48
0
def init_admin():
    role = ROLES['ADMIN']
    user = UserModel.query(UserModel.username=='admin').get()

    if user is None:
        #create admin
        password = pwd_context.encrypt('admin')
        admin = UserModel(
            username = '******',
            password = password,
            role = role,
            email = '*****@*****.**',
        )
        try:
            admin.put()
            print 'admin created'
        except CapabilityDisabledError:
            print 'creat fail'
    else:
        print 'admin exists'
Exemplo n.º 49
0
    def test_put_tweets_when_exist_same_user(self):
        data = [mock.Status(21, 20, u'same_user', u'text1'),
                mock.Status(22, 20, u'same_user', u'text2')]

        bot = OmiaiBot()
        bot._put_tweets(data)

        query = UserModel.all()
        users = query.filter('screen_name', u'same_user').fetch(2)

        eq_(len(users), 1)
 def dispatch_request(self, user_id, vib, matched_with=None):
     user = UserModel.get_by_id(int(user_id))
     user.vibrate_status = bool(int(vib))
     if not user.vibrate_status:
         user.matched_with = None
     if matched_with:
         user.matched_with = int(matched_with)
     user.put()
     u_dict = user.to_dict()
     u_dict["user_id"] = user.key.id()
     del u_dict["timestamp"]
     return json.dumps(u_dict)
Exemplo n.º 51
0
def load_user(user_id):
    """
        required by flask_login
        :param user_id: Type: Int
    """
    """
        It should return None (not raise an exception)
        if the ID is not valid.
        (In that case, the ID will manually be removed from the session
         and processing will continue.)
         :param user_id: primary key
    """
    return UserModel.get(user_id)
    def dispatch_request(self, user_id, count):
        my_key = ndb.Key("UserModel", int(user_id))
        user = my_key.get()
        others = []
        if UserModel.query().count() <= 1:
            return json.dumps(others)

        choose_keys = UserModel.query().fetch(keys_only=True)
        if my_key in choose_keys:
            choose_keys.remove(my_key)
        if len(choose_keys) > count:
            choose_keys = random.sample(choose_keys, count)

        dataset = [k.get() for k in choose_keys]
        for other in dataset:
            other_dic = {}
            other_dic["user_id"] = other.key.id()
            other_dic["photo_url"] = other.photo_url
            #other_dic["similarities"] = [random.randrange(1,11) for i in range(7)]
            other_dic["similarities"] = user.cal_sim(other)
            others.append(other_dic)
        return json.dumps(others)
    def dispatch_request(self, user_id):
        result = {}
        result["is_matched"] = False
        result["grades"] = []
        user = UserModel.get_by_id(int(user_id))
        if user.vibrate_status and user.matched_with is not None:
            user.vibrate_status = False
            user.put()
            match = UserModel.get_by_id(int(user.matched_with))
            result["is_matched"] = True
            result["user_id"] = match.key.id()
            result["name"] = match.name
            result["gender"] = match.gender
            result["photo_url"] = match.photo_url
            result["similarities"] = user.cal_sim(match)

        elif user.vibrate_status and user.matched_with is None:
            my_key = ndb.Key("UserModel", int(user_id))
            choose_keys = UserModel.query().fetch(keys_only=True)
            if my_key in choose_keys:
                choose_keys.remove(my_key)
                for choose_key in choose_keys:
                    match = choose_key.get()
                    if match.vibrate_status and match.matched_with is None and user.where is not None and match.where == user.where and user.cal_grade(match) > 10 - user.willing:
                        user.matched_with = match.key.id()
                        user.vibrate_status = False
                        user.put()
                        match.matched_with = int(user_id)
                        match.put()
                        result["is_matched"] = True
                        result["user_id"] = match.key.id()
                        result["name"] = match.name
                        result["gender"] = match.gender
                        result["photo_url"] = match.photo_url
                        result["similarities"] = user.cal_sim(match)
        return json.dumps(result)
 def dispatch_request(self, user_id, features):
     user = UserModel.get_by_id(int(user_id))
     user.features = "[" + features + "]"
     weights = [0] * 7
     features_list = features.split(",")
     for f in features_list:
         weights[int(f)] = 1.0/ len(features_list)
     user.weights = str(weights)
     initial_grade = {"[5,5,5]":"5"}
     user.grades = json.dumps(initial_grade)
     user.put()
     u_dict = user.to_dict()
     u_dict["user_id"] = user.key.id()
     del u_dict["timestamp"]
     return json.dumps(u_dict)
    def dispatch_request(self, user_id, gps):
        # Replace the API key below with a valid API key.
        #return "dafsdfsd"
        try:
            gmaps = googlemaps.Client(key='AIzaSyCNcSw3hYO2wes__ZHHp_emc7v8vsHkaM0')

            # Geocoding and address
            #"geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
            # Look up an address with reverse geocoding
            reverse_geocode_result = gmaps.reverse_geocode(gps)

            types = {"food":1, "gym":2, "cafe":3, "book_store":4, "health":5, "shopping_mall":6, "library":7, "park":8, "university":9}

            places = gmaps.nearest(gps, types=types.keys())

            res = {}
            location_type_index = 0 #unknown
            res["location_type"] = "unknown"  #unknown
            if places and len(places["results"]) > 0:
                for t in places["results"][0]["types"]:
                    if t in types.keys():
                        res["location_type"] = t
                        location_type_index = types[t]

            user = UserModel.get_by_id(int(user_id))
            user.where = reverse_geocode_result[0]["formatted_address"]
            user.gps = gps + ": " + res["location_type"]

            if user.locations is None:
                user.locations = str(location_type_index)
            elif len(user.locations) < 12 * 24:
                user.locations += str(location_type_index)
            else:
                user.locations = user.locations[1:] + str(location_type_index)
            user.put()
        except Exception as e:
            return json.dumps(places["results"]) + e.message

        res["locations"] = user.locations
        return json.dumps(res)
Exemplo n.º 56
0
def signup(request):
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']

            #save into db
            user = UserModel()
            user.username = username
            user.password = password
            user.email = email
            user.save()

            return render_to_response('account_success.html',{'username':username})

    else:
        form = UserForm()
        return render_to_response('account_signup.html',{'form':form})
Exemplo n.º 57
0
 def get(self):
     auth_user = self.auth.get_user_by_session()
     users = UserModel.query(UserModel.key != ndb.Key("UserModel", auth_user["user_id"])).fetch()
     return Response(users)
Exemplo n.º 58
0
 def dequeueUser(self):
     result = UserModel()
     result.name = self._redisClient.lpop(RedisContext.USER_LIST_KEY)
     return result
Exemplo n.º 59
0
def users():
    """
    user management
    """
    users = UserModel.query()
    return render_template('admin/users.html', users=users)
Exemplo n.º 60
0
 def __init__(self, application, request, **kwargs):
   self._users = UserModel()
   super(UserHandler, self).__init__(application, request, **kwargs)