Пример #1
0
class SearchNewHandler(BaseHandler):

    def __init__(self, application, request, **kwargs):
        super(SearchNewHandler, self).__init__(application, request, **kwargs)
        self.user_service = UserService(self.db)

    @tornado.web.authenticated
    def get(self, *args, **kwargs):
        current_username = self.get_secure_cookie(pre_system + 'username')

        current_username_entity = self.user_service.get_user(current_username)
        group_id = current_username_entity.group_id
        avatar = current_username_entity.avatar
        # if group_id == 0:
        #     self.redirect('/admin')
        #     return

        if not avatar:
            avatar = next_uuid()
        filename_url = 'static/img/avatar/{0}.png'.format(avatar)
        if not os.path.exists(filename_url):
            if img_create(avatar):
                current_username_entity.avatar = avatar
                self.user_service.save(current_username_entity)
            else:
                logging.warning('创建头像失败')
                avatar = 'icon'
        self.render('home_new.html', avatar=avatar, username=current_username)
Пример #2
0
def check_user_login_google(request):
    google_user = users.get_current_user()

    user_in_session = request.session.get('user', None)
    isnewuser = False
    if user_in_session == None:
        user, isnewuser = UserService().getorCreateCoolUserByGoogleUser(
            google_user)
        user = UserService().getUser(user)
    else:
        errormessage = UserService().updateGoogleID(user_in_session,
                                                    google_user)
        if errormessage:
            request.session['errormessage'] = errormessage
        user = UserService().getUser(user_in_session)

    request.session['user'] = user
    newmessagecount = UserService().getMessageCount({'isread': False}, user)
    user.newmessagecount = newmessagecount
    UserService().updateCoolUser(user)

    if isnewuser:
        back_to_url = '/setting'
    else:
        back_to_url = request.session.get('login_back_to_url', '/')
    return HttpResponseRedirect(back_to_url)
    def test_get_user_by_email(self):
        u2_email = "*****@*****.**"
        UserService.create_user_with_gmail(u2_email)
        user2a = UserService.get_user_by_email("*****@*****.**")
        user2b = UserService.get_user_by_email("*****@*****.**")

        self.assertEqual(user2a.email, "*****@*****.**")
        self.assertIsNone(user2b)
Пример #4
0
def reg():
    form = request.form
    if form['username'] and form['password']:
        username = form['username']
        password_md5 = hashlib.md5(
            form['password'].encode('utf-8')).hexdigest()
        UserService.regist_user(username, password_md5)
    return 'true'
    def test_check_email_availability(self):
        u1_email = "*****@*****.**"
        UserService.create_user_with_gmail(u1_email)

        self.assertFalse(
            UserService.check_email_availability("*****@*****.**"))
        self.assertTrue(
            UserService.check_email_availability("*****@*****.**"))
Пример #6
0
class UserCreate(Resource):
    def __init__(self, api=user_api):
        self.api = api
        self.service = UserService()

    @jwt_required
    @user_api.doc(description='create user',
                  parser=user_parser,
                  security='jwt')
    @user_api.marshal_with(user_dto)
    def post(self):
        args = user_parser.parse_args()
        name = args['username']
        password = args['password']
        email = args['email']
        if not self.service.is_exist(name):
            self.service.create_user(
                User(username=name, password=password, email=email))
            return self.service.find_user_by_name(name)
        else:
            user_api.abort(202, 'User already exist')

    @jwt_required
    @user_api.doc(description='retrieve user by user id',
                  parser=user_id_parser,
                  security='jwt')
    @user_api.marshal_with(user_dto)
    def get(self):
        args = user_id_parser.parse_args()
        id = args['id']
        user = self.service.find_user_by_id(id)
        if not user:
            user_api.abort(Response('No user found'))
        return user

    @jwt_required
    @user_api.doc(description='update user',
                  parser=update_use_parser,
                  security='jwt')
    def put(self):
        args = update_use_parser.parse_args()
        id = args['id']
        email = args['email']
        username = args['username']
        password = args['password']
        self.service.update_user(
            User(id=id, email=email, username=username, password=password))
        return self.service.find_user_by_id(id)

    @jwt_required
    @user_api.doc(description='delete user',
                  parser=user_id_parser,
                  security='jwt')
    def delete(self):
        args = user_id_parser.parse_args()
        id = args['id']
        self.service.delete_user(id)
        return Response("delete success")
Пример #7
0
def store_agreement():
    #immutableMultidict
    agreementData_dict = request.form.to_dict(flat=False)
    print(agreementData_dict)
    try:
        UserService.store_agreement(agreementData_dict)
        return "success"
    except KeyError:
        return "failure"
