Exemple #1
0
 def setUp(self):
     self.fake_logger = MagicMock()
     self.fake_redis = fakeredis.FakeStrictRedis()
     self.user_manager = UserManager(
         self.fake_redis,
         self.fake_logger,
     )
Exemple #2
0
    def __init__(self,
                 name='Repository',
                 location=path.join('Repositories', 'repo_1'),
                 roles_file_type='txt'):
        """
        Initialisation of a new :py:class:Repository object.

        :param name: The name of the :py:class:Repository object, the default value is 'Repository'.
        :param location: The path of the :py:class:Repository object, the default value is 'Repositories/repo_1'.
        :param roles_file_type: The type of roles metadata file, it can be: TXT, XML, JSON.
        """
        self._name = name
        self._location = location
        self._metadata_file = path.join(
            self._location, '{}_metadata.edd'.format(path.basename(name)))
        self._paths_file = path.join(self._location, PATHS_FILE)
        if roles_file_type.lower() in ['txt', 'xml', 'json']:
            self._roles_file_type = roles_file_type.lower()
        else:
            raise ValueError(
                "The roles_file_type must be txt, xml or json, not {}!".format(
                    roles_file_type))
        self.load()
        self._user_manager = UserManager(self._location, self._paths_file)
        self._document_manager = DocumentManager(self._location,
                                                 self._paths_file)
        schedule.every(BACKUP_FREQUENCY).days.at('4:00').do(self.create_backup)
        self.initialize_logger(self.location)
        logger.info("The repository is initialized.")
Exemple #3
0
    def __init__(self):
        logger.info("The app has started")
        databases = Databases()
        logger.info("DB initialized")

        self.telegram_updater = Updater(token=config.token)

        self.user_manager = UserManager(databases, self.telegram_updater.bot)
        self.telegram_updater.dispatcher.add_handler(
            MessageHandler(filters=[], callback=self.message_handler))
        self.telegram_updater.dispatcher.add_handler(
            CallbackQueryHandler(self.callback_handler))

        self.asyncio_handler = AsyncioFriendlyHandler(
            self.initialize_asyncio_loop)
        self.telegram_updater.dispatcher.add_handler(self.asyncio_handler)
        self.telegram_updater.dispatcher.add_error_handler(self.telegram_error)

        logger.debug('Adding asyncio update to queue')
        self.telegram_updater.update_queue.put(AsyncioUpdate())

        logger.info("Staring polling")
        self.telegram_updater.start_polling(
            timeout=config.timeout_for_pooling,
            bootstrap_retries=config.retries_on_error)
        logger.info("Idle")
        self.telegram_updater.idle()
Exemple #4
0
 def __init__(self, redis_pool, app):
     self.chess_manager = ChessManager(redis_pool)
     self.user_manager = UserManager(redis_pool, app)
     self.board_subscribers = {}
     self.redis_pool = redis_pool
     self.app = app
     # self.notify_next_turn()
     self.pool = Pool(1000)
Exemple #5
0
 def __init__(self, redis_pool, app, connected_websockets):
     self.chess_manager = ChessManager(redis_pool)
     self.user_manager = UserManager(redis_pool, app)
     self.tournament_manager = TournamentManager(redis_pool,
                                                 self.chess_manager)
     self.board_subscribers = {}
     self.redis_pool = redis_pool
     self.app = app
     self.connected_websockets = connected_websockets
Exemple #6
0
def production():
    """Production server that uses port 9090 for the websocket server.
    """
    app = Flask(__name__, static_folder='dist', static_url_path='')
    app_manager = apps.AppManager(catkin_ws=secrets.CATKIN_WS)
    client = MongoClient()
    db = client.rws
    user_manager = UserManager(db)
    robot_blueprint = Blueprint('robot', __name__)
    robot = Robot(robot_blueprint, user_manager)
    websocket_server = WebsocketServer(9090)
    server = RobotWebServer(app, app_manager, user_manager, robot,
                            websocket_server)
    return server
