예제 #1
0
def admin_users_add():
    user = User()
    user.id = ''
    user.firstname = ''
    user.lastname = ''
    user.email = ''
    return render_template('user.html', user=user)
  def create_standard_user(
      self
    , VIP
    , GLASSES_ID
    , PLATFORM_ID
    , HEADTRACKING_TARGET_NAME
    , WARNINGS
    ):
    _user = User()
    _user.my_constructor(self
                       , len(self.user_list)
                       , VIP
                       , GLASSES_ID
                       , HEADTRACKING_TARGET_NAME
                       , PLATFORM_ID
                       , self.navigation_list[PLATFORM_ID].trace_material)
    self.user_list.append(_user)

    # init border checker to warn user on platform
    if WARNINGS:
      if self.border_observer_list[PLATFORM_ID] == None:
        _checked_borders = [True, True, True, True]
        self.create_border_observer(_checked_borders, _user, self.navigation_list[PLATFORM_ID].platform)
      else:
        self.border_observer_list[PLATFORM_ID].add_user(_user)
    def test_user_password(self, testapp):
        """ Test password hashing and checking """

        admin = User(username="******", password="******")

        assert admin.username == 'admin'
        assert admin.check_password('supersafepassword')
예제 #4
0
	def connect(self):
		from ContentMgmt import ContentMgmt
		import User
		User.init_graphics()
		from User import interface_user

		self.user = interface_user.connect()
		if self.user != None:
			from db import db
			from University import University
			print 'access granted'
			self.connected = True
			self.user.settings.load_settings()
			def query(db, empty):
				return db.session.query(University).get(1)
			self.university = db.session_query(query, None,
			    'Timetableasy init : query(University).get(1)')
			self.contentmgr = ContentMgmt()
			# XXX what to do with that ?
			#if db.status == False:
			#	self.contentmgr.status_bar.add_action('icon', 9)
			self.contentmgr.status_bar.add_action('icon', 2)
			self.contentmgr.status_bar.set_connection_status(1)
			self.contentmgr.status_bar.check_date_display()
			# XXX first load of rights
			if (not self.user.is_admin()):
				self.contentmgr.menubar.admin.hide()
			self.contentmgr.show()
		else:
			print 'access denied'
예제 #5
0
파일: Game.py 프로젝트: bluemania/Code
 def setup_players(self):
     # ask how many players
     player_count = int(raw_input("How many players?: "))
     for count in range(player_count):
         temp_user_assign = User()
         temp_user_assign.name = "Player " + str(count + 1)
         self.users.append(temp_user_assign)
예제 #6
0
    def test_get_by_id(self):
        """Get user by ID."""
        user = User('foo', '*****@*****.**')
        user.save()

        retrieved = User.get_by_id(user.id)
        assert retrieved == user
예제 #7
0
	def post(self):
		username = self.request.get("username")
		password = self.request.get("password")
		verify = self.request.get("verify")
		email = self.request.get("email")
		has_error = False
		params = dict(username = username, email=email)
		if not valid_username(username):
			params['error_username'] = "******"
			has_error = True
		if not valid_password(password):
			params['error_password'] = "******"
			has_error = True
		if not (password == verify):		
			has_error = True
			params['error_verify'] = "Your passwords didn't match."
		if email:
			if not valid_email(email):
				params['error_email'] = "That's not a valid email."
				has_error = True

		if has_error:
			self.render('signup-form.html', **params)
		else:
			users = getByUsername(username)
			if users.count() != 0:
				params['error_user'] = "******"
				self.render('signup-form.html', **params)
			else:
				hash_password = pw_hash(password)
				u = User(username=username,password=hash_password,email=email)
				u.put()
				self.response.headers.add_header('Set-Cookie', 'user_id=%s; Path=/'%str(username))
				self.redirect('/')
예제 #8
0
 def adduser(self, userkey, uname):
     """Add a user to the datastore."""
     #Check for a user with that name
     if User.get(uname) is not None:
         raise RuntimeError("Username in use")
     if User.gql("WHERE googleacct = :1", users.get_current_user()).count() > 0:
         raise RuntimeError("Account in use")
     User.(key_name=uname, userkey=userkey, uname=uname).put()
예제 #9
0
def new_user(name, c):    # new user function creates a user object and builds it
    #directory = user_directory(name, c)     
    #disable deleting old directory to make a new one
    #if (file_exists(directory)):
    #    rmdir(directory)
    
    u = User(name, c)   #instantiate a user object with parameters username and user's classname  
    u.build()        #call user object method build() from User.py
    return u           # return built user object - used in Console.py 
예제 #10
0
 def post(self):
     args = user_parser.parse_args()
     user = User(first_name=args.first_name, last_name=args.last_name, username=args.username)
     user.set_password(args.password)
     db.session.add(user)
     db.session.commit()
     user_url = fields.Url('user_bp.user_detail', absolute=True)
     user_url = user_url.output(user_url.endpoint, {"username": user.username})
     return user, 201, {"Location": user_url}
예제 #11
0
def register():
    """Register new user."""
    form = RegisterForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True)
        flash('Thank you for registering. You can now log in.', 'success')
        return redirect(url_for('public.home'))
    else:
        flash_errors(form)
    return render_template('public/register.html', form=form)
