Example #1
0
def login():
    '''
    User Login
    parameters:
        user, password
    response:
        200:
            jwt: token
            roles: list of roles user is authorized for
        400:
            missing credentials
        401:
            not authorized
    '''
    if not request.is_json:
        raise InvalidUsage("Missing JSON in request")

    params = request.get_json()
    user = params.get('user', None)
    password = params.get('password', None)

    if not user:
        raise InvalidUsage("Missing username parameter")
    if not password:
        raise InvalidUsage("Missing password paramter")

    db_user = User.query.filter_by(username=user).first()
    if not db_user or db_user.password != password:
        raise UnauthorizedUse()
    roles = [role.name for role in db_user.roles]
    return jsonify(jwt=create_jwt(identity=user), roles=roles), 200
Example #2
0
    def create_new_user(username, email, password):
        """
        Add a new user
        :param username:
        :param email:
        :param password:
        :return: Json Object {username, token}| {error}
        """

        password = password.strip()

        if not re.match("^[a-zA-Z0-9_]*$", username):
            raise InvalidUsage(
                'the only special char available for username is _')

        if len(password) < 8:
            raise InvalidUsage('password must be greater than 7 chars')

        if not User.validate_new_email(email):
            raise InvalidUsage('email already exists or not valid')

        if User.get_by_id(username) is not None:
            raise InvalidUsage('username already exists')

        key = ndb.Key(User, username)
        new_user = User(key=key,
                        username=username,
                        email=email,
                        password=pbkdf2.crypt(
                            password, iterations=config.CRYPT_LOG_ROUNDS))
        new_user.put()
        token = new_user.encode_auth_token()
        return {'username': username, 'token': token}
Example #3
0
def set_count():
    '''
    Manually sets the count on a given day or
    delete count if personcount is empty

    Used for Admins to alter mistakes from callers
    '''
    params = request.get_json()

    personcount = params.get('numberOfPeople')
    shelterID = params.get('shelterID')
    day = params.get('day')

    if not all((shelterID, day)):
        raise InvalidUsage("Missing data", status_code=400)
    try:
        parsed_day = pendulum.parse(day, strict=False)
    except ValueError:
        raise InvalidUsage("Can't parse date", status_code=400)

    if not personcount:
        count = Count().query.filter_by(shelter_id=shelterID,
                                        day=parsed_day.isoformat()).delete()
        log = Log(shelter_id=shelterID,
                  from_number='web',
                  contact_type="Admin",
                  input_text="-",
                  action="delete_count",
                  parsed_text="")
        ret = {"personcount": None, "bedcount": None, "shelterID": shelterID}
    else:
        shelter = Shelter.query.get(int(shelterID))
        count = Count(shelter_id=shelterID,
                      personcount=personcount,
                      bedcount=shelter.capacity - int(personcount),
                      day=parsed_day.isoformat(),
                      time=func.now())
        log = Log(shelter_id=shelterID,
                  from_number="web",
                  contact_type="Admin",
                  input_text=personcount,
                  action="save_count",
                  parsed_text=personcount)
        ret = {
            "personcount": count.personcount,
            "bedcount": count.bedcount,
            "shelterID": shelterID
        }
        db.session.merge(count)

    try:
        db.session.add(log)
        db.session.commit()
    except IntegrityError as e:  # calls has a foreign key constraint linking it to shelters
        logging.error(e.orig.args)
        db.session().rollback()
        raise ServerError('Error Saving Data')

    return jsonify({"success": True, "counts": ret})
Example #4
0
def verify_reset_password_token(token):
  if token is None:
    raise InvalidUsage.unknown_error()
  user = get_user_from_token(token)
  if user is not None:
    auth = AuthModel.create(identity=user)
    return TokenizedUser(user, auth)
  raise InvalidUsage.user_not_found()
Example #5
0
def delete_session(id):
    session = Session.first(id=id)
    if session is None:
        raise InvalidUsage.session_not_found()
    try:
        session.delete(id)
    except IntegrityError:
        db.session.rollback()
        raise InvalidUsage.unknown_error()
    return jsonify(message='Session has been deleted')
Example #6
0
    def load_user_by_username(username):
        """
        Login user
        :param username:
        :return: User
        """

        if not username:
            raise InvalidUsage('missing required parameters')

        user = ndb.Key(User, username).get()
        if not user:
            raise InvalidUsage('user does not exist!')
        return user
Example #7
0
def unfollow_user(username):
    user = User.query.filter_by(username=username).first()
    if not user:
        raise InvalidUsage.user_not_found()
    current_user.profile.unfollow(user.profile)
    current_user.profile.save()
    return user.profile
