Exemple #1
0
    def post(self):
        args = get_args()
        email = args['email'].lower()
        pwd = args['pwd']

        user = User(email, pwd=pwd)

        if not user.is_user():
            err = email + ' is not signed up user.'
            raise InvalidUsage(err, status_code=403)

        is_tmp_pwd = user.check_tmp_pwd(pwd)
        if not user.check_pwd(pwd) and not is_tmp_pwd:
            err = 'Password is invalid.'
            raise InvalidUsage(err, status_code=400)

        if is_tmp_pwd and user.is_expired_tmp_pwd():
            err = 'Expired Temporary Password'
            raise InvalidUsage(err, status_code=406)

        auth_token, refresh_token, exp_time = user.generate_auth_token()
        user.authenticated = True

        result = {
            'auth_token': auth_token,
            'refresh_token': refresh_token,
            'exp_time': exp_time
        }

        if is_tmp_pwd:
            result['used_tmp_pwd'] = is_tmp_pwd

        return result
Exemple #2
0
    def post(self):
        args = get_args()
        user_model = UserModel.objects(email=args['email']).first()
        if user_model is None:
            raise InvalidUsage('User not found', 404)

        tmp_password = gen_pwd()

        body = render_template("pwd_reset_mail.template.html",
                               name=user_model.name,
                               password=tmp_password)

        try:
            charset = 'UTF-8'
            response = apitools.email_client.send_email(
                Destination={'ToAddresses': [user_model.email]},
                Message=dict(
                    Subject=dict(Data="[아롬] 임시 비밀번호 발급", Charset='utf8'),
                    Body=dict(Html=dict(Charset='utf8', Data=str(body)))),
                Source=app.config['CONTACT_EMAIL'])
        except Exception as ex:
            raise InvalidUsage("Email Server Error: {}".format(ex), 500)

        user_model.tmp_password = hash_pwd(tmp_password)
        user_model.tmp_password_valid_period = datetime.datetime.now() + \
                app.config['PASSWORD_RESET_EXPIRE_DURATION']
        user_model.save()

        return dict(result=True)
Exemple #3
0
    def post(self):
        args = get_args()
        image = args['image']
        if not image.content_type.startswith('image'):
            exceptionReport(g.user.user_db, get_path(), get_path_args(),
                            get_args())
            raise InvalidUsage("Invalid Image Type", 400)

        extension = image.filename.split('.')[-1]

        image_model = ImageAttachmentModel(user_id=g.user.user_db.user_id,
                                           extension=extension,
                                           orignal_name=image.filename)
        image_model.save()

        key = image_model.s3filename
        upload_config = TransferConfig(use_threads=False)

        try:
            result = s3.upload_fileobj(image,
                                       app.config['ATTACHMENT_S3_BUCKET'],
                                       key,
                                       ExtraArgs={
                                           "ACL": "public-read",
                                           "ContentType": image.content_type
                                       },
                                       Config=upload_config)
        except:
            image_model.delete()
            exceptionReport(g.user.user_db, get_path(), get_path_args(),
                            get_args())
            raise InvalidUsage("s3 upload error. try again", 500)

        return image_model.marshall()