예제 #12
0
def getUsers():
    if ('i' in request.args):
        resultados = User.listado(int(request.args['i']))
    elif ('a' in request.args):
        resultados = User.listado(0, request.args['a'])

    if (len(resultados) == 0):
        abort(404)
    else:
        return jsonify({ 'user': marshal(resultados, User.FIELDS) })
예제 #13
0
def create(name,pwd):
    res=User.getRes('select * from user where name=\"'+name+'\"')
    if len(res):#user已经存在
        return -1
    else:#user不存在
        User.getRes('insert into user (name,pwd,ufriends) values (\"'+name+'\",\"'+pwd+'\",\"\''+name+'\',\")')
        res=User.getRes('select * from user where name=\"'+name+'\"')
        if len(res)!=0:
            return 1
        else:
            return 0
예제 #14
0
파일: _reset.py 프로젝트: luzi82/HiSocial
def build(install_config):
    if install_config != None:
        cleanup = Cleanup()
        session = Database.create_sqlalchemy_session_push(cleanup)
        
        Group.add(session, "owner", "Owner")
        GroupPermission.set(session, "owner", "admin", 99999999, True)

        User.add_user_account(session, install_config.OWNER_USERNAME, install_config.OWNER_PASSWORD)
        UserGroup.join(session, install_config.OWNER_USERNAME, "owner")
        session.commit()
예제 #15
0
def command_guest_change_user_account_password(txt_user_id, txt_old_password, txt_new_password):
    cleanup = Cleanup()
    session = Database.create_sqlalchemy_session_push(cleanup)
    
    if not User.check_user_account_password(session, txt_user_id, txt_old_password):
        return hs_plugin.fail(reason="auth")
    
    User.change_password(session, txt_user_id, txt_new_password)
    session.commit()
    cleanup.clean_all();

    return hs_plugin.ok()
예제 #16
0
def populate_database():
    """
        Returns a list of College objects to be stored in the database
        Then they can be reconstructed by called
        colleges = db_load_colleges()
    """
    database_schools = []
    n = 0
    cols = []
    cols_with_size = get_sizes()
    while n < len(colleges_with_sat):
        c = C(colleges_with_sat[n], colleges_with_sat[n+1], colleges_with_sat[n+2], colleges_with_sat[n+3], colleges_with_sat[n+4])
        cols.append(c)
        n+=5
                
    for i in range(0, len(colleges)):
        name = colleges[i]
        if False: #db_college_exists(name):
            continue
        sats = {}
        size = 0
        tuition = 0
        address = ""
        zipcode = 0
        matched = False
        for c in cols:
            if levenshtein(c.name, name) < 3:
                matched = True
                sats['math'] = c.math_range
                sats['reading'] = c.read_range
        if not matched:
            sats = None
        for c in cols_with_size:
            #print c[0]
            if levenshtein(c[0], name) < 3:
                size = c[1]
                tuition = c[2]
                address = c[3]
                zipcode = c[4]
                #print c
                break
        college = College(name, "", i, sats, size, tuition, address, zipcode)
        #print college
        database_schools.append(college)
        #college.print_college()
        user = User()
        user.name = "Aaron"
        user.sats = {"math" : 800, "reading" : 800}

        #print college.find_location()
        #print college.get_difficulty()
    return database_schools
예제 #17
0
def testapp(request):
    app = create_app('{{cookiecutter.app_name}}.settings.TestConfig')
    client = app.test_client()

    db.app = app
    db.create_all()

    if getattr(request.module, "create_user", True):
        admin = User(username="******", password="******")
        admin.insert()
        my_role = Role(name='admin')
        my_role.insert()
        admin.add_roles('admin')

        non_admin = User(username="******", password="******")
        non_admin.insert()

        safe_commit()

    def teardown():
        db.session.remove()
        db.drop_all()

    request.addfinalizer(teardown)

    return client
예제 #18
0
	def addUser(self, formdata):
		confid = int(cherrypy.session['confid'])
		formdata = cjson.decode(formdata)
		
		newuser = User()
		results = newuser.new(formdata, confid)
		
		if results:
			if self.users.has_key(confid) == False:
				self.users[confid] = {}
			
			self.users[confid][newuser['id']] = newuser
		
		return cjson.encode({'result':results})
예제 #19
0
def login(provider_name):
    response = make_response()
    result = current_app.authomatic.login(
        WerkzeugAdapter(request, response), provider_name
    )

    if result:
        if result.user:
            first_login = False
            result.user.update()
            user = User.objects(provider=provider_name, user_id=result.user.id).first()
            if user is None:
                user = User(
                    username=result.user.username,
                    email=result.user.email,
                    name=result.user.name,
                    user_id=result.user.id,
                    provider=provider_name
                )
                user.save()
                first_login = True
            else:
                user.name = result.user.name
                user.email = result.user.email
                user.save()

            session['user_id'] = user.user_id
            return redirect_next()

        flash_error('Authentication failed')
        return redirect(url_for('auth.login_page', next=request.path))

    return response
