Exemplo n.º 1
0
def add_user():
    if request.method == "GET":
        return render_template("adduser.html")

    error = False
    (name, passwd, passwd_confirm, mail, admin) = map(
        request.form.get, ["name", "passwd", "passwd_confirm", "mail", "admin"]
    )
    if name in (None, ""):
        flash("The name is required.")
        error = True
    if passwd in (None, ""):
        flash("Please provide a password.")
        error = True
    elif passwd != passwd_confirm:
        flash("The passwords don't match.")
        error = True

    if admin is None:
        admin = True if User.query.filter(User.admin == True).count() == 0 else False
    else:
        admin = True

    if not error:
        status = UserManager.add(name, passwd, mail, admin)
        if status == UserManager.SUCCESS:
            flash("User '%s' successfully added" % name)
            return redirect(url_for("user_index"))
        else:
            flash(UserManager.error_str(status))

    return render_template("adduser.html")
Exemplo n.º 2
0
def add_user():
	if request.method == 'GET':
		return render_template('adduser.html')

	error = False
	(name, passwd, passwd_confirm, mail, admin) = map(request.form.get, [ 'name', 'passwd', 'passwd_confirm', 'mail', 'admin' ])
	if name in (None, ''):
		flash('The name is required.')
		error = True
	if passwd in (None, ''):
		flash('Please provide a password.')
		error = True
	elif passwd != passwd_confirm:
		flash("The passwords don't match.")
		error = True

	if admin is None:
		admin = True if User.query.filter(User.admin == True).count() == 0 else False
	else:
		admin = True

	if not error:
		status = UserManager.add(name, passwd, mail, admin)
		if status == UserManager.SUCCESS:
			flash("User '%s' successfully added" % name)
			return redirect(url_for('user_index'))
		else:
			flash(UserManager.error_str(status))

	return render_template('adduser.html')
Exemplo n.º 3
0
def login():
	return_url = request.args.get('returnUrl') or url_for('index')
	if session.get('userid'):
		flash('Already logged in')
		return redirect(return_url)

	if request.method == 'GET':
		return render_template('login.html')

	name, password = map(request.form.get, [ 'user', 'password' ])
	error = False
	if name in ('', None):
		flash('Missing user name')
		error = True
	if password in ('', None):
		flash('Missing password')
		error = True

	if not error:
		status, user = UserManager.try_auth(name, password)
		if status == UserManager.SUCCESS:
			session['userid'] = str(user.id)
			session['username'] = user.name
			flash('Logged in!')
			return redirect(return_url)
		else:
			flash(UserManager.error_str(status))

	return render_template('login.html')
Exemplo n.º 4
0
def add_user():
    if request.method == 'GET':
        return render_template('adduser.html')

    error = False
    (name, passwd, passwd_confirm, mail,
     admin) = map(request.form.get,
                  ['name', 'passwd', 'passwd_confirm', 'mail', 'admin'])
    if name in (None, ''):
        flash('The name is required.')
        error = True
    if passwd in (None, ''):
        flash('Please provide a password.')
        error = True
    elif passwd != passwd_confirm:
        flash("The passwords don't match.")
        error = True

    if admin is None:
        admin = True if User.query.filter(
            User.admin == True).count() == 0 else False
    else:
        admin = True

    if not error:
        status = UserManager.add(name, passwd, mail, admin)
        if status == UserManager.SUCCESS:
            flash("User '%s' successfully added" % name)
            return redirect(url_for('user_index'))
        else:
            flash(UserManager.error_str(status))

    return render_template('adduser.html')
Exemplo n.º 5
0
def change_password():
    if request.method == 'POST':
        current, new, confirm = map(request.form.get,
                                    ['current', 'new', 'confirm'])
        error = False
        if current in ('', None):
            flash('The current password is required')
            error = True
        if new in ('', None):
            flash('The new password is required')
            error = True
        if new != confirm:
            flash("The new password and its confirmation don't match")
            error = True

        if not error:
            status = UserManager.change_password(session.get('userid'),
                                                 current, new)
            if status != UserManager.SUCCESS:
                flash(UserManager.error_str(status))
            else:
                flash('Password changed')
                return redirect(url_for('user_profile'))

    return render_template('change_pass.html',
                           user=UserManager.get(session.get('userid'))[1].name)