Exemple #7
0
def test():
    """Test server. Most likely many of the objects will be mocked anyway.
    """
    app = Flask(__name__, static_folder='dist', static_url_path='')
    app_manager = apps.AppManager(catkin_ws=None)
    client = MongoClient()
    db = client.rws_test
    user_manager = UserManager(db)
    robot_blueprint = Blueprint('robot', __name__)
    robot = Robot(robot_blueprint, user_manager)
    websocket_server = WebsocketServer(9090)
    server = RobotWebServer(app, app_manager, user_manager, robot,
                            websocket_server)
    server._app.config['TESTING'] = True
    server._app = server._app.test_client()
    return server
Exemple #8
0
def sign_in():
    """Request to authenticate with the system"""
    try:
        username_email = flask.request.form['username']
        password = flask.request.form['password']
    except:
        return responses.get_invalid_request()

    try:
        user, jwt = UserManager(db).login(username_email, password)
    except:
        # TODO probably use a redirect instead of rendering
        return flask.render_template('index.html', login_error=True)

    response = flask.make_response(flask.redirect(CP_WEB_PATH))
    response.set_cookie('jwt', jwt)
    return response
Exemple #9
0
def development():
    """Development server.
    """
    app = Flask(__name__, static_folder='dist', static_url_path='')
    cors = CORS(
        app, resources={r'/api/*': {
            'origins': secrets.DEV_FRONTEND_ORIGIN
        }})
    app_manager = apps.AppManager(catkin_ws=secrets.CATKIN_WS)
    client = MongoClient()
    db = client.rws_dev
    user_manager = UserManager(db)
    robot_blueprint = Blueprint('robot', __name__)
    robot = Robot(robot_blueprint, user_manager)
    websocket_server = WebsocketServer(9090)
    server = RobotWebServer(app, app_manager, user_manager, robot,
                            websocket_server)
    return server
Exemple #10
0
    def __init__(self, api_key, api_base_url=None, _requestor=None):
        if api_key is None:
            raise TypeError('api_key cannot be blank.')

        if api_base_url is None:
            api_base_url = 'https://api.userkit.io/v1'
        else:
            api_base_url += '/v1'

        self.api_key = api_key
        self.api_base_url = api_base_url

        # make the encapsulated objects
        self._rq = _requestor or Requestor(self.api_key, self.api_base_url)
        self.users = UserManager(self._rq)
        self.invites = InviteManager(self._rq)
        self.emails = EmailManager(self._rq)
        self.widget = WidgetManager(self._rq)
        self.logs = LogsManager(self._rq)
Exemple #11
0
def register():
    """Request to register with the system"""
    try:
        email = flask.request.form['email']
        username = flask.request.form['username']
        display_name = flask.request.form['display-name']
        password = flask.request.form['password']
    except:
        return responses.get_invalid_request()

    try:
        UserManager(db).register(username, email, password, display_name)
        return flask.render_template('register.html', success=True)
    except:
        # Such user already existed
        return flask.render_template('register.html',
                                     success=False,
                                     email=email,
                                     username=username,
                                     display_name=display_name)
Exemple #12
0
 def test_delete_user(self):
     self.assertTrue(UserManager().delete_user(11))
Exemple #13
0
loginmanager.init_app(app)
loginmanager.login_view = 'user_login'
markup = dict([(klass.NAME, klass) for klass in markup.Markup.__subclasses__()
               ])[app.config.get('MARKUP')]

wiki = Wiki(app.config.get('CONTENT_DIR'), markup)

# FIX ME: This monkeypatching is pollution crap .
#         Should be possible to import them wherever,
#         Wiki class should be a singleton.
app.wiki = wiki
app.signals = wiki_signals
app.EditorForm = EditorForm
app.loginmanager = loginmanager
app.manager = manager
app.users = UserManager(app.config.get('DATA_DIR'), app)
app.check_password = check_password
app.make_password = make_password

