示例#1
0
def addFormUser(db, data):
	_firstname = data.get('firstname')
	_lastname = data.get('lastname')
	_password = data.get('password')
	_primary_provider = data.get('loginType')
	_email = data.get('email')
	_username = data.get('username')

	print(_email)
	#initialize user model
	user = User(_firstname,
             _lastname,
             _email,
             _primary_provider,
             _username,
             '')
	#save hashed user password
	user.password_hash(_password)
	#insert user to database
	db.session.add(user)
	data = db.session.commit()

	if not data:
		return {'success': 'User Created'}
	else:
		return {'error': 'There was a problem'}
示例#2
0
	def deletarUsuarios(self):
		login = raw_input("\nDigite o login do usuario: ")
		user = User()
		user = user.get(login)
		if user:
			user.remove()
		else:
			
			print "Usuario nao encontrado!"
示例#3
0
def delete_user(window):
    """allows the user to delete his user from the system (the database)"""
    del_window = messagebox.askyesno(
        title="Warning!",
        message="Are you sure you want\nto delete your user?"
        "\nThis action can't be undone.")  # asks the user if he is sure
    if del_window is True:  # if he presses "yes" the user is deleted and the game exits
        User.del_user(GameUI.logged_in_user.id)
        messagebox.showinfo(title="Goodbye", message="User deleted.")
        window.destroy()
class RecipeTestCase(unittest.TestCase):
    def setUp(self):
        self.user = User()

    def test_recipe_initialy_empty(self):
        self.assertEqual(self.user.recipes, {})

    def test_create_recipe_successfully(self):
        initial_recipe_count = len(self.user.recipes)
        self.user.create_recipe('Rolex','eggs')

        new_recipe_count = len(self.user.recipes)
        self.assertEqual(new_recipe_count - initial_recipe_count, 1)

    def test_create_recipe_when_recipe_already_exists(self):
        self.user.recipes = {'Peppers': ['black']}
        self.assertEqual(self.user.create_recipe('Peppers', 'black'),
                         'recipe already exists!', msg='recipe already exists!')

    def test_update_recipes(self):
        self.user.recipes = {'Peppers': ['black']}
        self.assertEqual(self.user.update_recipes(
            'Peppers', 'black_pepper'), {'black_pepper': ['black']})

    def test_updating_non_existing_recipe(self):
        self.user.recipes = {'Peppers': ['black']}
        self.assertEqual(self.user.update_recipes('Pepper', 'black'),
                         'recipe name does not exist here', msg='recipe name does not exist here')

    def test_update_recipe_item(self):
        self.user.recipes = {'Peppers': ['black']}
        self.assertEqual(self.user.update_recipe_item(
            'Peppers', 'black', 'blac'), {'Peppers': ['blac']})


    def test_updating_non_existing_recipe_item(self):
        self.user.recipes = {'Peppers': ['black']}
        self.assertEqual(self.user.update_recipe_item('Peppers', 'blac', 'bla'),
                         'Item not in recipe', msg='Item not in recipe')

    def test_read_recipe_items(self):
        self.user.recipes = {'Peppers': ['black', 'red']}
        self.assertEqual(self.user.read_recipes('Peppers'), ['black', 'red'])

    def test_delete_recipe(self):
        self.user.recipes = {'Peppers': ['black', 'red'], 'Onions': ['diced', 'ground']}
        self.assertEqual(self.user.delete_recipes(
            'Peppers'), {'Onions': ['diced', 'ground']})

    def test_delete_recipe_item(self):
        self.user.recipes = {'Peppers': ['black', 'red'], 'Onions': ['diced', 'ground']}
        self.assertEqual(self.user.delete_recipe_item('Peppers', 'black'), {
'Peppers': ['red'], 'Onions': ['diced', 'ground']})
示例#5
0
	def autenticaUsuario(self):
	   
		login = raw_input("\nDigite o login do usuario: ")
		senha = raw_input("\nDigite a senha do usuario: ")
		user = User()
		user.get(login)
		if user:
			if user.nome == login and user.senha == senha:
				print "\nSeja bem vindo %s! ",user.nome
			
			else:
				print "\nAcesso negado!"
		else:
			
			print "\nUsuario nao encontrado!"
