Ejemplo n.º 1
0
 def __init__(self):
     AccountModel.sync()
     self.__options: Dict[str, View] = {
         'i': InsertAccountView(),
         'l': ListAccountServicesView(),
         'r': ListAccountsByServiceView()
     }
Ejemplo n.º 2
0
def update_account(name):
    account = Account(name).export(load_extras=False)
    prepare_account(account)

    # TODO Parse coordinates
    # parse_location(account)

    AccountModel.objects(name=name).update(**account, upsert=True)
    def on_delete(self, req, resp):
        """
        DEVELOPMENT ONLY!

        Delete the account, and all the files belong to this account
        """
        logging.debug('in account delete')
        resp_dict = {}

        try:
            username = req.get_header('username') or ''
            password = req.get_header('password') or ''
            # email = req.get_header('email') or 'email'
            # params = req.get_param_as_list()
            # logging.debug('params:%s'%params)
            logging.debug('username:%s, password:%s' %
                (username, password))
        except:
            raise falcon.HTTPBadRequest('bad req',
                'when read from req, please check if the req is correct.')

        try:
            # user = AccountModel.get(AccountModel.username==username,
            #                             AccountModel.password==password)
            user = AccountModel.auth(username, password)
            logging.debug('delete after auth user')

            conn = swiftclient.client.Connection(self.conf.auth_url,
                            user.keystone_tenant+':'+user.keystone_username,
                                  user.password,
                                  auth_version=self.conf.auth_version)
            # for container in self.conf.services:
            #     conn.delete_container(username+'_'+container)
            logging.debug('delete after con swift user')

            keystonewrap.delete_user(user.keystone_tenant,
                    user.keystone_username,
                    user.keystone_password)
            logging.debug('after delete keytone user')
            q = AccountModel.delete().where(AccountModel.username==username,
                    AccountModel.password==password)
            q.execute()
            resp_dict['info'] = 'user:%s deleted successfully' % username
            resp_dict['username'] = username
            resp.status = falcon.HTTP_200

        except:
            logging.debug('in delete user Exception')
            resp_dict['info'] = 'delete user:%s not successfully' % username
            resp.status = falcon.HTTP_400
        resp.body = json.dumps(resp_dict, encoding='utf-8',
            sort_keys=True, indent=4)
Ejemplo n.º 4
0
 def put(self, id):
     self.abort_if_account_doesnt_exist(id)
     account = AccountModel.fromData(db.get(id))
     print(account.name)
     parser = reqparse.RequestParser()
     parser.add_argument('type', type=str)
     parser.add_argument('number', type=str)
     parser.add_argument('name', type=str)
     parser.add_argument('first_name', type=str)
     parser.add_argument('address', type=str)
     parser.add_argument('birthdate', type=str)
     args = parser.parse_args()
     if 'type' in args and args['type'] != None:
         account.type = args['type']
     if 'number' in args and args['number'] != None:
         account.number = args['number']
     if 'name' in args and args['name'] != None:
         account.name = args['name']
     if 'first_name' in args and args['first_name'] != None:
         account.first_name = args['first_name']
     if 'address' in args and args['address'] != None:
         account.address = args['address']
         location = geolocator.geocode(args['address'])
         if location != None:
             account.latitude = location.latitude
             account.longitude = location.longitude
         else:
             account.latitude = None;
             account.longitude = None;
     if 'birthdate' in args and args['birthdate'] != None:
         account.birthdate = args['birthdate']
     db.put(id, account.type, account.number, account.name, account.first_name, account.address, account.birthdate,
            account.latitude, account.longitude)
     return account
