Esempio n. 1
0
    def __add_user(self, _request):
        parser = reqparse.RequestParser()

        parser.add_argument("username",
                            type=str,
                            help="Username for new user",
                            location="json")

        parser.add_argument("password",
                            type=str,
                            help="Password for user",
                            location="json")

        if "devices" not in _request:
            raise BadRequestError(
                "List of device id to be assigned for user, pass empty list for None"
            )

        args = parser.parse_args()
        password = args["password"]
        hashed_password = generate_password_hash(password, method="sha256")

        user = models.User(
            username=args["username"],
            password=hashed_password,
            devices=_request["devices"],
        )
        try:
            user.save()
        except Exception:
            raise UserAlreadyExistsError(
                "User with given username already exists")
        return user.to_json()
Esempio n. 2
0
def create_user(db: Session, user: schemas.UserCreate) -> models.User:
    db_user = models.User(
        email=user.email)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Esempio n. 3
0
def add_user(address, coins=2000):
    private_key = ''.join(random.choices(ascii_letters, k=10))
    scope, _ = open_db(DB_FPATH)
    with scope() as s:
        s.add(
            models.User(address=address, private_key=private_key, coins=coins))
    print(f"Private key: {private_key}")
Esempio n. 4
0
def handleApply(code: schemas.Authcode, db: Session = Depends(get_db)):
    # 获取用户信息
    res_dic = utils.getUserinfo(code.code)
    # 判断申请用户是否在数据库内
    user = db.query(models.User).filter(
        res_dic['user_info']['openid'] == models.User.Openid).first()
    if user:
        if user.Authorized:
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail='您已是管理员')
        raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                            detail='您已向管理员申请,请勿重复申请')

    department = utils.getDepartment(res_dic['user_info']['unionid'])
    try:
        user = models.User(Nick=res_dic['user_info']['nick'],
                           Openid=res_dic['user_info']['openid'],
                           Department_name=department)
        db.add(user)
        db.commit()
    except:
        raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                            detail='录入信息异常')
    return {'code': 0}
Esempio n. 5
0
    async def test_guild_methods(self):
        """Test Guild Methods"""
        pool = await asyncpg.create_pool(**database_settings)
        client = SqlClient(pool)
        await client.setup()
        # Creating the user
        user = models.User(client, 1234)
        await user.save()

        user_exists = await client.get_user(1234)
        self.assertIsNotNone(user_exists)

        guild = models.Guild(client, 12345)
        await guild.save()
        await guild.add_member(1234)

        member_exists = await guild.get_member(1234)
        self.assertIsNotNone(member_exists)

        new_prefix = await guild.add_prefix(">>", 1234)
        self.assertIn(new_prefix.prefix, guild.prefixes)

        await guild.delete_prefix(new_prefix.prefix)
        self.assertNotIn(new_prefix.prefix, guild.prefixes)

        await guild.delete()
        response = await client.get_guild(12345)
        self.assertIsNone(response)
Esempio n. 6
0
def create_user(db: Session, user: schemas.UserCreate) -> models.User:  # USER
    db_user = models.User(email=user.email,
                          name=user.name,
                          photo_url=user.photo_url)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Esempio n. 7
0
def create_user(db: Session, user: schemas.UserCreate):
    fake_hashed_password = user.User_Password
    db_user = models.User(User_ID=user.User_Name,
                          User_Name=user.User_Name,
                          User_Password=fake_hashed_password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Esempio n. 8
0
def create_user():
    new_user = models.User()
    new_user.name = request.json['name']
    new_user.email = request.json['email']
    new_user.password_hash = new_user.set_password(request.json['password'])

    if db.session.query(models.User).filter_by(
            id=new_user.id, email=new_user.email).count() < 1:
        db.session.add(new_user)
        db.session.commit()
        return user_schema.jsonify(new_user)
    else:
        return exceptions.DbEntryExists[0], exceptions.DbEntryExists[1]
Esempio n. 9
0
def create_user(database: Session, user: schemas.UserCreate):
	'''Create a new user'''
	db_user = models.User(
		username=user.username,
		first_name=user.first_name,
		last_name=user.last_name,
		email=user.email,
		salted_password_hash=hash_password(user.username, user.password)
	)
	database.add(db_user)
	database.commit()
	database.refresh(db_user)
	return db_user
Esempio n. 10
0
 def add_user(ulist):
     out_data = "添加成功"
     for u in ulist:
         try:
             user = models.User(
                 name=u.get("name"),
                 passwd=u.get("password"),
                 gender=u.get("gender"),
                 group=u.get("group"),
                 phone=u.get("phone"),
             )
             user.save()
         except Exception as e:
             out_data = "添加失败\t" + str(e)
     return out_data
Esempio n. 11
0
 def check_credentials(self,
                       user: schemas.User,
                       session: Session = SessionLocal()):
     user_meta_as_dict = user.dict()
     user_meta_as_dict.update({
         "password":
         sha512(user_meta_as_dict.get("password").encode()).hexdigest()
     })
     user_model = models.User(**user_meta_as_dict)
     user_db = (session.query(models.User).filter(
         models.User.username == user_model.username).first())
     try:
         return user_db.password == user_model.password
     except:
         pass
Esempio n. 12
0
 def create_user(self,
                 user: schemas.User,
                 session: Session = SessionLocal()):
     user_meta_as_dict = user.dict()
     user_meta_as_dict.update({
         "password":
         sha512(user_meta_as_dict.get("password").encode()).hexdigest()
     })
     user_model = models.User(**user_meta_as_dict)
     session.add(user_model)
     try:
         session.commit()
         session.refresh(user_model)
     except Exception:
         session.rollback()
     finally:
         session.close()
    def create_user(self, data) -> dict:
        # check that there isnt a user with this email
        existing_user = (
            self.session.query(models.User).filter_by(email=data["email"]).first()
        )
        if existing_user is not None:
            raise errors.InvalidUserInput(
                "a user already exists with this email address"
            )

        # create the user
        user = models.User()
        user = user.update(data)
        self.session.add(user)
        self.session.commit()

        # return our created user
        output = schema.UserSchema().dump(user)
        return output
Esempio n. 14
0
def registration(db: Session,
                 user_data: schemas.UserCreate,
                 role: str = 'user') -> models.User:
    """Регистрация нового пользователя"""
    hashed_password = get_password_hash(user_data.password)
    new_user = models.User(nickname=user_data.nickname,
                           hashed_password=hashed_password,
                           is_active=True,
                           role=role)
    try:
        db.add(new_user)
        db.commit()
        db.refresh(new_user)
    except IntegrityError:
        print(f'Error: This nickname ({user_data.nickname}) is busy')
        db.rollback()
    except BaseException as e:
        print(f'Error: {e}')
        db.rollback()

    return new_user
Esempio n. 15
0
def get_user(token: str = Depends(oauth2_scheme),
             db: Session = Depends(get_db)):
    exception = HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                              detail='当前用户信息获取异常')
    try:
        token_decode = jwt.decode(token,
                                  Config.SECRET_KEY,
                                  algorithms=Config.ALGORITHM)
        openid = token_decode['openid']
    except:
        raise exception
    current_user = db.query(
        models.User).filter(models.User.Openid == openid).first()
    # 如果当前用户不在数据库内,则生成一个当前用户对象
    if not current_user:
        department = token_decode['department']
        nick = token_decode['nick']
        current_user = models.User(Openid=openid,
                                   Department_name=department,
                                   Nick=nick)
    return current_user