示例#6
0
def logout():
    try:
        return User.logout(request.headers['Id'],
                           request.headers['Token']
                           )
    except Exception as ex:
        return Tools.Result(False, ex.args)
示例#7
0
 def tearDownClass(cls):
     """resets the database changes"""
     cursor = User.db_connect()  # connects to db
     cursor.execute(
         """UPDATE [Users] SET [NumberOfWinnings]=0 WHERE [ID]=0""")
     cursor.execute("""UPDATE [Users] SET [NumberOfGames]=0 WHERE [ID]=0""")
     cursor.commit()  # executes SQL command
示例#8
0
def editProfile():
    form = ProfileForm()

    user = User.byId(session['user_id']) 
    if 'user_id' not in session:
        return redirect(url_for('signin'))
    
    if form.validate_on_submit() == False:
        
        form.firstname.data = user.first_name
        form.lastname.data = user.last_name
        form.about.data = user.about_me
    else:
    
        cursor= cnx.cursor()
        cursor=cnx.cursor()
        cursor.callproc('update_user',(user.user_id,form.firstname.data,form.lastname.data,form.about.data))
        cursor.close()
        cnx.commit()
        flash('saved changes')
    if form.change_password.data:   
            hashing_pwd = bcrypt.generate_password_hash(form.change_password.data,10)
            cursor = cnx.cursor()
            cursor.callproc("update_user_password", [user.user_id,hashing_pwd])
            cursor.close()
            flash('saved changes')
       
    return render_template('editProfile.html',form=form)
示例#9
0
    def test_statistics_won(self):
        """testing that the statistics are updated accordingly if the user won"""

        cursor = User.db_connect()
        cursor.execute("SELECT * FROM [Users] WHERE [ID]=0"
                       )  # selects the first row in the db (test row)
        rows = cursor.fetchall()

        User.add_score(0, won=True)

        cursor = User.db_connect()
        cursor.execute("SELECT * FROM [Users] WHERE [ID]=0"
                       )  # selects the updated first row in the db (test row)
        updated_rows = cursor.fetchall()

        self.assertEqual(updated_rows[0].NumberOfWinnings,
                         rows[0].NumberOfWinnings + 1)
示例#10
0
def profile_by_id(user_id):
        user = User.byId(user_id)
    
        cursor= cnx.cursor()
        cursor.callproc("get_article_titles_by_author", [user.user_id])
        articles = cursor.fetchall()
        cursor.close
        return render_template('profile.html', user=user, articles = articles)
示例#11
0
def enter_app():
    try:
        data = request.get_json()
        return User.enter_app(data['PhoneNumber'], data['UUID'])
    except Exception as ex:
        import traceback
        traceback.print_exc()
        return Tools.Result(False, ex.args)
示例#12
0
def update_profile_info():
    try:
        data = request.get_json()
        return User.update_profile_info(request.headers['Id'],
                                        data['Name'],
                                        data['Birthdate']
                                        )
    except Exception as ex:
        return Tools.Result(False, ex.args)
示例#13
0
 def test_db_connection(self):
     """testing the connection to the database"""
     cursor = User.db_connect()  # connects to db
     cursor.execute("SELECT * FROM [Users] WHERE [ID]=0"
                    )  # selects the first row in the db (test row)
     rows = cursor.fetchall()
     self.assertEqual(rows[0].FirstName, 'testFirstName')
     self.assertEqual(rows[0].LastName, 'testLastName')
     self.assertEqual(rows[0].Username, 'testUsername')
示例#14
0
    def test_statistics_lost(self):
        """testing that the statistics are updated accordingly if the user lost"""

        cursor = User.db_connect()
        cursor.execute("SELECT * FROM [Users] WHERE [ID]=0"
                       )  # selects the first row in the db (test row)
        rows = cursor.fetchall()

        User.add_score(0, won=False)

        cursor = User.db_connect()
        cursor.execute("SELECT * FROM [Users] WHERE [ID]=0"
                       )  # selects the updated first row in the db (test row)
        updated_rows = cursor.fetchall()

        self.assertEqual(updated_rows[0].NumberOfGames, rows[0].NumberOfGames +
                         1)  # the number of games should grow by 1
        self.assertEqual(updated_rows[0].NumberOfWinnings,
                         rows[0].NumberOfWinnings)