Ejemplo n.º 5
0
Archivo: app.py Proyecto: yubang/notes
def account(requestType):
    "用户帐号模块"

    g.message = request.args.get("error", "")

    if requestType == "login":
        #登录
        if request.method == "GET":
            g.title = u"登录"
            g.login = True
            return render_template("notes/account.html")
        else:
            username = request.form.get("username", None)
            password = request.form.get("password", "")
            password = hashlib.md5(password).hexdigest()

            dbSession = sessionMaker()
            query = dbSession.query(AccountModel)
            obj = query.filter(AccountModel.username == username).first()
            dbSession.close()

            if obj == None:
                #用户名不存在
                return redirect(u"/notes/account/login?error=用户名不存在")
            else:
                if obj.password == password:
                    #登录成功
                    session['uid'] = obj.id
                    return redirect(url_for("notes.index"))
                else:
                    #密码错误
                    return redirect(u"/notes/account/login?error=密码错误")

    else:
        if request.method == "GET":
            g.login = False
            g.title = u"注册"
            return render_template("notes/account.html")
        else:
            username = request.form.get("username", None)
            password = request.form.get("password", "")
            password = hashlib.md5(password).hexdigest()

            dbSession = sessionMaker()
            dao = AccountModel(username, password)
            dbSession.add(dao)
            try:
                dbSession.commit()
                session['uid'] = dao.id
                result = True
            except:
                dbSession.rollback()
                result = False

            dbSession.close()

            if result:
                return redirect(url_for("notes.index"))
            else:
                return redirect(u"/notes/account/register?error=用户名已经被注册")
Ejemplo n.º 6
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('type', type=str, required=True, help='Account type cannot be blank!')
     parser.add_argument('number', type=str, required=True, help='Account number cannot be blank!')
     parser.add_argument('name', type=str, required=True, help='User Name cannot be blank!')
     parser.add_argument('first_name', type=str, required=True, help='User Fist Name cannot be blank!')
     parser.add_argument('address', type=str, required=True, help='User address cannot be blank!')
     parser.add_argument('birthdate', type=str, required=True, help='User birthdate cannot be blank!')
     args = parser.parse_args()
     account = AccountModel(
         account_type = args['type'],
         account_number = args['number'],
         name = args['name'],
         first_name = args['first_name'],
         address = args['address'],
         birthdate = args['birthdate'],
         )
     account.id = db.get_max_id()+1
     location = geolocator.geocode(account.address)
     if location != None:
         account.latitude = location.latitude
         account.longitude = location.longitude
     else:
         account.latitude = None;
         account.longitude = None;
     db.post(account.type, account.number, account.name, account.first_name, account.address, account.birthdate,
             account.latitude, account.longitude)
     return account, status.HTTP_201_CREATED
Ejemplo n.º 7
0
    def create_user(self, user: UserCreate) -> User:
        """
        registering user
        :param user: dataclass with data for auth user
        :return: dataclass user
        """
        old_user = (self.session.query(AccountModel).filter
                    (AccountModel.email == user.email).first())

        if old_user is not None:
            raise ThisEmailAlreadyUse()

        password_hash = generate_password_hash(user.password)
        new_user = AccountModel(email=user.email, password=password_hash,
                                first_name=user.first_name,
                                last_name=user.last_name)
        self.session.add(new_user)
        self.session.commit()
        return self.get_user(new_user.as_dict().get('id'))
Ejemplo n.º 8
0
def save_account(account_name, access_token):
    settings = company_settings.get_company_settings(account_name,
                                                     access_token)
    AccountModel(id=account_name,
                 access_token=access_token,
                 company_name=settings.company_name,
                 currency=settings.currency,
                 logo_url=settings.logo_url,
                 address=settings.address,
                 phone=settings.phone).put()
    products.sync_products_for_account(account_name, access_token)
Ejemplo n.º 9
0
def is_valid_token(token):
    try:
        decoded_value = jwt.decode(jwt=token, key=current_app.config['SECRET_KEY'], algorithms=['HS256'])
    except jwt.exceptions.DecodeError:
        return False

    username = decoded_value.get('username')
    password = decoded_value.get('password')
    date_created = datetime.strptime(decoded_value.get('date_created'), datetime_format)

    is_expired = datetime.now() - date_created > timedelta(days=10)
    return AccountModel.is_valid_account(username=username, password=password) and not is_expired
Ejemplo n.º 10
0
def parse_location(account):
    location = account['profile'].get('location')

    if AccountModel.objects(
            name=account['name'],
            profile__location=location).first() or location is None:
        # Nothing to update
        return

    geolocator = Nominatim(user_agent="dtrip")
    location = geolocator.geocode(location)
    print(location.latitude, location.longitude)