Esempio n. 16
0
 async def get_user(self, pid: int) -> models.User:
     async with self.pool.acquire() as connection:
         response = await connection.fetchrow("SELECT * FROM users where id = $1", pid)
         if response:
             return models.User(client=self, **dict(response))
Esempio n. 17
0
 async def add_user(self, user: int) -> models.User:
     new_user = models.User(self, user)
     await self.execute("INSERT INTO users (id) VALUES ($1) ON CONFLICT (id) do nothing;", user)
     return new_user
Esempio n. 18
0
async def create_new_user(db: Session, username: str,
                          hashed_password: str) -> schemas.User:
    user = models.User(username=username, hashed_password=hashed_password)
    db.add(user)
    return user
Esempio n. 19
0
def store(tags):
    try:
        tso = TwitterSearchOrder()
        tso.set_keywords(tags, or_operator=True)

        sid = SentimentIntensityAnalyzer()

        # Provides the wrapper with the necessary data for making the calls and retrieving the data
        ts = TwitterSearch(consumer_key=key,
                           consumer_secret=secret,
                           access_token=token_key,
                           access_token_secret=token_secret)

        tweet_id_array = [
        ]  # using array instead of calling twitter search again, to make it more time efficient
        count = 0
        for tweet in ts.search_tweets_iterable(tso):
            count += 1

            if (tweet['user']['location'][0:8].lower() == 'edmonton'):
                tweet_id_array.append(tweet['id'])
                ss = sid.polarity_scores(tweet['text'])
                u = mod.User(tweet['user']['id'], tweet['user']['screen_name'],
                             tweet['user']['name'],
                             tweet['user']['followers_count'],
                             tweet['user']['favourites_count'],
                             tweet['user']['friends_count'],
                             tweet['user']['created_at'], timezone.now(),
                             tweet['user']['statuses_count'])

                mod.User.insert_user(tweet['user']['id'],
                                     tweet['user']['screen_name'],
                                     tweet['user']['name'],
                                     tweet['user']['followers_count'],
                                     tweet['user']['favourites_count'],
                                     tweet['user']['friends_count'],
                                     tweet['user']['created_at'],
                                     tweet['user']['statuses_count'])

                mod.Tweet.insert_tweet(
                    tweet['id'], tweet['text'], tweet['created_at'],
                    tweet['favorite_count'], tweet['retweet_count'],
                    tweet['in_reply_to_status_id'], tweet['lang'], u,
                    ss['compound'], ss['pos'], ss['neg'], ss['neu'],
                    get_sentiment_string(ss['compound']), 'retweeted_status'
                    in tweet)
                hashtags_list = tweet['entities']['hashtags']

                # Add the hashtags and duplicates are not added
                for hashtag in hashtags_list:
                    mod.Hashtag.insert_hashtag(tweet['id'],
                                               hashtag['text'].lower())

        # count and save the rep_count after all the tweet data is saved and updated in database
        for tweetid in tweet_id_array:
            rp_count = Tweet.objects.filter(tid_parent=tweetid).count()
            mod.Tweet.insert_replycount(tweetid, rp_count)

    except (TwitterSearchException, ConnectionError
            ) as e:  # take care of all those ugly errors if there are some
        print 'Exception:', e

    print count, 'tweets received'