Beispiel #1
0
def register():
    if request.method == "GET":
        user_id = auth.loggedInAs(request.cookies.get(key="session_token"))
        if user_id == None:
            return render_template("register.html", logged_in=0)
        else:
            return render_template(
                "redirect.html",
                dest="/",
                message="Already logged in! Redirecting soon...")
    elif request.method == "POST":
        if len(request.form["username"]) < 1:
            return render_template("redirect.html",
                                   dest="/register",
                                   message="Username is too short!")
        if len(request.form["username"]) > 32:
            return render_template("redirect.html",
                                   dest="/register",
                                   message="Username is too long!")
        if len(request.form["password"]) < 1:
            return render_template("redirect.html",
                                   dest="/register",
                                   message="Password is too short!")
        if len(request.form["password"]) > 128:
            return render_template("redirect.html",
                                   dest="/register",
                                   message="Password is too long!")
        if User.query.filter_by(
                username=request.form["username"]).count() != 0:
            return render_template("redirect.html",
                                   dest="/register",
                                   message="User with the username: "******"username"] +
                                   " already exists!")
        salt = secrets.token_bytes(64)
        hashed = hashlib.scrypt(password=request.form["password"].encode(),
                                salt=salt,
                                n=16384,
                                r=8,
                                p=1)
        user = User(username=request.form["username"],
                    admin=False,
                    used_quota=0,
                    max_quota=1e8,
                    password_salt=salt,
                    password_hash=hashed)
        if user.username == "Admin":
            user.admin = True
        db.session.add(user)
        db.session.commit()
        resp = make_response(
            render_template(
                "redirect.html",
                message="Registration successful! Redirecting soon...",
                dest="/login"))
        return resp
 def register_user(self, username, password, email, access_key, secret_key):
     if User.query.filter(User.username == username).first() == None:
         user = User(username=username,
                     email=email,
                     access_key=access_key,
                     secret_key=secret_key)
         user.hash_password(password)
         self.db_session.add(user)
         self.db_session.commit()
         return True
     else:
         return False
def signup():
    if request.method == 'GET':
        if 'new_user_username' not in session:
            # Try to log-in from home
            return redirect(url_for('index'))
        else:
            tmp = session[
                'new_user_username']  # Passed username from home page
            session.pop('new_user_username', None)
            return render_template('common_pages/signup.html', username=tmp)
    else:
        username = request.form['name']
        gender = request.form['gender']
        education = request.form['education']
        occupation = request.form['occupation']
        affiliation = request.form['affiliation']
        xp = request.form['years_xp']
        user_item = User(username=username,
                         gender=gender,
                         education=education,
                         occupation=occupation,
                         affiliation=affiliation,
                         years_xp=xp)
        db.session.add(user_item)
        db.session.commit()
        sign_in(username)
        return redirect(url_for('index'))
def checkAllRDSInstances(db_session):
    currentCaptures = getAllIncompleteCaptures(db_session)

    #The current time
    now = datetime.datetime.now() + datetime.timedelta(hours=8)

    #Go through all the captures we received
    for capture in currentCaptures:
        if capture['endTime'] == None:
            pass
        elif capture['endTime'] + datetime.timedelta(hours=1) <= now:
            user = getUserFromId(capture["userId"], db_session)[0]
            userObject = User(id=user[0],
                              username=user[1],
                              password=user[2],
                              email=user[3],
                              access_key=user[4],
                              secret_key=user[5],
                              notificationLife=user[6])
            thread = threading.Thread(target=completeCapture,
                                      args=(
                                          capture,
                                          userObject,
                                          db_session,
                                      ))
            thread.daemon = True
            thread.start()
            # completeCapture(capture, User(user), db_session)
        elif capture['startTime'] + datetime.timedelta(
                hours=1) <= now and capture['endTime'] + datetime.timedelta(
                    hours=1) > now:
            updateCapture(capture['captureId'], 1, db_session)
Beispiel #5
0
async def update_user(
    request: Request,
    user_id: str,
    data: UserRequestAPI,
    user: Optional[UserAPI] = Depends(get_user)) -> UserAPI:
    """Update user data"""
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Token"},
        )
    projects: List[Project] = [
        Project.get(id=project['id']) for project in data.projects
    ]
    context: Dict[Any] = {
        "username": data.username,
        "is_active": data.is_active,
        "projects": projects
    }
    if data.check_password:
        if not pwd_verify(data.check_password, user.password if user else ""):
            request.session[
                "fail_password_message"]: str = f"Invalid password!"
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Could not validate credentials",
                headers={"WWW-Authenticate": "Token"},
            )
    if data.new_password:
        context["password"] = pwd_hash(data.new_password)

    return UserAPI.parse_obj(User.update(context, id=user_id).to_dict())