Пример #8
0
    def test_save(self):
        u = User(
            username = '******',
            password = '******',
            email = '*****@*****.**'
        )

        us = UserService()
        us.find(5)
Пример #9
0
def store_userInfo():
    #immutableMultidict
    userData_dict = request.form.to_dict(flat=False)
    print("userData_dict", userData_dict)
    try:
        UserService.store_userInfo(userData_dict)
        return "success"
    except KeyError:
        return "failure"
Пример #10
0
def setting(request):
    if not check_user_login(request):
        return login(request)

    user = request.session.get('user')
    if request.method == 'POST':
        form = UserForm(data=request.POST, id=user.id)
        if form.is_valid():
            name = form.cleaned_data['name']
            gender = int(form.cleaned_data['gender'])
            email = form.cleaned_data['email']
            logo = form.cleaned_data['logo']
            isreceivemail = form.cleaned_data['isreceivemail']
            pagecount = form.cleaned_data['pagecount']
            if logo == '':
                logo = None
            UserService().editCoolUser(user.id, name, gender, email, logo,
                                       isreceivemail, pagecount)
    else:
        form = UserForm(initial={
            'name': user.name,
            'gender': user.gender,
            'logo': user.logo,
            'email': user.email,
            'isreceivemail': user.isreceivemail,
            'pagecount': user.pagecount
        },
                        id=user.id)
    '''
    sina_login_url = None
    if not user.sinaid:
        sina_login_url = _createSinaLoginUrl(request)
    '''
    google_login_url = None
    if not user.googleid:
        google_login_url = _createGoogleLoginUrl(request)
    user = UserService().getUser(user)
    request.session['user'] = user
    page_title = ugettext('Setting')
    pageinfo = PageInfo(page_menu_name='Setting',
                        user=user,
                        page_title=page_title)
    helptext_list = AdminService().getCategoryHelpTextList('Setting')
    form_action_url = '/setting/'
    return render_to_response(
        'user_setting.html',
        {
            'pageinfo': pageinfo,
            'form_action_url': form_action_url,
            'form': form,
            'user': user,
            'helptext_list': helptext_list,
            #'sina_login_url': sina_login_url,
            'google_login_url': google_login_url
        })
Пример #11
0
    def test_create_user_with_email_repeating_email(self):
        u1_email = "*****@*****.**"

        u2_email = "*****@*****.**"
        print("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE")

        user1 = UserService.create_user_with_gmail(u1_email)
        print(user1)

        self.assertEqual(user1.email, u1_email)

        self.assertFalse(UserService.create_user_with_gmail(u2_email))
Пример #12
0
def get_user_setting(email):
    print("Getting setting emails...")
    data = service.get_other_setting(email)

    # data is never None
    # if data is None:
    #     return jsonify({})

    # Create user setting if it does not exist
    if len(data) == 0:
        service.save_other_setting({"email": email})  # Create user setting
        data = service.get_other_setting(email)

    return data[0].to_json()
Пример #13
0
 def on_reset_password_pushButton_clicked(self):
     selected = self.users_tableView.selectionModel()
     if selected:
         indexes = selected.selectedRows()
         for index in indexes:
             try:
                 userid_index = self.rest_data_model.index(
                     index.row(), 0, QtCore.QModelIndex())
                 userid = self.rest_data_model.data(userid_index,
                                                    QtCore.Qt.DisplayRole)
                 name_index = self.rest_data_model.index(
                     index.row(), 1, QtCore.QModelIndex())
                 name = self.rest_data_model.data(name_index,
                                                  QtCore.Qt.DisplayRole)
                 r = UserService.reset_password(self.session, userid)
                 QtWidgets.QMessageBox.about(
                     self, _translate("UserManage", "info"),
                     _translate(
                         "UserManage",
                         "The password of user ({}) had be reset to 123456"
                     ).format(name))
             except Exception as e:
                 QtWidgets.QMessageBox.warning(
                     self, _translate("UserManage", "error"), str(e))
                 return
Пример #14
0
def create_app(test_config=None):
    app = Flask(__name__)
    app.config['JSON_AS_ASCII'] = False
    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    ## Persistenace Layer
    user_dao = UserDao(database)
    status_dao = StatusDao(database)

    ## Business Layer
    services = Services
    services.user_service = UserService(user_dao, config)
    services.status_service = StatusService(status_dao)

    ## 엔드포인트들을 생성
    create_endpoints(app, services)

    return app
