def get( self ): "Display board ready to be played" ## Pull out the requested game ID gameid = self.request.get( "gameid" ) ## Make sure a game ID was actually provided if not gameid: self.redirect( "/error" ) ## Initialize the game view game = GameView( gameid = gameid ) board = game.board.serialize() ## Look up player names player1 = User.by_id( int( game.player1 ) ) player2 = User.by_id( int( game.player2 ) ) user_id = self.user.key().id() ## It's my turn if the game is active and i'm the player to move is_my_turn = game.is_my_turn( user_id ) status = game.get_detailed_status( user_id ) ## Display the game to the user self.render( "play-game.html", player1 = player1.name, player2 = player2.name, board = board, turn = game.turn, is_my_turn = is_my_turn, status = status )
def register(self): try: self.textError.set("") username = self.username.get() password = self.password.get() repeatpassword = self.repeatPassword.get() email = self.email.get() nickname = self.nickname.get() if username != '' and password != '' and repeatpassword != '' and email != '' and nickname != '': if password == repeatpassword: if User.isValidPassword(password): if User.isValidEmail(email): user = User(email=email, password=password, nickname=nickname, name=username) self.controller.userData = user jsonuser = jsonpickle.encode(user) self.controller.sendMessageToServer( "REGISTER_ATTEMPT", jsonuser) else: self.textError.set("Invalid email format") else: self.textError.set("Password is too weak") else: # Error handeling !! self.textError.set("Passwords aren't the same") else: # Error handeling !! self.textError.set("Please fill in all the fields") except Exception as ex: self.textError.set("Email is already in use")
def login(self): try: self.textError.set("") email = self.email.get() password = self.password.get() print("__ %s __" % password) if email != '' and password != '': if User.isValidPassword(password): if User.isValidEmail(email): user = User(email=email, password=password, nickname="", name="") self.controller.userData = user jsonuser = jsonpickle.encode(user) self.controller.sendMessageToServer( "LOGIN_ATTEMPT", jsonuser) else: self.textError.set("Invalid email format") else: self.textError.set("Incorrect password") else: self.textError.set("Please fill in all fields") except Exception as ex: self.textError.set("Login failed")
def register(self, user): try: service = Service() if(service.is_valid_email(user['email'])): if(user['password']==user['confirmPassword']): mongo_config = MongoConfig() collection = mongo_config.db() if(collection): crypto = Crypto() user['password'] = crypto.encrypted_string(user['password']) if "confirmPassword" in user: del user['confirmPassword'] saved_user = collection.insert_one(user) email_queue = EmailService() email_queue.send_email(user['email'], 'Welcome to Utopia', self.email_text(user['firstName'])) user = User() user.user_id = str(saved_user.inserted_id) return user else: return "Unable to connect" else: return "Password did not match" else: return "Please enter proper email address" except Exception as e: return e
def login(data): try: conn = PgConfig.db() if(conn): cur = conn.cursor() login_query = "SELECT users.otp, users.user_id, users.first_name, users.last_name, users.color_theme, users.image\ FROM users WHERE users.email LIKE %s" cur.execute(login_query, (data['email'], )) user = cur.fetchone() response = User() if(user[0]==data['otp']): response.email= data['email'] response.user_id = user[1] response.first_name = user[2] response.last_name = user[3] response.color_theme = user[4] response.image = user[5] get_role_query = "SELECT user_role.role_id FROM user_role WHERE user_role.user_id = %s" cur.execute(get_role_query, (user[1],)) response.role_id = cur.fetchone()[0] response.token = (Jwt.encode_auth_token(user_id=user[1], role_id=response.role_id)).decode() cur.close() conn.close() return response else: return False else: return False except Exception as e: raise e
def _initNew( self, player1, player2 ): ## Create empty board self.board = Board() ## Save player info self.player1 = int( player1 ) self.player2 = int( player2 ) ## Save status self.status = "CHALLENGE" self.winner = None self.turn = 1 ## Create new Game instance self.game = Game( player1 = self.player1, player2 = self.player2, status = self.status, board = self.board.serialize(), turn = self.turn, winner = self.winner, parent = Game.games_key() ) ## Save new game to database key = self.game.put() self.gameid = key.id() ## Send an email to player 2 player1_name = User.get_user_name( self.player1 ) player2_user = User.by_id( self.player2 ) HexEmail.sendChallenge( player2_user.email, player1_name )
def login(self, data): try: mongo_config = MongoConfig() collection = mongo_config.db() if(collection): user_obj = User() search_user = {'email': data['email']} user = collection.find(search_user) crypto = Crypto() if(user): if(crypto.verify_decrypted_string(data['password'], user[0]['password'])): user_obj.first_name = user[0]['firstName'] #user_obj.last_name = user[0]['lastName'] user_obj.user_id = str(user[0]['_id']) user_obj.token = Jwt.encode_auth_token(user_id=user[0]['_id']).decode() return user_obj else: return "Invalid Credentials" else: return "User not available" else: return "Unable to connect to database" except IndexError as IE: return "User not available" except Exception as e: raise e
def create_new_user(): print( "\n\nWelcome to BudgetBuddy!\nBelow we will get you setup with a new account!" ) Username = input("\n\nPlease input a Username: "******"Problem fetching the user from the database") print( "***ERROR WITH ACCOUNT CREATION PROBLEM***\n\nReturning to login page" ) login() while temp_user != "User Not Found": Username = input("\n\nUsername Taken, Please input a new Username: "******"Unable to fetch user from database") login() First_Name = input("\nPlease input your first name: ") First_Name = First_Name.upper() First_Name = First_Name.strip() Last_Name = input("\nPlease input your last name: ") Last_Name = Last_Name.upper() Last_Name = Last_Name.strip() Password = input("\nPlease input a password: "******"\nPlease re-input your password: "******"Unable to commit new user to database") login() print("\n***TIME TO LOGIN***\n")
def createUser(): body = request.get_json() user = User(name=body.get('name')) db.session.add(user) db.session.commit() publish('events.users.created', UserCreated(user.name, user.id).to_string()) return {"success": True, "data": user.toDict()}
def main_menu(): try: user = User() while True: # input choice print("1. BDO Login") print("2. GPM Login") print("3. Member Login") print("Press Any Other key to Exit......") choice = int(input("Enter choice: ")) if choice == 1: os.system('clear') # redirect to login page user_access = user.bdo_login(db) if user_access[0] == 'true': bdo_id = user_access[1] # redirect to display_panel of bdo display_panel_bdo(bdo_id, db) else: print("Wrong Credentials, login again!") main_menu() elif choice == 2: os.system('clear') # initialize customer instance user_access = user.gpm_login(db) if user_access[0] == 'true': gpm_id = user_access[1] # redirect to dashboard display_panel_gpm(gpm_id, db) else: print("Wrong Credentials, login again!") main_menu() elif choice == 3: os.system('clear') # initialize customer instance user_access = user.member_login(db) if user_access[0] == 'true': member_id = user_access[1] # redirect to dashboard display_panel_member(member_id, db) else: print("Wrong Credentials, login again!") main_menu() else: os.system('clear') print("Thank You for Using This Application") time.sleep(2) sys.exit() except Error as se: db.conn.rollback() print("Something went wrong: {}".format(se)) except ValueError as ve: print("Invalid Choice, Please enter a valid number") except Exception as e: print("exception handled: {}".format(e))
def add_user(): try: new_user = User(request.json["email"], request.json["password"]) response = new_user.create() except: response = {"message": "BAD_REQUEST"} return jsonify(response)
def del_user(): try: new_user = User(id_token=request.json['id_token']) response = new_user.delete() except: response = {"message": "BAD_REQUEST"} return jsonify(response)
def createNewNetwork(self, localip, localport, username): logging.info("Creating a new network") localip = str(localip.get()) localport = str(localport.get()) username = str(username.get()) localport = str(localport) """Initialize DHT""" initialization = DHT() self.encryption.generate_keys() # Create a user object, set all user variables to the data gathered in the form user = User() user.ip = localip user.port = localport user.username = username user.publicKey = self.encryption.getPublicKey().decode("utf-8") user.nodeid = self.Utils.generateID(user.username) # Convert our user to json format so we can save it to file userAsJSON = json.dumps(user.toDict()) # Register username in a local file so we know who we are file = open("User.json", "w+") file.write(str(userAsJSON)) file.close() initialization = DHT() initialization.fingerTable.nodeid = user.toDict() initialization.writeDHTInformation()
def check_fb_user_existence(email): conn = None cur = None try: conn = PgConfig.db() if(conn): cur = conn.cursor() select_query = "SELECT user_id, first_name, color_theme, image FROM users WHERE email LIKE %s AND type = %s" cur.execute(select_query, (email, 'fb', )); obj = cur.fetchone() response = User() if(obj): get_role = "SELECT role_id FROM user_role WHERE user_id = %s" cur.execute(get_role, (obj[0],)); role = cur.fetchone() response.email= email response.user_id = obj[0] response.role_id = role[0] response.first_name = obj[1] response.color_theme = obj[2] response.image = obj[3] response.token = (Jwt.encode_auth_token(user_id=obj[0], role_id=response.role_id)).decode() cur.close() conn.close() return response else: cur.close() conn.close() return False else: return False except Exception as e: return e
def done( self ): #make sure the user doesn't already exist u = User.by_name( self.username ) if u: msg = 'That user already exists.' self.render('signup-form.html', error_username = msg) else: u = User.register( self.username, self.password, self.email ) u.put() self.login( u ) self.redirect( "/" )
def signup(): data = request.json email = data["email"] password = data["password"] user = User(email=email, password=password) print(user) config.db.session.add(user) config.db.session.commit() return jsonify(token=user.token())
def signup(self, document): user = User(firstName=document["firstName"], lastName=document["lastName"], email=document["email"], password=document["password"]) user.validate( ) # TODO: enclose this in a try/catch block /check if its an error with the type entered if (self.save(user)): return True else: return False
def signup_google(): data = request.json from pprint import pprint pprint(data) code = request.data oauth_flow = flow_from_clientsecrets('./config/client_secret_google.json', scope='') pprint(oauth_flow) oauth_flow.redirect_uri = 'http://localhost:5000' credentials = oauth_flow.step2_exchange(data) access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'% access_token) print("access_token ->",access_token) print("url ->",url) result = json.loads(requests.get(url).text) pprint(result) email = result['email'] password = result['user_id'] user = User(email=email, password=password) print(user) config.db.session.add(user) config.db.session.commit() return {"token":user.token()}, 200 # flow = OAuth2WebServerFlow(client_id=client_secret_google['web']['client_id'], # client_secret=client_secret_google['web']['client_secret'], # scope='', # redirect_uri='http://localhost:5000') # credentials = flow.step2_exchange(code) # try: # # Upgrade the authorization code into a credentials object # oauth_flow = flow_from_clientsecrets('./config/client_secret_google.json', scope='') # pprint(oauth_flow) # oauth_flow.redirect_uri = 'postmessage' # credentials = oauth_flow.step2_exchange(code) # except FlowExchangeError: # return {"eoro":"er"}, 400 return {}, 200
def UpdateUserInfo(): if not request.json: abort(400) json = request.get_json() user = User(userID=current_user.id, name=current_user.name, email=current_user.email, bio=json['bio'], vehicle=json['vehicle']) db.table("Users").update(user.getDatabaseModel(), Query().id == current_user.id) return jsonify(user.getDatabaseModel())
def findUser(id, db): dbUser = db.table("Users").get(Query().id == id) if dbUser is not None: return User(dbUser['id'], dbUser['name'], dbUser['email'], dbUser['bio'], dbUser['vehicle']) else: return None
def api_root(): print(request.form) if request.method == 'POST' and request.form: try: session = session_factory() user = User(request.form["name"]) session.add(user) session.commit() session.close() publish('user_created', user.to_json_string()) return user.to_json_string() except Exception as ex: return ex else: return "Where is the image?"
def login(): result = Result() if not request.is_json: result.AddError("Missing JSON in request") username = request.json.get('Email', None) password = request.json.get('Password', None) if not username: result.AddError("Missing username parameter") if not password: result.AddError("Missing password parameter") loggingUser = User.objects(Email=username).first() if loggingUser is None: result.AddError("Invalid login or password") return result.ToResponse() userHash = loggingUser.Password userRole = loggingUser.AccountType userId = loggingUser.Id forToken = TokenInfo(username, userRole, userId) if checkPassword(password, userHash): access_token = create_access_token(identity=forToken) refresh_token = create_refresh_token(identity=forToken) result.Value = json.dumps({ 'access_token': access_token, 'refresh_token': refresh_token }) else: result.AddError("Invalid login or password") return result.ToResponse()
def start_new_game(self): users = [ User.get_or_create(display_name=self.black_name, defaults={'token': '1'})[0], User.get_or_create(display_name=self.white_name, defaults={'token': '2'})[0] ] timer = Timer() players = {Color.black: users[0], Color.white: users[1]} self.game = Game.new_game(size=9, rule_set=get_japanese_rule_set(), players=players, timer=timer) self.game.save() self.api.start_game(self.game) return self.game
def get_current_user(self): if self.user is None: session = Session.get_from_cookie(self) if session is not None: session.save() self.user = User.find(session.user_model_id) return self.user
def post(self): have_error = False username = self.request.get("username") password = self.request.get("password") params = dict(error_username=None, error_password=None) # Validates fields if not Validation.valid_username(username): params["error_username"] = "******" have_error = True if not Validation.valid_password(password): params["error_password"] = "******" have_error = True if have_error: self.render("login.html", **params) else: # Login user log_user = User.login(username, password) if log_user: self.login(log_user) self.redirect("/") else: self.render( "login.html", credential_error= "There seems to be an error with your credentials, please check" )
def __init__(self): user = User().toDict() self.successor = user self.predecessor = user self.nodeid = user self.finger1 = user self.finger2 = user
def Login(): if not request.json or not "tokenObj" in request.json or not "profileObj" in request.json: abort(400) try: json = request.get_json() token = json['tokenObj'] idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), app.config['CLIENT_ID']) if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') userid = idinfo['sub'] userTable = db.table("Users") dbUser = userTable.get(Query().id == userid) if dbUser == None: profile = json['profileObj'] dbUser = { 'id': userid, 'name': profile['name'], 'email': profile['email'], 'bio': "", 'vehicle': "" } userTable.insert(dbUser) user = User(dbUser['id'], dbUser['name'], dbUser['email']) login_user(user, remember=True) return render_template("index.html", client_id=app.config["CLIENT_ID"]) except ValueError: abort(403)
def unserializeUser(self, serializedUser): """ Permet de désérialiser un utilisateur :param serializedUser: L'utilisateur sérialisé :type serializedUser: dict :return: L'utilisateur désérialisé :rtype: User """ email = None if "email" not in serializedUser else \ serializedUser["email"] publications = None if "publications" not in serializedUser else \ self.unserializePublications(serializedUser["publications"]) friends = None if "friends" not in serializedUser else \ serializedUser["friends"] user = User( serializedUser["username"], serializedUser["firstName"], serializedUser["lastName"], serializedUser["privacySetting"], email, publications, friends ) return user
def refresh(): result = Result() username = get_jwt_identity() loggingUser = User.objects(Email=username).first() loggingUser = User.objects(Email=username).first() userRole = loggingUser.AccountType userId = loggingUser.Id forToken = TokenInfo(username, userRole, userId) if loggingUser is None: result.AddError("User not found/Invalid Token") return result.ToResponse() ret = { 'access_token': create_access_token(identity=forToken), 'refresh_token': create_refresh_token(identity=forToken) } result.Value = json.dumps(ret) return result.ToResponse()
def getUser(self, **kwargs): if not User.objects(**kwargs): return False user = User.objects.get( **kwargs) #use objects.get to retreive one result return user
def get_detailed_status( self, user_id ): ## Pending games if self.status == "CHALLENGE": player2_name = User.get_user_name( self.player2 ) return "Waiting for %s to accept challenge" % player2_name ## Active games if self.is_my_turn( user_id ): return "My move" if self.status == "ACTIVE": return "Opponent's turn" ## Completed games if self.status == "COMPLETE": winner_name = User.get_user_name( self.winner ) return "%s has won" % winner_name
def login(email): data = { "email": email } user = User(data) val = user.find if val is None: abort(404) else: return make_response(jsonify({"user_type":val['userType']}), 200)
def add_user(): if request.method == 'POST': login = request.form['username'] email = request.form['email'] new_user = User(login, email) db.session.add(new_user) db.session.commit() return redirect(url_for('home_controller.users'))
def post(self): name = self.request.args['name'] password = self.request.args['password'] user = User() user.set_username_and_password(name, password) user.save() return user.to_mongo(fields=['_id'])
def post( self ): ## Make sure the user is logged in if not self.user: self.redirect( "/login" ) return cancel = self.request.get( "cancel" ) gameid = self.request.get( "gameid" ) ## If the user hit "cancel" then refresh the board if cancel: self._cancel_move( gameid ) return else: ## Retrieve this game from the database game = GameView( gameid = gameid ) if game: ## Grab the move row = self.request.get( "row" ) col = self.request.get( "col" ) try: game.update_game( user = self.user, row = int( row ), col = int( col ) ) except WrongTurnException as e: self.render( "/play?gameid=%s" % gameid, error = e.message ) return ## Send email to opponent telling them it's their turn player1_name = User.get_user_name( game.player1 ) player2 = User.by_id( game.player2 ) if player2.email and player2.move_emails: HexEmail.sendMoveNotice( player2.email, player1_name ) ## Redirect to homepage self.redirect( "/home" ) else: logging.error( "That's not a valid game" ) self.redirect( "/" )
def _build_game_set( self, games ): data = [] for game in games: gameid = game.key().id() view = GameView( gameid = gameid ) user_id = self.user.key().id() player1_name = User.get_user_name( view.player1 ) player2_name = User.get_user_name( view.player2 ) data.append( { "gameid": gameid, "player1": player1_name, "player2": player2_name, "status": view.get_detailed_status( user_id ) } ) return data
def post(self): username = self.request.get("username") password = self.request.get("password") u = User.login(username, password) # @UndefinedVariable if u: self.login(u) self.redirect("/home") else: msg = "Invalid login" self.render("login-form.html", error=msg)
def post(self): if not User.by_name('postrwall'): u_test = User.register('postrwall', 'postrwall') u_test.put() username = self.request.get('username') password = self.request.get('password') u = User.login(username, password) if u: self.login(u) self.redirect('/Admin/') else: Utils.template2handler(self, 'admin-login.html', { 'title': 'Please Login', 'admin':True, 'error':'Incorrect Login/Password, please try again.', 'username':username })
def register(): if request.cookies.get('username'): return redirect("/kusurabakma") if session.get("done"): return redirect("/kusurabakma") if request.args.get("age"): u = User() u.age = request.args.get("age") u.sex = request.args.get("sex") u.musician = json.loads(request.args.get("musician")) u.yil = int(request.args.get("yil")) u.save() return redirect("/question") return render_template('register.html')
def get( self ): ## Make sure the user is logged in if not self.user: self.redirect( "/login" ) return ## Query out the other users all_users = User.all().order( "-name" ).fetch( limit = 100 ) all_users = list( all_users ) ## Define a UserItem as a name and id UserItem = namedtuple( "UserItem", [ "name", "id" ] ) users = [] for user in all_users: if user.name != self.user.name: users.append( UserItem( user.name, user.key().id() ) ) self.render( "new-challenge.html", users = users )
def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) uid = self.read_secure_cookie( 'user_id' ) self.user = uid and User.by_id( int( uid ) ) #@UndefinedVariable
def get(self): self.response.headers['Content-Type'] = 'text/html' self.response.out.write('Database Initialisation ... <br />') Event(name="Reggae Sun Ska", date=datetime.date(2012, 8, 3), description="Awesome Reggae Festival in Bordeaux", posterUrl="http://p.gap.free.fr/web/images_agenda/2979_1_img.jpg", webpage="http://www.reggaesunska.com/2012/", address="Bordeaux, France", price=float(50), artists=['Jimmy Cliff', 'Ayo', 'Damian Marley', 'Groundation' ], genres=['Reggae', 'Dub'], creator=User.by_name('postrwall')).put() Event(name="Szigets 2012", date=datetime.date(2012, 8, 6), description="Biggest Europeean Festival", posterUrl="http://www.spectacles.carrefour.fr/image_actualites//sziget-2012-officielle.jpg", webpage="http://www.reggaesunska.com/2012/", address="Budapest, Hungary", price=float(50), artists=['Placebo', 'The Stone Roses', 'The Ting Tings', 'Axwell', 'Korn', 'The XX'], genres=['Rock', 'Indie', 'Electro', 'Folk'], creator=User.by_name('postrwall')).put() Event(name="Bpitch Control", date=datetime.date(2012, 7, 21), description="Another party in the Berghain", posterUrl="http://www.residentadvisor.net/images/events/flyer/2012/7/de-0721-354493-19974-front.jpg", webpage="http://www.reggaesunska.com/2012/", address="Berghain, Am Wriezener Bahnhof, 10243 Berlin", price=float(10), artists=['Kiki', 'DJ Red', 'Shinedoe', 'Marcel Fengler', 'Thomas Muller'], genres=['Electro', 'Minimal'], creator=User.by_name('postrwall')).put() Event(name="Berlin Festival", date=datetime.date(2012, 9, 7), description="Yearly festival in Tempelhof", posterUrl="http://www.indiemeute.de/wp-content/uploads/2012/05/Berlin-Festival-20121.jpg", webpage="http://www.reggaesunska.com/2012/", address="Tempelhof Airport", price=float(50), artists=['The Killers', 'Paul Kalkbrenner', 'Sigur Ros', 'Franz Ferdinand', 'Kraftklub'], genres=['Electro', 'Minimal', 'Rock', 'Indie'], creator=User.by_name('postrwall')).put() Event(name="Les vieilles Charrues", date=datetime.date(2012, 7, 19), description="French festival in Britany", posterUrl="http://burnmebaby.fr/wp-content/uploads/2012/07/Vieilles-Charrues-Affiche.jpg", webpage="http://www.reggaesunska.com/2012/", address="Le Mans, France", price=float(30), artists=['Bob Dylan', 'Sting', 'Portishead', 'The Cure', 'LMFAO'], genres=['Electro', 'Minimal', 'Rock', 'Indie'], creator=User.by_name('postrwall')).put() Event(name="Open Air Berlin at Rummelsburger Bucht", date=datetime.date(2012, 8, 05), description="Awesome Open Air with Extrawelt", posterUrl="../images/de-0805-348219-47340-front.jpg", webpage="http://www.reggaesunska.com/2012/", address="Rummelsburger Bucht, Berlin, Germany", price=float(15), artists=['Extrawelt', 'Monika Kruse', 'Ruede Hagelstein', 'Sis'], genres=['Electro', 'Minimal'], creator=User.by_name('postrwall')).put() self.response.out.write('Database Initialised')
def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) uid = self.read_secure_cookie('user_id') self.user = uid and User.by_id(int(uid)) if not self.user: self.redirect('/Admin/Login')