Beispiel #6
0
async def get_users(user: Optional[UserAPI] = Depends(
    get_user)) -> List[UserAPI]:
    """Get all users"""
    if user is None or user.role != UserRole.super:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Token"},
        )

    return [UserAPI.parse_obj(user.to_dict()) for user in User.get_all()]
Beispiel #7
0
async def delete_user(
    user_id: int, user: Optional[UserAPI] = Depends(get_user)) -> UserAPI:
    """Delete chosen user"""
    if user is None or user.role != UserRole.super:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Token"},
        )

    return UserAPI.parse_obj(User.delete(id=user_id).to_dict())
  def create(self, order):
    user = User.get_or_none(User.id == order.get("userId"))
    if user == None:
      return Response(data="userId not found", status=404)

    product = Product.get_or_none(Product.id == order.get("productId"))
    if product == None:
      return Response(data="productId not found", status=404)

    Order.create(product=product, user=user)
    return Response()
    def test_user_created(self):
        username = "******"
        password = "******"
        access_key = "access_key"
        secret_key = "secret_key"

        user = User(username=username, password=password,
                access_key=access_key, secret_key=secret_key)
        assert username == user.username
        assert password == user.password
        assert access_key == user.access_key
        assert secret_key == user.secret_key
def get_user(token: Optional[str] = Depends(get_token)) -> Optional[UserAPI]:
    if token:
        # get user data
        token_data: Optional[TokenData] = token_validate(token)

        if token_data:
            user: UserAPI = UserAPI.parse_obj(
                User.get(id=token_data.sub).to_dict())
            if user.is_active:
                return user

    return None
Beispiel #11
0
async def create_user(
    request: Request,
    data: UserAPI,
    user: Optional[UserAPI] = Depends(get_user)) -> Any:
    if user is None or user.role != UserRole.super:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Token"},
        )

    #  check if such username exists
    if User.get(username=data.username):
        request.session["username_exists"] = f"Such Username already exists!"
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)

    data.password = pwd_hash(data.password)
    data.projects = [
        Project.get(id=project_id) for project_id in data.projects
    ]

    return UserAPI.parse_obj(User.create(data.dict()).to_dict())
Beispiel #12
0
async def login(request: Request, form: OAuth2PasswordRequestForm = Depends()):
    """Create login page"""

    username: str = form.username
    password: str = form.password

    if User.get(username=username):
        user: Optional[UserAPI] = UserAPI.parse_obj(
            User.get(username=username).to_dict())

    else:
        request.session[
            "fail_login_message"]: str = f"Username '{username}' doesn't exist!"
        return RedirectResponse(url="/login",
                                status_code=status.HTTP_303_SEE_OTHER)

    # validate user
    if not pwd_verify(password, user.password if user else ""):
        # raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid user or password")
        request.session[
            "fail_login_message"]: str = f"Invalid Username or Password!"
        return RedirectResponse(url="/login",
                                status_code=status.HTTP_303_SEE_OTHER)

    # build data
    data: TokenData = TokenData(sub=user.id,
                                exp=time_utc_now() +
                                timedelta(seconds=JWT_TOKEN_EXPIRE))

    # generate token
    token: JWTToken = token_create(JWT_KEY, JWT_ALGORITHM, data)

    # save token value to the session
    request.session["token"] = token.access_token

    return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
Beispiel #13
0
    def verify_token(*args, **kwargs):
        token = request.headers.get('Auth-Token')
        if not token:
            return {"message": "User is not authenticated."}
        # First query the database to see if the token exists to someone
        # If it doesn't it means it is invalid
        user = User.query.filter_by(token=token).first()
        if user is None:
            return {"message": "User is not authenticated."}

        if User.verify_auth_token(token) is not "Valid":
            return {
                "message":
                "User is not authenticated: {} token".format(token_state)
            }
        return f(*args, **kwargs)
Beispiel #14
0
def create_user(data):
    _username = data.get('username')
    _email = data.get('email')
    _password = data.get('password')

    # Make sure username doesn't exist already
    user = User.query.filter(User.username == _username).first()
    if user is not None:
        abort(
            400, "Error creating user. Username '{}' already exists.".format(
                _username))

    newUser = User(_username, _email, _password)
    log.info("newUser: {}".format(newUser))
    db.session.add(newUser)
    db.session.commit()
    return {'token': newUser.token, 'user': newUser}
Beispiel #15
0
 def wrapper(self, *args, **kwargs):
     token = request.headers.get('X-API-KEY', '')
     if not token:
         return "", 401, {
             "WWW-Authenticate": "Basic realm='Authentication required'"
         }
     try:
         uuid = jwt.decode(token, app.config['SECRET_KEY'])['user_id']
     except (KeyError, jwt.ExpiredSignatureError):
         return "", 401, {
             "WWW-Authenticate": "Basic realm='Authentication required'"
         }
     user = User.find_user_by_uuid(uuid)
     if not user:
         return "", 401, {
             "WWW-Authenticate": "Basic realm='Authentication required'"
         }
     return func(self, *args, **kwargs)
