示例#1
0
def parse_time_range(value: str) -> Tuple[datetime, datetime]:
    """ Return tuple containing min/max time for given text representation. """
    one_day = timedelta(days=1)
    one_second = timedelta(seconds=1)
    almost_one_day = one_day - one_second

    value = value.lower()
    if not value:
        raise errors.ValidationError("Empty date format.")

    if value == "today":
        now = datetime.utcnow()
        return (
            datetime(now.year, now.month, now.day, 0, 0, 0),
            datetime(now.year, now.month, now.day, 0, 0, 0) + almost_one_day,
        )

    if value == "yesterday":
        now = datetime.utcnow()
        return (
            datetime(now.year, now.month, now.day, 0, 0, 0) - one_day,
            datetime(now.year, now.month, now.day, 0, 0, 0) - one_second,
        )

    match = re.match(r"^(\d{4})$", value)
    if match:
        year = int(match.group(1))
        return (datetime(year, 1, 1), datetime(year + 1, 1, 1) - one_second)

    match = re.match(r"^(\d{4})-(\d{1,2})$", value)
    if match:
        year = int(match.group(1))
        month = int(match.group(2))
        return (
            datetime(year, month, 1),
            datetime(year, month + 1, 1) - one_second,
        )

    match = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})$", value)
    if match:
        year = int(match.group(1))
        month = int(match.group(2))
        day = int(match.group(3))
        return (
            datetime(year, month, day),
            datetime(year, month, day + 1) - one_second,
        )

    raise errors.ValidationError("Invalid date format: %r." % value)
示例#2
0
def start_password_reset(ctx: rest.Context,
                         params: Dict[str, str]) -> rest.Response:
    user_name = params['user_name']
    user = users.get_user_by_name_or_email(user_name)
    if not user.email:
        raise errors.ValidationError(
            'User %r hasn\'t supplied email. Cannot reset password.' %
            (user_name))
    token = auth.generate_authentication_token(user)

    if 'SERVER_NAME' in ctx.env:
        url = ctx.env['SERVER_NAME'].rstrip('/')
    elif 'HTTP_ORIGIN' in ctx.env:
        url = ctx.env['HTTP_ORIGIN'].rstrip('/')
    elif 'HTTP_HOST' in ctx.env:
        url = ctx.env['HTTP_HOST'].rstrip('/')
    else:
        url = ''
    url += '/password-reset/%s:%s' % (user.name, token)

    mailer.send_mail('noreply@%s' % config.config['name'], user.email,
                     MAIL_SUBJECT.format(name=config.config['name']),
                     MAIL_BODY.format(name=config.config['name'], url=url))

    return {}
def start_password_reset(ctx: rest.Context,
                         params: Dict[str, str]) -> rest.Response:
    user_name = params["user_name"]
    user = users.get_user_by_name_or_email(user_name)
    if not user.email:
        raise errors.ValidationError(
            "User %r hasn't supplied email. Cannot reset password." %
            (user_name))
    token = auth.generate_authentication_token(user)

    if config.config["domain"]:
        url = config.config["domain"]
    elif "HTTP_ORIGIN" in ctx.env:
        url = ctx.env["HTTP_ORIGIN"].rstrip("/")
    elif "HTTP_REFERER" in ctx.env:
        url = ctx.env["HTTP_REFERER"].rstrip("/")
    else:
        url = ""
    url += "/password-reset/%s:%s" % (user.name, token)

    mailer.send_mail(
        config.config["smtp"]["from"],
        user.email,
        MAIL_SUBJECT.format(name=config.config["name"]),
        MAIL_BODY.format(name=config.config["name"], url=url),
    )

    return {}
示例#4
0
 def post(self, ctx, user_name):
     ''' Verify token from mail, generate a new password and return it. '''
     user = users.get_user_by_name_or_email(user_name)
     good_token = auth.generate_authentication_token(user)
     token = ctx.get_param_as_string('token', required=True)
     if token != good_token:
         raise errors.ValidationError('Invalid password reset token.')
     new_password = users.reset_user_password(user)
     ctx.session.commit()
     return {'password': new_password}