예제 #20
0
파일: api.py 프로젝트: mazz/kifu
def new_user(request):
    """Add a new user to the system manually."""
    rdict = request.params

    u = User()

    u.username = unicode(rdict.get('username'))
    u.email = unicode(rdict.get('email'))
    passwd = get_random_word(8)
    u.password = passwd
    u.activated = True
    u.is_admin = False
    u.api_key = User.gen_api_key()

    try:
        DBSession.add(u)
        DBSession.flush()
        # We need to return the password since the admin added the user
        # manually.  This is only time we should have/give the original
        # password.
        ret = dict(u)
        ret['random_pass'] = passwd
        return _api_response(request, ret)

    except IntegrityError, exc:
        # We might try to add a user that already exists.
        LOG.error(exc)
        request.response.status_int = 400
        return _api_response(request, {
            'error': 'Bad Request: User exists.',
        })
예제 #21
0
def command_user_remove_user_account(txtf_user_token, txt_user_id):
    cleanup = Cleanup()
    session = Database.create_sqlalchemy_session_push(cleanup)
    
    if not Permission.get_user_permission(session, txtf_user_token, "admin"):
        return hs_plugin.fail(reason="permission")
    
    if not User.check_user_account_exist(session, txt_user_id):
        return hs_plugin.fail(reason="user_id")
    
    User.remove_user_account(session, txt_user_id)
    session.commit()
    cleanup.clean_all();

    return hs_plugin.ok()
    def create_user(
        self,
        VIP,
        AVATAR_VISIBILITY_TABLE,
        HEADTRACKING_TARGET_NAME,
        EYE_DISTANCE,
        NO_TRACKING_MAT=avango.gua.make_trans_mat(0, 0, 0),
    ):

        _user = User()
        _user.my_constructor(
            self, len(self.users), VIP, AVATAR_VISIBILITY_TABLE, HEADTRACKING_TARGET_NAME, EYE_DISTANCE, NO_TRACKING_MAT
        )

        self.users.append(_user)
예제 #23
0
def sample_data():
    """
    Creates a set of sample data
    """
    from {{cookiecutter.app_name}}.models import Role
    user = User(username="******", password="******")

    my_role = Role(name='admin')
    my_role.add_abilities('create_users', 'delete_users')

    user.add_roles('admin', 'superadmin')

    db.session.add(user)
    db.session.add(my_role)
    db.session.commit()
예제 #24
0
 def get(self):
     cookieValue = self.request.cookies.get('username')
     username = User.check_secure_value(cookieValue)
     if username:
         self.render_html('welcome.html', username = username)
     else:
         self.logout()
예제 #25
0
파일: views.py 프로젝트: uisky/flask-fish
def login():
    is_ajax = request.args.get('ajax')

    def success():
        if is_ajax:
            return jsonify(status='ok')
        else:
            return redirect(request.args.get('next', '/'))

    def fail(error):
        if is_ajax:
            return jsonify(status='error', errors=[error])
        else:
            flash(error, 'danger')
            return redirect(url_for('front.index'))

    user = User.query.filter(User.email == request.form.get('email')).first()

    if user and User.hash_password(request.form.get('password', '')) == user.password_hash:
        if not login_user(user, remember=True):
            return fail('Пароль верный, но ваш аккаунт не активен.')
    else:
        return fail('Неправильный e-mail или пароль.')

    return success()
예제 #26
0
def command_human_create_user_account(txtf_turing_turing,env_ip,txt_user_id, txt_password):

    cleanup = Cleanup()
    session = Database.create_sqlalchemy_session_push(cleanup)

    if(User.check_user_account_exist(session, txt_user_id)):
        return hs_plugin.fail(reason=FAIL_REASON_USER_EXIST)
    
    User.add_user_account(session, txt_user_id, txt_password)
    
    session.commit()
    cleanup.clean_all();

    token = UserLoginToken.generate_user_login_token(txt_user_id)
    
    return hs_plugin.ok({"user_login_token":token})
예제 #27
0
    def post(self):
        """
        Post method is called when user tries to login.
        Login credentials are checked in the following way:
            - It is checked if the username exists in the database
            - It is checked if the the hashed password matches the password
              hash as stored in the database
        After successful login the user is redirected to a "welcome" page.
        """
        username = self.request.get('username')
        password = self.request.get('password')

        user = User.User.by_name(username)

        if not user:
            error_username = "******"
            return self.render('login.html', error_username=error_username)
        elif not User.valid_pw(username, password, user.pw_hash):
            error_password = "******"
            return self.render('login.html',
                               username=username,
                               error_password=error_password)
        else:
            self.login(user)  # Sets the cookie with user id
            return self.redirect('/blog/welcome')
예제 #28
0
def command_user_create_user_account(txtf_user_token,txt_user_id, txt_password):
    cleanup = Cleanup()
    session = Database.create_sqlalchemy_session_push(cleanup)
    
    if not Permission.get_user_permission(session, txtf_user_token, "admin"):
        return hs_plugin.fail(reason="permission")
    
    if User.check_user_account_exist(session, txt_user_id):
        return hs_plugin.fail(reason=FAIL_REASON_USER_EXIST)

    User.add_user_account(session, txt_user_id, txt_password)
    
    session.commit()
    cleanup.clean_all();
    
    return hs_plugin.ok()
예제 #29
0
    def get(self, id):
       	resultados = User.listado(id)

        if (len(resultados) == 0):
            abort(404)
        else:
        	return { 'user': marshal(resultados, User.FIELDS) }
