Пример #1
0
def register():
    register_form = forms.SignupForm(request.form)
    current_app.logger.info(request.form)
    error = ''
    if request.method == 'POST' and not register_form.validate():
        error = "Registration error"

    elif request.method == 'POST' and register_form.validate():
        username = request.form['username']

        if u'CREATOR' in request.form['user_role']:
            isAdmin = True
        else:
            isAdmin = False

        password_hash = flask_bcrypt.generate_password_hash(
            request.form['password'])

        user = User(username=username, password=password_hash, admin=isAdmin)

        try:
            user.save()
            if login_user(user, remember=False):
                return redirect('/')
            else:
                error = "Unable to log in"
        except:
            error = "Error on registration - possible duplicate logins"

    data = {'form': register_form, 'error': error}

    return render_template("auth/register.html", **data)
Пример #2
0
def updateTaskStatusByUserIdByGameIdByTaskId():
    if request.method == 'POST':
        data = request.json
        current_app.logger.debug('get data from frontend.')
        current_app.logger.debug(data)
        doc = User(user_id=current_user.user_id).get_user_doc()
        if 'gameid' in data and 'taskid' in data and 'status' in data and doc:
            game_status = json.loads(doc.game_status)
            # update user game status
            game_status[data['gameid']]['tasks'][
                data['taskid']]['status'] = data['status']
            game_status = json.dumps(game_status)
            current_app.logger.debug('update game status.')
            current_app.logger.debug(game_status)
            try:
                status = User.set_game_status(current_user.user_id,
                                              game_status)
                status &= User.set_last_active_time(current_user.user_id)
                if not status:
                    current_app.logger.debug(
                        'update db for game status complete.')
                else:
                    current_app.logger.debug(
                        'update db for game status failed.')
            except:
                current_app.logger.debug('db transaction failed')

    else:
        return render_template(
            '/auth/internalerror.html',
            msg='Invalid request arguments.',
        )
Пример #3
0
def register():
	register_form = forms.SignupForm(request.form)
	current_app.logger.info(request.form)
	error = ''
	if request.method == 'POST' and False == register_form.validate():
		error = "Registration error"

	elif request.method == 'POST' and register_form.validate():
		email = request.form['email']

		if u'CREATOR' in request.form['user_role']:
			isAdmin = True
		else:
			isAdmin = False

		password_hash = flask_bcrypt.generate_password_hash(request.form['password'])

		user = User(email=email, password=password_hash, admin=isAdmin)

		try:
			user.save()
			if login_user(user, remember=False):
				return redirect('/')
			else:
				error = "Unable to log in"
		except:
			error = "Error on registration - possible duplicate emails"

	data = {
		'form': register_form,
		'error': error
	}

	return render_template("/auth/register.html", **data)
Пример #4
0
def load_user(id):
    if id is None:
        redirect('/login/twitter')
    user = User()
    user = user.get_by_id(id)
    if user.is_active():
        return user
    else:
        redirect('/login/twitter')
Пример #5
0
def load_user(id):
	if id is None:
		redirect('/login')
	user = User()
	user = user.get_by_id(id)
	if user.is_active():
		return user
	else:
		redirect('/login')
Пример #6
0
def register():
    register_form = forms.SignupForm(request.form)
    current_app.logger.debug(request.form)
    error_message = ''
    if request.method == 'POST':
        if not register_form.validate():
            current_app.logger.debug(register_form.errors)
            error_message = '密码不一致'
            current_app.logger.debug('密码不一致!')
        else:
            #if not recaptchaCheck(request.form['g-recaptcha-response']):
            #return '请点击人机身份验证!'
            # Prepare User with register info from form
            access_code_obj = AccessCode.from_access_code(
                request.form['access_code'], )
            if access_code_obj is None:
                error_message = '邀请码不正确'
                current_app.logger.debug('邀请码不正确!')
                current_app.logger.debug('wrong access code!')
            else:
                # If we get access code correctly
                reg_timestamp = datetime.datetime.now()
                user = User(
                    user_id=str(uuid.uuid4()),  # generate unique user id
                    email=request.form['email'],
                    username=request.form['username'],
                    password=flask_bcrypt.generate_password_hash(
                        request.form['password'], ),
                    role=access_code_obj.role,
                    register_t=reg_timestamp,
                    expire_t=reg_timestamp +
                    datetime.timedelta(days=access_code_obj.expiration, ),
                    last_active_t=reg_timestamp,
                )
                current_app.logger.debug('Try to save and login!')
                #try:
                user.save_register()
                current_app.logger.debug('Save new user completed!')
                if login_user(user, remember=True):
                    current_app.logger.debug('Login successful!')
                    current_app.logger.debug('user %s' % user.user_id)
                    return redirect('/userGameStatuses')
                else:
                    error_message = '登录失败'
                    current_app.logger.debug('Login successful!')
                    current_app.logger.debug('登录失败!')
            #except:
            #    current_app.logger.error(
            #        'Error on Registration - possible duplicate emails.'
            #    )

    # Prepare registration form
    template_data = {'form': register_form, 'error_message': error_message}
    return render_template('/auth/register.html', **template_data)