示例#5
0
def parse_time_range(value: str) -> Tuple[datetime, datetime]:
    ''' Return tuple containing min/max time for given text representation. '''
    one_day = timedelta(days=1)
    one_second = timedelta(seconds=1)
    almost_one_day = one_day - one_second

    value = value.lower()
    if not value:
        raise errors.ValidationError('비어있는 날짜 형식.')

    if value == 'today':
        now = datetime.utcnow()
        return (datetime(now.year, now.month, now.day, 0, 0,
                         0), datetime(now.year, now.month, now.day, 0, 0, 0) +
                almost_one_day)

    if value == 'yesterday':
        now = datetime.utcnow()
        return (datetime(now.year, now.month, now.day, 0, 0, 0) - one_day,
                datetime(now.year, now.month, now.day, 0, 0, 0) - one_second)

    match = re.match(r'^(\d{4})$', value)
    if match:
        year = int(match.group(1))
        return (datetime(year, 1, 1), datetime(year + 1, 1, 1) - one_second)

    match = re.match(r'^(\d{4})-(\d{1,2})$', value)
    if match:
        year = int(match.group(1))
        month = int(match.group(2))
        return (datetime(year, month,
                         1), datetime(year, month + 1, 1) - one_second)

    match = re.match(r'^(\d{4})-(\d{1,2})-(\d{1,2})$', value)
    if match:
        year = int(match.group(1))
        month = int(match.group(2))
        day = int(match.group(3))
        return (datetime(year, month,
                         day), datetime(year, month, day + 1) - one_second)

    raise errors.ValidationError('잘못된 날짜 형식: %r.' % value)
示例#6
0
def finish_password_reset(ctx: rest.Context,
                          params: Dict[str, str]) -> rest.Response:
    user_name = params['user_name']
    user = users.get_user_by_name_or_email(user_name)
    good_token = auth.generate_authentication_token(user)
    token = ctx.get_param_as_string('token')
    if _hash(token) != _hash(good_token):
        raise errors.ValidationError('Invalid password reset token.')
    new_password = users.reset_user_password(user)
    versions.bump_version(user)
    ctx.session.commit()
    return {'password': new_password}
示例#7
0
 def serialize(self, options: List[str]) -> Any:
     field_factories = self._serializers()
     if not options:
         options = list(field_factories.keys())
     ret = {}
     for key in options:
         if key not in field_factories:
             raise errors.ValidationError(
                 'Invalid key: %r. Valid keys: %r.' %
                 (key, list(sorted(field_factories.keys()))))
         factory = field_factories[key]
         ret[key] = factory()
     return ret
示例#8
0
 def get(self, _ctx, user_name):
     ''' Send a mail with secure token to the correlated user. '''
     user = users.get_user_by_name_or_email(user_name)
     if not user.email:
         raise errors.ValidationError(
             'User %r hasn\'t supplied email. Cannot reset password.' %
             (user_name))
     token = auth.generate_authentication_token(user)
     url = '%s/password-reset/%s:%s' % (
         config.config['base_url'].rstrip('/'), user.name, token)
     mailer.send_mail('noreply@%s' % config.config['name'], user.email,
                      MAIL_SUBJECT.format(name=config.config['name']),
                      MAIL_BODY.format(name=config.config['name'], url=url))
     return {}
示例#9
0
def start_password_reset(_ctx: rest.Context,
                         params: Dict[str, str]) -> rest.Response:
    user_name = params['user_name']
    user = users.get_user_by_name_or_email(user_name)
    if not user.email:
        raise errors.ValidationError(
            'User %r hasn\'t supplied email. Cannot reset password.' %
            (user_name))
    token = auth.generate_authentication_token(user)
    url = '%s/password-reset/%s:%s' % (config.config['base_url'].rstrip('/'),
                                       user.name, token)
    mailer.send_mail('noreply@%s' % config.config['name'], user.email,
                     MAIL_SUBJECT.format(name=config.config['name']),
                     MAIL_BODY.format(name=config.config['name'], url=url))
    return {}
示例#10
0
def start_password_reset(_ctx: rest.Context,
                         params: Dict[str, str]) -> rest.Response:
    user_name = params['user_name']
    user = users.get_user_by_name_or_email(user_name)
    if not user.email:
        raise errors.ValidationError(
            '사용자 %r님은 이메일 주소를 등록하지 않았습니다. 비밀번호를 재설정할 수 없습니다.' % (user_name))
    token = auth.generate_authentication_token(user)
    url = '%s/password-reset/%s:%s' % (config.config['base_url'].rstrip('/'),
                                       user.name, token)
    mailer.send_mail(
        formataddr((str(Header(config.config['smtp']['user_display'],
                               'utf-8')), config.config['smtp']['user'])),
        user.email, MAIL_SUBJECT.format(name=config.config['name']),
        MAIL_BODY.format(name=config.config['name'], url=url))
    return {}