Example #1
0
def add_user(github_name):
    """ Manually add users -- to populate initial stuff. Should not really be used in prod. """

    import random

    user = User(str(hash(random.random())))
    github_user = github.get(f'/users/{github_name}')

    user.github_id = github_user['id']
    user.github_login = github_user['login']
    user.name = github_user["name"]
    user.org = github_user["company"]
    user.blog = github_user["blog"]
    user.email = github_user["email"]
    user.discord = f'{github_name}#{random.randint(1000,9999)}'

    #oof code duplication :(
    repos = github.get(github_user["repos_url"])
    repos, langs = [repo["url"] for repo in repos], [repo["language"] for repo in repos]
    big_doc = make_doc_from_repos(repos)

    lang_features = form_language_feature_vector(langs)
    readme_features = doc2vec(big_doc)

    feature_vec = np.concatenate((readme_features, lang_features))

    user.embedding = feature_vec.tobytes()


    db_session.add(user)
    db_session.commit()

    user = User.query.filter_by(github_id=github_user['id']).first()
    print(user.id)
    make_pairs(user.id)
Example #2
0
    def POST(self, **params):

        # Try to grab it from the body
        user = cherrypy.request.json.get('username')
        # if there isn't one respond 400 Bad request
        if user is None:
            raise cherrypy.HTTPError(400, 'Username needed')

        u = User()
        u.username = user

        # checks if mongoengine raises an exception like:
        #   - user already exist
        #   - username to long
        try:
            u.save()
        except Exception as e:
            raise cherrypy.HTTPError(400, str(e))

        cherrypy.response.status = 201
        return {
            "status": 201,
            "data": {
                "id": str(u.id),
                "username": u.username,
                "greenhouses": u.greenhouses
            }
        }
Example #3
0
def create_user(db: Session, user: schemas.User):
    user = models.User()
    user.name = name
    user.age = age
    db.add(user)
    db.commit()
    db.refresh(user)
    return user
Example #4
0
def create_user(user: User):
    stackpath = "create_user"
    print('\x1b[0;33;44m' + "def----->" + '\x1b[0m', stackpath)

    user.password = bcrypt.hashpw(user.password.encode('UTF-8'),
                                  bcrypt.gensalt(14))
    db_user = user_db(user)
    user.id = db_user.createUser_returnId()

    user = get_user_by_username(username=user.username)

    print("user created")
    print('\x1b[0;33;44m' + "<-----def" + '\x1b[0m', stackpath)
    return user
Example #5
0
def create_user(request: schemas.User, db: Session = Depends(get_db)):
    user_detail = request.dict()
    password = user_detail.get('password')
    user_detail['password'] = get_hashed_pass(password)
    new_user = models.User(**user_detail)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return {"detail":"user created succesfully"}
Example #6
0
async def create_user(item: UserItem):
    session = create_session()
    try:
        user = User()
        user.email = item.email
        user.password = item.password
        session.add(user)
        session.commit()
        return fastapi.responses.Response(status_code=200)
    except sa.exc.IntegrityError as exc:
        raise fastapi.exceptions.HTTPException(status_code=409,
                                               detail={
                                                   'exception':
                                                   "UniqueError",
                                                   'column':
                                                   str(exc.orig).split(' ')[-1]
                                               })

    finally:
        session.close()
Example #7
0
def authorized(oauth_token):
    next_url = request.args.get('next') or url_for('index')
    if oauth_token is None:
        flash("Authorization failed.")
        return redirect(next_url)

    user = User.query.filter_by(github_access_token=oauth_token).first()
    if user is None:
        user = User(oauth_token)

    user.github_access_token = oauth_token

    g.user = user
    github_user = github.get('/user')
    user.github_id = github_user['id']
    user.github_login = github_user['login']
    user.name = github_user["name"]
    user.org = github_user["company"]
    user.blog = github_user["blog"]
    user.email = github_user["email"]

    #check to see if this user already 
    check_user = User.query.filter_by(github_id=user.github_id).first() #github id should also be unique :)
    if not check_user:
        g.user = user
        db_session.add(user)
        session['user_id'] = user.id
    else:
        #we don't actually add the new user object if a previous user with this ID exists
        check_user.github_access_token = oauth_token
        g.user = check_user
        session['user_id'] = check_user.id


    
    #db_session.add(user) this may only be necessary in certain situations
    
    db_session.commit()

    #dumb hack to get user ids to work.
    #TODO: make this better... sometime
    usr = User.query.filter_by(github_id=g.user.github_id).first()
    g.user = usr
    session['user_id'] = usr.id

    return redirect(next_url)