Пример #15
0
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    # Persistenace Layer
    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    # Business Layer
    s3_client = boto3.client("s3",
                             aws_access_key_id=app.config['S3_ACCESS_KEY'],
                             aws_secret_access_key=app.config['S3_SECRET_KEY'])

    services = Services
    services.user_service = UserService(user_dao, app.config, s3_client)
    services.tweet_service = TweetService(tweet_dao)

    # 엔드포인트들을 생성
    create_endpoints(app, services)

    return app
Пример #16
0
def login(request):
    if check_user_login(request):
        user = UserService().getUser(request.session.get('user', None))
        request.session['user'] = user
        return HttpResponseRedirect('/')

    if request.path == '/login/' or request.path == '/logout/':
        login_back_to_url = '/'
    else:
        login_back_to_url = request.path

    request.session['login_back_to_url'] = login_back_to_url

    google_login_url = _createGoogleLoginUrl(request)
    #sina_login_url = _createSinaLoginUrl(request)
    errormessage = request.session.get('errormessage', None)
    request.session['errormessage'] = None

    return render_to_response(
        'user_login.html',
        {
            'google_login_url': google_login_url,
            #'sina_login_url':sina_login_url,
            'errormessage': errormessage
        })
Пример #17
0
def update_medicine_stock(medicine_id):
    # check if the len of request.json is greater than 0. An empty array delivers a len of 0
    if not len(request.json) == 0 and (
            not request.json or not medicine_id
            or not request.headers.get('Authorization')):
        abort(400)

    username = __username()
    stock_dict = request.json

    userService = UserService.UserService()
    me = userService.get_me(username)

    if not me:
        abort(404)

    medicineService = MedicineService.MedicineService()
    medicine = medicineService.get_medicine_by_id(medicine_id)

    if not medicine:
        abort(404)

    try:
        stockService = StockService.StockService()
        print(me)
        response = stockService.update_stock(medicine_id, me['user_id'],
                                             stock_dict)
        return jsonify(response), 200
    except Error.NotFoundError as err:
        abort(404)
Пример #18
0
def create_app():
    """

    Returns :
        생성된 플라스크 앱 객체

    Authors :
        [email protected] (손수정)

    History :
        2020-08-19 ([email protected]) : 초기 생성

    """

    app = Flask(__name__)
    #CORS 설정
    CORS(app)
    #config 설정
    app.config.from_pyfile("config.py")
    # DAO 생성
    user_dao = UserDao()
    # Service 생성
    user_service = UserService(user_dao)
    # view blueprint 등록
    app.register_blueprint(create_user_endpoints(user_service))
    app.register_blueprint(create_admin_user_endpoints(user_service))

    return app
Пример #19
0
class AuthLogin(Resource):
    def __init__(self, api=auth_api):
        self.api = api
        self.service = UserService()

    @auth_api.doc(description='login auth', parser=login_parser)
    def post(self):
        args = login_parser.parse_args()
        name = args['username']
        password = args['password']
        logger.info("user %s login", name)
        user = self.service.find_user_by_name(name)
        if user and user.check_password(password):
            access_token = create_access_token(identity=user.id)
            refresh_token = create_refresh_token(identity=user.id)
            # Store the tokens in our store with a status of not currently revoked.
            add_token_to_database(access_token,
                                  app.config['JWT_IDENTITY_CLAIM'])
            add_token_to_database(refresh_token,
                                  app.config['JWT_IDENTITY_CLAIM'])
            ret = {
                'access_token': access_token,
                'refresh_token': refresh_token
            }
            return ret
        else:
            return Response('Auth failed')
Пример #20
0
def add_new_user():
    user_data = request.json

    print(user_data)
    UserService().add_new(email=user_data["email"],
                          name=user_data["name"],
                          secret=user_data["secret"])

    user = UserService().find_by_email(user_data["email"]).one()

    return jsonify({
        "user_id": user.id,
        "email": user.email,
        "key": user.key,
        "name": user.name,
    })