示例#15
0
    def add_user(self, username):
        if [user for user in self.users.values() if user.name == username]:
            raise Exception("user name already exists")

        uid = uuid.uuid1()
        usr = User(username, uid)
        self.users[uid] = usr

        print(usr.id, usr.name, sep=" - ")
        return uid
示例#16
0
def profile():
    form = ProfileForm()
    if 'user_id' not in session:
        return redirect(url_for('signin'))

    else:
        user = User.byId(session['user_id'])
        cursor= cnx.cursor()
        cursor.callproc("get_article_titles_by_author", [user.user_id])
        articles = cursor.fetchall()
        cursor.close
        return render_template('profile.html', user=user, articles = articles)
示例#17
0
def complete_sign_up():
    try:
        data = request.get_json()
        return User.complete_sign_up(data['PhoneNumber'],
                                     data['Name'],
                                     data['BirthDate'],
                                     data['Gender']
                                     )
    except Exception as ex:
        import traceback
        traceback.print_exc()
        return Tools.Result(False, ex.args)
示例#18
0
    def processUsers(self, fromServer):
        fromServer = fromServer[fromServer.index("USER") + 5:-5]
        fromServer = fromServer.split("#")

        users = []
        index = 1
        id = ""
        name = ""
        surname = ""
        lastname = ""
        password = ""
        connected = ""
        active = ""

        for row in fromServer:
            if index == 1:
                id = row

            if index == 2:
                name = row

            if index == 3:
                surname = row

            if index == 4:
                lastname = row

            if index == 5:
                password = row

            if index == 6:
                connected = row

            if index == 7:
                active = row

            if row == "USER" or row == "END":
                aux = User(id, name, surname, lastname, password, connected,
                           active)
                print(id, name, surname, lastname, password, connected, active)
                users.append(aux)
                index = 0

            index += 1

        return users
示例#19
0
def register_user(reg_screen, first_name, last_name, username, email, password,
                  confirm):
    """takes the values the user entered when signing up, checks for errors and shows them on the screen. 
     if everything is valid the user is registered"""
    try:
        error.destroy(
        )  # if there's already an error on the screen, deletes it first
    except NameError:
        pass

    def error_label(text):  # shows the error on the screen
        global error
        error = ttk.Label(reg_screen,
                          text=text,
                          font=("Calibri Bold", 12),
                          foreground='black',
                          background='light blue')
        error.pack()

    if len(first_name.get()) == 0 or len(last_name.get()) == 0 or len(username.get()) == 0 or len(email.get()) == 0 or \
            len(password.get()) == 0 or len(confirm.get()) == 0:
        error_label("missing required info")
    elif not first_name.get().isalpha():
        error_label("Invalid first name")
    elif not last_name.get().isalpha():
        error_label("Invalid last name")
    elif len(username.get()) > 10:
        error_label("username can't exceed 10 characters")
    elif not username.get().isalnum():
        error_label("username must contain only letters and numbers")
    elif len(email.get().split('@')) != 2:
        error_label("Invalid email")
    elif len(password.get()) < 6:
        error_label("password must be at least 6 characters long")
    elif password.get().isalnum() and (password.get().isalpha()
                                       or password.get().isnumeric()):
        error_label("password must contain letters and numbers")
    elif password.get() != confirm.get():
        error_label("password's don't match")

    else:
        user_reg = User.create_user(first_name.get(), last_name.get(),
                                    username.get(), email.get(),
                                    password.get())
        error_label(user_reg)
示例#20
0
def login_button_click(screen, username_login, password_login):
    """after the login button is pressed, verifies the user exists in the database and enters the game menu"""
    try:
        global incorrect
        incorrect.destroy(
        )  # if there's already an error on the screen, deletes it first
    except NameError:
        pass
    GameUI.logged_in_user = User.verify_login(
        username_login.get(), password_login.get())  # verifies user's login
    if GameUI.logged_in_user != "Username or Password Incorrect":  # if the user's info is correct, enters the game menu
        screen.destroy()
        menu_screen()
    else:  # if not, returns an error message
        incorrect = ttk.Label(text="Username or Password Incorrect",
                              font=("Cooper black", 12),
                              foreground='black',
                              background='light blue')
        incorrect.pack(pady=5)