예제 #30
0
def clientUSER(arg):
    if arg.con.pw is None:
        arg.con.sendLine(
            ":[email protected] 464 :You need to send a password (user:pass) before sending the USER command"
        )
        arg.con.close()
        arg.passthough = False
    else:
        if arg.con.user is None:
            arg.passthough = False
            p = arg.con.pw.split(":")
            if len(p) != 2:
                arg.con.sendLine(":[email protected] 464 :Invalid server password format")
                arg.con.close()
                return
            user = User.resolve([0])
            if user is None:
                arg.con.sendLine(":[email protected] 464 :Invalid user credentials")
                arg.con.close()
                return
            h = hashlib.sha512()
            h.update(p[1])
            if user.data["pass"] != h.hexdigest():
                arg.con.sendLine(":[email protected] 464 :Invalid user credentials")
                arg.con.close()
                return
            con.user = user
예제 #31
0
파일: server.py 프로젝트: qhdalong/chat
def main():
    global userlist,userlist_length

    ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('服务器套接字已创建......')
    address = '127.0.0.1'
    port = 9999
    print('服务器地址及端口已设置......')
    ServerSocket.bind((address,port))
    print('服务器地址及端口已绑定......')
    ServerSocket.listen(5)
    print('服务器监听进程已开启......')
    print('服务器已启动......')
    while True:
        ClientConn, ClinetAddress = ServerSocket.accept()
        user = User.User(ClientConn, userlist_length, ClinetAddress)      
        print('用户[%s]已连接' % str(userlist_length))
        userlist.append(user)
        userlist_length += 1
        thr = threading.Thread(target=hand_user_conn, args=(user,))
        thr.start()
예제 #32
0
def get_mail():
    context = context_manager.get('get-age-followup')

    age = context.parameters['age']['amount']
    prefernce = context.parameters['food-perference']
    gender = context.parameters['gender']
    weight = context.parameters['unit-weight']['amount']
    height = context.parameters['unit-length']['amount']
    email = context.parameters['email']
    activity = context.parameters['activity-level']
    user = User.User(gender=gender,
                     age=age,
                     weight=weight,
                     height=height,
                     taste=prefernce,
                     activityLevel=activity,
                     email=email)
    menu = EngineClient.createMenuAndSendMail(user)

    speech = "A new cool menu will be sent to you shortly!"
    return ask(speech)
예제 #33
0
async def submissions(ctx, name=None, num=1):
    # No user is given
    if name is None:
        await ctx.channel.send(">>> **Parameters** (User, Amount)\n" +
                               "**User**: Name of the user on DMOJ\n" +
                               "**Amount: ** Amount of submissions to get")
        return
    try:
        user = User.User(name)
    except:
        await ctx.channel.send("That user does not exist")
        return

    submission = user.recent_submission(num)

    if submission.verdict == "AC":
        await ctx.channel.send(f"{user.name} AC'd on {submission.problem.name} worth {submission.problem.points} points HOLY SHIT "
                               f"<:PogU:594138006999269427>\nLink: {submission.problem.link}")
    else:
        await ctx.channel.send(f"{user.name} F*****G {submission.verdict}'d on {submission.problem.name} worth {submission.problem.points} points "
                               f"LMAOOOOOO <:PepeLaugh:594138680898355200>\nLink: {submission.problem.link}")
예제 #34
0
파일: game.py 프로젝트: hencic00/Poker
    def startGame(self):
        data = {}
        data['agenda'] = "gameStart"
        data['data'] = {'players': [], 'startingCash': []}
        for user in self.lobby['users'].values():
            self.addPlayer(Player(self.startingCash, user))
            #add user to data object for sending of initial players
            data['data']['players'].append({
                'playerSid':
                user['sid'],
                'username':
                User.getUsername(user['sid'])
            })

        comms.broadcastToPlayers(self.players, data)
        result = self.startNewRound()
        if (result == False):
            for x in range(len(self.players) - 1, -1, -1):
                self.removePlayerFromGame(x)
        #endGameUsers se dodaja ko nekdo zapusti igro ali zmaga
        return self.endGameUsers
예제 #35
0
def createUser():
    createUserForm = CreateUserForm(request.form)

    if request.method == 'POST' and createUserForm.validate():
        usersDict = {}
        db = shelve.open('storage.db', 'c')
        try:
            usersDict = db['Users']
        except:
            print("Error in retrieving Users from storage.db.")
            user = User.User(createUserForm.firstName.data,
                             createUserForm.lastName.data,
                             createUserForm.membership.data,
                             createUserForm.gender.data,
                             createUserForm.remarks.data)
            usersDict[user.get_userID()] = user
            db['Users'] = usersDict
            db.close()
            return redirect(url_for('retrieveUsers'))
        return redirect(url_for('home'))
    return render_template('createUser.html', form=createUserForm)
예제 #36
0
    def test_unique_username(self, testapp, dbsession):

        user = User(
            username='******',
            email='*****@*****.**',
            password='******'
        )
        dbsession.add(user)
        # Go to home
        response = testapp.get('/')
        # Click create account
        response = response.click('Create account')
        # get the form
        form = response.form
        # Fill it
        form['username'] = '******'  # same username
        form['email'] = '*****@*****.**'
        form['password'] = '******'
        # Submit form
        response = form.submit()
        assert 'Username already registered' in response