Пример #7
0
def assignMentor():
    if request.method == 'POST':
        data = request.json
        current_app.logger.debug(data)
        if 'mentor' in data:
            User.set_mentor(data['mentor'])
    else:
        return render_template(
            '/auth/internalerror.html',
            msg='Invalid request arguments.',
        )
Пример #8
0
async def command_check(ctx):
    """ Creating logs for each command """
    user = User(0)
    user.set_logs_infos(ctx.message.author.name, ctx.message.author.avatar,
                        ctx.message.author.id)

    if (ctx.guild != None):
        logs.add_log(
            user, ctx.guild.name + '/' + str(ctx.message.channel) + ' : ' +
            ctx.message.content)
    else:
        logs.add_log(user,
                     str(ctx.message.channel) + ' : ' + ctx.message.content)
    return True
Пример #9
0
def login():
    if request.method == "POST" and "email" in request.form:
        email = request.form["email"]
        userObj = User()
        user = userObj.get_by_email_w_password(email)
     	if user and password(user.password,request.form["password"]) and user.is_active():
			remember = request.form.get("remember", "no") == "yes"

			if login_user(user, remember=remember):
				flash("Logged in!")
				return redirect('/file-upload')
			else:
				flash("unable to log you in")

    return render_template("/auth/login.html")
Пример #10
0
def login():
	if request.method == "POST" and "email" in request.form:
		email = request.form["email"]
		u = User()
		user = u.get_by_email_w_password(email)

		if user and flask_bcrypt.check_password_hash(user.password, request.form["password"]) and user.is_active():
			remember = request.form.get("remember", "no") == "no"

			if login_user(user, remember=remember):
				return redirect('/events/create')
			else:
				pass

	return render_template("/auth/login.html")
Пример #11
0
def manage_users():
    options = set_options()
    # tutaj kod

    cnx, cursor = connect_db()

    # u = User()
    # u.username = '******'
    # u.email = '*****@*****.**'
    # u.set_password('nimbus2000', '1999')
    # u.save_to_db(cursor)

    # u = User.load_user_by_id(cursor, 2)
    # print(u.id)
    # print(u.email)
    # print(u.username)

    users = User.load_all_users(cursor)
    print('{} users:'.format(len(users)))
    print('-----')
    for user in users:
        print(user.id)
        print(user.username)
        print(user.email)
        print('-----')

    close_connection(cnx, cursor)
Пример #12
0
def register():

    if request.method == 'POST' and form.validate():
        email = request.form['email']

	password = request.form['password']

	user = User(email,password)
	print user
        form.populate_obj(user)
        user.save()

        login.login_user(user)
        return redirect(url_for('login'))

    return render_template("/auth/register.html")
Пример #13
0
def login():
    if request.method == "POST" and "username" in request.form:
        username = request.form["username"]
        u = User()
        user = u.get_by_username_w_password(username)

        if user and flask_bcrypt.check_password_hash(
                user.password, request.form["password"]) and user.is_active():
            remember = request.form.get("remember", "no") == "no"

            if login_user(user, remember=remember):
                return redirect('/events/create')
            else:
                pass

    return render_template("auth/login.html")