Example #8
0
async def create_user(User: UserCreate,
                      db: Session = Depends(get_db),
                      current_user: User = Depends(get_current_active_user)):
    try:
        user = UserModel(**User.dict())
        user.password = encryptPassword(user.password)
        db.add(user)
        db.commit()
        db.refresh(user)
    except SQLAlchemyError as e:
        raise Exception(e)
    return user
Example #9
0
def get_user_by_id(userid: int, isAdmin=Depends(is_logged_user_admin)):
    stackpath = "get_user_by_id"
    print('\x1b[0;30;44m' + "get------>" + '\x1b[0m', stackpath)

    db_user = user_db.get_user_by_id(userid)

    if not db_user:
        return {"error": "user not found"}

    user = User.to_User_model(db_user)

    print('\x1b[0;30;44m' + "<------get" + '\x1b[0m', stackpath)
    return user
Example #10
0
def register_user(user: User):
    stackpath = "register_user"
    print('\x1b[0;30;44m' + "post------>" + '\x1b[0m', stackpath)

    exist_user = get_user_by_username(user.username)
    if (exist_user):
        raise HTTPException(status_code=400, detail='Username already taken')

    new_user = create_user(user)

    usermodel = User.to_User_model(new_user)
    token = jwt.encode(usermodel.dict(), JWT_SECRET)

    print('\x1b[0;30;44m' + "<------post" + '\x1b[0m', stackpath)
    return {'access_token': token, 'user_type': usermodel.user_type}
Example #11
0
def login_generate_token(form_data: OAuth2PasswordRequestForm = Depends()):
    stackpath = "login_generate_token"
    print('\x1b[0;30;44m' + "post------>" + '\x1b[0m', stackpath)

    user = authenticate_user(form_data.username, form_data.password)

    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail='Invalid username or password')

    usermodel = User.to_User_model(user)
    token = jwt.encode(usermodel.dict(), JWT_SECRET)

    print('\x1b[0;30;44m' + "<------post" + '\x1b[0m', stackpath)
    return {'access_token': token, 'user_type': usermodel.user_type}
Example #12
0
def get_current_user(token: str = Depends(oauth2scheme)):
    stackpath = "get_current_user"
    print('\x1b[0;33;44m' + "def----->" + '\x1b[0m', stackpath)

    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])

        user = user_db.get_user_by_id(payload["id"])
        user = User.to_User_model(user)

    except:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail='Invalid username or password')

    print('\x1b[0;33;44m' + "<-----def" + '\x1b[0m', stackpath)
    return user
Example #13
0
def create_user_item(db: Session, item: schemas.User):
    db_item = models.User(**item.dict())
    db.merge(db_item)
    db.commit()
    return db_item
Example #14
0
 async def get_user_by_id(self, user_id: str) -> User:
     user = await self._users_collection.find_one(
         {"_id": ObjectId(user_id)})
     if user is None:
         raise KeyError("Invalid user")
     return User(**user, user_id=str(user["_id"]))
Example #15
0
async def get_image():
    user = User(**{'id': 23, 'name': 'Jordan'})
    image = UploadImage(**{'title': 'Test', 'description': 'Description'})
    # return GetImage(user=user, image=image)
    return JSONResponse(status_code=404, content={"message": "Item not found"})
Example #16
0
 async def get_user_by_username(self, username: str) -> User:
     user = await self._users_collection.find_one({"username": username})
     if user is None:
         raise KeyError("Invalid user")
     return User(**user, user_id=str(user["_id"]))
Example #17
0
def create_user(user_in: UserIn) -> User:
    user = User(id=len(USER_ID_TO_USER) + 1, **user_in.dict())
    USER_ID_TO_USER[user.id] = user
    USER_TOKEN_TO_USER[user.token] = user
    return user
Example #18
0
async def get_me(current_user: User = Depends(get_current_user)):
    return UserBase(**current_user.dict())