Example #8
0
def login_user(email, password, **kwargs):
    user = User.query.filter_by(email=email).first()
    if user is not None and user.check_password(password):
        user.token = create_access_token(identity=user, fresh=True)
        return user
    else:
        raise InvalidUsage.user_not_found()
    def put(self, user_id: int = None):
        """Updates user's info"""
        if user_id != current_user.id:
            raise InvalidUsage.user_not_authorized()
        args: Dict = user_info_parser.parse_args()

        newpwd = args.pop("password")
        pwdcheck = args.pop("password_check")

        if newpwd:
            if newpwd != pwdcheck:
                raise UserExceptions.password_check_invalid()
            current_user.password = newpwd

        photo: werkzeug.datastructures.FileStorage = args.pop("photo")

        if photo:
            photostorage = FileHandler(data=photo.stream,
                                       title=photo.filename,
                                       url=current_user._photo)
            photostorage.save()
            current_user.photo = photostorage

        for key, val in args.items():
            if hasattr(current_user, key) and val is not None:
                setattr(current_user, key, val)

        db.session.commit()

        return current_user
Example #10
0
 def decode_auth_token(auth_token):
     """
     Validates the auth token
     :param auth_token:
     :return: Json Object {username} | {error}
     """
     try:
         payload = jwt.decode(auth_token, config.SECRET_KEY)
         blacklisted = Blacklist.query(Blacklist.token == auth_token).get()
         if blacklisted:
             raise InvalidUsage('This token is not valid anymore')
         return {'username': payload['sub']}
     except jwt.ExpiredSignatureError:
         raise InvalidUsage('Signature expired. Please log in again')
     except jwt.InvalidTokenError:
         raise InvalidUsage('Invalid token. Please log in again')
Example #11
0
def make_comment_on_article(slug, body, **kwargs):
    article = Article.query.filter_by(slug=slug).first()
    if not article:
        raise InvalidUsage.article_not_found()
    comment = Comment(article, current_user.profile, body, **kwargs)
    comment.save()
    return comment
Example #12
0
def update_shelter():
    '''
    Updates or creates an new shelter
    Response:
        200:
            JSON object with the shelter data
    '''
    form = newShelterForm()
    shelter = {}
    shelter['id'] = form.id.data
    shelter['name'] = form.name.data
    shelter['description'] = form.description.data
    shelter['phone'] = form.phone.data or None
    shelter['login_id'] = form.login_id.data
    shelter['capacity'] = form.capacity.data
    shelter['active'] = form.active.data
    shelter['visible'] = form.visible.data
    shelter['public'] = form.public.data

    shelter = Shelter(**shelter)

    try:
        shelter = db.session.merge(shelter)
        db.session.commit()
    except IntegrityError as e:
        logging.warning(e.orig.args)
        db.session().rollback()
        raise InvalidUsage("Values must be unique", status_code=400)
    return jsonify(shelter.toDict())
Example #13
0
 def newfn():
     errors = {}
     for a in _args:
         if a not in request.args:
             errors[a] = 'This field is required'
     if errors:
         raise InvalidUsage(payload={'errors': errors})
     return func()
Example #14
0
    def user_lookup_callback(_jwt_header, jwt_data):

        from app.apis.v1.users.models import Session, User

        session = Session.get(token=jwt_data["jti"], user_id=jwt_data["user"])
        g.session = session
        if not session:
            raise InvalidUsage.invalid_session()
        user_id = jwt_data["user"]
        user = User.get(id=user_id)
        if not user or not user.active:
            raise InvalidUsage.user_not_authorized()

        identity = generate_principal_identity(user)
        identity_changed.send(app, identity=identity)

        return user
Example #15
0
 def load_timeline(entity_key):
     """
     load a timeline by its key
     :param entity_key:
     :return: timeline entity | {error}
     """
     try:
         timeline = ndb.Key(urlsafe=entity_key).get()
     except TypeError:
         return {
             'error': 'problem with this timeline. sure this link is valid?'
         }
     if not timeline:
         raise InvalidUsage('timeline does not exist')
     if not timeline.active:
         raise InvalidUsage('timeline does not exist anymore')
     return timeline
Example #16
0
def update_article(slug, **kwargs):
    article = Article.query.filter_by(
        slug=slug, author_id=current_user.profile.id).first()
    if not article:
        raise InvalidUsage.article_not_found()
    article.update(updatedAt=dt.datetime.utcnow(), **kwargs)
    article.save()
    return article
    def delete(self, user_id: int, slug: str):
        if current_user.id != user_id and not g.identity.provides(
                RoleNeed("admin")):
            raise InvalidUsage.user_not_authorized()
        user_session = Session.get(slug=slug, user_id=user_id)
        user_session.delete(True)

        return