Ejemplo n.º 11
0
Archivo: twitter.py Proyecto: m00n/mutc
    def __init__(self, config):
        QObject.__init__(self)

        self.account_model = AccountModel(self)

        self.subscriptions = LockableDict()

        self.panel_model = PanelModel(
            self,
            self.subscriptions,
        )

        self.thread = TwitterThread(self, self.subscriptions, config["limits"])
        self.thread.newTweets.connect(self.newTweets.emit)

        self.logger = Logger("twitter")
Ejemplo n.º 12
0
Archivo: twitter.py Proyecto: m00n/mutc
class Twitter(QObject):
    newTweets = pyqtSignal(object, list)
    newSubscription = pyqtSignal("QVariant")

    accountCreated = pyqtSignal(QObject)

    tweetRemoved = pyqtSignal("QVariant")
    tweetChanged = pyqtSignal(bool, unicode, object)

    newTweetsForModel = pyqtSignal(TweetModel, list, int)

    requestSent = pyqtSignal("QVariant", "QVariant")

    def __init__(self, config):
        QObject.__init__(self)

        self.account_model = AccountModel(self)

        self.subscriptions = LockableDict()

        self.panel_model = PanelModel(
            self,
            self.subscriptions,
        )

        self.thread = TwitterThread(self, self.subscriptions, config["limits"])
        self.thread.newTweets.connect(self.newTweets.emit)

        self.logger = Logger("twitter")

    def locking(func):
        @wraps(func)
        def wrapper(self, *args, **kwds):
            try:
                func(self, *args, **kwds)
            except Exception as error:
                self.requestSent.emit(False, unicode(error))
            else:
                self.requestSent.emit(True, None)

        return wrapper

    def check_selected_accounts(self, accounts):
        if not accounts:
            raise NoAccountSelectedException(
                "You have to select at least one account"
            )

    def on_account_connected(self, account):
        self.panel_model.setScreenName(account.uuid, account.me.screen_name)

    @pyqtSlot("QVariant")
    def subscribe(self, request):
        subscription = create_subscription(
            request["type"],
            request["account"],
            request.get("args", "")
        )

        tweet_model = self.panel_model.addPanel(subscription)
        self.tweetRemoved.connect(tweet_model.removeTweet)
        self.tweetChanged.connect(tweet_model.replaceTweet)

        self.thread.force_check.set()

    @pyqtSlot("QVariant", "QVariant", "QVariant")
    @async
    @locking
    def tweet(self, accounts, tweet, in_reply=None):
        self.check_selected_accounts(accounts)
        in_reply = in_reply if in_reply else None

        for account in accounts:
            safe_api_request(
                lambda api=account.api: api.update_status(tweet, in_reply)
            )

    @pyqtSlot("QVariant", "QVariant")
    @async
    @locking
    def retweet(self, accounts, tweet_id):
        self.check_selected_accounts(accounts)

        for account in accounts:
        	# warum die beiden so unterschiedlich?
            status = safe_api_request(
                lambda api=account.api: api.retweet(tweet_id),
            )
            old_status = safe_api_request(
                lambda: account.api.get_status(tweet_id)
            )

            status.retweeted = True
            status.created_at = old_status.created_at

            if hasattr(old_status, "retweeted_status"):
                # RTed a retweet
                status.other_retweet = old_status

            self.tweetChanged.emit(False, tweet_id, status)

    @pyqtSlot("QVariant", "QVariant")
    @async
    @locking
    def undo_retweet(self, accounts, tweet_id):
        self.check_selected_accounts(accounts)

        for account in accounts:
            status = safe_api_request(
                lambda: account.api.destroy_status(tweet_id)
            )
            self.tweetChanged.emit(True, tweet_id, status.retweeted_status)


    @pyqtSlot("QVariant", "QVariant")
    @async
    @locking
    def favorite(self, accounts, tweet_id):
        self.check_selected_accounts(accounts)

        for account in accounts:
            self.logger.debug("api.create_favorite({0})", tweet_id)

            status = safe_api_request(
                lambda api=account.api: api.create_favorite(tweet_id),
            )

            status.favorited = True

            self.tweetChanged.emit(False, tweet_id, status)

    @pyqtSlot("QVariant", "QVariant")
    @async
    @locking
    def undo_favorite(self, accounts, tweet_id):
        self.check_selected_accounts(accounts)

        for account in accounts:
            self.logger.debug("api.destroy_favorite({0})", tweet_id)

            status = safe_api_request(
                lambda: account.api.destroy_favorite(tweet_id)
            )

            status.favorited = False

            self.tweetChanged.emit(True, tweet_id, status)

            # Remove tweet from Favorites-Panels
            for subscription, model in self.panel_model.panels:
                print repr(tweet_id), subscription.subscription_type, subscription.account, account
                if subscription.subscription_type == "favorites" \
                   and subscription.account == account:
                    call_in_mainloop(model.removeTweet, tweet_id)

    @pyqtSlot("QVariant", "QVariant", "QVariant")
    @async
    @locking
    def send_direct_message(self, account, to_twitter_id, text):
        safe_api_request(
            lambda: account.api.send_direct_message(
                user_id=to_twitter_id,
                text=text
            )
        )

    @pyqtSlot("QVariant")
    @async
    @locking
    def destroy_tweet(self, tweet_id):
        # FIXME
        status = self.account_model.accounts[0].api.get_status(tweet_id)
        author_id = status.author.id

        for account in self.account_model.accounts:
            if author_id == account.me.id:
                account.api.destroy_status(tweet_id)
                self.requestSent.emit(True, None)

                self.tweetRemoved.emit(tweet_id)

                break
        else:
            raise TweepError(
                "This tweet doesn't belong to any of your accounts"
            )

    @pyqtSlot("QVariant", "QVariant")
    @async
    @locking
    def destroy_direct_message(self, account, tweet_id):
        safe_api_request(
            lambda: account.api.destroy_direct_message(tweet_id)
        )
        self.tweetRemoved.emit(tweet_id)

    @pyqtSlot(result=QObject)
    def new_account(self):
        account = Account()
        account.setParent(self)
        #account.ready.connect(partial(self.announce_account, account))
        self.accountCreated.emit(account)
        return account

    def add_account(self, account):
        self.account_model.addAccount(account)
        account.connected.connect(self.on_account_connected)

    def connect(self):
        """
        Connects all account and starts the TwitterThread which fetches
        new tweets
        """
        for account in self.account_model.accounts:
            account.connect()

        self.thread.start()

    @pyqtSlot("QVariant")
    @async
    @locking
    def debug_tweet(self, tweet):
            self.logger.debug("debug_tweet: {0}", tweet)