예제 #37
0
 def name(bot, update):
     try:
         print(update.message.text)
         text = elimina_tildes(update.message.text)
         id = update.message.chat.id
         d_users[id] = t4.User(text, id)
         update.message.reply_text(text=("Usuari *" + text +
                                         "* creat correctament!"),
                                   parse_mode=telegram.ParseMode.MARKDOWN)
         update.message.reply_text(text=(
             "Recorda que pots consultar el temps restant i el contingut de la motxilla amb /info i pots aturar la conversa amb /cancel"
         ))
         update.message.reply_text(
             text="Prem start per començar la partida",
             reply_markup=ReplyKeyboardMarkup([["start"]],
                                              one_time_keyboard=True))
         global to_type
         to_type = [["start"]]
         return HELLO
     except Exception:
         traceback.print_exc()
예제 #38
0
 def registerUser(self, user):
     for registeredUser in self.userList:
         if user.username == registeredUser.username:
             print(user.username + " is not available")
             return user.username + " is not available"
         if user.email == registeredUser.email:
             print(user.email + " is not available")
             return user.email + " is not available"
     credential = self.credentialValidation(user.username, user.password,
                                            user.email)
     if credential is True:
         user = User(user.username, user.password, user.email)
         fileObject = open(self.userListFileName, 'ab')
         pickle.dump(user, fileObject)
         fileObject.close()
         self.userList.append(user)
         print("Created User:"******"successfully")
         return True
     else:
         print("Created User:"******"failed")
         return "Your " + credential + " is not valid"
def login(users):
    email = input("Enter Email Address: ")
    password = input("Enter Password: "******"Password or Email Do Not Match what is stored",
                      "\nExiting Secure Drop")
                sys.exit()

    print("Password or Email Do Not Match what is stored",
          "\nExiting Secure Drop")
    sys.exit()
예제 #40
0
    def actionController(self, id, mes):
        """Главный контроллер"""

        self.user = User.UserClass(id)
        action = self.user.check_action()

        if mes == config.command['Cancel']:  # Отмена команд при ключевом слове
            self.user.del_action()
            self.user.message('Команда отменена')
            self.__log(
                "Пользователь {id}, отменил команду".format(id=self.user.id))

        elif mes in self.command and not action[
                'code']:  # Выполнение команды если она есть в списке
            self.methods[self.command[mes]['action']](mes)

        elif action['code']:  # Выполняет команду, ели она уже выбрана
            self.methods[action['action']](mes, True)

        else:  # Неверный ввод
            self.error('not command')
예제 #41
0
 def test_removeEmployee(self):
     user = User('TestA')
     user.id = 1
     user2 = User('TestB')
     user2.id = 2
     # remove in an empty positionTree
     self.assertRaises(InvalidArgument, self.department.removeEmployee,
                       user.id)
     # employee not found
     self.department.addPosition('A', None)
     self.department.addEmployee('A', user)
     self.assertRaises(InvalidArgument, self.department.removeEmployee,
                       user2.id)
     # employee found
     self.department.removeEmployee(user.id)
     self.assertEqual(None, self.department.findEmployeePosition(user.id))
예제 #42
0
    def receive(self, msg):
        print("receive '%s' state %s" % (msg.rstrip(), self.__state))
        message = Global.Message(msg)

        # Check validity of the message.
        if not message.is_valid():
            print("Invalid message received.")
            return self.error(self.errorBadFormat)

        if message.get_code() == 1 and self.__state == State.StateWaitUser:

            if not re.match(Global.REGEX_USER, message.get_content()):
                print("Error991")
                return self.error(self.errorUser)

            self.__user = User.User(message.get_content())

            if self.__user.is_user_valid():
                self.__state = State.StateWaitChallenge
                return Global.get_message(2, self.__user.get_challenge()), True
            else:
                print("Error992")
                return self.error(self.errorUser)

        elif message.get_code(
        ) == 4 and self.__state == State.StateWaitChallenge:

            if not re.match(Global.REGEX_CHALLENGE, message.get_content()):
                print("Error993")
                return self.error(self.errorChallenge)

            if self.__user.is_challenge_valid(message.get_content()):
                self.__state = State.StateConnected
                return Global.get_message(5, "Challenge ok"), True
            else:
                print("Error994")
                return self.error(self.errorChallenge)

        print("Error995")
        return self.error(self.errorBadProtocol)
예제 #43
0
def welcome():
    user = User(redisServer, db)
    user.authenticate()

    if user.isAuthenticated and user.has_checkins():
        r = make_response(redirect('/%s/' % user.username))
    elif user.isAuthenticated:
        user.get_checkins()
        r = make_response(
            Template(filename='templates/index.html').render(
                logged_in=True, user=user.username, hasCheckins=False))
    else:
        r = make_response(
            Template(filename='templates/index.html').render(
                logged_in=False,
                user=user.username,
                hasCheckins=False,
                loginUrl=oauth_login_url(next_url=user.get_base_url())))

    if user.sessID:
        r.set_cookie('_sid', user.sessID)

    return r