Пример #14
0
def manage_users():
    options = set_options()
    # kodzik tutaj

    cnx, cursor = connect_to_db()

    # u = User()
    # u.username = '******'
    # u.email = "*****@*****.**"
    # u.set_password('passat_b5', '1999')
    # u.save_to_db(cursor)

    # u = User.load_user_by_id(cursor,1)
    # print(u.id)
    # print(u.email)
    # print(u.username)

    users = User.load_all_users(cursor)
    print('{} users:'.format(len(users)))
    for user in users:
        print(user.id)
        print(user.username)
        print(user.email)
        print("------")

    close_connection(cnx, cursor)
Пример #15
0
def login():
    error_message = ''
    if request.method == 'POST':
        #if not recaptchaCheck(request.form['g-recaptcha-response']):
        #return '请点击人机身份验证!'
        # check form keys
        if 'email' in request.form and 'password' in request.form:
            user = User.from_email(request.form['email'])
            if user is None:
                error_message = '此邮箱可能并未注册'
                current_app.logger.debug('此邮箱可能并未注册!')
            elif not flask_bcrypt.check_password_hash(
                    user.password,
                    request.form['password'],
            ):
                error_message = '登录密码不正确'
                current_app.logger.debug('登录密码不正确!')
            elif (user.expire_t.date() - datetime.date.today()).days < 0:
                error_message = '账户已过期'
                current_app.logger.debug('账户已过期!')
            else:
                if login_user(user, remember=True):
                    current_app.logger.debug('登录成功!')
                    return redirect('/userGameStatuses')
                else:
                    error_message = '登录失败'
                    current_app.logger.debug('登录失败!')
    return render_template('/auth/login.html', error_message=error_message)
Пример #16
0
def main():
    """
    Create user object and use the C-Car API.
    Test application and prepare real time use cases
    :return:
    """
    Driver = User(car='audiA3', mode='kierowca')
    Driver.connect_to_device()
    Driver.get_actual_gas_level()
    Driver.get_actual_speed()

    print 'speed: %s, gas level: %s' % (Driver.speed, Driver.gas)
Пример #17
0
def get_task(requesttype):
    """Defines the api and what is returned to the end user"""
    if requesttype == 'r':
        key, username, mods, pp, ranked = parse_params(
            request.args)  # Parses the parameters to be used
        if not key or not username:  # Handler for when the key or username isn't defined as a parameter
            return jsonify({'error': 'Bad request'})
        if check_key(
                key
        ) == False:  # This checks if the provided key is a valid key
            return jsonify({'error': 'Not a valid api key'})
        if limit_check(
                key
        ) == False:  # This checks if the key hasn't reached it's rate limit
            engine.recommend(User(username), 3)  # Self explanatory
            return jsonify({
                'username': username,
                'mods': mods,
                'pp': pp,
                'ranked': ranked,
                'recommended': build_map(engine)
            })
        else:  # This is for when the rate limit has been reached
            return jsonify(
                {'error': 'Rate limit for this key has been reached'})
    elif requesttype == 'user':
        key, username, _, _, _ = parse_params(
            request.args)  # Parses the parameters to be used
        if not key or not username:  # Handler for when the key or username isn't defined as a parameter
            return jsonify({'error': 'Bad request'})
        if check_key(
                key
        ) == False:  # This checks if the provided key is a valid key
            return jsonify({'error': 'Not a valid api key'})
        if limit_check(
                key
        ) == False:  # This checks if the key hasn't reached it's rate limit
            return jsonify(build_user(User(username)))
        else:  # This is for when the rate limit has been reached
            return jsonify(
                {'error': 'Rate limit for this key has been reached'})
    else:
        return jsonify({'error': 'Unknown api route'})
Пример #18
0
    def generate_new_key(self, osu_id: int, discord_id: int):
        """ Generating a new key """
        discord_id = int(discord_id)

        link_dictionary[osu_id] = [key(), discord_id]

        # Creating the user
        user = User(osu_id)

        return link_dictionary[osu_id][0].get()
Пример #19
0
def oauth_authorized(resp):
    next_url = request.args.get('next') or '/'
    if resp is None:
        return redirect(next_url)
    username = resp['screen_name']
    session['access_token'] = resp['oauth_token']
    session['screen_name'] = username
    session['twitter_token'] = (resp['oauth_token'], resp['oauth_token_secret'])

    user = User().get_by_username(username=username)
    if user is None:
        user = User(username=username, admin=True)  # , password=flask_bcrypt.generate_password_hash(username))
        user.save()
        sleep(50)
        if login_user(user, remember=False):
            return redirect('/')
    else:
        login_user(user)
        sleep(50)
        return redirect('/')