示例#21
0
def signInUser(_username, _password):
	
	user = User.verify_token(_username)
	if user:
		return user
		# if user.primary_provider == 'facebook':
		# 	authFB.refresh_Token(user)
		# if user.primary_provider == 'google':
		# if user.primary_provider == 'twitter':
		

	#Getting the user object IF there is any with that username
	user = User.query.filter_by(username=_username, primary_provider="FORM").first()
	if user:
		response = user.verify_pass(_password)
		if response:
			return user
		else:
			return False
	else:
		return False
示例#22
0
 def replace_username():
     """checks the username the user entered and if it's available changes it in the database"""
     global username_error
     try:
         username_error.destroy(
         )  # if there's already an error on the screen, deletes it first
     except NameError:
         pass
     if User.change_username(GameUI.logged_in_user.id,
                             new_username.get()) != "Username changed":
         username_error = ttk.Label(username_screen,
                                    text="Username already exists",
                                    font=("Calibri Bold", 12),
                                    foreground='black',
                                    background='light blue')
         username_error.pack()
     else:  # changes the username in the database and informs the user
         ttk.Label(
             username_screen,
             text=
             "Username changed. To be updated\n   you shall re-enter the program",
             font=("Calibri Bold", 12),
             foreground='black',
             background='light blue').pack()
示例#23
0
def login_as_guest():
    try:
        data = request.get_json()
        return User.login_as_guest(data['UUID'])
    except Exception as ex:
        return Tools.Result(False, ex.args)
                continue

            data_entry_time = data_entry_datetime.time()
            # log(f"data_entry_time: {data_entry_time} vs hr_time: {hr_time}")
            user_data_entry_idx += 1

            if (data_entry_time == hr_time):
                # log("procdata_entry_timeessor_time == hr_time")
                # log(f"setting data_entry_time's hr to {hr_value}")
                user_data_entry.hr_value = hr_value
                break
            else:
                user_data_entry.hr_value = None


for user_dict in get_users():
    process_user_data(
        User(user_dict[CONF.GET_USERS_KEYS.USER_ID_KEY],
             user_dict[CONF.GET_USERS_KEYS.ACCESS_TOKEN_KEY]))

# while(True):
#     log("Awoken!")

#     # Refreshes access tokens which are about to get old.
#     demonhandler.refreshTokens()

#     # Fetches data for each user.
#     demonhandler.fetchData()

#     log("Sleepings...")
#     time.sleep(3600)
示例#25
0
 def processUser(self, fromServer):
     fromServer = fromServer.split("#")
     user = User(fromServer[4], fromServer[5], fromServer[6], fromServer[7],
                 fromServer[8], fromServer[9], fromServer[10])
     return user
示例#26
0
def get_activation_code(phone_number):
    try:
        return User.get_activation_code(phone_number)
    except Exception as ex:
        return Tools.Result(False, ex.args)
示例#27
0
	def listarUsuario(self):
	
		all_users = User()
		all_users = all_users.listAll()
		for user in all_users:
			print user.id,"-",user.nome
示例#28
0
def resend_activation_code_to_phone_number():
    try:
        data = request.get_json()
        return User.resend_activation_code_to_phone_number(data['PhoneNumber'])
    except Exception as ex:
        return Tools.Result(False, ex.args)
示例#29
0
from flask import *
from functools import wraps
from Classes.User import User

app = Flask(__name__)

app.secret_key = 'free23456789'
users = {'admin': 'admin', 'art': 'art'}
user = User()


def login_required(test):
    @wraps(test)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return test(*args, **kwargs)
        else:
            flash("You need to login first.")
            return redirect(url_for('login'))

    return wrap


@app.route('/index')
@login_required
def index():
    lists = user.recipes
    return render_template('index.html', lists=lists)


@app.route('/signup', methods=['GET', 'POST'])
示例#30
0
async def mine(ctx):
    print(ctx.author.name + " mines")
    #Set or Get User
    u = User(ctx.author.id, ctx.author.name)
    u.StartMine()
    await ctx.send("Finished Mining")