예제 #44
0
    async def for_aiter(self):
        allc = await User.select().count()
        count = 0
        async for user in User:
            assert isinstance(user, User)
            if user.id == 1:
                assert user.name == 'at7h'
            count += 1
        assert count == allc

        count = 0
        async for user in User.select():
            assert isinstance(user, User)
            if user.id == 1:
                assert user.name == 'at7h'
            count += 1
        assert count == allc

        for i in range(20, 270):
            await User.insert(password=i).do()

        allc = await User.select().count()
        count = 0
        async for user in User:
            assert isinstance(user, User)
            if user.id == 1:
                assert user.name == 'at7h'
            count += 1
        assert count == allc

        try:
            assert User[1]
            assert False, "Should raise NotImplementedError"
        except NotImplementedError:
            pass
        try:
            assert user in User
            assert False, "Should raise NotImplementedError"
        except NotImplementedError:
            pass
예제 #45
0
def user_add():
    log_path()
    errors = None

    if request.method == 'GET':
        form = UserAddForm()

    elif request.method == 'POST':
        form = UserAddForm(request.form)

        if form.validate():
            _log.log('form validated', LogType.INFO)
            newUser = User.User()
            form.populate_obj(newUser)

            try:
                newUser.Add()
            except ErrorHandler.ErrorHandler as error:
                flash('Error {0}: {1}'.format(error.status_code,
                                              error.message),
                      category='danger')
                return render_template('user_add.html',
                                       form=form,
                                       errors=errors,
                                       title='Add a User')

            _log.log('added user {}'.format(newUser), LogType.INFO)
            flash('Success: User added', category='success')

            return (redirect(url_for('user')))

        else:
            flash('Error: User not added', category='error')
            errors = form.errors

    return render_template('user_add.html',
                           form=form,
                           errors=errors,
                           title='Add a User')
예제 #46
0
    async def for_ddl(self):
        try:
            await Model.create()
            assert False, "Should raise err.NotAllowedError"
        except err.NotAllowedError:
            pass
        try:
            await Model.drop()
            assert False, "Should raise err.NotAllowedError"
        except err.NotAllowedError:
            pass

        csql = await People.show().create_syntax()
        assert ("CREATE TABLE `people` (\n"
                "  `id` int(11) NOT NULL AUTO_INCREMENT,\n"
                "  `name` varchar(45) DEFAULT NULL,\n"
                "  `gender` tinyint(1) unsigned DEFAULT NULL,\n"
                "  `age` tinyint(4) unsigned DEFAULT NULL,\n") in csql
        csql = await Employee.show().create_syntax()
        assert ("  `salary` float DEFAULT NULL,\n"
                "  `departmentid` int(11) DEFAULT NULL,\n"
                "  `phone` varchar(254) DEFAULT '',\n"
                "  `email` varchar(100) DEFAULT '',\n"
                "  PRIMARY KEY (`id`),\n"
                "  KEY `idx_age_salary` (`age`,`salary`)\n") in csql
        csql = await User.show().create_syntax()
        assert ("  `nickname` varchar(100) DEFAULT NULL,\n"
                "  `pwd` varchar(254) DEFAULT NULL,\n"
                "  `role` int(11) DEFAULT '0',\n"
                "  `loginat` datetime DEFAULT NULL,\n"
                "  PRIMARY KEY (`id`),\n"
                "  UNIQUE KEY `unidx_nickname` (`nickname`),\n"
                "  KEY `idx_name` (`name`)\n") in csql
        assert (await User.show().columns())[0]['Field'] == 'id'
        assert len(await User.show().indexes()) == 3
        assert (await User.show().indexes())[0]['Key_name'] == 'PRIMARY'
        assert (await User.show().indexes())[1]['Key_name'] == 'unidx_nickname'
        assert (await User.show().indexes())[1]['Column_name'] == 'nickname'
        assert str(User.show()) == '<Show object for <Table `helo`.`user_`>>'
예제 #47
0
 async def fetchInvite(user):
     inviteChannel = User.get_invite_channel(user.id)
     if inviteChannel == "":
         return ""
     try:
         channel = bot.get_channel(int(inviteChannel))
         if channel == None:
             await logger.log(
                 "Channel not found! ChannelID: " +
                 inviteChannel, bot, "WARNING")
         invite = await channel.create_invite(
             max_uses=1,
             max_age=3600,
             reason="noDoot - Instant Invite for " + user.name +
             ". Expires in 1 hour, single use.")
         return " You can join back to the guild you wanted to join using this link: <" + invite.url + ">!"
     except Exception as e:
         await logger.log(
             "Could not generate an invite to the user ( " +
             user.name + " `" + str(user.id) + "`)! - " +
             str(e), bot, "DEBUG")
         return ""
예제 #48
0
    def test_delete(self):
        user = User.User()
        user.username = '******'
        user.password = '******'
        user.email_address = '*****@*****.**'
        user.first_name = 'test'
        user.middle_name = 'testy'
        user.last_name = 'testerson'
        user.date_of_birth = '1945-01-01'

        user.Add()

        exists = True

        user = User.User.GetByUsername('testingdelete')

        User.User.Remove(user)

        if (not user):
            exists = False

        assert exists
예제 #49
0
 def Restore(cls):
     t = []
     stn = back.getState()
     print stn
     for word in stn.split():
         t.append(word)
     print t
     UserNM = str(t[2])
     PassWD = str(t[3])
     DBNM = str(t[0])
     DBWD = str(t[1])
     SNo = int(t[4])
     Us = User.User("Lecturer", str(UserNM), str(PassWD), str(SNo))
     f = open('Config.txt', "w")
     cls.setUserUsername(str(Us.getUsrNm()), f)
     cls.setUserPassword(str(Us.getPwd()), f)
     cls.setDBUsername(DBNM, f)
     cls.setDBPassword(DBWD, f)
     cls.setSubNo(str(Us.getNoSub()), f)
     cls.SetDB(DBNM, DBWD, UserNM, PassWD, SNo)
     Example().onInfo2()
     print "Restored Sucessfully"
