Beispiel #1
0
def update_user():
    """update specific or collection of field in a row of users table """
    user = User.query.filter(User.user_id == current_user.user_id).one()
    if user is None:
        raise MyException('need user login', status_code=401)

    if request.json == {}:
        raise MyException('update field cannot be empty', status_code=400)

    username = request.json.get('username', None)
    if username is not None:
        user.username = username

    firstname = request.json.get('firstname', None)
    if firstname is not None:
        user.firstname = firstname

    lastname = request.json.get('lastname', None)
    if lastname is not None:
        user.lastname = lastname

    db.session.commit()
    user_data = dict()
    user_data['username'] = user.username
    user_data['firstname'] = user.firstname
    user_data['lastname'] = user.lastname
    return user_data
def change_password(email, old_password, new_password):
    user = User.find_user_by_email(email)
    if user is None:
        raise MyException('could not find email', status_code=404)
    if password_verify(user.password, old_password):
        if (PasswordValidation.is_check_none_space_length(new_password) and PasswordValidation.is_check_char(
                new_password) and PasswordValidation.is_check_special_char(new_password)):
            user.password = password_hashing(new_password)
            db.session.commit()
            return {'changed_password': new_password}
    raise MyException('please enter a valid password', status_code=400)
Beispiel #3
0
def update_email(token):
    """ update email verifying it and set status to true"""
    try:
        token_data = decode_token(token)
        email = token_data['email']
        username = token_data['username']
    except Exception:
        raise MyException('please click the link to verify your email', status_code=404)
    user = User.query.filter(User.username == username).first()
    if user is None:
        raise MyException('invalid user', status_code=404)
    user.email = email
    db.session.commit()
    user.email_status = True
    return {"updated_email": email}
Beispiel #4
0
def list_user(id):
    """return user by id"""

    user = User.find_user_by_id(id)
    if user is None:
        raise MyException('could not find this id', status_code=404)
    return user.write_to_dict()
 def post(cls):  # user registration
     try:
         data = request.get_json()
         if not data:
             return {
                 'message': 'required to enter all the fields',
                 'error': 'bad request, 400'
             }, 400
         return add_user(data['firstname'], data['lastname'],
                         data['username'], data['email'], data['password'])
     except Exception as err:
         if "username" in err.args[0]:
             raise MyException('this username is already taken try next',
                               status_code=406)
         else:
             raise MyException('email must be unique', status_code=406)
Beispiel #6
0
def _func_op_img(save_img_dir, x, y, z, map_kind, split_n):
    _img = None
    try:
        # urlから取得した画像をメモリの保持
        _req_url = '%s/%s/%d/%d/%d.png' % (img_url, map_kinds[map_kind], z, x,
                                           y)
        _res = requests.get(_req_url, stream=True)
        _img = Image.open(BytesIO(_res.content))

        # 光学画像のファイルパス
        _save_op_img_path = '%s/completed.png' % save_img_dir

        # 最終完成イメージ保存
        _img.save(_save_op_img_path, quality=95)

        _ver_s, _hori_s = _img.size
        # 切り取り間隔を取得
        _ver_interval, _hori_interval = _calc_interval(_ver_s, _hori_s,
                                                       split_n)
        # 光学画像を切り取り、保存する処理
        _split_and_save_img(_img, _ver_interval, _hori_interval, save_img_dir,
                            split_n)
    except:
        raise MyException("couldn't split or save optical image", 500)
    finally:
        if _img is not None:
            _img.close()
Beispiel #7
0
def _calc_interval(ver_s, hori_s, split_n):
    try:
        ver_interval = ver_s / split_n
        hori_interval = hori_s / split_n
        return ver_interval, hori_interval
    except ZeroDivisionError as e:
        raise MyException('zero division error', 400)
Beispiel #8
0
def generate_update_email_token(email):
    """return email update token and send it to the user email address"""

    user = User.query.filter(User.username == get_jwt()['sub']).first()
    if not user:
        raise MyException('invalid user', status_code=404)
    email_verify_token = create_access_token(identity=user.user_id,
                                             fresh=True,
                                             expires_delta=timedelta(hours=1),
                                             additional_claims={
                                                 'email': email,
                                                 'username': user.username
                                             })
    try:
        msg = Message(subject="email verification",
                      sender=os.environ.get('MAIL_USERNAME'),
                      recipients=[email])
        msg.body = 'click the link below to verify email'
        msg.html = "<href>" f"{email_verify_token}" "</href>"
        mail.send(msg)
    except Exception:
        print(
            'message:- this are test email, you can use real email in a sender and recipients'
        )
    finally:
        return email_verify_token