Example #18
0
def unfavorite_an_article(slug):
    profile = current_user.profile
    article = Article.query.filter_by(slug=slug).first()
    if not article:
        raise InvalidUsage.article_not_found()
    article.unfavourite(profile)
    article.save()
    return article
Example #19
0
    def cancel(self):

        if not current_user:
            raise InvalidUsage.user_not_found()
        self.cancelled = True
        self.cancelled_by_id = current_user.id
        self.date_cancelled = datetime.now(tz=current_app.config["TZ"])
        db.session.commit()
Example #20
0
def delete_comment_on_article(slug, cid):
    article = Article.query.filter_by(slug=slug).first()
    if not article:
        raise InvalidUsage.article_not_found()

    comment = article.comments.filter_by(id=cid,
                                         author=current_user.profile).first()
    comment.delete()
    return '', 200
Example #21
0
def register_user(username, password, email, **kwargs):
    try:
        userprofile = UserProfile(
            User(username, email, password=password, **kwargs).save()).save()
        userprofile.user.token = create_access_token(identity=userprofile.user)
    except IntegrityError:
        db.session.rollback()
        raise InvalidUsage.user_already_registered()
    return userprofile.user
Example #22
0
def save_session(words, chars, accuracy):
    user = current_user
    try:
        session = Session.create(words=words,
                                 chars=chars,
                                 accuracy=accuracy,
                                 user_id=user.id)
    except IntegrityError:
        db.session.rollback()
        raise InvalidUsage.unknown_error()
    return session
Example #23
0
 def load_user_by_token(token):
     """
     load an user from its token
     :param token:
     :return: User object | {error}
     """
     token = User.decode_auth_token(token)
     user = User.get_by_id(token['username'])
     if user is not None:
         return user
     raise InvalidUsage('this user does not exist anymore')
Example #24
0
    def post(self, role_id: int):
        role = Role.get(id=role_id)
        if not role:
            raise abort(404)
        args = self.parser.parse_args()
        entity = Entity.get(id=args.pop("entity_id"))
        if not entity:
            raise InvalidUsage.custom_error("invalid entity", 401)
        role.add_entity(entity, **args)

        return role
Example #25
0
def reset_password(password):
  user = current_user
  try:
    user.password = password
    db.session.commit()
  except IntegrityError:
    db.session.rollback()
    raise InvalidUsage.unknown_error()
  return jsonify({
    'message': f'Password has been reset for {user.username}'
  })
    def post(self):
        args = entity_parser.parse_args()

        if Entity.query.filter_by(name=args.get("name")).count() > 0:
            raise InvalidUsage.custom_error(
                "There's an entity with the same name", 401)

        entity = Entity(**args)
        entity.save()

        return entity
Example #27
0
    def login_user(username, password):
        """
        Login user
        :param username:
        :param password:
        :return: Json Object {username, token}
        """

        if not username or not password:
            raise InvalidUsage('missing required parameters')

        user = ndb.Key(User, username).get()
        if not user:
            raise InvalidUsage('user does not exist, sign in now!')
        if user.password != pbkdf2.crypt(
                password, user.password, iterations=config.CRYPT_LOG_ROUNDS):
            raise InvalidUsage('wrong password')

        token = user.encode_auth_token()
        return {'username': user.username, 'token': token}
Example #28
0
def register(email, username, password, **kwargs):
  try:
    user = User.create(
      email=email,
      username=username,
      password=password,
      **kwargs
    )
  except IntegrityError:
    db.session.rollback()
    raise InvalidUsage.user_already_registered()
  auth = AuthModel.create(identity=user)
  return TokenizedUser(user, auth)
Example #29
0
 def put(self, role_id: int):
     role = Role.get(id=role_id)
     if not role:
         raise abort(404)
     args = self.parser.parse_args()
     entity_id = args.pop("entity_id")
     entity: List[Entity] = [
         ent for ent in role.entity_permissions
         if ent.entity_id == entity_id
     ]
     if len(entity) != 1:
         raise InvalidUsage.custom_error("invalid entity", 401)
     entity[0].update(ignore_none=True, **args)
     return role
Example #30
0
def get_user_sessions(id):
  user = User.first(id=id)
  if user is None:
    raise InvalidUsage.user_not_found()
  page = request.args.get('page', 1, type=int)
  pagination = user.sessions.paginate(
    page, per_page=25, error_out=False
  )
  sessions = pagination.items
  return PaginationModel(
    page=page,
    data=sessions,
    total_pages=max(pagination.total // 25, 1),
    total_results=pagination.total
  )