Пример #21
0
 def on_remove_pushButton_clicked(self):
     selected = self.users_tableView.selectionModel()
     if selected:
         indexes = selected.selectedRows()
         for index in indexes:
             try:
                 userid_index = self.rest_data_model.index(
                     index.row(), 0, QtCore.QModelIndex())
                 userid = self.rest_data_model.data(userid_index,
                                                    QtCore.Qt.DisplayRole)
                 name_index = self.rest_data_model.index(
                     index.row(), 1, QtCore.QModelIndex())
                 name = self.rest_data_model.data(name_index,
                                                  QtCore.Qt.DisplayRole)
                 r = QtWidgets.QMessageBox.information(
                     self, _translate("UserManage", "Confirm"),
                     _translate(
                         "UserManage",
                         "Are you sure to remove the user ({})?").format(
                             name),
                     QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
                 if r == QtWidgets.QMessageBox.No:
                     return
                 r = UserService.remove_user(self.session, userid)
             except Exception as e:
                 QtWidgets.QMessageBox.warning(
                     self, _translate("UserManage", "error"), str(e))
                 return
             self.rest_data_model.removeRows(index.row(), 1,
                                             QtCore.QModelIndex())
Пример #22
0
def create_app(test_config=None):
    app = Flask(__name__)
    app.config['JSON_AS_ASCII'] = False

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    product_dao = ProductDao()
    seller_dao = SellerDao()
    order_dao = OrderDao()
    user_dao = UserDao()
    coupon_dao = CouponDao()
    event_dao = EventDao()

    services = Services

    services.product_service = ProductService(product_dao, app.config)
    services.seller_service = SellerService(seller_dao, app.config)
    services.order_service = OrderService(order_dao, app.config)
    services.user_service = UserService(user_dao, app.config)
    services.coupon_service = CouponService(coupon_dao, app.config)
    services.event_service = EventService(event_dao, app.config)

    create_endpoints(app, services)

    return app
Пример #23
0
def create_app(test_config=None):

    app = Flask(__name__)

    #SetUp config
    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.update(test_config)

    # database engin와 연동된 session maker 생성, connection 필요시마다 session instance 생성
    database = create_engine(DB_URL,
                             encoding='utf-8',
                             pool_size=10,
                             max_overflow=5,
                             poolclass=QueuePool)

    Session = sessionmaker(bind=database)
    session = Session()

    #SetUp CORS
    CORS(app)

    #SetUp Persistence Layer
    user_dao = UserDao()

    #SetUp Business Layer
    services = Services
    services.user_service = UserService(user_dao)

    #SetUp Presentation Layer
    create_endpoints(app, services, session)

    return app
Пример #24
0
    def findAssetId(self, srcAccount):

        userInfo = srcAccount
        userService = UserService.UserService()
        userAssetArray = userService.findAssetId(userInfo.address)

        return userAssetArray
Пример #25
0
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        # app.config.from_pyfile("config.py")
        app.config.update({
            'DB': config.db,
            'DB_URL': config.db_url,
            'JWT_SECRET_KEY': config.jwt_secret_key
        })
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    services = Services
    services.user_service = UserService(user_dao, app.config)
    services.tweet_service = TweetService(tweet_dao)

    create_endpoints(app, services)

    return app
Пример #26
0
 def openUserManageTab(self, session):
     """用户管理"""
     title = "{}({})".format(self.tab_title_user_manage, session.name)
     if title not in self.tabs or self.tabs[title] is None:
         if not session.running:
             QtWidgets.QMessageBox.warning(
                 self, _translate("MainWindow", "info"),
                 _translate("MainWindow", "The server is disconnected. Please connect first!")
             )
         else:
             try:
                 data = RestDataTableModel(
                     ['userid', 'name', 'start_time'], [
                         _translate("UserManage", "userid"),
                         _translate("UserManage", "name"),
                         _translate("UserManage", "start_time")
                     ], UserService.query_users(session)
                 )
                 print(data)
             except Exception as e:
                 logging.error(e)
                 QtWidgets.QMessageBox.warning(
                     self, _translate("MainWindow", "error"), "{}: {}".format(e.__class__.__name__, e)
                 )
                 return
             tab = HkuUserManagerWidget(session, data, self.main_tab)
             self.main_tab.addTab(tab, title)
             self.tabs[title] = tab
Пример #27
0
def create_app(test_config=None):

    app = Flask(__name__)

    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    s3_client = boto3.client('s3',
                             aws_access_key_id=app.config['S3_ACCESS_KEY'],
                             aws_secret_access_key=app.config['S3_SECRET_KEY'])
    services = Services
    services.user_service = UserService(user_dao, app.config, s3_client)
    services.tweet_service = TweetService(tweet_dao)

    create_endpoints(app, services)

    return app
Пример #28
0
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)

    ## Persistenace Layer
    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    ## Business Layer
    services = Services
    services.user_service = UserService(user_dao, config)
    services.tweet_service = TweetService(tweet_dao)

    ## Create Endpoints
    create_endpoints(app, services)

    return app