Beispiel #9
0
 def is_user_login(*args, **kwargs):
     verify_jwt_in_request()
     username = get_jwt()
     user = User.query.filter(User.username == username).first()
     if user is None:
         raise MyException('login required', status_code=401)
     return func(*args, **kwargs)
Beispiel #10
0
 def is_check_admin(*args, **kwargs):
     try:
         verify_jwt_in_request()
         role = get_jwt()
         if role['admin']:
             return func(*args, **kwargs)
     except Exception:
         raise MyException('you are not authorised for this operation', status_code=401)
Beispiel #11
0
def user_login(username, password):
    """authenticate user and assign access and refresh tokens to that user """

    user = User.find_user_by_username(username)
    if not user:
        raise MyException('could not find this username', status_code=404)
    if not password_verify(user.password, password):
        raise MyException('invalid password', status_code=400)
    if user.email_status is False:
        raise MyException('please verify your email', status_code=401)
    access_token, refresh_token = generate_token(user.username, user.role)
    return jsonify(
        username=user.username,
        access_token=access_token,
        refresh_token=refresh_token,
        role=user.role
    )
Beispiel #12
0
def get_request():
    try:
        req_args = request.args
        x, y, z, map_kind, split_n = int(req_args.get('x')), int(
            req_args.get('y')), int(
                req_args.get('z')), req_args.get('kind'), int(
                    req_args.get('split_n'))
        if x <= 0 or y <= 0 or z <= 0 or split_n <= 0:
            raise MyException(
                'invalid parameter. x, y, z, split_n variables must be greater than 0',
                400, req_args)
        return x, y, z, map_kind, split_n
    except (ValueError, TypeError) as e:
        raise MyException('invalid parameter. please confirm query string',
                          400, req_args)
    except e:
        raise MyException('internal server error', 500, req_args)
Beispiel #13
0
def update_role(username, role):
    """update user's role"""

    user = User.find_user_by_username(username)
    if user is None:
        raise MyException('could not find this username', status_code=404)
    user.role = role
    db.session.commit()
    return user.write_to_dict()
Beispiel #14
0
def delete_user(id):
    """ delete row in a user table"""

    user = User.find_user_by_id(id)
    if user is None:
        raise MyException('could not find this id', status_code=404)
    db.session.delete(user)
    db.session.commit()
    return {'deleted': user.user_id}
Beispiel #15
0
    def __init__(self, fpath):
        #        print('I\'m constructor func.')
        # equivalently, assert statement
        #        assert os.path.isfile(fpath), 'Neither a file input Nor with a Absolute/Relative path.'

        if not os.path.isfile(fpath):
            raise expt.MyException(
                "Neither a file input Nor with a Absolute/Relative path.")
        else:
            self.fpath = fpath
            #            self.outList = []
            self.outDF = pd.DataFrame()
Beispiel #16
0
def _func_sar_img(save_img_dir, x, y, z, map_kind, split_n):
    # 画像保存ディレクトリ作成
    _save_sar_png_img_dir = save_img_dir + '/sar'
    if not _make_img_path(_save_sar_png_img_dir):
        raise MyException("img directory couldn't be made", 500)

    _save_sar_png_img_path = _save_sar_png_img_dir + '/completed.png'
    if _has_sar_img(_save_sar_png_img_path):
        return

    # ハードコードされているmapからvalueを取得するためのkey
    key = '%s-%d-%d-%d' % (map_kinds[map_kind], z, x, y)

    # SAR画像のtifのapi path
    _sar_img_api_path = _get_sar_tif_img_path(key)

    try:
        # SARのフル画像を規定のサイズにcropし、pngに変換してsaveする
        _crop_and_save_convert_sar_png_img(_sar_img_api_path,
                                           _save_sar_png_img_path, key)
    except:
        raise MyException("couldn't save sar png img", 500)

    # SARのpng画像を分割して保存
    _img = None
    try:
        _img = Image.open(_save_sar_png_img_path)
        _ver_s, _hori_s = _img.size
        # 切り取り間隔を取得
        _ver_interval, _hori_interval = _calc_interval(_ver_s, _hori_s,
                                                       split_n)

        # SAR画像を切り取り、保存する処理
        _split_and_save_img(_img, _ver_interval, _hori_interval,
                            _save_sar_png_img_dir, split_n)
    except:
        raise MyException("couln't split and save sar img", 500)
    finally:
        if _img is not None:
            _img.close()