app.jinja_env.globals.update(user_can_edit=user_can_edit)

#===============================================================================
# VARIABLE STATIC FILE
#===============================================================================

for cs in CUSTOM_STATICS_LIST:
    csvalue = app.config.get(cs)
    if csvalue:
        csbasename = os.path.basename(csvalue)
        cspath = (csvalue if os.path.isabs(cs) else os.path.join(
            app.config["WIKI_ROOT"], csvalue))
Exemple #14
0
# app.config['DEBUG'] = options.debug
# app.config['CONTENT_DIR'] = options.directory
app.config['TITLE'] = 'wiki'
# app.config['AUTHENTICATION_METHOD'] = options.authentication_method
app.config['AUTHENTICATION_METHOD'] = 'cleartext'
app.config['SEARCH_IGNORE_CASE'] = True

try:
    app.config.from_pyfile(
        os.path.join(app.config.get('CONTENT_DIR'), 'config.py'))
except IOError:
    print("Startup Failure: You need to place a "
          "config.py in your content directory.")

wiki = Wiki(app.config.get('CONTENT_DIR'))
users = UserManager(app.config.get('CONTENT_DIR'))

users.add_user('admin',
               'dev',
               authentication_method=app.config.get('AUTHENTICATION_METHOD'))

loginmanager = LoginManager()
loginmanager.init_app(app)
loginmanager.login_view = 'user_login'
"""
    Forms
    ~~~~~
"""


# https://stackoverflow.com/questions/13585663/flask-wtfform-flash-does-not-display-errors
Exemple #15
0
def reset_password():
    """Request to reset user password"""
    UserManager(db).reset_password(None, "", "")
Exemple #16
0
 def test_get_user(self):
     user_manager = UserManager()
     self.assertEqual(11, user_manager.get_user(11).id)
Exemple #17
0
from flask import Flask, jsonify, request
from reviews import ReviewManager
from users import UserManager

rm = ReviewManager()
um = UserManager()

app = Flask(__name__)


@app.route('/users/login', methods=['GET'])
def login():
    username = request.args.get('username')
    password = request.args.get('password')
    return jsonify(user_id=um.login(username, password))


@app.route('/users/register', methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    user_id = um.create_account(username, password)
    return jsonify(user_id=user_id)


@app.route('/reviews/save', methods=['POST'])
def save_review():
    user_id = request.form.get('user_id')
    review = request.form.get('review')
    grade = request.form.get('grade')
    major = request.form.get('major')
Exemple #18
0
 def get_user_manager(self):
     if self._user_manager is None:
         self._user_manager = UserManager(self)
     return self._user_manager
Exemple #19
0
                             text=etc.text["submit"] + str(mark) + '/100' +
                             etc.text["submit_end"],
                             parse_mode='markdown',
                             reply_markup=reply_markup)
    # comments = Review.getComments(user.place['id'], user.chat_id)

    # if len(comments) > 0:
    #     message = mark_text(update, comments,0,user)
    #     context.bot.send_message(update.message.chat.id, text=message, parse_mode='markdown', reply_markup=ReplyKeyboardRemove())

    UM.delete_user(user.chat_id)


if __name__ == "__main__":
    # Initialized BOT
    UM = UserManager()
    updater = Updater(token=environ['bot_token'], use_context=True)
    dispatcher = updater.dispatcher

    # Commands
    dispatcher.add_handler(CommandHandler('start', start_state))

    # help command
    dispatcher.add_handler(CommandHandler('help', help_state))

    # place command
    dispatcher.add_handler(CommandHandler('place', place_state))

    # Location handler
    dispatcher.add_handler(MessageHandler(Filters.location, location_state))
Exemple #20
0
 def test_add_users(self):
     user_manager = UserManager()
     self.assertEqual('test',
                      user_manager.add_user('test', 'password').get('name'))