Ejemplo n.º 13
0
def delete_account(account_name):
    account = AccountModel.get_by_id(account_name)
    if account:
        products.remove_for_account(account_name)
        account.key.delete()
Ejemplo n.º 14
0
def get_access_token(account_name):
    account = AccountModel.get_by_id(account_name)
    if account:
        return account.access_token
Ejemplo n.º 15
0
 def render(self) -> None:
     service = input('Qual o nome do serviço? ')
     username = input('Qual o nome do usuário? ')
     password = input('Qual a senha? ')
     AccountModel(service, username, password).insert()
Ejemplo n.º 16
0
    def on_get(self, req, resp):
        """
        :returns: info of the user in the req.header
        """
        logging.debug('in account get')
        resp_dict = {}

        try:
            username = req.get_header('username') or ''
            password = req.get_header('password') or ''
            # email = req.get_header('email') or 'email'
            # params = req.get_param_as_list()
            # logging.debug('params:%s'%params)
            logging.debug('username:%s, password:%s' %
                (username, password))
        except:
            raise falcon.HTTPBadRequest('bad req',
                'when read from req, please check if the req is correct.')

        try:
            logging.debug('in account model get')

            # user = AccountModel.get(AccountModel.username==username,
            #                             AccountModel.password==password)
            user = AccountModel.auth(username, password)

            resp_dict['info'] = 'successfully get user:%s' % username
            resp_dict['username'] = user.username
            resp_dict['email'] = user.email
            resp_dict['account_level'] = user.account_level
            resp_dict['join_date'] = user.join_date
            resp_dict['keystone_info'] = user.keystone_info
            resp_dict['disk_container'] = user.disk_container
            resp_dict['auth'] = 1

            # keystone_info = swiftwrap.createuser(new_user.keystone_tenant,
            #     new_user.keystone_username,
            #     new_user.keystone_password, new_user.account_level)

            resp.status = falcon.HTTP_200
        except UserNotExistException:
            logging.debug('in UserNotExistException')

            resp_dict['info'] = 'user:%s does not exist' % username
            resp_dict['auth'] = 0
            resp.status = falcon.HTTP_400
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        except PasswordIncorrectException:
            logging.debug('in PasswordIncorrectException')
            resp_dict['info'] = 'user:%s password not correct' % username
            resp_dict['auth'] = 0
            resp.status = falcon.HTTP_400
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        # except:
        #     # `username` is a unique column, so this username already exists,
        #     # making it safe to call .get().
        #     resp_dict['info'] = 'user:%s does not exist or password not right' % username
        #     logging.debug('user does not exist or password not right...')
        #     resp.status = falcon.HTTP_200
        else:
            resp.body = json.dumps(resp_dict, encoding='utf-8')