示例#31
0
def login_verification():
    try:
        data = request.get_json()
        return User.login_verification(data['PhoneNumber'], data['VerificationCode'])
    except Exception as ex:
        return Tools.Result(False, ex.args)
 def setUp(self):
     self.user = User()
示例#33
0
    def play_against_comp():
        """running the game against the computer"""

        Square.length = 40
        player = Player(GameUI.logged_in_user.username)
        player.set_board(1)

        opponent = Player("Computer")
        opponent.set_board(2)

        pygame.init()
        done = False
        clock = pygame.time.Clock()
        pygame.display.set_caption("© Battleship by Shani Daniel ©")  # sets window title

        screen = pygame.display.set_mode(
            (opponent.board.end.x + player.board.start.x + Square.length, opponent.board.end.y + 80))
        screen.fill(BoardUI.color_index["light blue"])

        TextUI.write_title(screen, "Hello %s! Welcome to Battleship! You are going to play against the computer."
                           % GameUI.logged_in_user.username, 0)
        GameUI.placing_rules(screen)  # shows the rules on the game screen

        BoardUI.draw_board(screen, player.board)
        BoardUI.draw_board(screen, opponent.board)

        GameAgainstComp.rand_place_ships(opponent)  # the computer randomly places it's ships

        player_turn = True
        start_game = False
        game_over = False
        stat_check = False

        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                    if game_over is False:
                        if GameUI.exit_window() is True:
                            done = True
                    else:
                        done = True

                GameUI.placing_ships(screen, event, player, start_game, game_over)  # lets the player place his ships

                ship_count = 0
                for ship in player.board.ships:
                    if ship.square_start is not None and ship.square_end is not None:
                        ship_count += 1
                if ship_count == 5:  # checks if all the ships were placed
                    start_game = True
                    for line in range(5):
                        TextUI.clear_title(screen, line)

                if player.check_if_lost() is True:  # shows result if the game ended with loss
                    TextUI.clear_title(screen, 0, 110)
                    TextUI.write_title(screen, "You Lost!", 1, 48)
                    start_game = False
                    game_over = True
                    for ship in opponent.board.ships:
                        if not ship.is_ship_sunk(opponent):
                            BoardUI.color_ship(screen, ship, BoardUI.color_index["blue"])
                    for square in opponent.board.ship_shot:
                        BoardUI.color_square(screen, square, BoardUI.color_index["red"])
                    break

                if opponent.check_if_lost() is True:
                    # shows result if the game ended with win and adds it to the statistics
                    TextUI.clear_title(screen, 0, 110)
                    TextUI.write_title(screen, "You Won!", 1, 48)
                    if game_over is False:
                        User.add_score(GameUI.logged_in_user.id, won=True)
                        GameUI.logged_in_user.num_of_wins += 1
                    start_game = False
                    game_over = True
                    for ship in player.board.ships:
                        if not ship.is_ship_sunk(player):
                            BoardUI.color_ship(screen, ship, BoardUI.color_index["blue"])
                    for square in player.board.ship_shot:
                        BoardUI.color_square(screen, square, BoardUI.color_index["red"])
                    break

                if start_game is True and game_over is False:
                    if stat_check is False:
                        # if the game started and this action wasn't made yet, add the game to the statistics
                        GameUI.logged_in_user.num_of_games += 1
                        User.add_score(GameUI.logged_in_user.id)
                        stat_check = True

                    if player_turn is True:  # runs the player's turn
                        TextUI.write_title(screen, "Play!", 0.5, 40)
                        TextUI.clear_title(screen, 2, 36)
                        TextUI.write_title(screen, "Your Turn", 2, 36)
                        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                            pos = pygame.mouse.get_pos()
                            if BoardUI.get_squares_position(opponent, pos) is not None:
                                if BoardUI.shoot(screen, opponent, pos) == "success":
                                    player_turn = False  # pass the turn to the computer
                                    TextUI.clear_title(screen, 1, 66)
                                    TextUI.write_title(screen, "%s's Turn" % opponent.username, 2, 36)
                        break

                    if opponent.check_if_lost() is False:
                        pygame.time.delay(1000)  # delays the computer's response to make the game more interactive

                    if player_turn is False and opponent.check_if_lost() is False:
                        rand_pos_square = GameAgainstComp.rand_shoot(player)
                        BoardUI.shoot(screen, player, (rand_pos_square.x, rand_pos_square.y))
                        player_turn = True
                for coord in player.board.empty_shot:
                    BoardUI.draw_x(screen, BoardUI.get_squares_position(player, (coord.x, coord.y)))
                for coord in player.board.ship_shot:
                    BoardUI.color_square(screen, BoardUI.get_squares_position(player, (coord.x, coord.y)),
                                         BoardUI.color_index["red"])

            pygame.display.flip()
            clock.tick(60)
        pygame.quit()