Exemple #4
0
    def new_func(*args, **kwargs):
        auth_token = request.headers.get('authorization')
        if auth_token:
            auth_token = auth_token.encode()
            try:
                user_id = jwt.decode(auth_token,
                                     app.config['SECRET_KEY'],
                                     algorithms='HS512')['sub']
            except jwt.ExpiredSignatureError:
                raise InvalidUsage(
                    'Auth Token was expired. Try Again for refresh token.',
                    status_code=401)
            except Exception:
                raise InvalidUsage('Auth Token is invalid.', status_code=401)
            try:
                user_db = UserModel.objects.get(user_id=user_id)
            except UserModel.DoesNotExist:
                raise InvalidUsage('This user does not exist.',
                                   status_code=401)

            if user_db.auth_token and auth_token == user_db.auth_token.encode(
            ):
                g.user = User(user_db.email, authenticated=True)
                return func(*args, **kwargs)
            else:
                raise InvalidUsage('Auth Token is invalid. Try Again.',
                                   status_code=401)
        else:
            raise InvalidUsage('Auth Token is not found. Try Again.',
                               status_code=401)
    def post(self):
        args = get_args()
        fbauth_token = args['facebook_auth_token']

        resp = FacebookApi.debug_token(fbauth_token)
        if 'error' in resp or not resp['data']['is_valid'] or \
                resp['data']['app_id'] != app.config['FACEBOOK_APP_ID']:
            raise InvalidUsage("Authroization Failed", 403)
        facebook_id = str(resp['data']['user_id'])
        try:
            user_model = UserModel.objects.get(facebook_id=facebook_id)
        except UserModel.DoesNotExist:
            raise InvalidUsage("User Not Found", 404)

        user = User()
        user.user_db = user_model
        auth_token, refresh_token, exp_time = user.generate_auth_token()
        user.authenticated = True

        return {
            'result': True,
            'auth_token': auth_token,
            'refresh_token': refresh_token,
            'exp_time': exp_time
        }
    def post(self, device_id):

        user_db = g.user.user_db
        user_id = user_db.user_id
        res = iot_client.get_thing_shadow(thingName=device_id)
        payload = json.loads(res['payload'].read())
        state = payload['state']
        reported = state.get('reported', {})
        desired = state.get('desired', {})

        if device_id in user_db.devices:
            exceptionReport(g.user.user_db, get_path(), get_path_args(),
                            get_args())
            raise InvalidUsage('Already Registered Device', 409)

        if user_id == reported['owner_id']:
            user_db.update(**{'set__devices__' + device_id: device_id})
            user_db.reload()

            return state
        else:
            exceptionReport(g.user.user_db, get_path(), get_path_args(),
                            get_args())
            raise InvalidUsage('This user is not owner of this device.',
                               status_code=401)
    def new_func(*args, **kwargs):
        device_id = kwargs['device_id']
        user_id = g.user.user_db.user_id
        res = iot_client.get_thing_shadow(thingName=device_id)
        payload = json.loads(res['payload'].read())
        state = payload['state']['reported']
        owner_id = state.get('owner_id', None)
        if type(owner_id) is list:  #array2str search formater
            owner_id = owner_id[0]
            payload = json.dumps(
                {'state': {
                    'reported': {
                        "owner_id": owner_id
                    }
                }})
            iot_client.update_thing_shadow(thingName=device_id,
                                           payload=payload)

        try:
            user_db = UserModel.objects.get(user_id=user_id)
        except UserModel.DoesNotExist:
            raise InvalidUsage('This user is not found.', status_code=401)

        if user_id == owner_id and device_id in user_db.devices:  #original user
            return func(*args, **kwargs)
        else:
            raise InvalidUsage('This user is not owner of this device.',
                               status_code=401)
    def post(self):
        args = get_args()
        fbauth_token = args['facebook_auth_token']

        token_resp = FacebookApi.debug_token(fbauth_token)
        if 'error' in token_resp or not token_resp['data']['is_valid'] or \
                token_resp['data']['app_id'] != app.config['FACEBOOK_APP_ID']:
            raise InvalidUsage("Authroization Failed", 403)
        facebook_id = str(token_resp['data']['user_id'])

        if UserModel.objects(facebook_id=facebook_id).first() is not None:
            raise InvalidUsage("Already existing facebook user", 403)

        signup(args,
               random_pw=True,
               validate_pw=False,
               facebook_id=facebook_id)

        return {'result': True}
Exemple #9
0
    def post(self):
        g.user.user_db.update(unset__auth_token=1)
        if g.user.user_db.access_token:
            g.user.user_db.update(unset__access_token=1)
        g.user.user_db.reload()
        if g.user.user_db.auth_token or g.user.user_db.access_token:
            raise InvalidUsage('Token does not deleted. Try Again.',
                               status_code=500)
        g.user.authenticated = False

        return dict(result=True)
Exemple #10
0
    def delete(self, attachment_id):
        img = ImageAttachmentModel.objects.with_id(attachment_id)
        if img is None:
            exceptionReport(g.user.user_db, get_path(), get_path_args(),
                            get_args())
            raise InvalidUsage("Image Not Found", 404)

        if img.user_id != g.user.user_db.user_id:
            exceptionReport(g.user.user_db, get_path(), get_path_args(),
                            get_args())
            raise InvalidUsage("Image Uploaded by another user", 403)
        try:
            s3.delete_object(Bucket=app.config['ATTACHMENT_S3_BUCKET'],
                             Key=img.s3filename)
        except:
            exceptionReport(g.user.user_db, get_path(), get_path_args(),
                            get_args())
            raise InvalidUsage("s3 delete error. try again", 500)

        img.delete()
        return dict(result=True)
Exemple #11
0
    def post(self):
        args = get_args()
        kauth_token = args['kakao_auth_token']

        resp = KakaoApi.user_info(kauth_token)

        if 'code' in resp:
            raise InvalidUsage("Authorization Failed", 403)

        kakao_id = str(resp['id'])
        properties = resp['properties']
        profile_image = properties['profile_image']
        nickname = properties['nickname']
        thumbnail_image = properties['thumbnail_image']

        if UserModel.objects(kakao_id=kakao_id).first() is not None:
            raise InvalidUsage("Already existing kakao user", 403)

        signup(args, random_pw=True, validate_pw=False, kakao_id=kakao_id)

        return {'result': True}