Beispiel #16
0
 def get(self):
     auth = request.authorization
     if not auth:
         return "", 401, {
             "WWW-Authenticate": "Basic realm='Authentication required'"
         }
     user = User.find_user_by_username(auth.get('username', ''))
     if not user or not check_password_hash(user.password,
                                            auth.get('password', '')):
         return "", 401, {
             "WWW-Authenticate": "Basic realm='Authentication required'"
         }
     token = jwt.encode(
         {
             "user_id": user.uuid,
             "exp": datetime.datetime.now() + datetime.timedelta(hours=1)
         }, app.config['SECRET_KEY'])
     return jsonify({"token": token.decode('utf-8')})
Beispiel #17
0
 def post():
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception:
         raise InternalServerError
Beispiel #18
0
 def wrapper(self, *args, **kwargs):
     token = request.headers.get('X-API-KEY', '')
     if not token:
         return '', 401, {
             'WWW-Authenticate': 'Basic realm="Authenticate required"'
         }
     try:
         uuid = jwt.decode(token,
                           app.config['SECRET_KEY'],
                           algorithms=["HS256"])['user_id']
     except (KeyError, jwt.ExpiredSignatureError):
         return '', 401, {
             'WWW-Authenticate': 'Basic realm="Authenticate required"'
         }
     user = User.find_user_by_uuid(uuid)
     if not user:
         return '', 401, {
             'WWW-Authenticate': 'Basic realm="Authenticate required"'
         }
     return func(self, *args, **kwargs)
Beispiel #19
0
    def get(self):
        auth = request.authorization
        if not auth:
            return '', 401, {
                'WWW-Authenticate': "Basic realm='Authentication required'"
            }

        user = User.find_by_name(auth.get('username', ''))
        if not user or not check_password_hash(user.password,
                                               auth.get('password', '')):
            return '', 401, {
                'WWW-Authenticate': "Basic realm='Authentication required'"
            }

        token = jwt.encode(
            {
                'user_id': user.uuid,
                'exp': datetime.datetime.now() + datetime.timedelta(hours=1)
            }, app.config['SECRET_KEY'])

        return jsonify({'token': token})
Beispiel #20
0
 def set_test_user_and_create_token(self):
     user = User(username="******",
                 password="******",
                 email="*****@*****.**")
     bike = Bike(
         model="test_model",
         riding_style="test_style",
         description="test_description",
         release_date=datetime.datetime.strptime("2021-11-08", "%Y-%m-%d"),
         price=10000.0,
         rating=5.0,
     )
     db.session.add(user)
     db.session.add(bike)
     user_id = db.session.query(User).filter_by(
         username='******').first()
     token = jwt.encode(
         {
             "user_id": user_id.uuid,
             "exp": datetime.datetime.now() + datetime.timedelta(hours=2)
         }, app.config["SECRET_KEY"])
     yield token, bike.uuid
     db.session.rollback()
Beispiel #21
0
 def _transfer_fields(self, obj: User,
                      obj_to_register: UserToRegister) -> User:
     if isinstance(obj_to_register, OperatorToRegister):
         obj.last_name = obj_to_register.last_name
         obj.first_name = obj_to_register.first_name
         obj.patronymic = obj_to_register.patronymic
     elif isinstance(obj_to_register, SecurityToRegister):
         obj.last_name = obj_to_register.last_name
         obj.first_name = obj_to_register.first_name
         obj.patronymic = obj_to_register.patronymic
         obj.position = obj_to_register.position
     elif isinstance(obj_to_register, ContractorRepresentativeToRegister):
         obj.last_name = obj_to_register.last_name
         obj.first_name = obj_to_register.first_name
         obj.patronymic = obj_to_register.patronymic
         obj.email = obj_to_register.email
         obj.telephone_number = obj_to_register.telephone_number
         obj.contractor_id = obj_to_register.contractor_id
     return obj
Beispiel #22
0
 def create(self, request):
     user = User.create(name=request.get("name"), age=request.get("age"))
     return Response(data=user)
Beispiel #23
0
 def delete(self, id):
     deleted = User.delete().where(User.id == id).execute()
     return Response() if deleted > 0 else Response(data="id not found",
                                                    status=404)
Beispiel #24
0
 def update(self, id, user):
     query = User.update(user).where(User.id == id)
     updated = query.execute()
     return Response() if updated > 0 else Response(data="id not found",
                                                    status=404)
Beispiel #25
0
 def get(self):
     users = list(map(model_to_dict, User.select()))
     return Response(data=users)