Пример #20
0
    def link_account(self, osu_id: int, key: string):
        """ Trys to link an account """

        # Creating the user
        user = User(osu_id=osu_id)

        str_id = str(osu_id)

        if link_dictionary[str_id][0].get() == key:
            # The key is right : linking user
            user.discord_id = link_dictionary[str_id][1]
            user.save_user_profile()
            return

        elif link_dictionary[str_id][0].get() == None:
            # This key seems to be expired
            link_dictionary.pop(str_id)
            raise ValueError("The key you are looking for expired")

        else:
            raise KeyError("This key doesn't exists")
Пример #21
0
def getStudentGameStatuses():
    #try:
    students = []
    for user in User.get_users_by_mentor(current_user.username):
        students.append({
            'name': user.username,
            'games': json.loads(user.game_status),
        })
    return render_template(
        '/auth/student_game_statuses.html',
        Students=students,
    )
Пример #22
0
def admin_entry_create():

    user = User().get_by_id(g.user)
    if user.is_admin(): pass
    else:
        return render_template(
            'index.html',
            error=
            "User role: COMMENTER. You are not authorized to post events.",
            events=models.Event.objects.order_by("-last_updated"))

    if request.method == "POST":
        if request.form.get('starting_at') == '' or request.form.get(
                'ending_at') == '':
            error = 'Fill in DateTime fields'
            data = {'title': 'Create event', 'event': None, 'error': error}
            return render_template('event/event_edit.html', **data)

        event = models.Event()
        event.title = request.form.get('title')
        event.description = request.form.get('content')
        event.starting_at = datetime.strptime(request.form.get('starting_at'),
                                              '%Y-%m-%d %H:%M:%S')
        event.ending_at = datetime.strptime(request.form.get('ending_at'),
                                            '%Y-%m-%d %H:%M:%S')

        event.user = current_user.get_mongo_doc()
        event.save()

        status = event.title + ': ' + event.description
        if len(status) > 140: status = status[:137] + '...'
        tweets.post(status=status)

        return redirect('/events/%s' % event.id)
    else:
        data = {
            'title': 'Create new event',
            'event': None,
        }
        return render_template('event/event_edit.html', **data)
Пример #23
0
async def on_command_error(ctx, error):
    if (type(error.original) == discord.errors.Forbidden):
        print("Cannot send messages to this user (FORBIDDEN)")
        pass
    elif (ctx.command):
        errors = traceback.format_exception(type(error), error,
                                            error.__traceback__)
        output = ''
        for line in errors:
            output += line

        user = User(0)
        user.set_logs_infos(ctx.message.author.name, ctx.message.author.avatar,
                            ctx.message.author.id)
        logs.add_error_log(user,
                           'On command {}'.format(ctx.command.qualified_name),
                           output)
        logs.send_logs()

        await ctx.send('Crap, an error ! Need some healing ? {}'.format(
            settings['discord_server']))
        bot.logger.exception(type(error).__name__, exc_info=error)
Пример #24
0
def admin_entry_create():

	user = User().get_by_id(g.user)
	if user.is_admin(): pass
	else:
		return render_template('index.html', error="User role: COMMENTER. You are not authorized to post events.", events=models.Event.objects.order_by("-last_updated"))

	if request.method == "POST":
		if request.form.get('starting_at') == '' or request.form.get('ending_at') == '':
			error = 'Fill in DateTime fields'
			data = {
				'title': 'Create event',
				'event': None,
				'error': error
			}
			return render_template('event/event_edit.html', **data)

		event = models.Event()
		event.title = request.form.get('title')
		event.description = request.form.get('content')
		event.starting_at = datetime.strptime(request.form.get('starting_at'), '%Y-%m-%d %H:%M:%S')
		event.ending_at = datetime.strptime(request.form.get('ending_at'), '%Y-%m-%d %H:%M:%S')

		event.user = current_user.get_mongo_doc()
		event.save()

		status = event.title + ': ' + event.description
		if len(status) > 140: status = status[:137] + '...'
		tweets.post(status=status)

		return redirect('/events/%s' % event.id)
	else:
		data = {
			'title': 'Create new event',
			'event': None,
		}
		return render_template('/event/event_edit.html', **data)