Beispiel #17
0
def index():
    # query stringのパラメータ取得
    _x, _y, _z, _map_kind, _split_n = get_request()

    # 画像を保存するディレクトリ
    _save_img_dir = 'dst/%s/%d-%d-%d-%d' % (map_kinds[_map_kind], _z, _x, _y,
                                            _split_n)
    if not _make_img_path(_save_img_dir):
        raise MyException("img directory couldn't be made", 500)

    # 光学画像を保存、分割する
    _func_op_img(_save_img_dir, _x, _y, _z, _map_kind, _split_n)
    # SAR画像を切り取り、保存する処理
    _func_sar_img(_save_img_dir, _x, _y, _z, _map_kind, _split_n)

    return jsonify({'message': 'image processing was completed'})
def forgot_password(email):
    user = User.find_user_by_email(email)
    if user is None:
        raise MyException('could not find email', status_code=404)
    password = generate_password()
    try:
        msg = Message(subject="Reset Password", sender=os.environ.get('MAIL_USERNAME'),
                      recipients=[email])
        msg.html = "<body><h1>"f"New password is {password}</h1>""</body>"
        mail.send(msg)

    except Exception:
        print('message:- this are test emails  you can also use real emails in a sender and recipients')
    finally:
        user.password = password_hashing(password)
        db.session.commit()
        return {'password': password}
Beispiel #19
0
def email_verify(token):
    """ verify user email and update email_status to active """

    try:
        token_data = decode_token(token)
        email = token_data['email']
    except Exception:
        raise MyException('please click the link to verify your email',
                          status_code=404)
    user = User.find_user_by_email(email)
    if not user:
        return {'message': 'invalid email, 404'}, 404
    user.email_status = True
    db.session.commit()
    return jsonify(
        email=user.email,
        email_status=user.email_status,
    )
Beispiel #20
0
def _crop_and_save_convert_sar_png_img(read_sar_img_api_path,
                                       save_sar_png_img_path,
                                       key,
                                       op_size=256):
    _left, _upper, _right, _lower = _get_sar_crop_params(key)
    _box = (_left, _upper, _right, _lower)

    _img = None
    try:
        _req_url = '%s%s' % (sar_img_url, read_sar_img_api_path)
        _res = requests.get(_req_url, stream=True)
        _img = Image.open(BytesIO(_res.content))
        _img.point(lambda i: i * (1. / 256)).convert('L').crop(_box).resize(
            (op_size, op_size)).save(save_sar_png_img_path,
                                     'PNG',
                                     quality=True)
    except:
        raise MyException("couldn't crop sar full image", 500)
    finally:
        if _img is not None:
            _img.close()
Beispiel #21
0
 def post(self):
     data = request.get_json()
     if not data:
         raise MyException('enter new email', status_code=404)
     return generate_update_email_token(data["email"])
Beispiel #22
0
 def put(cls):
     data = request.get_json()
     if not data:
         raise MyException('fields cannot be empty', status_code=400)
     return change_password(data['email'], data['old_password'],
                            data['new_password'])
Beispiel #23
0
 def post(cls):
     data = request.get_json()
     if not data:
         raise MyException('fields cannot be empty', status_code=400)
     return forgot_password(data['email'])
 def post(cls):
     data = request.get_json()
     if not data:
         raise MyException('field cannot be empty', status_code=400)
     return generate_email_token(data['email'])
Beispiel #25
0
def _get_sar_crop_params(key):
    try:
        return sar_crop_params[key]
    except KeyError as e:
        raise MyException('sar crop parameter nothing', 400)
Beispiel #26
0
def _get_sar_tif_img_path(key):
    try:
        return sar_tif_img_path[key]
    except KeyError as e:
        raise MyException('sar crop parameter nothing', 400)
 def put(cls):
     try:
         return update_user()
     except Exception as err:
         raise MyException('this username is taken try next',
                           status_code=406)
Beispiel #28
0
 def patch(cls):
     data = request.get_json()
     if not data:
         raise MyException('fields cannot be empty', status_code=400)
     return update_role(data['username'], data['role'])
Beispiel #29
0
 def patch(self):
     data = request.get_json()
     if not data:
         raise MyException('something is wrong, please try again later',
                           status_code=500)
     return update_email(data["token"])
 def patch(cls):
     data = request.get_json()
     if not data:
         raise MyException('field cannot be empty', status_code=400)
     return email_verify(data['token'])