Exemplo n.º 6
0
def login():
    return_url = request.args.get('returnUrl') or url_for('index')
    if session.get('userid'):
        flash('Already logged in')
        return redirect(return_url)

    if request.method == 'GET':
        return render_template('login.html')

    name, password = map(request.form.get, ['user', 'password'])
    error = False
    if name in ('', None):
        flash('Missing user name')
        error = True
    if password in ('', None):
        flash('Missing password')
        error = True

    if not error:
        status, user = UserManager.try_auth(name, password)
        if status == UserManager.SUCCESS:
            session['userid'] = str(user.id)
            session['username'] = user.name
            flash('Logged in!')
            return redirect(return_url)
        else:
            flash(UserManager.error_str(status))

    return render_template('login.html')
Exemplo n.º 7
0
  def test_get_all_users(self):
    mocked_key_dir = MagicMock()
    mocked_file = MagicMock()
    mocked_dir = MagicMock()
    mocked_re = MagicMock()

    mocked_user = MagicMock()
    mocked_user.get_by_name.return_value = 'test_user'

    mocked_path.return_value = mocked_key_dir
    mocked_dir.isdir.return_value = True
    mocked_file.isdir.return_value = False
    mocked_file.__str__ = lambda x: 'ok_file'

    mocked_re.compile().findall.return_value = ['file1.pub']

    mocked_key_dir.walk.return_value = [mocked_file, mocked_dir]

    UserManager.__bases__ = (MockManager, )
    with patch.multiple('managers.user', User=mocked_user,
                        Path=mocked_path, re=mocked_re):
      users = UserManager('~/path/to/admin/gitolite/repo')

      eq_(users.all(), ['test_user'])
      mocked_path.has_calls([call(mocked_path, 'keydir')])
      eq_(mocked_key_dir.walk.call_count, 1)
      eq_(mocked_dir.isdir.call_count, 1)
      eq_(mocked_file.isdir.call_count, 1)

      mocked_re.compile.has_calls([call('(\w.pub)')])
      mocked_re.compile('\w.pub').findall.assert_called_once_with('ok_file')

      mocked_user.get_by_name.assert_called_once_with('file1', mocked_path,
                                                      mocked_git)
Exemplo n.º 8
0
def login():
    return_url = request.args.get("returnUrl") or url_for("index")
    if session.get("userid"):
        flash("Already logged in")
        return redirect(return_url)

    if request.method == "GET":
        return render_template("login.html")

    name, password = map(request.form.get, ["user", "password"])
    error = False
    if name in ("", None):
        flash("Missing user name")
        error = True
    if password in ("", None):
        flash("Missing password")
        error = True

    if not error:
        status, user = UserManager.try_auth(name, password)
        if status == UserManager.SUCCESS:
            session["userid"] = str(user.id)
            session["username"] = user.name
            flash("Logged in!")
            return redirect(return_url)
        else:
            flash(UserManager.error_str(status))

    return render_template("login.html")
Exemplo n.º 9
0
def del_user(uid):
    status = UserManager.delete(uid)
    if status == UserManager.SUCCESS:
        flash('Deleted user')
    else:
        flash(UserManager.error_str(status))

    return redirect(url_for('user_index'))
Exemplo n.º 10
0
def del_user(uid):
	status = UserManager.delete(uid)
	if status == UserManager.SUCCESS:
		flash('Deleted user')
	else:
		flash(UserManager.error_str(status))

	return redirect(url_for('user_index'))