Пример #25
0
def getUserGameStatuses():
    if request.method == 'GET':
        doc = User(user_id=current_user.user_id).get_user_doc()
        game_status = json.loads(doc.game_status)
        profile = {}
        profile['teacher'] = (doc.role in ('a', 'm'))
        profile['admin'] = (doc.role == 'a')
        profile['games'] = game_status
        current_app.logger.debug('user game status:')
        current_app.logger.debug(profile)
        return render_template('/auth/gamestatuses.html', Profile=profile)
    return render_template(
        '/auth/internalerror.html',
        msg='User Id Missing in Request Arguments.',
    )
Пример #26
0
def manage_users():
    options = set_options()

    # tutaj kod
    # 4 ify

    cnx, cursor = connect_to_db()

    # u=User()
    # u.username = '******'
    # u.email = '*****@*****.**'
    # u.set_password('passat_a5', '1999')
    # u.save_to_db(cursor)
    u = User.load_user_by_id(cursor, 1)
    print(u.id)
    print(u.email)
    print(u.username)
    close_connection(cnx, cursor)
Пример #27
0
def oauth_authorized(resp):
    next_url = request.args.get('next') or '/'
    if resp is None:
        return redirect(next_url)
    username = resp['screen_name']
    session['access_token'] = resp['oauth_token']
    session['screen_name'] = username
    session['twitter_token'] = (resp['oauth_token'],
                                resp['oauth_token_secret'])

    user = User().get_by_username(username=username)
    if user is None:
        user = User(
            username=username, admin=True
        )  # , password=flask_bcrypt.generate_password_hash(username))
        user.save()
        sleep(50)
        if login_user(user, remember=False):
            return redirect('/')
    else:
        login_user(user)
        sleep(50)
        return redirect('/')
Пример #28
0
def load_user(user_id):
    return User.from_user_id(user_id)
def worker(timesheets):
    # Get Timesheet Billings
    timesheetUris = []
    for value in timesheets.values():
        timesheetUris.append(value['uri'])

    data = {"timesheetUris": timesheetUris}

    parsed = RepliconClient.query('TimesheetService1',
                                  'BulkGetTimesheetDetails', data)

    for result in parsed['d']:
        timesheet = result['uri']
        slug = result['slug']
        print("Timesheet: {} {}".format(timesheet, slug))
        date_range = result['dateRange']
        start_date = datetime(int(date_range['startDate']['year']),
                              int(date_range['startDate']['month']),
                              int(date_range['startDate']['day']))
        end_date = datetime(int(date_range['endDate']['year']),
                            int(date_range['endDate']['month']),
                            int(date_range['endDate']['day']))
        # puts "StartDate: #{start_date} EndDate: #{end_date}"
        billings = []
        for ta in result['timeAllocations']:
            uri = ta['uri']
            if not ta['project']:  #time off
                continue
            duration = float(ta['duration']['hours']) + float(
                ta['duration']['minutes']) / 60
            date = datetime(int(ta['date']['year']), int(ta['date']['month']),
                            int(ta['date']['day']))
            user_slug = ta['user']['slug']
            hourly_rate = timesheets[slug]['HourlyRate'] if ta[
                'billingRate'] else 0
            project_uri = ta['project']['uri']
            project_slug = ta['project']['slug']
            user_uri = ta['user']['uri']

            billings.append({
                'Entrydate':
                date,
                'Staffingweek':
                date - timedelta(days=date.weekday()),
                'Billhours':
                duration,
                'HourlyRate':
                hourly_rate,
                'Startdate':
                start_date,
                'Enddate':
                end_date,
                'Projectname':
                Project().name(project_uri),
                'Projectcode':
                Project().code(project_uri),
                'email':
                User().email(user_uri),
                'Title':
                User().title(user_uri),
                'TimesheetSlug':
                slug[1:1000],  #slug without dot
                'ProjectSlug':
                project_slug,
                'UserSlug':
                user_slug,
            })

        # billings = sorted(
        #   billings,
        #   key=lambda billing: "{}{}{}".format(
        #     billing['Projectcode'],
        #     billing['email'],
        #     billing['Entrydate'].strftime('%Y-%m-%d')
        #   )
        # )
        downloaded_billings.extend(billings)