Ejemplo n.º 17
0
    def on_put(self, req, resp):
        """
        :param req.header.username: the username
        :param req.header.password: password
        :param req.header.email: email

        :returns: a json contains info of the operation, if the register is
            success or failed
        """
        logging.debug('in account put')
        resp_dict = {}

        try:
            username = req.get_header('username') or ''
            password = req.get_header('password') or ''
            email = req.get_header('email') or 'email'
            # params = req.get_param_as_list()
            # logging.debug('params:%s'%params)
            logging.debug('username:%s, password:%s, email:%s' %
                (username, password, email))
        except:
            raise falcon.HTTPBadRequest('bad req',
                'when read from req, please check if the req is correct.')

        try:
            logging.debug('in account put create')

            with database.atomic():
                # AccountModel.create(username=username,
                #     password=password,
                #     email=email,
                #     join_date=str(datetime.datetime.now())+' GMT+8',
                #     account_level=0,
                #     swift_tenant='test',
                #     swift_username=username,
                #     swift_password=password)
                new_user = AccountModel.create(username=username,
                    password=password,
                    email=email,
                    join_date=str(datetime.datetime.now())+' GMT+8',
                    account_level=0,
                    keystone_tenant=self.conf.account,
                    keystone_username=username,
                    keystone_password=password,
                    disk_container=username+'_'+self.conf.disk_container,
                    keystone_info='')
                logging.debug('in account put create database.atomic')

            # conn = swiftclient.client.Connection(self.conf.auth_url,
            #                       self.conf.account_username,
            #                       self.conf.password,
            #                       auth_version=self.conf.auth_version or 1)
            keystone_info = swiftwrap.create_user(new_user.keystone_tenant,
                new_user.keystone_username,
                new_user.keystone_password,
                new_user.account_level)
            logging.debug('keystone_info:%s' % keystone_info)
            q = AccountModel.update(keystone_info=keystone_info).where(
                AccountModel.username == username,
                AccountModel.password == password)
            q.execute()
            resp_dict['info'] = 'successfully create user:%s' % username
            resp_dict['username'] = username
            resp.status = falcon.HTTP_201
        except KeystoneUserCreateException:
            logging.error('in restapi KeystoneUserCreateException!')
            q = AccountModel.delete().where(AccountModel.username==username,
                    AccountModel.password==password)
            q.execute()
            resp_dict['info'] = 'create user failed, did not create user:%s' % username
            resp.status = falcon.HTTP_500
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        except peewee.IntegrityError:
            logging.warning('in account put create except')

            # `username` is a unique column, so this username already exists,
            # making it safe to call .get().
            old_user = AccountModel.get(AccountModel.username == username)
            logging.warning('user exists...')
            resp_dict['info'] = 'user exists, did not create user:%s' % username
            resp.status = falcon.HTTP_409
            try:
                change_user = AccountModel.get(AccountModel.username==username,
                                AccountModel.password==password)
            except:
                logging.debug('change user data failed...')
        except:
            logging.error('restapi_keystone put account Exception!')
            q = AccountModel.delete().where(AccountModel.username==username,
                    AccountModel.password==password)
            q.execute()
            resp_dict['info'] = 'create user failed, did not create user:%s' % username
            resp.status = falcon.HTTP_400
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        resp.body = json.dumps(resp_dict, encoding='utf-8')
Ejemplo n.º 18
0
    def on_get(self, req, resp):
        """
        :param req.header.username: the username, should be tenant:user when dev
        :param req.header.password: password

        :returns: a json contains all objects in disk container, and metameata
                {"meta":{}, "objects":{"obj1": {}}}
        """
        resp_dict = {}
        try:
            username = req.get_header('username')
            password = req.get_header('password')
            logging.debug('username:%s, password:%s' % (username, password))
        except:
            raise falcon.HTTPBadRequest('bad req',
                'please check if the req is correct, put username and \
                    password in the headers.')
        try:
            logging.debug('self.conf.auth_url: %s,  conf.auth_version: %s' % (
                self.conf.auth_url, self.conf.auth_version))

            user = AccountModel.auth(username, password)
            resp_dict['info'] = 'successfully get user:%s' % username
            resp_dict['username'] = user.username
            resp_dict['email'] = user.email
            resp_dict['account_level'] = user.account_level
            resp_dict['join_date'] = user.join_date
            resp_dict['keystone_info'] = user.keystone_info
            logging.debug('before conn to swift, resp_dict:%s' % resp_dict)

            conn = swiftclient.Connection(
                            self.conf.auth_url,
                            user.keystone_tenant+':'+user.keystone_username,
                            user.password,
                            auth_version=self.conf.auth_version)
            meta, objects = conn.get_container(user.disk_container)
            logging.debug('meta: %s,   objects: %s' % (meta, objects))

            resp_dict = {}
            resp_dict['meta'] = meta
            objs = {}
            for obj in objects:
                logging.debug('obj:%s' % obj.get('name'))
                objs[obj.get('name')] = obj
            resp_dict['objects'] = objs
            logging.debug('resp_dict:%s' % resp_dict)
        except UserNotExistException:
            logging.debug('in UserNotExistException')
            resp_dict['info'] = 'user:%s does not exist' % username
            resp.status = falcon.HTTP_404
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        except PasswordIncorrectException:
            logging.debug('in PasswordIncorrectException')
            resp_dict['info'] = 'user:%s password not correct' % username
            resp.status = falcon.HTTP_401
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        except:
            description = ('Unknown error, username and passwd ok!')
            raise falcon.HTTPServiceUnavailable(
                    'Service Error',
                    description,
                    30)
        resp.status = falcon.HTTP_200
        resp.body = json.dumps(resp_dict, encoding='utf-8',
            sort_keys=True, indent=4)