示例#34
0
async def play(ctx):
    print(ctx.author.id)
    User(ctx.author.id, ctx.author.name)
    await ctx.send("Registered")
示例#35
0
def stats_screen():
    """in this screen the user can see the top 5 players in the game and watch his game statistics """
    cursor = User.db_connect()  # connecting to the database
    cursor.execute(
        "SELECT TOP(5) [Username], [NumberofWinnings] FROM [Users] WHERE [ID]!=0 ORDER BY [NumberofWinnings]"
        " DESC"
    )  # selects the top 5 players with the highest number of winnings
    rows = cursor.fetchall()  # gets the values that were selected
    stats_win = ThemedTk(
        theme="Smog")  # created the statistics window themed "smog"
    style = ttk.Style(stats_win)
    style.configure("Treeview.Heading",
                    font=("Calibri Bold", 14))  # styles the tables headings
    style.configure("Treeview",
                    font=("Calibri", 12))  # styles the tables fields

    ttk.Label(stats_win, text='Top Players', font=("Cooper black", 32), foreground='black', background='light blue')\
        .pack(pady=30)
    frame = ttk.Frame(stats_win)  # frames the top players table
    frame.pack(padx=20, pady=20)

    table = ttk.Treeview(frame, columns=(1, 2), show="headings",
                         height='5')  # creates the table

    table.column(1, anchor="c")
    table.column(2, anchor="c")
    table.pack(fill="both", expand=True)
    # centers the table columns and adds the table to the window

    table.heading(1, text="Player")
    table.heading(2, text="Number of Winnings")
    # writes the table headings

    for row in rows:
        table.insert(
            "", "end", values=list(row)
        )  # inserts the values that were given by the database to the table

    stats_win.geometry('540x540')
    stats_win.title("© Battleship by Shani Daniel ©")
    stats_win.configure(background='light blue')

    num_games = GameUI.logged_in_user.num_of_games  # gets the number of games the current user has played from the db
    num_wins = GameUI.logged_in_user.num_of_wins  # gets the number of games the current user has won from the db
    if num_games != 0:
        win_per = int(
            100 * (num_wins / num_games))  # calculates the winnings percentage
    else:  # if the user's number of games is zero, return 0
        win_per = 0
    ttk.Label(stats_win,
              text='Your Statistics:',
              font=("Cooper Black", 20),
              foreground='black',
              background='light blue').pack(pady=20)
    ttk.Label(stats_win,
              text='Number of games you played: %s' % num_games,
              font=("Calibri Bold", 16),
              foreground='black',
              background='light blue').pack(pady=5)
    ttk.Label(stats_win,
              text='Number of games you won: %s' % num_wins,
              font=("Calibri Bold", 16),
              foreground='black',
              background='light blue').pack(pady=5)
    ttk.Label(stats_win,
              text='Winning percentage: %s%%' % win_per,
              font=("Calibri Bold", 16),
              foreground='black',
              background='light blue').pack(pady=5)
    # creates the labels and adds the statistics we got for the current user

    stats_win.mainloop()
示例#36
0
def get_profile_info():
    try:
        return User.get_profile_info(request.headers['Id'])
    except Exception as ex:
        return Tools.Result(False, ex.args)
示例#37
0
	def cadastraUsuario(self):
		login = raw_input("\nDigite o nome do usuario: ")
		senha = raw_input("\nDigite a senha de usuario: ")
		novo_usuario = User(login,senha)
		novo_usuario.save()