예제 #50
0
def login(request):
    if request.user:
        request.session.flash("info; You're already signed in")
        return HTTPSeeOther(location=request.route_url('home'))
    form = LoginForm(request.POST)
    login_url = request.route_url('login')
    referrer = request.url
    if referrer == login_url:
        referrer = '/'  # never use the login form itself as came_from
    came_from = request.params.get('came_from', referrer)
    if request.method == 'POST' and form.validate():
        username = form.username.data
        user = User.by_username(request.dbsession, username)
        if user and user.verify_password(form.password.data):
            headers = remember(request, user.id)
            return HTTPSeeOther(location=came_from, headers=headers)

        message = 'Failed login. Incorrect username or password'
        form.username.errors.append(message)
        return dict(form=form, came_from=came_from, title="User Login")
    return dict(form=form, came_from=came_from,
                title="User Login")
예제 #51
0
def parseUser(url, depth, maxdepth):
    print(depth)
    if depth > maxdepth:
        return
    print(url)
    page = requests.get(url)
    tree = html.fromstring(page.content)

    name = tree.xpath('//h1[@class="userProfileName"]/text()')
    if len(name) == 0:
        return  # User has no name, or user does not exist any more.
    print(name[0].strip())

    ratings = tree.xpath('//div[@class="leftContainer"]/div[@class="leftAlignedImage"]/a[not(@class="userPagePhoto")]')
    print(len(ratings))
    print(ratings[0].get("href"))

    link = baseurl + ratings[0].get("href") + "&per_page=infinite"
    print(link)
    user = User.User(name[0].strip())
    user = parseReviews(link, user, depth, maxdepth) # just pass depth along
    users.append(user)
예제 #52
0
    def sign_up(self):
        while True:
            id = input("아이디를 입력해주세요(특수문자 X): ")
            if not id.isalnum():
                print("error: 특수문자가 들어있습니다.")
                continue
            if id.upper() in self.users:
                print("error: 동일한 아이디가 있습니다.")
                continue
            pwd = input("비밀번호를 입력해주세요(\\사용불가): ")
            if '\\' in pwd:
                print("error: \\ 문자가 들어있습니다.")
                continue
            name = input("이름을 입력해주세요: ")
            if not name.isalpha():
                print("error: 문자가 아닙니다.")

            menu = ["나가기", "완료", "다시하기"]
            self.print_menu(menu)
            while True:
                opt = self.select_option()
                if opt == -1:
                    continue
                elif opt < 0 and opt >= len(menu):
                    self.out_of_range_error()
                    continue
                else:
                    break
            if opt == 0:
                break
            elif opt == 2:
                continue

            new_user = User.User(id, pwd, name)
            self.users[id.upper()] = new_user
            print("")
            print("축하합니다 ", id, "님")
            print("회원가입 완료되었습니다.")
            break
예제 #53
0
    def search(self, keyword):
        db = GateWay()

        # empty all result list
        self.users = []
        self.teams = []
        self.idprojs = []
        self.teamprojs = []

        userlist = db.search_by_user_id(keyword)

        for i in range(len(userlist)):
            self.users.append(User(userlist[i][0]))

        teamlist = db.search_by_team_id(keyword)

        for i in range(len(teamlist)):
            self.teams.append(Team(teamlist[i][0]))

        self.idprojs = db.search_by_indivprojectid(keyword)

        self.teamprojs = db.search_by_teamprojectid(keyword)
예제 #54
0
def createUser():
    createUserForm = CreateUserForm(request.form)
    if request.method == "POST" and createUserForm.validate():
        db = shelve.open("storage.db", "c")
        try:
            usersDict = db["Users"]
            User.User.countID = int(list(usersDict.keys())[-1])
        except:
            usersDict = {}
            print("Error in retrieving Users from storage.db")
        #? using class to create user instance
        user_instance = User.User(createUserForm.firstName.data,
                                  createUserForm.lastName.data,
                                  createUserForm.gender.data,
                                  createUserForm.membership.data,
                                  createUserForm.remarks.data)
        usersDict[user_instance.get_userID()] = user_instance
        db["Users"] = usersDict
        db.close()

        return redirect(url_for("retrieveUsers"))
    return render_template("createUser.html", form=createUserForm)
def test_register(testapp: TestApp, db: Session, democontent: None) -> None:
    """Test POST /api/users."""
    res = testapp.post_json(
        "/api/users",
        {"user": {"email": "*****@*****.**", "password": "******", "username": "******"}},
        status=201,
    )

    response = copy.deepcopy(res.json)
    response["user"]["token"] = jwt.decode(
        res.json["user"]["token"], "secret", algorithms=["HS512"]
    )
    user = User.by_username("foo", db=db)
    assert response == {
        "user": {
            "email": "*****@*****.**",
            "token": {"sub": str(user.id), "iat": 1546300800},  # type: ignore
            "username": "******",
            "bio": None,
            "image": None,
        }
    }