Пример #29
0
def login():
    user = request.json

    if user != None:
        try:
            db_user = UserService.getUserByUsername(user.get("username"))

            if Bcrypt.check_password_hash(db_user["password"],
                                          user["password"]):

                out = {
                    "username": db_user["username"],
                    "email": db_user["email"],
                    "group": db_user["group"]
                }

                return {"msg": "Successful login", "data": out}, 200

            else:
                return {"msg": "Unsuccessful login"}

        except Exception as e:
            return {
                "msg": f"Error trying to authenticate user {user['username']}",
                "Error": e
            }, 422
Пример #30
0
def create_app(test_config = None):
    app = Flask(__name__)

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database =create_engine(app.config['DB_URL'], encoding='utf-8', max_overflow =0 )

    ## Persistence layer
    user_dao = UserDao(database)
    tweet_dao = TweetDao(database)

    ## Business layer
    services =Services
    services.user_service = UserService(user_dao, app.config)
    services.tweet_service = TweetService(tweet_dao)

    ## 엔드포인트 생성
    create_endpoints(app, services)

    # persistence, business, presentation layer 모두 연결된 flask application 생성
    return app
Пример #31
0
def check_user_login_sina(request):
    try:
        oauth_verifier = request.GET.get('oauth_verifier', None)
        request_token = request.session.get('oauth_request_token', None)
        request.session['oauth_request_token'] = None
        
        auth=OAuthHandler(consumer_key, consumer_secret)
        
        auth.request_token=request_token
        access_token=auth.get_access_token(oauth_verifier)
    
        request.session['oauth_access_token'] = access_token
        
        api = API(auth)
        sina_user = api.me()
        
        user_in_session = request.session.get('user', None)
        isnewuser = False
        if user_in_session == None:
            user, isnewuser = UserService().getorCreateCoolUserBySinaUser(sina_user)
            user = UserService().getUser(user)
        else:
            errormessage = UserService().updateSinaID(user_in_session, sina_user)      
            if errormessage:
                request.session['errormessage'] = errormessage      
            user = UserService().getUser(user_in_session)
            
        request.session['user'] = user
        newmessagecount = UserService().getMessageCount({'isread':False}, user)
        user.newmessagecount = newmessagecount
        UserService().updateCoolUser(user)
        
        if isnewuser:
            back_to_url = '/setting'
        else:
            back_to_url = request.session.get('login_back_to_url', '/')
        
        return HttpResponseRedirect(back_to_url)
    except WeibopError:
        errormessage = ugettext('Auth sina twitter account failed, please retry.')
        request.session['errormessage'] = errormessage
        return login(request)
Пример #32
0
    def post(self):
        have_error = False
        self.username = self.request.get("username")
        self.password = self.request.get("password")
        self.verify = self.request.get("verify")
        self.email = self.request.get("email")

        params = dict(username=self.username,  # dictionary for all errors
                      email=self.email)

        if not UserService.valid_username(self.username):
            params['username_error'] = 'Invalid username'
            have_error = True

        if not UserService.valid_password(self.password):
            params['password_error'] = 'Invalid password'
            have_error = True
        elif self.password != self.verify:
            params['password_mismatch_error'] = 'Passowrds do not match'
            have_error = True

        if not UserService.valid_email(self.email):
            params['email_error'] = 'Invalid email'
            have_error = True

        if have_error:
            self.render("signup.html", **params)

        else:
            u = User.by_name(self.username)
            if u:
                msg = 'The user already exists'
                self.render('signup.html', username_error=msg)
            else:
                u = UserService.register(
                    self.username,
                    self.password,
                    self.email
                )
                u.put()
                self.set_secure_cookie("user_id", str(u.key().id()))
                self.redirect("/blog")
Пример #33
0
    def post(self):
        username = self.request.get("username")
        password = self.request.get("password")

        u = UserService.validate_login(username,password)

        if u:
            self.login(u)
            self.redirect("/blog")
        else:
            msg = "Invalid login"
            self.write_form(username_error=msg)
Пример #34
0
def check_user_login_google(request):
    google_user = users.get_current_user()
    
    user_in_session = request.session.get('user', None)
    isnewuser = False
    if user_in_session == None:
        user, isnewuser = UserService().getorCreateCoolUserByGoogleUser(google_user)    
        user = UserService().getUser(user)
    else:
        errormessage = UserService().updateGoogleID(user_in_session, google_user)  
        if errormessage:
            request.session['errormessage'] = errormessage           
        user = UserService().getUser(user_in_session)
                    
    request.session['user'] = user
    newmessagecount = UserService().getMessageCount({'isread':False}, user)
    user.newmessagecount = newmessagecount
    UserService().updateCoolUser(user)
    
    if isnewuser:
        back_to_url='/setting'
    else:
        back_to_url = request.session.get('login_back_to_url', '/')
    return HttpResponseRedirect(back_to_url)