def setUp(self): rfk.init() rfk.database.init_db("sqlite://") setup_settings() try: self.user = User.add_user('teddydestodes', 'roflmaoblubb') self.other_user = User.add_user('test', 'test') except UserNameTakenException: pass rfk.database.session.commit()
def copy_users(): streamer = oldsession.query(Streamer).yield_per(50) for olduser in streamer: print olduser.username if User.get_user(olduser.username) is None: user = User.add_user(olduser.username, olduser.password) rfk.database.session.add(user) rfk.database.session.flush() rfk.database.session.commit()
def next_shows(): """Return the next planned show(s) Keyword arguments: - dj_id -- filter by dj - dj_name -- filter by dj - limit -- limit the output (default=5) """ dj_id = request.args.get('dj_id', None) dj_name = request.args.get('dj_name', None) limit = request.args.get('limit', 5) clauses = [] clauses.append(Show.begin > datetime.utcnow()) try: if dj_id: clauses.append(UserShow.user == User.get_user(id=dj_id)) if dj_name: clauses.append(UserShow.user == User.get_user(username=dj_name)) result = Show.query.join(UserShow).filter(*clauses).order_by( Show.begin.asc()).limit(limit).all() data = {'next_shows': {'shows': []}} if result: for show in result: begin = show.begin.isoformat() end = show.end.isoformat() dj = [] for usershow in show.users: dj.append({ 'dj_name': usershow.user.username, 'dj_id': usershow.user.user, 'status': usershow.status }) data['next_shows']['shows'].append({ 'show_id': show.show, 'show_name': show.name, 'show_description': show.description, 'show_flags': show.flags, 'show_begin': begin, 'show_end': end, 'dj': dj }) else: data = {'next_shows': None} return jsonify(wrapper(data)) except UserNotFoundException: return jsonify(wrapper({'next_shows': None}))
def last_shows(): """Return show history Keyword arguments: - dj_id -- filter by dj - dj_name -- filter by dj - limit -- limit the output (default=5) """ dj_id = request.args.get("dj_id", None) dj_name = request.args.get("dj_name", None) limit = request.args.get("limit", 5) clauses = [Show.end < datetime.utcnow()] try: if dj_id: clauses.append(UserShow.user == User.get_user(id=dj_id)) if dj_name: clauses.append(UserShow.user == User.get_user(username=dj_name)) result = Show.query.join(UserShow).filter(*clauses).order_by(Show.begin.desc()).limit(limit).all() data = {"last_shows": {"shows": []}} if result: for show in result: begin = show.begin.isoformat() end = show.end.isoformat() dj = [] for usershow in show.users: dj.append( {"dj_name": usershow.user.username, "dj_id": usershow.user.user, "status": usershow.status} ) data["last_shows"]["shows"].append( { "show_id": show.show, "show_name": show.name, "show_description": show.description, "show_flags": show.flags, "show_begin": begin, "show_end": end, "dj": dj, } ) else: data = {"last_shows": None} return jsonify(wrapper(data)) except UserNotFoundException: return jsonify(wrapper({"last_shows": None}))
def next_shows(): """Return the next planned show(s) Keyword arguments: - dj_id -- filter by dj - dj_name -- filter by dj - limit -- limit the output (default=5) """ dj_id = request.args.get('dj_id', None) dj_name = request.args.get('dj_name', None) limit = request.args.get('limit', 5) clauses = [] clauses.append(Show.begin > datetime.utcnow()) try: if dj_id: clauses.append(UserShow.user == User.get_user(id=dj_id)) if dj_name: clauses.append(UserShow.user == User.get_user(username=dj_name)) result = Show.query.join(UserShow).filter(*clauses).order_by(Show.begin.asc()).limit(limit).all() data = {'next_shows': {'shows': []}} if result: for show in result: begin = show.begin.isoformat() end = show.end.isoformat() dj = [] for usershow in show.users: dj.append( {'dj_name': usershow.user.username, 'dj_id': usershow.user.user, 'status': usershow.status}) data['next_shows']['shows'].append({ 'show_id': show.show, 'show_name': show.name, 'show_description': show.description, 'show_flags': show.flags, 'show_begin': begin, 'show_end': end, 'dj': dj }) else: data = {'next_shows': None} return jsonify(wrapper(data)) except UserNotFoundException: return jsonify(wrapper({'next_shows': None}))
def doAuth(username, password): """authenticates the user this function will also disconnect the current user if the user to be authenticated has a show registered. if that happened this function will print false to the user since we need a graceperiod to actually disconnect the other user. Keyword arguments: username password """ if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: if kick(): logger.info('kicking user') sys.stdout.write('false') return logger.info('accepted auth for %s' % (username,)) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('rejected auth for %s (invalid password)' % (username,)) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('rejected auth for %s (invalid user)' % (username,)) sys.stdout.write('false') rfk.database.session.commit()
def doConnect(data): """handles a connect from liquidsoap Keyword arguments: data -- list of headers """ logger.info('connect request %s' % (json.dumps(data),)) try: auth = data['Authorization'].strip().split(' ') if auth[0].lower() == 'basic': try: username, password = base64.b64decode(auth[1]).decode('utf-8').split(':', 1) except UnicodeDecodeError: username, password = base64.b64decode(auth[1]).decode('latin-1').split(':', 1) if username == 'source': username, password = password.split(username_delimiter, 1) else: raise ValueError user = User.authenticate(username, password) if user.get_setting(code='use_icy'): if 'ice-genre' in data: user.set_setting(data['ice-genre'], code='icy_show_genre') if 'ice-name' in data: user.set_setting(data['ice-name'], code='icy_show_name') if 'ice-description' in data: user.set_setting(data['ice-description'], code='icy_show_description') show = init_show(user) rfk.database.session.commit() logger.info('accepted connect for %s' % (user.username,)) print user.user except (rexc.base.UserNotFoundException, rexc.base.InvalidPasswordException, KeyError): logger.info('rejected connect') kick()
def doMetaData(data): logger.debug('meta %s' % (json.dumps(data),)) if 'userid' not in data or data['userid'] == 'none': print 'no userid' return user = User.get_user(id=data['userid']) if user == None: print 'user not found' return if 'artist' in data: artist = data['artist'].strip() else: artist = None if 'title' in data: title = data['title'].strip() else: title = None if 'song' in data: song = data['song'].split(' - ', 1) if (artist is None) or (len(artist) == 0): artist = song[0] if (title is None) or (len(title) == 0): title = song[1] show = init_show(user) if artist is None and title is None: track = Track.current_track() if track: track.end_track() else: track = Track.new_track(show, artist, title) rfk.database.session.commit()
def dj(): """Returns complete dj information Keyword arguments: - dj_id -- database id of the requested dj - dj_name -- nickname of the requested dj Returns: {'dj': {'dj_id': x, 'dj_name': x }} At least one argument is required """ dj_id = request.args.get('dj_id', None) dj_name = request.args.get('dj_name', None) try: user = User.get_user(id=dj_id, username=dj_name) return jsonify( wrapper({'dj': { 'dj_id': user.user, 'dj_name': user.username }})) except rexc.base.UserNotFoundException: return jsonify(wrapper({'dj': None})) except AssertionError: return jsonify(wrapper(None, 400, 'missing required query parameter'))
def login(): form = login_form(request.form) if request.method == 'POST' and form.validate(): username = form.username.data try: user = User.get_user(username=username) if user and user.check_password(password=form.password.data): user.authenticated = True remember = form.remember.data if login_user(user, remember=remember): user.last_login = now() loc = rfk.helper.get_location(request.remote_addr) if 'country_code' in loc and loc[ 'country_code'] is not None: user.country = loc['country_code'] rfk.database.session.commit() flash('Logged in!', 'success') return redirect( request.args.get('next') or url_for('index')) else: form.username.errors.append( 'There was an error while logging you in.') flash('There was an error while logging you in.', 'error') else: form.username.errors.append('Invalid User or Password.') flash('Invalid username or password.') except UserNotFoundException: form.username.errors.append('Invalid User or Password.') flash('Invalid username or password.') return render_template('login.html', form=form, TITLE='Login')
def login(): form = login_form(request.form) if request.method == 'POST' and form.validate(): username = form.username.data try: user = User.get_user(username=username) if user and user.check_password(password=form.password.data): user.authenticated = True remember = form.remember.data if login_user(user, remember=remember): user.last_login = now() loc = rfk.helper.get_location(request.remote_addr) if 'country_code' in loc and loc['country_code'] is not None: user.country = loc['country_code'] rfk.database.session.commit() flash('Logged in!', 'success') return redirect(request.args.get('next') or url_for('index')) else: form.username.errors.append('There was an error while logging you in.') flash('There was an error while logging you in.', 'error') else: form.username.errors.append('Invalid User or Password.') flash('Invalid username or password.') except UserNotFoundException: form.username.errors.append('Invalid User or Password.') flash('Invalid username or password.') return render_template('login.html', form=form, TITLE='Login')
def settings(): form = SettingsForm(request.form, username=current_user.username, email=current_user.mail, show_def_name=current_user.get_setting(code='show_def_name'), show_def_desc=current_user.get_setting(code='show_def_desc'), show_def_tags=current_user.get_setting(code='show_def_tags'), show_def_logo=current_user.get_setting(code='show_def_logo'), use_icy=current_user.get_setting(code='use_icy')) if request.method == "POST" and form.validate(): if current_user.check_password(password=form.old_password.data): if form.new_password.data: current_user.password = User.make_password(form.new_password.data) current_user.mail = form.email.data current_user.set_setting(code='show_def_name', value=form.show_def_name.data) current_user.set_setting(code='show_def_desc', value=form.show_def_desc.data) current_user.set_setting(code='show_def_tags', value=form.show_def_tags.data) current_user.set_setting(code='show_def_logo', value=form.show_def_logo.data) current_user.set_setting(code='use_icy', value=form.use_icy.data) rfk.database.session.commit() flash(gettext('Settings successfully updated.'), 'success') return redirect(url_for('settings')) else: form.old_password.errors.append(gettext('Wrong password.')) return render_template('settings.html', form=form, TITLE='Settings', imgur={'client': rfk.CONFIG.get('site', 'imgur-client')})
def doAuth(username, password): """authenticates the user this function will also disconnect the current user if the user to be authenticated has a show registered. if that happened this function will print false to the user since we need a graceperiod to actually disconnect the other user. Keyword arguments: username password """ if username == 'source': username, password = password.split(username_delimiter) try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: if kick(): logger.info('kicking user') sys.stdout.write('false') return logger.info('accepted auth for %s' %(username,)) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('rejected auth for %s (invalid password)' %(username,)) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('rejected auth for %s (invalid user)' %(username,)) sys.stdout.write('false') rfk.database.session.commit()
def liquidsoap_disconnect(): """Handles a client disconnect from liquidsoap """ userid = request.get_json() logger.info('liquidsoap_disconnect: diconnect for userid %s' % (userid,)) if userid == 'none' or userid == '': logger.warn('liquidsoap_disconnect: no userid supplied!') session.commit() return 'Whooops no userid?' user = User.get_user(id=int(userid)) if user: usershows = UserShow.query.filter(UserShow.user == user, UserShow.status == UserShow.STATUS.STREAMING).all() for usershow in usershows: usershow.status = UserShow.STATUS.STREAMED if usershow.show.flags & Show.FLAGS.UNPLANNED: usershow.show.end_show() session.commit() track = Track.current_track() if track: track.end_track() session.commit() return 'true' else: return 'no user found'
def doConnect(data): """handles a connect from liquidsoap Keyword arguments: data -- list of headers """ logger.info('connect request %s' % (json.dumps(data),)) try: auth = data['Authorization'].strip().split(' ') if auth[0].lower() == 'basic': username, password = base64.b64decode(auth[1]).split(':', 1) if username == 'source': username, password = password.split(username_delimiter, 1) else: raise ValueError user = User.authenticate(username, password) if user.get_setting(code='use_icy'): if 'ice-genre' in data: user.set_setting(data['ice-genre'],code='icy_show_genre') if 'ice-name' in data: user.set_setting(data['ice-name'],code='icy_show_name') if 'ice-description' in data: user.set_setting(data['ice-description'],code='icy_show_description') show = init_show(user) rfk.database.session.commit() logger.info('accepted connect for %s' %(user.username,)) print user.user except (rexc.base.UserNotFoundException, rexc.base.InvalidPasswordException, KeyError): logger.info('rejected connect') kick()
def doDisconnect(userid): logger.info('doDisconnect: diconnect for userid %s' % (userid, )) if userid == "none" or userid == '': print "Whooops no userid?" logger.warn('doDisconnect: no userid supplied!') rfk.database.session.commit() return user = User.get_user(id=int(userid)) if user: usershows = UserShow.query.filter( UserShow.user == user, UserShow.status == UserShow.STATUS.STREAMING).all() for usershow in usershows: usershow.status = UserShow.STATUS.STREAMED if usershow.show.flags & Show.FLAGS.UNPLANNED: usershow.show.end_show() rfk.database.session.commit() track = Track.current_track() if track: track.end_track() publish.track_change() publish.show_change() rfk.database.session.commit() else: print "no user found"
def login(): form = login_form(request.form) if request.method == 'POST' and form.validate(): username = form.username.data try: user = User.get_user(username=username) if user and user.check_password(password=form.password.data): user.authenticated = True remember = form.remember.data if login_user(user, remember=remember): if not user.last_login: flash(gettext('<strong>Tip:</strong> It appears that this is your first login, if you need any help please visit our help section by clicking <a href="/help">here</a>.'), 'info') user.last_login = now() loc = rfk.helper.get_location(request.remote_addr) if 'country_code' in loc and loc['country_code'] is not None: user.country = loc['country_code'] rfk.database.session.commit() flash(gettext('Login successful. Welcome %s!' % user.username), 'success') return redirect(request.args.get('next') or url_for('index')) else: form.username.errors.append(gettext('There was an error while logging you in.')) #flash('There was an error while logging you in.', 'error') else: form.username.errors.append(gettext('Invalid User or Password.')) #flash('Invalid username or password.') except UserNotFoundException: form.username.errors.append(gettext('Invalid User or Password.')) #flash('Invalid username or password.') return render_template('login.html', form=form, TITLE='Login')
def last_tracks(): """Return the last played tracks Keyword arguments: - dj_id -- filter by dj - dj_name -- filter by dj - limit -- limit the output (default=5) """ dj_id = request.args.get('dj_id', None) dj_name = request.args.get('dj_name', None) limit = int(request.args.get('limit', 5)) limit = limit if limit <= 50 else 50 clauses = [] clauses.append(Track.end < datetime.utcnow()) if dj_id is not None: clauses.append(UserShow.user == User.get_user(id=dj_id)) if dj_name is not None: clauses.append(UserShow.user == User.get_user(username=dj_name)) result = Track.query.join(Show).join(UserShow).filter(*clauses).order_by( Track.end.desc()).limit(limit).all() data = {'last_tracks': {'tracks': []}} if result: for track in result: begin = track.begin.isoformat() end = track.end.isoformat() data['last_tracks']['tracks'].append({ 'track_id': track.track, 'track_begin': begin, 'track_end': end, 'track_title': track.title.name, 'track_artist': track.title.artist.name }) else: data = {'last_tracks': None} return jsonify(wrapper(data))
def setup_default_user(username, password): users = [User.add_user(username, password)] for user in users: rfk.database.session.add(user) user.add_permission(code='manage-liquidsoap') user.add_permission(code='manage-relays') user.add_permission(code='admin') print "[users] Added %s" % user.username rfk.database.session.commit()
def last_tracks(): """Return the last played tracks Keyword arguments: dj_id -- filter by dj dj_name -- filter by dj limit -- limit the output (default=5) """ dj_id = request.args.get('dj_id', None) dj_name = request.args.get('dj_name', None) limit = request.args.get('limit', 5) limit = limit if limit <= 50 else 50 clauses = [] clauses.append(Track.end < datetime.utcnow()) if dj_id is not None: clauses.append(UserShow.user == User.get_user(id=dj_id)) if dj_name is not None: clauses.append(UserShow.user == User.get_user(username=dj_name)) result = Track.query.filter(*clauses).order_by(Track.end.desc()).limit(limit).all() data = {'last_tracks': {'tracks': []}} if result: for track in result: begin = track.begin.isoformat() end = track.end.isoformat() data['last_tracks']['tracks'].append({ 'track_id': track.track, 'track_begin': begin, 'track_end': end, 'track_title': track.title.name, 'track_artist': track.title.artist.name }) else: data = {'last_tracks': None} return jsonify(wrapper(data))
def last_tracks(): """Return the last played tracks Keyword arguments: - dj_id -- filter by dj - dj_name -- filter by dj - limit -- limit the output (default=5) """ dj_id = request.args.get("dj_id", None) dj_name = request.args.get("dj_name", None) limit = int(request.args.get("limit", 5)) limit = limit if limit <= 50 else 50 clauses = [Track.end < datetime.utcnow()] if dj_id is not None: clauses.append(UserShow.user == User.get_user(id=dj_id)) if dj_name is not None: clauses.append(UserShow.user == User.get_user(username=dj_name)) result = Track.query.join(Show).join(UserShow).filter(*clauses).order_by(Track.end.desc()).limit(limit).all() data = {"last_tracks": {"tracks": []}} if result: for track in result: begin = track.begin.isoformat() end = track.end.isoformat() data["last_tracks"]["tracks"].append( { "track_id": track.track, "track_begin": begin, "track_end": end, "track_title": track.title.name, "track_artist": track.title.artist.name, } ) else: data = {"last_tracks": None} return jsonify(wrapper(data))
def setUp(self): rfk.init() rfk.database.init_db("sqlite://") app.template_folder = '../templates/' app.static_folder = '../static/' app.static_url_path = '/static' self.app = app.test_client() user_1 = User.add_user('teddydestodes', 'roflmaoblubb') user_2 = User.add_user('loom', 'bestes') key_1 = ApiKey(application='app_1', description='key_1', user=user_1) key_1.gen_key() self.key_1 = key_1.key key_2 = ApiKey(application='app_2', description='key_2', user=user_2, flag=ApiKey.FLAGS.DISABLED) key_2.gen_key() self.key_2 = key_2.key rfk.database.session.add(key_1, key_2) rfk.database.session.commit()
def register(): form = register_form(request.form) if request.method == "POST" and form.validate(): try: user = User.add_user(form.username.data, form.password.data) if form.email.data: user.mail = form.email.data session.commit() except UserNameTakenException: form.username.errors.append('Username already taken!') return render_template("register.html", form=form)
def check(): ret = {} try: if User.get_user(username=request.form['username']) == None: ret['username'] = '******' else: ret['username'] = '******' except KeyError: pass response = jsonify(ret) response.status_code = 200 return response
def finish(): ret = {'success': False} try: if not User.check_username(request.form['username']): ret['username'] = '******' elif len(request.form['password']) == 0: ret['password'] = '******' elif len(request.form['stream_password']) == 0: ret['stream_password'] = '******' elif User.get_user(username=request.form['username']) == None: ret['success'] = True user = User(request.form['username'], User.make_password(request.form['password']), User.make_password(request.form['stream_password'])) session.add(user) session.commit() else: ret['username'] = '******' except KeyError: pass response = jsonify(ret) response.status_code = 200 return response
def register(): form = register_form(request.form) if request.method == "POST" and form.validate(): try: user = User.add_user(form.username.data, form.password.data) if form.email.data: user.mail = form.email.data rfk.database.session.commit() flash(gettext('Registration successful. You can now login'), 'success') return redirect(url_for("login")) except UserNameTakenException: form.username.errors.append(gettext('Username already taken!')) return render_template("register.html", form=form, TITLE='Register')
def register(): form = register_form(request.form) if request.method == "POST" and form.validate(): try: user = User.add_user(form.username.data, form.password.data) if form.email.data: user.mail = form.email.data rfk.database.session.commit() flash('Registration successful.', 'success') return redirect(url_for("login")) except UserNameTakenException: form.username.errors.append('Username already taken!') return render_template("register.html", form=form, TITLE='Register')
def info(user): user = User.get_user(username=user) upcoming_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.begin >= now()).order_by( Show.begin.asc()).limit(5).all() last_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.end <= now()).order_by( Show.end.desc()).limit(5).all() if user: ball = iso_country_to_countryball(user.country) return render_template('user/info.html', username=user.username, ball=ball, st=user.get_total_streamtime(), shows={'upcoming': upcoming_shows, 'last': last_shows}) else: abort(404)
def doConnect(data): """Handles a connect from liquidsoap Keyword arguments: data -- list of headers """ publish_show = False # better to not store any passwords in our logs safe_dump = data.copy() safe_dump.pop('Authorization', None) logger.info('doConnect: connect request %s' % (json.dumps(safe_dump), )) rfk.database.session.commit() try: auth = data['Authorization'].strip().split(' ') if auth[0].lower() == 'basic': try: username, password = base64.b64decode( auth[1]).decode('utf-8').split(':', 1) except UnicodeDecodeError: username, password = base64.b64decode( auth[1]).decode('latin-1').split(':', 1) if username == 'source': username, password = password.split(username_delimiter, 1) else: raise ValueError user = User.authenticate(username, password) if user.get_setting(code='use_icy'): if 'ice-genre' in data: user.set_setting(data['ice-genre'], code='icy_show_genre') if 'ice-name' in data: user.set_setting(data['ice-name'], code='icy_show_name') if 'ice-description' in data: user.set_setting(data['ice-description'], code='icy_show_description') show = init_show(user) publish_show = show.show logger.info('doConnect: accepted connect for %s' % (user.username, )) print user.user except (rexc.base.UserNotFoundException, rexc.base.InvalidPasswordException, KeyError): logger.info('doConnect: rejected connect, initiate kick...') kick() rfk.database.session.commit() publish.show_change(publish_show)
def info(user): try: user = User.get_user(username=user) except rfk.exc.base.UserNotFoundException: abort(404) # checking user rank if user.has_permission('admin'): rank = gettext('Admin') else: rank = gettext('User') # count planned and unplanned shows planned_shows = Show.query.join(UserShow).filter( UserShow.user == user, Show.flags == Show.FLAGS.PLANNED).count() unplanned_shows = Show.query.join(UserShow).filter( UserShow.user == user, Show.flags == Show.FLAGS.UNPLANNED).count() total_shows = planned_shows + unplanned_shows # list upcoming and recent shows upcoming_shows = Show.query.join(UserShow).filter( UserShow.user == user, Show.begin >= now()).order_by(Show.begin.asc()).limit(5).all() last_shows = Show.query.join(UserShow).filter( UserShow.user == user, Show.end <= now()).order_by(Show.end.desc()).limit(5).all() stats = {} for us in UserStatistic.query.filter(UserStatistic.user == user).all(): stats[us.code] = us.statistic.current_value().value return render_template('user/info.html', TITLE=user.username, user=user, rank=rank, planned_shows=planned_shows, unplanned_shows=unplanned_shows, total_shows=total_shows, st=user.get_total_streamtime(), shows={ 'upcoming': upcoming_shows, 'last': last_shows }, stats=stats)
def liquidsoap_meta_data(): """Handles track changes Returns error message if something suspicious happens Returns 'true' when everything worked like expected """ data = request.get_json() logger.debug('liquidsoap_meta_data: %s' % (json.dumps(data),)) if 'userid' not in data or data['userid'] == 'none': session.commit() return 'no userid' user = User.get_user(id=data['userid']) if user is None: session.commit() return 'user not found' if 'artist' in data: artist = data['artist'].strip() else: artist = None if 'title' in data: title = data['title'].strip() else: title = None if 'song' in data: song = data['song'].split(' - ', 1) if (artist is None) or (len(artist) == 0): artist = song[0] if (title is None) or (len(title) == 0): title = song[1] show = init_show(user) if artist is None and title is None: track = Track.current_track() if track: track.end_track() else: track = Track.new_track(show, artist, title) session.commit() return 'true'
def liquidsoap_auth(): """Authenticates a user This function will also disconnect the current user if the user to be authenticated has a show registered. If that happens this function will print false to the user since we need a grace period to actually disconnect the other user. Which means that the user has to reconnect! Keyword arguments: - username - password """ data = request.get_json() username, password = data['username'], data['password'] if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: logger.info('liquidsoap_auth: cleaning harbor because of planned show') if kick(): logger.info('liquidsoap_auth: harbor is now clean, reconnect pl0x') session.commit() return 'false' else: logger.info('liquidsoap_auth: harbor was empty, go ahead') logger.info('liquidsoap_auth: accepted auth for %s' % username) session.commit() return 'true' except rexc.base.InvalidPasswordException: logger.info('liquidsoap_auth: rejected auth for %s (invalid password)' % username) session.commit() return 'false' except rexc.base.UserNotFoundException: logger.info('liquidsoap_auth: rejected auth for %s (invalid user)' % username) session.commit() return 'false'
def doConnect(data): """Handles a connect from liquidsoap Keyword arguments: data -- list of headers """ publish_show = False # better to not store any passwords in our logs safe_dump = data.copy() safe_dump.pop('Authorization', None) logger.info('doConnect: connect request %s' % (json.dumps(safe_dump),)) rfk.database.session.commit() try: auth = data['Authorization'].strip().split(' ') if auth[0].lower() == 'basic': try: username, password = base64.b64decode(auth[1]).decode('utf-8').split(':', 1) except UnicodeDecodeError: username, password = base64.b64decode(auth[1]).decode('latin-1').split(':', 1) if username == 'source': username, password = password.split(username_delimiter, 1) else: raise ValueError user = User.authenticate(username, password) if user.get_setting(code='use_icy'): if 'ice-genre' in data: user.set_setting(data['ice-genre'], code='icy_show_genre') if 'ice-name' in data: user.set_setting(data['ice-name'], code='icy_show_name') if 'ice-description' in data: user.set_setting(data['ice-description'], code='icy_show_description') show = init_show(user) publish_show = show.show logger.info('doConnect: accepted connect for %s' % (user.username,)) print user.user except (rexc.base.UserNotFoundException, rexc.base.InvalidPasswordException, KeyError): logger.info('doConnect: rejected connect, initiate kick...') kick() rfk.database.session.commit() publish.show_change(publish_show)
def copy_shows(): local = pytz.timezone('Europe/Berlin') shows = oldsession.query(Show).yield_per(50) for oldshow in shows: if oldshow.streamer != None: user = User.get_user(username=oldshow.streamer.username) if oldshow.type == 'UNPLANNED': flag = NShow.FLAGS.UNPLANNED elif oldshow.type == 'PLANNED': flag = NShow.FLAGS.PLANNED show = NShow(name=oldshow.name[:50], description=oldshow.description, flags=flag, begin=local.normalize(local.localize(oldshow.begin).astimezone(pytz.utc)), end=local.normalize(local.localize(oldshow.end).astimezone(pytz.utc))) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(user) rfk.database.session.flush() rfk.database.session.commit()
def doMetaData(data): logger.debug('meta %s' % (json.dumps(data),)) if 'userid' not in data or data['userid'] == 'none': print 'no userid' return user = User.get_user(id=data['userid']) if user == None: print 'user not found' return artist = data['artist'] or '' title = data['title'] or '' if 'song' in data: song = data['song'].split(' - ', 1) if ('artist' not in data) or (len(data['artist'].strip()) == 0): artist = song[0] if ('title' not in data) or (len(data['title'].strip()) == 0): title = song[1] show = init_show(user) track = Track.new_track(show, artist, title) rfk.database.session.commit()
def dj(): """Return complete dj information Keyword arguments: dj_id -- database id of the requested dj dj_name -- nickname of the requested dj At least one argument is required """ dj_id = request.args.get('dj_id', None) dj_name = request.args.get('dj_name', None) try: user = User.get_user(id=dj_id, username=dj_name) return jsonify(wrapper({'dj': {'dj_id': user.user, 'dj_name': user.username }})) except rexc.base.UserNotFoundException: return jsonify(wrapper({'dj': None})) except AssertionError: return jsonify(wrapper(None, 400, 'missing required query parameter'))
def doAuth(username, password): """Authenticates a user This function will also disconnect the current user if the user to be authenticated has a show registered. If that happens this function will print false to the user since we need a grace period to actually disconnect the other user. (Which means that the user has to reconnect.) Keyword arguments: - username - password """ if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: logger.info('doAuth: cleaning harbor because of planned show') if kick(): sys.stdout.write('false') logger.info('doAuth: harbor is now clean, reconnect pl0x') rfk.database.session.commit() return else: logger.info('doAuth: harbor was empty, go ahead') logger.info('doAuth: accepted auth for %s' % username) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('doAuth: rejected auth for %s (invalid password)' % username) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('doAuth: rejected auth for %s (invalid user)' % username) sys.stdout.write('false') rfk.database.session.commit()
def doAuth(username, password): """Authenticates a user This function will also disconnect the current user if the user to be authenticated has a show registered. If that happens this function will print false to the user since we need a grace period to actually disconnect the other user. (Which means that the user has to reconnect.) Keyword arguments: - username - password """ if username == 'source': try: username, password = password.split(username_delimiter) except ValueError: pass try: user = User.authenticate(username, password) show = Show.get_current_show(user) if show is not None and show.flags & Show.FLAGS.PLANNED: logger.info('cleaning harbor') if kick(): sys.stdout.write('false') logger.info('harbor is now clean, reconnect pl0x') rfk.database.session.commit() return else: logger.info('harbor was empty, go ahead') logger.info('accepted auth for %s' % (username)) sys.stdout.write('true') except rexc.base.InvalidPasswordException: logger.info('rejected auth for %s (invalid password)' % (username)) sys.stdout.write('false') except rexc.base.UserNotFoundException: logger.info('rejected auth for %s (invalid user)' % (username)) sys.stdout.write('false') rfk.database.session.commit()
def doDisconnect(userid): logger.info('doDisconnect: diconnect for userid %s' % (userid,)) if userid == "none" or userid == '': print "Whooops no userid?" logger.warn('doDisconnect: no userid supplied!') rfk.database.session.commit() return user = User.get_user(id=int(userid)) if user: usershows = UserShow.query.filter(UserShow.user == user, UserShow.status == UserShow.STATUS.STREAMING).all() for usershow in usershows: usershow.status = UserShow.STATUS.STREAMED if usershow.show.flags & Show.FLAGS.UNPLANNED: usershow.show.end_show() rfk.database.session.commit() track = Track.current_track() if track: track.end_track() rfk.database.session.commit() else: print "no user found"
def settings(): form = SettingsForm( request.form, username=current_user.username, email=current_user.mail, show_def_name=current_user.get_setting(code='show_def_name'), show_def_desc=current_user.get_setting(code='show_def_desc'), show_def_tags=current_user.get_setting(code='show_def_tags'), show_def_logo=current_user.get_setting(code='show_def_logo'), use_icy=current_user.get_setting(code='use_icy')) if request.method == "POST" and form.validate(): if current_user.check_password(password=form.old_password.data): if form.new_password.data: current_user.password = User.make_password( form.new_password.data) current_user.mail = form.email.data current_user.set_setting(code='show_def_name', value=form.show_def_name.data) current_user.set_setting(code='show_def_desc', value=form.show_def_desc.data) current_user.set_setting(code='show_def_tags', value=form.show_def_tags.data) current_user.set_setting(code='show_def_logo', value=form.show_def_logo.data) current_user.set_setting(code='use_icy', value=form.use_icy.data) rfk.database.session.commit() flash('Settings successfully updated.', 'success') return redirect(url_for('settings')) else: form.old_password.errors.append('Wrong password.') ball = rfk.helper.iso_country_to_countryball(current_user.country) return render_template( 'settings.html', form=form, TITLE='Settings', ball=ball, imgur={'client': rfk.CONFIG.get('site', 'imgur-client')})
def login(): form = login_form(request.form) if request.method == 'POST' and form.validate(): username = form.username.data try: user = User.get_user(username=username) if user and user.check_password(password=form.password.data): user.authenticated = True remember = form.remember.data if login_user(user, remember=remember): if not user.last_login: flash( gettext( '<strong>Tip:</strong> It appears that this is your first login, if you need any help please visit our help section by clicking <a href="/help">here</a>.' ), 'info') user.last_login = now() loc = rfk.helper.get_location(request.remote_addr) if 'country_code' in loc and loc[ 'country_code'] is not None: user.country = loc['country_code'] rfk.database.session.commit() flash( gettext('Login successful. Welcome %s!' % user.username), 'success') return redirect( request.args.get('next') or url_for('index')) else: form.username.errors.append( gettext('There was an error while logging you in.')) #flash('There was an error while logging you in.', 'error') else: form.username.errors.append( gettext('Invalid User or Password.')) #flash('Invalid username or password.') except UserNotFoundException: form.username.errors.append(gettext('Invalid User or Password.')) #flash('Invalid username or password.') return render_template('login.html', form=form, TITLE=gettext('Login'))
def copy_shows(): local = pytz.timezone('Europe/Berlin') shows = oldsession.query(Show).yield_per(50) for oldshow in shows: if oldshow.streamer != None: user = User.get_user(username=oldshow.streamer.username) if oldshow.type == 'UNPLANNED': flag = NShow.FLAGS.UNPLANNED elif oldshow.type == 'PLANNED': flag = NShow.FLAGS.PLANNED show = NShow(name=oldshow.name[:50], description=oldshow.description, flags=flag, begin=local.normalize( local.localize(oldshow.begin).astimezone( pytz.utc)), end=local.normalize( local.localize(oldshow.end).astimezone(pytz.utc))) rfk.database.session.add(show) rfk.database.session.flush() show.add_user(user) rfk.database.session.flush() rfk.database.session.commit()
def info(user): try: user = User.get_user(username=user) except rfk.exc.base.UserNotFoundException: abort(404) # checking user rank if user.has_permission('admin'): rank = 'Admin' else: rank = 'User' # count planned and unplanned shows planned_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.flags == Show.FLAGS.PLANNED).count() unplanned_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.flags == Show.FLAGS.UNPLANNED).count() total_shows = planned_shows + unplanned_shows # list upcoming and recent shows upcoming_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.begin >= now()).order_by( Show.begin.asc()).limit(5).all() last_shows = Show.query.join(UserShow).filter(UserShow.user == user, Show.end <= now()).order_by( Show.end.desc()).limit(5).all() stats = {} for us in UserStatistic.query.filter(UserStatistic.user == user).all(): stats[us.code] = us.statistic.current_value().value return render_template('user/info.html', TITLE=user.username, user=user, rank=rank, planned_shows=planned_shows, unplanned_shows=unplanned_shows, total_shows=total_shows, st=user.get_total_streamtime(), shows={'upcoming': upcoming_shows, 'last': last_shows}, stats=stats)
def login(): form = login_form(request.form) if request.method == "POST" and form.validate(): username = form.username.data try: user = User.get_user(username=username) if user and user.check_password(password=form.password.data): user.authenticated = True remember = form.remember.data if login_user(user, remember=remember): user.last_login = now() session.commit() flash("Logged in!") return redirect(request.args.get("next") or url_for("index")) else: form.username.errors.append('There was an error while logging you in.') flash("Sorry, but you could not log in.") else: form.username.errors.append('Invalid User or Password.') flash(u"Invalid username or password.") except UserNotFoundException: form.username.errors.append('Invalid User or Password.') flash(u"Invalid username or password.") return render_template("login.html", form=form)
def load_user(userid): return User.get_user(id=int(userid))