Exemple #12
0
    def get(self):
        args = get_args()
        if args.get('user_id', None):
            try:
                user_db = UserModel.objects.get(user_id=args.get('user_id'))
            except UserModel.doesNotExist:
                raise InvalidUsage('User does not exist.', status_code=404)

            return dict(
                user_info=dict(name=user_db.name, picture=user_db.picture))
        else:
            user = g.user.user_db
            return dict(user_info=user.marshall())
Exemple #13
0
def signup(user_info,
           random_pw=False,
           validate_pw=True,
           kakao_id=None,
           facebook_id=None):
    email = user_info.get('email').lower()
    pwd = user_info.get('pwd')
    name = user_info.get('name')
    birthday = user_info.get('birthday')
    gender = user_info.get('gender')

    place = user_info.get('place')
    space = user_info.get('space')
    purpose = user_info.get('purpose')

    prefer_scents = user_info.get('prefer_scents')

    if email is None:
        raise InvalidUsage("Email is required", status_code=400)

    try:
        validate_email(email, check_deliverability=False)
    except:
        raise InvalidUsage("Email is not valid", status_code=403)

    if pwd is None:
        if random_pw:
            pwd = str(uuid.uuid4())
        else:
            raise InvalidUsage("Password is requied", status_code=400)

    if validate_pw:
        pattern = r"^(?=.*[A-Za-z])(?=.*\d)(?=.*[`\-=\\\[\];',\./~!@#$%^&*\(\)_\+|\{\}:\"<>\?])" \
                  r"[A-Za-z\d`\-=\\\[\];',\./~!@#$%^&*\(\)_\+|\{\}:\"<>\?]{8,}$"
        if not re.match(pattern, pwd):
            raise InvalidUsage("Password is not secure one", status_code=400)

    if UserModel.objects(Q(email=email)).first() is not None:
        err = email + ' already exists.'
        raise InvalidUsage(err, status_code=403)

    UserModel(user_id=str(uuid.uuid4()),
              kakao_id=kakao_id,
              facebook_id=facebook_id,
              email=email,
              password=hash_pwd(pwd),
              name=name,
              birthday=birthday,
              gender=gender,
              place=place,
              space=space,
              purpose=purpose,
              prefer_scents=prefer_scents).save()

    try:
        user = UserModel.objects.get(email=email)
    except UserModel.DoesNotExist:
        err = email + ' signup failed. Try again.'
        raise InvalidUsage(err, status_code=500)
Exemple #14
0
    def post(self):
        args = get_args()
        auth_token = request.headers.get('authorization')
        refresh_token = args['refresh_token']

        if auth_token and refresh_token:
            auth_token = auth_token.encode()
            refresh_token = refresh_token.encode()
            try:
                user_id = jwt.decode(auth_token,
                                     app.config['SECRET_KEY'],
                                     algorithms='HS512',
                                     options=dict(verify_exp=False))['sub']
            except jwt.InvalidTokenError:
                raise InvalidUsage('Auth Token is invalid.', status_code=401)

            try:
                user_db = UserModel.objects.get(user_id=user_id)
            except UserModel.DoesNotExist:
                raise InvalidUsage('This user does not exist.',
                                   status_code=401)

            if refresh_token == user_db.refresh_token.encode():
                user = User(user_db.email, user_id=user_id)
                auth_token, refresh_token, exp_time = user.generate_auth_token(
                )
                return {
                    'auth_token': auth_token,
                    'refresh_token': refresh_token,
                    'exp_time': exp_time
                }
            else:
                raise InvalidUsage('Refresh Token is invalid.',
                                   status_code=401)
        else:
            raise InvalidUsage('Token is not found.', status_code=401)
Exemple #15
0
    def post(self):
        args = get_args()
        kauth_token = args['kakao_auth_token']

        resp = KakaoApi.access_token_info(kauth_token)
        if 'code' in resp:
            raise InvalidUsage("Authroization Failed", 403)
        kakao_id = str(resp['id'])
        try:
            user_model = UserModel.objects.get(kakao_id=kakao_id)
        except UserModel.DoesNotExist:
            raise InvalidUsage("User Not Found", 404)

        user = User()
        user.user_db = user_model
        auth_token, refresh_token, exp_time = user.generate_auth_token()
        user.authenticated = True

        return {
            'result': True,
            'auth_token': auth_token,
            'refresh_token': refresh_token,
            'exp_time': exp_time
        }