예제 #56
0
    def signInMethod(self, controller, username, password):
        '''
            Sign's into user's account

            Checks the attempted password with the set password and ensure they are equal before logging in and then changing the frame to the user's accoutn

            Parameters
            ----------
            controller : object
                The controller object so that the method can change frames
            username : string
                The username entered by the user to log in
            password : string
                The password entered by the user to log in

            Returns
            -------
            String

            Raises
            ------
            None

            '''

        if username == '' or password == '':
            popupAlert("Fill out all fields")
        else:
            userList = [
                line.rstrip('\n') for line in open('objectDirectory.txt')
            ]
            if username not in userList:
                popupAlert("Invalid username")
            elif user.signInPortal(username, password) == True:
                global usersName
                usersName = username
                controller.show_frame(UserAccount)
            else:
                popupAlert("Wrong Password")
예제 #57
0
def compare_samples():
    global Output
    try:
        Output = ""
        a = nu.user()
        a.record_sample("temp", 0)
        cost = 80
        flag = ""
        MFCCout = np.loadtxt("temp0.txt")
        for folder in os.listdir(compareroot):
            for file in os.listdir(compareroot + "/" + folder):
                MFCCin = np.loadtxt(compareroot + "/" + folder + "/" + file)
                if (len(MFCCout[0]) > len(MFCCin[0])):
                    inp1 = MFCCin
                    inp2 = MFCCout
                else:
                    inp1 = MFCCout
                    inp2 = MFCCin
                D, wp = lb.sequence.dtw(inp1, inp2, subseq=True)
                bestcost = D[wp[-1, 0], wp[-1, -1]]
                slope = linregress(wp[:, 1], wp[:, 0])
                if slope[0] > 0.75 and slope[0] < 1.25:
                    if bestcost < cost:
                        cost = bestcost
                        slope1 = slope[0]
                        flag = folder
        if cost == 80:
            print("sorry,no user matched")
            Output = "No one"
        else:
            Output = flag
            print("The voice matched to {}".format(flag))
            print("bestcost={}".format(cost))
            print("slope={}".format(slope1))
            print(Output)
    except FileNotFoundError:
        print("file not found")
    if os.path.exists('temp0.txt'):
        os.remove('temp0.txt')
예제 #58
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text='Welcome', font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        label2 = tk.Label(self, text='Select image one from:')
        label2.place(x=70, y=40)
        button1 = ttk.Button(self,
                             text='File Explorer',
                             command=self.callBackOne)
        button1.place(x=50, y=65)
        button1alt = ttk.Button(self,
                                text='Image Library',
                                command=self.callBackOneAlt)
        button1alt.place(x=130, y=65)

        label3 = tk.Label(self, text='Select image two from:')
        label3.place(x=70, y=90)
        button2 = ttk.Button(self,
                             text='File Explorer',
                             command=self.callBackTwo)
        button2.place(x=50, y=115)
        button2alt = ttk.Button(self,
                                text='Image Library',
                                command=self.callBackTwoAlt)
        button2alt.place(x=130, y=115)

        button3 = ttk.Button(self,
                             text='Compare Images!',
                             command=self.displayLabel)
        button3.place(x=75, y=150)

        button4 = ttk.Button(
            self,
            text='Sign out',
            command=lambda: [controller.show_frame(StartPage),
                             user.logOut()])
        button4.place(x=90, y=200)
예제 #59
0
    def CreateUser(self, event):
        un = self.tbun.GetValue()
        ps = self.tbps.GetValue()

        if un != "" and ps != "":
            if len(ps) >= 10:
                users = fio.get_available_user_list()
                make_user = True
                for u in users:
                    if u == un:
                        make_user = False
                        break
                if make_user:
                    usr = user.User(un)

                    self.GetParent().GetParent().GetParent(
                    ).key = sec.make_key(usr.salt, str(ps))
                    usr.control = sec.encrypt_data(
                        "jinxx",
                        self.GetParent().GetParent().GetParent().key)
                    fio.create_user_file(usr)
                    self.GetParent().GetParent().GetParent().OnUserEnter(
                        usr,
                        self.GetParent().GetParent().GetParent().key)
                    self.tbun.SetValue("")
                    self.tbps.SetValue("")
                    self.GetParent().RefreshUserList()
                else:
                    wx.MessageBox(
                        'User already exists. Please enter another username.',
                        'Error', wx.OK)

            else:
                wx.MessageBox('Password must be at least 10 characters.',
                              'Error', wx.OK)
        else:
            wx.MessageBox('Please enter a username and password.', 'Error',
                          wx.OK)
예제 #60
0
 def updateStatus(self, changes, data=None, id=None):
     # 회원 등록
     if changes == 'enroll':
         if self.searchMember(data[0]) is False:
             member = User.User()
             member.id = data[0]
             member.pw = data[1]
             member.name = data[2]
             self.members.append(member)
         else:
             print('중복된 아이디 입니다.')
     # 책 대출
     elif changes == 'borrow':
         member = self.searchMember(id)
         if isinstance(member, User.User) and self.checkRentable(id):
             member.borrowedList.append(data)
         else:
             '대출이 불가능합니다.'
     # 책 반납
     elif changes == 'return':
         member = self.searchMember(id)
         if isinstance(member, User.User):
             member.borrowedList.remove(data)