Beispiel #1
0
def delete_user(id):
    """``DELETE`` |API_URL_BASE|/user/:user_id

    Delete a user. Superuser can't be deleted.

    :param id: user id

    Response JSON:

    .. code-block:: javascript

        // success
        {$errors: null}

        // failed
        {$errors: {id: 'this is user does not exist.'}}

    Permission require: ``DELETE_USER``
    """
    try:
        User.get(User.id == id).delete_instance()
    except User.DoesNotExist:
        return {'id': '该用户ID不存在'}

    signals.event_emitted.send(current_app._get_current_object(),
                               type='User: Delete',
                               description='delete user(%s).' % id)
Beispiel #2
0
def get_user(id):
    """``GET`` |API_URL_BASE|/user/:user_id

    Get information of a user.

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            users: {
                id: string,
                name: string,
                role: {id: integer, name: string},
                expired: boolean,
                last_login: integer
            ]
        }

        // failed
        {$errors: {id: 'this user does not exist.'}}

    Permission required: ``READ_USER``
    """
    try:
        user = User.get(User.id == id)
    except User.DoesNotExist as ex:
        return {'id': '该用户不存在!'}

    return None, {'user': user.to_dict()}
Beispiel #3
0
def login_verify(email, password):

    try:
        user = User.get(User.email == email,
                        User.password == encrypt_password(password))

    except User.DoesNotExist:
        raise User.DoesNotExist

    else:
        user.last_login = datetime.datetime.now()
        user.save()
        return user
Beispiel #4
0
def update(id):
    form = UpdateUserForm(request.form)
    user = User.get(User.id == id)
    if form.validate_on_submit():
        User.update(first_name=form.first_name.data,
                    middle_name=form.middle_name.data,
                    last_name=form.last_name.data,
                    email_address=form.email_address.data,
                    phone_number=form.phone_number.data,
                    address=form.address.data,
                    birth_date=form.birth_date.data,
                    type=form.type.data,
                    updated_at=datetime.now()).where(User.id == id).execute()
        flash('User successfully updated')
        return redirect(url_for('user.index'))
    return render_template('user/update.html', form=form, user=user)
Beispiel #5
0
def is_logged_in_core(request):
    '''
    Determines if a logged-in user exists.
    '''
    user_name = request.get_cookie("login", secret=SECRET_KEY) or None

    if user_name is None:
        raise UserNotFound("User at {} attempted to access '{}'. Not logged in.".format(
            request.remote_addr,
            request.path))
    try:
        user_found = User.get(User.email == user_name)
    except User.DoesNotExist:
        raise UserNotFound("User at {} attempted to log in as '{}'. User not found.".format(
            request.remote_addr,
            user_name))

    return user_found
Beispiel #6
0
def is_logged_in_core(request):
    '''
    Determines if a logged-in user exists.
    '''
    user_name = request.get_cookie("login", secret=SECRET_KEY) or None

    if user_name is None:
        raise UserNotFound(
            "User at {} attempted to access '{}'. Not logged in.".format(
                request.remote_addr, request.path))
    try:
        user_found = User.get(User.email == user_name)
    except User.DoesNotExist:
        raise UserNotFound(
            "User at {} attempted to log in as '{}'. User not found.".format(
                request.remote_addr, user_name))

    return user_found
Beispiel #7
0
    def test_modify_user(self):
        with self.ctx:
            user = User.create(id='testid',
                               password='******',
                               name='testname')

        payload_json = {
            'name': 'testname_',
            'password': '******',
            'expired': True
        }
        self.login_as_su()
        resp = self.client.patch(self.api_url_base + '/user/' + user.id,
                                 content_type='application/json',
                                 data=json_dumps(payload_json))
        self.assertResponseRestfulAndSuccess(resp)

        user = User.get(User.id == user.id)
        password_cipher = self.encode_password(payload_json['password'])
        self.assertEqual(user.password, password_cipher)
        self.assertEqual(user.name, payload_json['name'])
        self.assertEqual(user.expired, payload_json['expired'])
Beispiel #8
0
def view(id):
    user = User.get(User.id == id)
    return render_template('user/view.html', user=user)
