def test_base(self): db.Session.add(db.User(name='Test1', age=30, role='test')) db.Session.add(db.User(name='Test2', age=40, role='test')) db.Session.flush() users = db.Session.query(db.User).all() self.assertEqual(len(users), 2) self.assertEqual(users[0].name, 'Test1') self.assertEqual(users[1].name, 'Test2')
def edit_info(): error = None urname = session['username'] other = db.User(urname).display_profile() info = strword(other) if request.method == 'POST': db.User(urname).edit_profile(request.form['fname'], request.form['what'], request.form['where'], request.form['dob'], request.form['about']) flash("Your info. have been updated") return redirect(url_for("show_all")) return render_template("edit_info.html", info=info, error=error)
def create_user(self, user: discord.User): session = self.session_manager() if self.config["local_avatars"]: r = requests.get(user.avatar_url_as(format='png')) with open(f"static/avatars/{user.id}.png", 'wb') as avatarfile: avatarfile.write(r.content) avatar_url = f"avatars/{user.id}.png" localized = True else: avatar_url = user.avatar_url localized = False new_user = db.User(id=user.id, name=user.name, discriminator=user.discriminator, is_bot=user.bot, avatar=str(avatar_url), created_at=user.created_at, last_updated=datetime.datetime.now(), localized_avatar=localized) session.merge(new_user) session.commit() session.close()
def signup(): try: # Log call and get params: logger = logging.getLogger('app') logger.debug('\n/signup') params = json.loads(request.data) logger.debug(params) username = params['username'] password = params['password'] logger.debug('Executing ... ') # Data base and paybook logic: signup_response = { 'sdk_message': 'User already exists' } #End of signup_response db_user = _DB.User( username, password) # This is the app user (stored in app's data base) user_exist = db_user.do_i_exist() logger.debug('User exist: ' + str(user_exist)) if not user_exist: logger.debug('Singning up user ... ') pb_user = paybook_sdk.User( name=username ) # This is the paybook user (stored in paybook's data base) signup_response = pb_user.get_json() db_user.set_id_user(signup_response['id_user']) db_user.save() signup_response['sdk_message'] = 'User signed up' logger.debug('Sending response ... ') signup_response = _Utilities.Success(signup_response).get_response() except paybook_sdk.Error as error: signup_response = error.get_json() return signup_response
def new_user(self, user, email, email_confirm, password, password_confirm): u = db.User.by_email(email) if u != None: return {}, {}, { "email": [ u"La dirección '%s' ya está dada de alta, escoja otra." % email ] } errors = defaultdict(list) if len(user.strip()) < 4: errors["user"].append( "El nombre de usuario debe tener al menos 4 caracteres.") if email != email_confirm: errors["email_confirm"].append( "La dirección de correo y la confirmación no coinciden") if len(password.strip()) < 6: errors["password"].append( "La contraseña debe tener 6 caracteres o más") if password != password_confirm: errors["password_confirm"].append( "La contraseña y la confirmación deben coincidir") if len(errors) == 0: u = db.User() u.email = email u.set_password(password, self.key) u.name = user u.groups.append( db.session().query( db.CatalogEntry )\ .filter( db.CatalogEntry.catalog_name == "user_groups" )\ .filter( db.CatalogEntry.value == "Usuarios" )\ .first() ) db.session().add(u) db.session().commit() return helpers.get(db.User).to_dictionary(u), {}, {} return {}, {}, dict(errors)
def post(self): json = flask.request.json helper_functions.check_missing_fields(json, 'user', 'password') username = json['user'] password = json['password'] if len( list(db.User.query().filter_by_property( name=username).fetch_all())) == 0: if len(password) >= CONSTANTS.min_password_len: salt = helper_functions.generate_cryptographically_random_string( 8) hashed_password = helper_functions.hash_with_salt( password, salt) user_vertex = db.User(name=username, password=hashed_password, salt=salt) user_vertex.add_to_graph() encoded = helper_functions.generate_jwt(user_vertex) return {'token': encoded}, HTTPStatus.CREATED else: return f'Password too short. Minimum {CONSTANTS.min_password_len} characters long', HTTPStatus.NOT_ACCEPTABLE else: return 'Username already in use', HTTPStatus.CONFLICT
def login(): try: # Log call and get params: logger = logging.getLogger('app') logger.debug('\n/login') params = json.loads(request.data) logger.debug(params) username = params['username'] password = params['password'] logger.debug('Executing ... ') # Data base and paybook logic: db_user = _DB.User(username, password) logger.debug('DB authentication ... ') if db_user.login(): id_user = db_user.get_id_user() logger.debug('Id user: '******'Invalid username or password', 400).get_response() except paybook_sdk.Error as error: login_response = error.get_json() return login_response
def post(self): password = self.get_argument('password', '') try: entity_id = int(password[2:-3]) entity = db.Entity(user_locale=self.get_user_locale(), user_id=entity_id) applicant = entity.get(entity_id=entity_id, limit=1) applicant_id = applicant.get('id') applicant_email = applicant.get('properties', {}).get('user', {}).get('values', [])[0].get('value') applicant_password = applicant.get('properties', {}).get('password', {}).get('values', [])[0].get('value') if applicant_password != password: raise Exception('Invalid password') except: return self.render('application/signin.html', page_title = self.get_user_locale().translate('application'), message = 'password_error', ) session_key = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(32)) + hashlib.md5(str(time.time())).hexdigest() user_key = hashlib.md5(self.request.remote_ip + self.request.headers.get('User-Agent', None)).hexdigest() db.User().create( provider = 'application', id = applicant_id, email = applicant_email, language = self.settings['default_language'], session = session_key+user_key ) self.set_secure_cookie('session', str(session_key)) self.redirect('/application/form')
def update_user(self, email, name): self.reset_add_task_limit(email) user = self.get_user(email) or db.User() user.email = email user.name = name self.session.add(user) self.session.commit()
def login(): user = request.form['user'] password = request.form['password'] if(hashlib.md5(password).hexdigest() == db.User().Validation(user)[0]): session['username'] = user return 'True' else: return 'False'
def cmd_start(bot, update): __session = db.Session() __session.add( db.User(telegram_id=update.message.from_user.id, chat_id=update.message.chat_id)) __session.commit() update.message.reply_text(text=config.MSG_START)
def register(): def step_2(): return flask.render_template('register.html', key_id=request.form['key_id'], vcode=request.form['vcode'], characters=key_info['characters']) if request.method == 'GET': # step 1 return flask.render_template('register.html') else: try: key_info = update_entities.check_api_key(request.form['key_id'], request.form['vcode']) except InvalidAPI as e: flask.flash(e.message) return flask.redirect(flask.url_for('register')) char_id = request.form.get('character_id') username = request.form.get('username') password = request.form.get('password') email = request.form.get('email') if not char_id or not username or not password or not email: if char_id or username or password or email: flask.flash('You must pick a character, username, and password and provide an email address.') # step 2 return step_2() else: # step 3 for whitespace in string.whitespace: if whitespace in username: flask.flash('Whitespace is not allowed in usernames.') return step_2() if '@' not in email or '.' not in email: flask.flash("That doesn't look like a valid e-mail address.") return step_2() char_id = int(char_id) for char in key_info['characters']: if char['character_id'] == char_id: update_entities.update_for_char(char) break else: flask.abort(400) password, salt = db.User.hash_pw(password) user = db.User(username=username, password=password, salt=salt, email=email, apikey_id=int(request.form['key_id']), apikey_vcode=request.form['vcode'], character_id=char_id) db.session.add(user) try: db.session.commit() except sqlalchemy.exc.DBAPIError as e: if e.orig.code == '23505': # unique_violation flask.flash('Username or email already exists.') return step_2() else: raise session.permanent = True session['user_id'] = user.id return flask.redirect(flask.url_for('home'))
def ppage(profile): error = None if 'username' in session: if dbase.user.find({"name": profile}).count() > 0: if profile == session['username']: edit = "Edit" other = db.User(profile).display_profile() info = strword(other) if info[0] == "XPROFILEX": info[0] = profile #the info have been shown ppost = db.User(profile).display_ppost() posts = list(ppost) comments_num = {} for p in posts: if p.get('comment'): comments_num[p.get('_id')] = len(p.get('comment')) return render_template("profile.html", info=info, edit=edit, posts=posts, comments_num=comments_num) else: other = db.User(profile).display_profile() info = strword(other) if info[0] == "XPROFILEX": info[0] = profile #the info have been shown ppost = db.User(profile).display_ppost() posts = list(ppost) comments_num = {} for p in posts: if p.get('comment'): comments_num[p.get('_id')] = len(p.get('comment')) return render_template("profile.html", info=info, posts=posts, comments_num=comments_num) else: error = "There's No such a User!" return render_template("404.html") else: abort(401)
def auth(): user = db.User(login=request.form['login'], password=request.form['password']) if user.is_login: login_user(user) return redirect(url_for('account', id=user.id)) else: return render_template('sign_in.html', warn='Incorrect login or password')
def view_user_list(): new_user = db.User() model = data_models.Model(new_user, None, db.User) form = UserForm(request.form, obj=new_user) model.add_form(ACTION_CREATE.name, form) user_query = db.User.query().order(db.User.name) property_list = (name_field, email_field) return views.view_std_entity_list(model, 'User List', ACTION_CREATE, property_list, user_query)
def post(self): """ Creates User Entity Variables: name - Required location - required - where they live job - required- what their job title is score - links the user to a happiness index score """ #Checks for JSON if 'application/json' not in self.request.accept: self.response.status = 406 self.response.status_message = "Error, this API requires a JSON type object" return #Creates a new user in the database newUser = db.User() username = self.request.get('username', default_value=None) password = self.request.get('password', default_value=None) name = self.request.get('name', default_value=None) location = self.request.get('location', default_value=None) job = self.request.get('job', default_value=None) score = self.request.get_all('scores[]', default_value=None) #Assigns the fields passed in through the POST request if name: newUser.name = name else: self.response.status = 400 self.response.status_message = "Error, name required" if location: newUser.location = location if job: newUser.job = job if username: newUser.username = username if password: newUser.password = password #if a score is already provided, append that to the scores list if score: for i in score: newUser.scores.append(ndb.Key(db.Score, int(i))) #pushes the entry to the database key = newUser.put() out = newUser.to_dict() self.response.write(json.dumps(out)) return
def create_account(): if request.method != "POST": return {} new_user = db.User(request.form.get("username"), request.form.get("email"), request.form.get("password")) db.db.session.add(new_user) db.db.session.commit() return { "message": "User created successfully.", "username": request.form.get("username") }
def db_save_user(email, name, picture): '''save to User and return u_id''' user = g.db_session.query(db.User).filter(db.User.email==email).first() if not user: # user not exist, new one user = db.User(email=email, name=name, picture=picture) g.db_session.add(user) else: # update user info user.name, user.picture = name, picture g.db_session.commit() return user.u_id
def post(self): session = Session() new_user = db.User(flask.request.form['username'], flask.request.form['first_name'], flask.request.form['last_name'], flask.request.form['password']) session.add(new_user) session.commit() flask.flash('Welcome! Please log in now!') return flask.redirect(flask.url_for('login'))
def buildSchemaTopology(self, schema, serverOsh): oshv = ObjectStateHolderVector() osh = self._buildDbSchemaOsh('database_instance', schema.name, schema.create_time) osh.setContainer(serverOsh) oshv.add(osh) if schema.createdBy: ownerOsh = self.buildUserOsh(db.User(schema.createdBy)) ownerOsh.setContainer(serverOsh) oshv.add(modeling.createLinkOSH('ownership', ownerOsh, osh)) oshv.add(ownerOsh) return oshv
def need_update_user(database, current_time): cursor = database.cursor() command = """ SELECT * FROM USER """ cursor.execute(command) user_ids = [db.User(item, True) for item in cursor.fetchall()] user_ids = [ item.id for item in user_ids if (current_time - item.last_updated).seconds >= item.update_period ] return user_ids
def reg(): login = request.form['login'] password = request.form['password'] password_again = request.form['password_again'] reg = db.Reg(login, password, password_again) if reg.success: user = db.User(login=login, password=password) login_user(user) return redirect(url_for('account', id=user.id)) else: return redirect(url_for('index', warn=reg.warn))
def submit_search(): user = db.User() if auth.is_login: user = db.db_session.query(db.User).filter( db.User.u_name == session.get('current_user')).first() keyword = request.form.get('search_input') search_data = db.search(keyword) bars = search_data.get('bar') posts = search_data.get('post') return render_template('search.html', user=user, bars=bars, posts=posts, old_keyword=keyword)
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: user_id = get_user_id(tracker) previous_exp = tracker.get_slot('previous_exp') objective = tracker.get_slot('objective') property = tracker.get_slot('property') if previous_exp == 'low': level = 1 elif previous_exp == 'middle': level = 2 elif previous_exp == 'high': level = 3 if objective == 'muscle': purpose = '근육증가' elif objective == 'lose_weight': purpose = '체중감량' elif objective == 'balanced': purpose = '균형' if property == 'a': preffered_split_cnt = 1 criteria = '없음' elif property == 'b': preffered_split_cnt = 2 criteria = '상체/하체' elif property == 'c': preffered_split_cnt = 2 criteria = '부위별' elif property == 'd': preffered_split_cnt = 2 criteria = '부위별' elif property == 'e': preffered_split_cnt = 3 criteria = '부위별' elif property == 'f': preffered_split_cnt = 4 criteria = '부위별' u = db.User(user_id, purpose, criteria, preffered_split_cnt, level, 1, 0) db.create_user_info(u) if debug: dispatcher.utter_message("action_registration called!") return []
def login(): error = None name = str(request.form['uname']) pword = str(request.form['pword']) if name == "" or pword == "": error = "fill the both fields" else: db.User(name).log_in(pword) if 'username' in session: flash("Welcome back {}".format(name)) return redirect(url_for('show_all')) else: error = "wrong info.try to log in again" return render_template('hello.html', error=error)
def buildUsersOsh(self, dbUsers, databaseOsh): '@types: list[MaxDbUser], osh -> oshv' oshv = ObjectStateHolderVector() for user in dbUsers: osh = self.buildUserOsh(user) osh.setContainer(databaseOsh) if user.createdBy: label = user.createdBy + ":" + user.name osh.setStringAttribute('user_label', label) ownerOsh = self.buildUserOsh(db.User(user.createdBy)) ownerOsh.setContainer(databaseOsh) oshv.add(modeling.createLinkOSH('ownership', ownerOsh, osh)) oshv.add(ownerOsh) oshv.add(osh) return oshv
def index(page): if auth.is_login(): current_user = session.get('current_user') current_user = db.db_session.query( db.User).filter(db.User.u_name == current_user).first() age = db.get_age(current_user.u_id) my_created_bars = db.get_my_bars(current_user.u_id) my_concentrated_bars = db.get_my_concentrated_bars(current_user.u_id) return render_template('index.html', user=current_user, age=age, my_created_bars=my_created_bars, my_concentrated_bars=my_concentrated_bars, current_page=page) return render_template('index.html', user=db.User(), current_page=page)
def db_insert_user(usr, sess, req_id): insert = db.User(user_id=usr.user_id, domain=usr.domain, request_user_id=req_id, first_name=usr.first_name, last_name=usr.last_name, user_status=usr.user_status, init_data=str(dt.now()), offset=usr.offset, sex=usr.sex, age=usr.age, city=usr.city) sess.add(insert) sess.commit() return insert
def put__user_in_db(): # try to catch exceptions try: # initialize database session session = db.Session() # Create a User class instance user = db.User(user_id=1234, first_name='Yura', last_name='Pit', username='******') print( f'user_id of user object before adding to db: -> {user.user_id}' ) # Place an object in the Session session.add(user) # add to db session.commit() # Find user which user_id = 1234 user_from_db = session.query( db.User).filter_by(username='******').first() print(f'User object from db ->' f'\n id -> {user_from_db.id}' f'\n user_id -> {user_from_db.user_id}' f'\n first_name -> {user_from_db.first_name}' f'\n last_name -> {user_from_db.last_name}' f'\n username -> {user_from_db.username}') # find user u = session.query(db.User).filter_by(username='******').first() # set new username u.username = '******' # Place an object in the Session session.add(user) # add to db session.commit() # print all records from User table print('All RECORDS') for user in session.query(db.User).all(): print(f'-' * 50 + f'\n id -> {user.id}' f'\n user_id -> {user.user_id}' f'\n first_name -> {user.first_name}' f'\n last_name -> {user.last_name}' f'\n username -> {user.username}') except Exception as e: print(e)
def add_user(email): # add user with given email check_email(email) try: import sequencer uid = sequencer.seq('users', sequencer.mock_seq) user = db.User(uid, email) db.session.add(user) db.session.commit() except sqlalchemy.exc.IntegrityError: db.session.rollback() raise UserAlreadyExistsException return uid