Ejemplo n.º 19
0
    def __call__(self, req, resp, path2file):
        """
        :param req.header.username: the username, should be tenant:user when dev
        :param req.header.password: password
        :path2file the part in the request url /v1/disk/(?P<path2file>.+?), to
            identify the resource to manipulate

        :returns: a json contains correspond response info
            GET: the temp_url of the file in a resp dict
            PUT: the auth_token and storage_url in a resp dict for uploading file
            DELETE: description of if the operation success or fail
        """
        logging.debug('in sink req.method:%s  path2file:%s' % (
            req.method, path2file))
        resp_dict = {}

        try:
            username = req.get_header('username') or 'un'
            password = req.get_header('password') or 'pw'
            req_dir = req.get_header('dir') or None
            logging.debug('username:%s, password:%s' % (username, password))
        except:
            raise falcon.HTTPBadRequest('bad req',
                'when read from req, please check if the req is correct.')

        if req.method == 'GET':
            try:
                user = AccountModel.auth(username, password)
                os_options = {'tenant_name':user.keystone_tenant}

                storage_url, auth_token = swiftclient.client.get_auth(
                                        self.conf.auth_url,
                                  user.keystone_tenant+':'+user.keystone_username,
                                  user.password,
                                   os_options=os_options,
                                      auth_version=self.conf.auth_version)
                logging.debug('url:%s, toekn:%s' % (storage_url, auth_token))
                # if path2file[-1] is '/':
                if req_dir:
                    meta, objects = conn.get_container(user.disk_container,
                        delimiter='/',
                        prefix=req_dir)
                    logging.debug('meta: %s,   objects: %s' % (meta, objects))
                    resp_dict['meta'] = meta
                    logging.debug('resp_dict:%s' % resp_dict)
                    objs = {}
                    for obj in objects:
                        logging.debug('obj:%s' % obj.get('name'))
                        objs[obj.get('name')] = obj
                    resp_dict['objects'] = objs
                else:
                    temp_url = get_temp_url(storage_url, auth_token,
                                                  user.disk_container, path2file)
                    resp_dict = {}
                    # resp_dict['meta'] = meta
                    resp_dict['temp_url'] = temp_url
                    resp_dict['path2file'] = path2file
                resp.status = falcon.HTTP_200
                # logging.debug('resp_dict:%s' % resp_dict)
            except UserNotExistException:
                logging.debug('in UserNotExistException')
                resp_dict['info'] = 'user:%s does not exist' % username
                resp.status = falcon.HTTP_404
                resp.body = json.dumps(resp_dict, encoding='utf-8')
            except PasswordIncorrectException:
                logging.debug('in PasswordIncorrectException')
                resp_dict['info'] = 'user:%s password not correct' % username
                resp.status = falcon.HTTP_401
                resp.body = json.dumps(resp_dict, encoding='utf-8')
            except:
                description = ('Unknown error, username and passwd ok!')
                raise falcon.HTTPServiceUnavailable(
                        'Service Error',
                        description,
                        30)

        elif req.method == 'PUT':
            try:
                # if path2file:
                logging.debug(' path2file:%s' % (path2file))

                # logging.debug('env:%s , \nstream:%s, \ncontext:, \ninput:' % (
                # req.env, req.stream.read()))

                user = AccountModel.auth(username, password)
                os_options = {'tenant_name':user.keystone_tenant}
                storage_url, auth_token = swiftclient.client.get_auth(
                                        self.conf.auth_url,
                                user.keystone_tenant+':'+user.keystone_username,
                                  user.password,
                                  os_options=os_options,
                                      auth_version=self.conf.auth_version)
                logging.debug('url:%s, toekn:%s, if dir:%s' %
                    (storage_url, auth_token, req_dir))

                if req_dir:
                    # modify to create multiple dir when req_dir with multiple '/'
                    req_dir = req_dir.rstrip('/')
                    req_dir += '/'

                    content_type = 'application/directory'
                    obj = None

                    swiftclient.client.put_object(storage_url, auth_token,
                              user.disk_container, req_dir, obj,
                              content_type=content_type)

                    resp_dict['info'] = 'successfully create fold:%s' % req_dir
                else:
                    logging.debug('in else')

                    logging.debug('url:%s, token:%s' % (storage_url, auth_token))
                    resp_dict['auth_token'] = auth_token
                    resp_dict['storage_url'] = storage_url + '/' + \
                        user.disk_container + '/' + path2file
                resp.status = falcon.HTTP_201
                logging.debug('resp_dict:%s' % resp_dict)

            except:
                raise falcon.HTTPBadRequest('bad req',
                    'username or password not correct!')

        elif req.method == 'DELETE':
            resp_dict = {}

            try:
                # if path2file:
                logging.debug(' path2file:%s' % (path2file))
                # logging.debug('env:%s , \nstream:%s, \ncontext:, \ninput:' % (
                # req.env, req.stream.read()))
                user = AccountModel.auth(username, password)
                conn = swiftclient.client.Connection(self.conf.auth_url,
                                  user.keystone_tenant+':'+user.keystone_username,
                                  user.password,
                                  auth_version=self.conf.auth_version)
                meta, objects = conn.get_container(user.disk_container,
                    prefix=path2file)
                logging.debug('meta: %s,  \n objects: %s' % (meta, objects))
                if objects:
                    for obj in objects:
                        conn.delete_object(user.disk_container, obj['name'])
                        resp_dict['description_'+obj['name']] = \
                            '{} have been deleted'.format(obj['name'])
                else:
                    resp_dict['description'] = 'There is no file to be \
                        deleted'
                resp.status = falcon.HTTP_204
                logging.debug('resp_dict:%s' % resp_dict)

            except:
                raise falcon.HTTPBadRequest('bad req',
                    'username or password not correct!')
        resp.body = json.dumps(resp_dict, encoding='utf-8',
            sort_keys=True, indent=4)