Exemplo n.º 11
0
 def user_add(self, name, admin, password, email):
     if not password:
         password = getpass.getpass()
         confirm  = getpass.getpass('Confirm password: '******'t match"
             return
     status = UserManager.add(name, password, email, admin)
     if status != UserManager.SUCCESS:
         print >>sys.stderr, UserManager.error_str(status)
Exemplo n.º 12
0
  def test_create_user_succesfully(self):
    mocked_user = MagicMock(return_value='test_username')

    UserManager.__bases__ = (MockManager, )
    with patch.multiple('managers.user', User=mocked_user,
                        Manager=MagicMock()):
      users = UserManager('~/path/to/admin/gitolite/repo')

      eq_('test_username', users.create('test_username', 'key_path'))
      mocked_user.assert_called_once_with(mocked_path, mocked_git,
                                          'test_username', keys=['key_path'])
Exemplo n.º 13
0
def user_changepass(name, password):
    if not password:
        password = getpass.getpass()
        confirm = getpass.getpass('Confirm password: '******'t match"
            return
        status = UserManager.change_password2(name, password)
        if status != UserManager.SUCCESS:
            print >> sys.stderr, UserManager.error_str(status)
        else:
            print "Successfully changed '{}' password".format(name)
Exemplo n.º 14
0
  def test_get_user(self):
    mocked_user = MagicMock()
    mocked_user.get_by_name.return_value = 'test_user'

    UserManager.__bases__ = (MockManager, )
    with patch.multiple('managers.user', User=mocked_user):
      users = UserManager('~/path/to/admin/gitolite/repo')

      eq_('test_user', users.get('test_user'))
      mocked_user.get_by_name.assert_called_once_with('test_user',
                                                      mocked_path,
                                                      mocked_git)
Exemplo n.º 15
0
def user_changepass(name, password):
    if not password:
        password = getpass.getpass()
        confirm  = getpass.getpass('Confirm password: '******'t match"
            return
        status = UserManager.change_password2(name, password)
        if status != UserManager.SUCCESS:
            print >>sys.stderr, UserManager.error_str(status)
        else:
            print "Successfully changed '{}' password".format(name)
Exemplo n.º 16
0
def user_changepass():
    username, password = map(request.args.get, ['username', 'password'])
    if not username or not password:
        return request.error_formatter(10, 'Missing parameter')

    if username != request.username and not request.user.admin:
        return request.error_formatter(50, 'Admin restricted')

    status = UserManager.change_password2(username, password)
    if status != UserManager.SUCCESS:
        return request.error_formatter(0, UserManager.error_str(status))

    return request.formatter({})
Exemplo n.º 17
0
def user_changepass():
	username, password = map(request.args.get, [ 'username', 'password' ])
	if not username or not password:
		return request.error_formatter(10, 'Missing parameter')

	if username != request.username and not request.user.admin:
		return request.error_formatter(50, 'Admin restricted')

	status = UserManager.change_password2(username, password)
	if status != UserManager.SUCCESS:
		return request.error_formatter(0, UserManager.error_str(status))

	return request.formatter({})
Exemplo n.º 18
0
def user_del():
    if not request.user.admin:
        return request.error_formatter(50, 'Admin restricted')

    username = request.args.get('username')
    user = User.query.filter(User.name == username).first()
    if not user:
        return request.error_formatter(70, 'Unknown user')

    status = UserManager.delete(user.id)
    if status != UserManager.SUCCESS:
        return request.error_formatter(0, UserManager.error_str(status))

    return request.formatter({})
Exemplo n.º 19
0
def user_del():
	if not request.user.admin:
		return request.error_formatter(50, 'Admin restricted')

	username = request.args.get('username')
	user = User.query.filter(User.name == username).first()
	if not user:
		return request.error_formatter(70, 'Unknown user')

	status = UserManager.delete(user.id)
	if status != UserManager.SUCCESS:
		return request.error_formatter(0, UserManager.error_str(status))

	return request.formatter({})
Exemplo n.º 20
0
class BaseWSHandler(WebSocketHandler):
    @property
    def db(self):
        return self.application.db

    CONNECTIONS_BY_VIDEO_ID = {}

    def add_connection(self, video_id, connection):
        """ Add connection to global manager """
        if video_id not in self.CONNECTIONS_BY_VIDEO_ID:
            self.CONNECTIONS_BY_VIDEO_ID[video_id] = []
        self.CONNECTIONS_BY_VIDEO_ID[video_id].append(connection)

    def remove_connection(self, video_id, connection):
        """ Remove connection from global manager """
        if video_id not in self.CONNECTIONS_BY_VIDEO_ID:
            self.CONNECTIONS_BY_VIDEO_ID[video_id] = []
        self.CONNECTIONS_BY_VIDEO_ID[video_id].remove(connection)

    def get_connections(self, video_id):
        """ Gets all connections from global manager """
        if video_id not in self.CONNECTIONS_BY_VIDEO_ID:
            self.CONNECTIONS_BY_VIDEO_ID[video_id] = []
        return self.CONNECTIONS_BY_VIDEO_ID[video_id]

    def initialize(self):
        """ Constructor. """
        self.user_manager = UserManager(self.db)
        self.video_manager = VideoManager(self.db)

    def check_user(self, id, auth):
        """ Given an id and auth, checks if the auth matches the id. """
        return self.user_manager.check_auth(id, auth)
Exemplo n.º 21
0
def user_profile():
    prefs = ClientPrefs.query.filter(
        ClientPrefs.user_id == uuid.UUID(session.get('userid')))
    return render_template('profile.html',
                           user=UserManager.get(session.get('userid'))[1],
                           api_key=config.get('lastfm', 'api_key'),
                           clients=prefs)
Exemplo n.º 22
0
def index():
	stats = {
		'artists': db.Artist.query.count(),
		'albums': db.Album.query.count(),
		'tracks': db.Track.query.count()
	}
	return render_template('home.html', stats = stats, admin = UserManager.get(session.get('userid'))[1].admin)
Exemplo n.º 23
0
def check_admin():
    if not request.path.startswith('/user'):
        return

    if request.endpoint in ('user_index', 'add_user', 'del_user',
                            'export_users', 'import_users',
                            'do_user_import') and not UserManager.get(
                                session.get('userid'))[1].admin:
        return redirect(url_for('index'))
Exemplo n.º 24
0
def check_admin():
    if not request.path.startswith("/user"):
        return

    if (
        request.endpoint in ("user_index", "add_user", "del_user", "export_users", "import_users", "do_user_import")
        and not UserManager.get(session.get("userid"))[1].admin
    ):
        return redirect(url_for("index"))
Exemplo n.º 25
0
def change_mail():
    user = UserManager.get(session.get("userid"))[1]
    if request.method == "POST":
        mail = request.form.get("mail")
        # No validation, lol.
        user.mail = mail
        db_sess.commit()
        return redirect(url_for("user_profile"))

    return render_template("change_mail.html", user=user)
Exemplo n.º 26
0
def change_mail():
    user = UserManager.get(session.get('userid'))[1]
    if request.method == 'POST':
        mail = request.form.get('mail')
        # No validation, lol.
        user.mail = mail
        db_sess.commit()
        return redirect(url_for('user_profile'))

    return render_template('change_mail.html', user=user)
Exemplo n.º 27
0
def index():
    stats = {
        'artists': db.Artist.query.count(),
        'albums': db.Album.query.count(),
        'tracks': db.Track.query.count()
    }
    return render_template('home.html',
                           stats=stats,
                           admin=UserManager.get(
                               session.get('userid'))[1].admin)
Exemplo n.º 28
0
def change_mail():
	user = UserManager.get(session.get('userid'))[1]
	if request.method == 'POST':
		mail = request.form.get('mail')
		# No validation, lol.
		user.mail = mail
		db_sess.commit()
		return redirect(url_for('user_profile'))

	return render_template('change_mail.html', user = user)
Exemplo n.º 29
0
def lastfm_reg():
    token = request.args.get('token')
    if token in ('', None):
        flash('Missing LastFM auth token')
        return redirect(url_for('user_profile'))

    lfm = LastFm(UserManager.get(session.get('userid'))[1], app.logger)
    status, error = lfm.link_account(token)
    flash(error if not status else 'Successfully linked LastFM account')

    return redirect(url_for('user_profile'))
Exemplo n.º 30
0
def lastfm_reg():
	token = request.args.get('token')
	if token in ('', None):
		flash('Missing LastFM auth token')
		return redirect(url_for('user_profile'))

	lfm = LastFm(UserManager.get(session.get('userid'))[1], app.logger)
	status, error = lfm.link_account(token)
	flash(error if not status else 'Successfully linked LastFM account')

	return redirect(url_for('user_profile'))
Exemplo n.º 31
0
def lastfm_reg():
    token = request.args.get("token")
    if token in ("", None):
        flash("Missing LastFM auth token")
        return redirect(url_for("user_profile"))

    lfm = LastFm(UserManager.get(session.get("userid"))[1], app.logger)
    status, error = lfm.link_account(token)
    flash(error if not status else "Successfully linked LastFM account")

    return redirect(url_for("user_profile"))
Exemplo n.º 32
0
def authorize():
	if not request.path.startswith('/rest/'):
		return

	error = request.error_formatter(40, 'Unauthorized'), 401

	if request.authorization:
		status, user = UserManager.try_auth(request.authorization.username, request.authorization.password)
		if status == UserManager.SUCCESS:
			request.username = request.authorization.username
			request.user = user
			return

	(username, password) = map(request.args.get, [ 'u', 'p' ])
	if not username or not password:
		return error

	status, user = UserManager.try_auth(username, password)
	if status != UserManager.SUCCESS:
		return error

	request.username = username
	request.user = user
Exemplo n.º 33
0
def user_add():
	if not request.user.admin:
		return request.error_formatter(50, 'Admin restricted')

	username, password, email, admin = map(request.args.get, [ 'username', 'password', 'email', 'adminRole' ])
	if not username or not password or not email:
		return request.error_formatter(10, 'Missing parameter')
	admin = True if admin in (True, 'True', 'true', 1, '1') else False

	status = UserManager.add(username, password, email, admin)
	if status == UserManager.NAME_EXISTS:
		return request.error_formatter(0, 'There is already a user with that username')

	return request.formatter({})
Exemplo n.º 34
0
def authorize():
    if not request.path.startswith('/rest/'):
        return

    error = request.error_formatter(40, 'Unauthorized'), 401

    if request.authorization:
        status, user = UserManager.try_auth(request.authorization.username, request.authorization.password)
        if status == UserManager.SUCCESS:
            request.username = request.authorization.username
            request.user = user
            return

    (username, password) = map(request.args.get, [ 'u', 'p' ])
    if not username or not password:
        return error

    status, user = UserManager.try_auth(username, password)
    if status != UserManager.SUCCESS:
        return error

    request.username = username
    request.user = user
Exemplo n.º 35
0
def change_password():
	if request.method == 'POST':
		current, new, confirm = map(request.form.get, [ 'current', 'new', 'confirm' ])
		error = False
		if current in ('', None):
			flash('The current password is required')
			error = True
		if new in ('', None):
			flash('The new password is required')
			error = True
		if new != confirm:
			flash("The new password and its confirmation don't match")
			error = True

		if not error:
			status = UserManager.change_password(session.get('userid'), current, new)
			if status != UserManager.SUCCESS:
				flash(UserManager.error_str(status))
			else:
				flash('Password changed')
				return redirect(url_for('user_profile'))

	return render_template('change_pass.html', user = UserManager.get(session.get('userid'))[1].name)
Exemplo n.º 36
0
def change_password():
    if request.method == "POST":
        current, new, confirm = map(request.form.get, ["current", "new", "confirm"])
        error = False
        if current in ("", None):
            flash("The current password is required")
            error = True
        if new in ("", None):
            flash("The new password is required")
            error = True
        if new != confirm:
            flash("The new password and its confirmation don't match")
            error = True

        if not error:
            status = UserManager.change_password(session.get("userid"), current, new)
            if status != UserManager.SUCCESS:
                flash(UserManager.error_str(status))
            else:
                flash("Password changed")
                return redirect(url_for("user_profile"))

    return render_template("change_pass.html", user=UserManager.get(session.get("userid"))[1].name)
Exemplo n.º 37
0
def login_check():
	if request.path.startswith('/rest/'):
		return

	if request.endpoint != 'login':
		should_login = False
		if not session.get('userid'):
			should_login = True
		elif UserManager.get(session.get('userid'))[0] != UserManager.SUCCESS:
			session.clear()
			should_login = True

		if should_login:
			flash('Please login')
			return redirect(url_for('login', returnUrl = request.script_root + request.url[len(request.url_root)-1:]))
Exemplo n.º 38
0
def user_add():
    if not request.user.admin:
        return request.error_formatter(50, 'Admin restricted')

    username, password, email, admin = map(
        request.args.get, ['username', 'password', 'email', 'adminRole'])
    if not username or not password or not email:
        return request.error_formatter(10, 'Missing parameter')
    admin = True if admin in (True, 'True', 'true', 1, '1') else False

    status = UserManager.add(username, password, email, admin)
    if status == UserManager.NAME_EXISTS:
        return request.error_formatter(
            0, 'There is already a user with that username')

    return request.formatter({})
Exemplo n.º 39
0
def login_check():
    if request.path.startswith('/rest/'):
        return

    if request.endpoint != 'login':
        should_login = False
        if not session.get('userid'):
            should_login = True
        elif UserManager.get(session.get('userid'))[0] != UserManager.SUCCESS:
            session.clear()
            should_login = True

        if should_login:
            flash('Please login')
            return redirect(
                url_for('login',
                        returnUrl=request.script_root +
                        request.url[len(request.url_root) - 1:]))
Exemplo n.º 40
0
class WebhookController(Resource):
    def __init__(self):
        super().__init__()

        self.user_manager = UserManager()
        self.manager = WebhookManager()

    def post(self):
        if request.json is None or not request.json:
            return error_response("Request must be application/json"), 400

        schema = WebhookSchema()
        load = schema.load(request.json)

        if load.errors:
            return load.errors, 400

        user = self.user_manager.get_user_from_request(request)

        if user is None:
            return error_response("Couldn't authenticate user from token"), 401

        if load.data is None or "id" not in load.data:
            return error_response("Error grabbing repository for user"), 400

        # TODO: Add webhook user validation back in, this will require allowing users to join organizations
        #if user.id != load.data.get("id"):
        #    return error_response("Repository not owned by requester"), 403

        dock_url = "".join(
            [settings.JOB_URL, "/repo",
             load.data.get("id"), "/job"])
        response = self.manager.create_webhook(owner=user,
                                               repo=load.data.get("name"),
                                               url=dock_url)

        print(response)
        print(response.json())

        return {}, 400
Exemplo n.º 41
0
def user_add(name, admin=False, email=None):
    password = prompt_pass("Please enter a password")
    if password:
        status = UserManager.add(name, password, email, admin)
        if status != UserManager.SUCCESS:
            print >>sys.stderr, UserManager.error_str(status)
Exemplo n.º 42
0
def user_profile():
    return render_template(
        "profile.html", user=UserManager.get(session.get("userid"))[1], api_key=config.get("lastfm", "api_key")
    )
Exemplo n.º 43
0
 def test_create_user_with_no_key(self):
   with patch.multiple('managers.manager',
                       Git=MagicMock(),
                       Path=MagicMock()):
     users = UserManager('~/path/to/admin/gitolite/repo')
     users.create('test_username')
Exemplo n.º 44
0
def check_admin():
    if not request.path.startswith('/folder'):
        return

    if not UserManager.get(fl_sess.get('userid'))[1].admin:
        return redirect(url_for('index'))
Exemplo n.º 45
0
 def initialize(self):
     """ Constructor. """
     self.user_manager = UserManager(self.db)
     self.video_manager = VideoManager(self.db)
     self.user = self.login()
Exemplo n.º 46
0
def check_admin():
	if not request.path.startswith('/user'):
		return

	if request.endpoint in ('user_index', 'add_user', 'del_user', 'export_users', 'import_users', 'do_user_import') and not UserManager.get(session.get('userid'))[1].admin:
		return redirect(url_for('index'))
Exemplo n.º 47
0
def lastfm_unreg():
	lfm = LastFm(UserManager.get(session.get('userid'))[1], app.logger)
	lfm.unlink_account()
	flash('Unliked LastFM account')
	return redirect(url_for('user_profile'))
Exemplo n.º 48
0
  def __init__(self, admin_repository):
    self.admin_repository = admin_repository

    self.users = UserManager(admin_repository)
    self.repos = RepositoryManager(admin_repository)
Exemplo n.º 49
0
def lastfm_unreg():
    lfm = LastFm(UserManager.get(session.get('userid'))[1], app.logger)
    lfm.unlink_account()
    flash('Unliked LastFM account')
    return redirect(url_for('user_profile'))
Exemplo n.º 50
0
class BaseHandler(RequestHandler):
    @property
    def db(self):
        return self.application.db

    def initialize(self):
        """ Constructor. """
        self.user_manager = UserManager(self.db)
        self.video_manager = VideoManager(self.db)
        self.user = self.login()

    def render(self, template, title, args={}):
        """ Making the render follow our formatting. """
        super(BaseHandler, self).render(template, title=title, args=args)

    def flash(self, message, m_type="info"):
        """ Stores a "flash" cookie with a message and message type to be
            destroyed upon consumption. """
        self.set_secure_cookie("message", base64.encodestring(message))
        self.set_secure_cookie("message_type", base64.encodestring(m_type))

    def consume_flash(self):
        """ Gets a stored flash cookie and destroys it. """
        message = self.get_secure_cookie("message")
        m_type = self.get_secure_cookie("message_type")
        if not message:
            return None
        message = base64.decodestring(message)
        if not m_type:
            m_type = "info"
        else:
            m_type = base64.decodestring(m_type)

        self.clear_cookie("message")
        self.clear_cookie("message_type")
        return {'message': message, 'message_type': m_type}

    def store_auth(self, id):
        """ Stores the user's auth cookie. """
        auth = self.user_manager.get(id, "auth")
        if not auth:
            raise Exception(
                "Failed to store auth cookie. Could not user_manager.get(" +
                str(id) + ", '" + str(auth) + "').")
        self.set_secure_cookie("user_auth", auth)

    def login(self):
        """ Returns the current user's data using UserManager's consume_auth, and store the new cookie.
            If the current user doesn't exist, one is created. """
        cookie = self.get_secure_cookie("user_auth")
        if cookie:
            user_id = self.user_manager.consume_auth(cookie)
        if (not cookie) or (not user_id):
            user_id = self.user_manager.create_new()
        self.store_auth(user_id)
        return self.user_manager.get(user_id)

    def logout(self):
        """ Deletes the user's stored cookie, after consuming it for good measure. """
        cookie = self.get_secure_cookie("user_auth")
        if (cookie):
            self.user_manager.consume_auth(cookie)
        self.clear_cookie("user_auth")

    def check_argument(self, argument):
        "Utility method to check if argument exists and isn't blank."
        return ((argument in self.request.arguments)
                and (self.get_argument(argument) != ''))
Exemplo n.º 51
0
class User(AbstractBaseUser):
    """ defines a user model """
    class Meta:
        db_table = 'users'

    REGULAR_USER_LEVEL = 'regular_user'
    ADMIN_LEVEL = 'website_admin'
    SUPERADMIN_LEVEL = 'super_admin'

    USER_LEVELS = [(REGULAR_USER_LEVEL, 'Regular User'),
                   (ADMIN_LEVEL, 'Company admin'),
                   (SUPERADMIN_LEVEL, 'Super Admin')]

    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['password', 'first_name', 'last_name']

    objects = UserManager()

    email = EmailField(max_length=64, unique=True)

    password = CharField(max_length=256)

    first_name = CharField(max_length=64)

    last_name = CharField(max_length=64)

    address = CharField(max_length=128, default=None, null=True, blank=True)

    level = CharField(max_length=32,
                      default=REGULAR_USER_LEVEL,
                      choices=USER_LEVELS)

    created_at = DateTimeField(auto_now_add=True)

    updated_at = DateTimeField(auto_now=True)

    def is_admin(self):
        return self.level == self.ADMIN_LEVEL

    def is_super_admin(self):
        return self.level == self.SUPERADMIN_LEVEL

    def is_regular_user(self):
        return self.level == self.REGULAR_USER_LEVELx

    def get_foreign_key_objects(self):
        pass

    def to_dict(self):
        data = OrderedDict()
        data['email'] = self.email
        data['surname'] = self.first_name
        data['name'] = self.last_name
        data['level'] = self.level
        data['created'] = self.created_at
        data['updated'] = self.updated_at
        data['last_login'] = self.last_login

        return data

    def to_string(self):
        return self.first_name + ' ' + self.last_name
Exemplo n.º 52
0
def user_add(name, admin=False, email=None):
    password = prompt_pass("Please enter a password")
    if password:
        status = UserManager.add(name, password, email, admin)
        if status != UserManager.SUCCESS:
            print >> sys.stderr, UserManager.error_str(status)
Exemplo n.º 53
0
"""
Endpoints for user management
"""
import json

from flask import Blueprint, request, Response
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from managers.user import UserManager

bp_users = Blueprint('users', __name__)

pg_client = create_engine('postgres://127.0.0.1/pixel')
Session = sessionmaker(bind=pg_client)

users = UserManager()


@bp_users.route('/users', methods=['POST'])
def create_user():
    session = Session()
    data = json.loads(request.data)
    username = data['username']
    email = data['email']
    password = str(data['password'])
    try:
        user = users.create_user(session, username, email, password)
        res = json.dumps(user.json), 201
    except Exception as e:
        if 'Key (username)' in e.message:
            res = 'Username {} is already used'.format(username)
Exemplo n.º 54
0
def check_admin():
	if not request.path.startswith('/folder'):
		return

	if not UserManager.get(fl_sess.get('userid'))[1].admin:
		return redirect(url_for('index'))
Exemplo n.º 55
0
    def __init__(self):
        super().__init__()

        self.user_manager = UserManager()
        self.manager = WebhookManager()
Exemplo n.º 56
0
def user_profile():
	prefs = ClientPrefs.query.filter(ClientPrefs.user_id == uuid.UUID(session.get('userid')))
	return render_template('profile.html', user = UserManager.get(session.get('userid'))[1], api_key = config.get('lastfm', 'api_key'), clients = prefs)