Пример #30
0
                if self.precision == 0.0:
                    self.precision = 0.0
                    break  #Failed to find any beatmap
            else:
                self.recommendatons.append(Beatmap(beatmap_id[0]))
                self.mods.append(mods.replace('_', ''))
                #Saving the recommendation into the user profile
                preset.user.get_recommended(mods,
                                            "'" + str(beatmap_id[0]) + "'")

        if (len(self.recommendatons) == count):
            #Saving the users recommendations if everything is fine
            preset.user.save_user_profile()

        return self.recommendatons


if __name__ == '__main__':
    # --- Test lines !

    now = time.time()
    engine = REngine()
    engine.recommend(Preset(User(osu_name="Renondedju")), 10)
    print("Done, here are the results ({}), {}% of precision".format(
        len(engine.recommendatons), engine.precision * 100))
    for i in range(10):
        print(engine.recommendatons[i].beatmap_id, end=' - ')
        print(engine.mods[i])
    print('Done in {} s'.format(time.time() - now))
Пример #31
0
def run_irc():
    irc = IRCbot('irc.ppy.sh', settings['irc_username'], settings['irc_token'])
    engine = REngine()
    stayonline = True

    logs.add_warning_log('Connecting to irc.ppy.sh:6667 as ' + irc.nick)
    logs.send_logs()

    irc.connect()    

    while stayonline:
        try:
            message = irc.get_privmsg()
            if (message[0]): #if we got a message
                print('From ' + message[1]['sender'] + ' : ' + message[1]['message'])
                user = User(osu_name=message[1]['sender'])
                logs.add_log(user, 'IRC : ' + message[1]['message'])

                #checking if the message is a command
                if (message[1]['message'].startswith(settings['prefix'])):
                    command = message[1]['message'].strip(settings['prefix']).split(' ', 1)
                    
                    command_text  = command[0]
                    command_param = ""

                    if (len(command) > 1):
                        command_param = command[1]

                    if (command_text == 'test'):
                        irc_command_test(irc, user)
                    if (command_text == 'help'):
                        irc_command_help(irc, user)
                    if (command_text == 'link'):
                        irc_command_link(irc, user, command_param)
                    if (command_text == 'r'):
                        irc_command_recommend(irc, user, command_param)

            #Checking buffer and sending messages if needed
            irc.check_buffer()

        except KeyboardInterrupt:
            irc.close()

        except Exception as e:
            ex_type, ex, tb = sys.exc_info()
            errors = traceback.format_tb(tb)
            date   = datetime.now().strftime('%Y/%m/%d at %H:%M:%S')

            errorReport = '\n\n---ERROR REPORT---  ' + date + '\n'
            for error in errors:
                errorReport += error
            errorReport += '{0} : {1}'.format(type(ex).__name__, ex.args)
            
            logs.add_error_log(User(osu_name=message[1]['sender']), message[1]['message'], errorReport)
            irc.send_message(message[1]['sender'], 'Damn ! An error ! I created a report, this should be fixed soon :)')
            print (errorReport)


    irc.close()

    logs.add_warning_log('IRC connexion closed')
    logs.send_logs()
Пример #32
0
            selected_mods = 'HD'
        elif mods == Mods.DoubleTime:
            selected_mods = 'DT'
        elif mods == Mods.DoubleTime | Mods.Hidden:
            selected_mods = 'DTHD'
        elif mods == Mods.DoubleTime | Mods.HardRock:
            selected_mods = 'DTHR'
        elif mods == Mods.HardRock | Mods.Hidden:
            selected_mods = 'HRHD'
        elif mods == Mods.DoubleTime | Mods.HardRock | Mods.Hidden:
            selected_mods = 'DTHRHD'

        for mod in self.mods:
            if (mod == selected_mods):
                self.mods[mod] = 100.0
            else:
                self.mods[mod] = 0.0

        return


if __name__ == '__main__':
    #Just some test lines

    peppy = User(2)
    preset = Preset(peppy, 'stream')
    print(preset.mode)
    print(peppy.playstyle)
    print(preset.playstyle)
    preset.select_mods(Mods.Hidden)
    print(preset.mods['HD'])
Пример #33
0
class TestUser(unittest.TestCase):
    device = unittest.Mock()
    user = User(car="audi", state="False", device=device)