Ejemplo n.º 20
0
    def on_post(self, req, resp):
        """
        :param req.header.username: the username, should be tenant:user when dev
        :param req.header.password: password

        :returns: a json contains the successfully changed files
        """
        resp_dict = {}
        try:
            username = req.get_header('username') or 'un'
            password = req.get_header('password') or 'pw'
            logging.debug('in home post, username:%s, password:%s' % (username, password))
        except:
            raise falcon.HTTPBadRequest('bad req',
                'when read from req, please check if the req is correct.')
        try:
            # logging.debug('env:%s , \nstream:%s, \ncontext:%s, \ninput:%s, \n\
            #     params: %s , ' % (
            #     req.env, req.stream.read(), req.context,
            #     req.env['wsgi.input'], req.params))

            logging.debug('self.conf.auth_url: %s,  conf.auth_version: %s' % (
                self.conf.auth_url, self.conf.auth_version))

            """
            TODO:
            Add data_check here for robust
            """
            update_list = ast.literal_eval(req.params.get('data'))
            pretty_logging({'update_list':update_list})
            update_list = update_list.get('disk')
            move_list = []
            copy_list = []
            move_list = list_with_key(update_list, 'move')
            copy_list = list_with_key(update_list, 'copy')

            # if len(update_list) > 0:
            #     for pair in update_list:
            #         # pretty_logging(pair)
            #         pretty_logging(move_list, 'movelist')
            #         pretty_logging(copy_list, 'copylist')
            # else:
            #     pretty_logging({}, 'no files in update_list!')

            user = AccountModel.auth(username, password)
            pretty_logging({'tenent:':user.keystone_tenant,
                'username':user.username,
                'disk_container':user.disk_container})
            if len(move_list) > 0:
                for pair in move_list:
                    # pretty_logging(pair)
                    pretty_logging(pair, 'movelist')
                    swiftwrap.move_object(user.keystone_tenant,
                                    user.keystone_username,
                                    user.password,
                                    user.disk_container,
                                    pair.get('from'),
                                    pair.get('move'))
            else:
                pretty_logging({}, 'no files in update_list!')


            if len(copy_list) > 0:
                for pair in copy_list:
                    # pretty_logging(pair)
                    pretty_logging(pair, 'copylist')
                    swiftwrap.copy_object(user.keystone_tenant,
                                    user.keystone_username,
                                    user.password,
                                    user.disk_container,
                                    pair.get('from'),
                                    pair.get('copy'))
            else:
                pretty_logging({}, 'no files in update_list!')

            # user = AccountModel.get(AccountModel.username==username,
            #                             AccountModel.password==password)
            logging.debug('1st resp_dict:%s' % resp_dict)

            resp_dict['info'] = 'successfully get user:%s' % username
            resp_dict['username'] = user.username
            resp_dict['email'] = user.email
            resp_dict['account_level'] = user.account_level
            resp_dict['join_date'] = user.join_date
            resp_dict['keystone_info'] = user.keystone_info
            logging.debug('2nd resp_dict:%s' % resp_dict)

        except UserNotExistException:
            logging.debug('in UserNotExistException')
            resp_dict['info'] = 'user:%s does not exist' % username
            resp.status = falcon.HTTP_404
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        except PasswordIncorrectException:
            logging.debug('in PasswordIncorrectException')
            resp_dict['info'] = 'user:%s password not correct' % username
            resp.status = falcon.HTTP_401
            resp.body = json.dumps(resp_dict, encoding='utf-8')
        except:
            description = ('Unknown error, username and passwd ok!')
            raise falcon.HTTPServiceUnavailable(
                    'Service Error',
                    description,
                    30)
        resp.status = falcon.HTTP_201
        resp.body = json.dumps(resp_dict, encoding='utf-8',
            sort_keys=True, indent=4)
Ejemplo n.º 21
0
 def render(self) -> None:
     services = tuple(account.service for account in AccountModel.list_all())
     print(services)
Ejemplo n.º 22
0
 def render(self) -> None:
     service = input('Qual o nome do serviço? ')
     accounts = AccountModel.list_by_service(service)
     print(tuple((a.username, a.password) for a in accounts))