Beispiel #9
0
def login():
    """``GET`` |API_URL_BASE|/login/

    Login, parameters are passed through query string.

    :param id: **Query**
    :param password: **Query**
    :param timestamp: **Query** client's timestamp(ms)
    :param remember: **Query** optional, boolean value

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            user: {
                id: string,
                name: string,
                role: {id: integer, name: string},
                expired: boolean,
                last_login: integer
            }
        }

        // failed
        {
            $errors: {
                id: 'this user id does not exist.',
                password: '******',
                timestamp: 'login session is invalid any more. please refresh.'
            }
        }
    """
    id = request.args.get('id', '')
    password = request.args.get('password', '')
    client_timestamp = request.args.get('timestamp', 0, type=int)
    remember = request.args.get('remember', 'false') == 'true'

    try:
        user = User.get(User.id == id)
    except User.DoesNotExist:
        return {'id': '用户ID不存在'}

    if not user.check_password(password, client_timestamp):
        signals.event_emitted.send(
            current_app._get_current_object(),
            type='Auth: Login',
            description='user(%s) attempts to log in using wrong password.' %
                        user.id
        )
        return {'password': '******'}

    server_time = int(time() * 1000)
    time_pass = server_time - client_timestamp
    if abs(time_pass) > app_config['USER_LOGIN_TIMEOUT']:
        signals.event_emitted.send(
            current_app._get_current_object(),
            type='Auth: Login',
            description='user(%s) attempts to log in using expired timestamp.'
                        % user.id
        )
        return {'timestamp': '登陆会话超时,请刷新重试'}

    login_user(user, remember=remember)

    signals.event_emitted.send(
        current_app._get_current_object(),
        type='Auth: Login',
        description='user(%s) login.' % user.id
    )

    return None, {'user': user.to_dict()}
Beispiel #10
0
def modify_user(id=None):
    """``PATCH`` |API_URL_BASE|/user/
    ``PATCH`` |API_URL_BASE|/user/:user_id

    Modify user information. User's role can't be modified.
    If no ``id`` was given then id will be automatically set to
    current user's id in this session.

    :param id: if not set, use ``current_user.get_id()``
    :param password: **JSON Param** plain password, without encoding
    :param boolean expired: **JSON Param**

    Response JSON:

    .. code-block:: javascript

        // success
        {
            $errors: null,
            user: {
                id: string,
                name: string,
                role: {id: integer, name: string},
                expired: boolean,
                last_login: integer
            }
        }

        // failed
        {
            $errors: {
                permission: 'your are not allowed to change other user.',
                name: 'this name is invalid.',
                password: '******',
                name: 'this name is duplicated.',
                id: 'this id is duplicated.'
            }
        }

    Permission require:

        * ``MODIFY_USER``
        * ``MODIFY_OTHER_USER`` (if attempt to modify other user.)
    """
    json = request.get_json()

    id = id or current_user.get_id()
    if id != current_user.get_id() \
            and not current_user.can(Permission.MODIFY_OTHER_USER):
        return {'permission': 'Your are not allowed to change other user.'}

    name = json.get('name')
    if name and not re_match(app_config['USER_NAME_PATTERN'], name):
        return {'name': app_config['USER_NAME_DESCRIPTION']}

    password = json.get('password')
    if password \
            and not re_match(app_config['USER_PASSWORD_PATTERN'],
                             password):
        return {'password': app_config['USER_PASSWORD_DESCRIPTION']}

    expired = json.get('expired')

    if User.select().where(User.name == name).count() == 1:
        return {'name': '该昵称 %s 已存在' % name}

    try:
        this_user = User.get(User.id == id)
    except User.DoesNotExist:
        return {'id': '该用户ID %s 不存在' % id}

    if name:
        this_user.name = name

    if password:
        this_user.set_password(password)

    if expired:
        this_user.expired = bool(expired)

    # if nothing change, keep database unchanged
    if this_user.dirty_fields:
        this_user.save()

        signals.event_emitted.send(
            current_app._get_current_object(),
            type='User: Modify',
            description='modify properties %s of user(%s).' %
            (','.join([f.name for f in this_user.dirty_fields]), id))

    return None, {'user': this_user.to_dict()}