Exemple #1
0
    def test_14_create_delete_user(self):
        realm = "sqlrealm"
        resolver = "SQL1"
        parameters = self.parameters
        parameters["resolver"] = resolver
        parameters["type"] = "sqlresolver"

        rid = save_resolver(parameters)
        self.assertTrue(rid > 0, rid)

        (added, failed) = set_realm(realm, [resolver])
        self.assertEqual(len(failed), 0)
        self.assertEqual(len(added), 1)

        # Create the user
        uid = create_user(resolver, {"username": "******",
                                     "givenname": "achmed"},
                                     password="******")
        self.assertTrue(uid > 6)

        user = User("achmed3", realm=realm)
        r = user.check_password("secret")

        # delete user
        r = user.delete()
        self.assertTrue(r)
 def test_10_invalidate_delete_user(self):
     # Validate that deleting users actually invalidates the cache. For that, we first need an editable resolver
     self._create_sql_realm()
     # The cache is initially empty
     self.assertEquals(UserCache.query.count(), 0)
     # The following adds an entry to the cache
     user = User(login="******", realm=self.sql_realm)
     self.assertEquals(UserCache.query.count(), 1)
     uinfo = user.info
     user.delete()
     # This should have removed the entry from the cache
     self.assertEqual(UserCache.query.count(), 0)
     # We add the user again for the other tests
     create_user(self.sql_resolver, uinfo)
     self.assertEqual(UserCache.query.count(), 0)
     self._delete_sql_realm()
Exemple #3
0
    def test_14_create_delete_user(self):
        realm = "sqlrealm"
        resolver = "SQL1"
        parameters = self.parameters
        parameters["resolver"] = resolver
        parameters["type"] = "sqlresolver"

        rid = save_resolver(parameters)
        self.assertTrue(rid > 0, rid)

        (added, failed) = set_realm(realm, [resolver])
        self.assertEqual(len(failed), 0)
        self.assertEqual(len(added), 1)

        # Create the user
        uid = create_user(resolver, {
            "username": "******",
            "givenname": "achmed"
        },
                          password="******")
        self.assertTrue(uid > 6)

        user = User("achmed3", realm=realm)
        r = user.check_password("secret")

        # delete user
        r = user.delete()
        self.assertTrue(r)
 def test_10_invalidate_delete_user(self):
     # Validate that deleting users actually invalidates the cache. For that, we first need an editable resolver
     self._create_sql_realm()
     # The cache is initially empty
     self.assertEquals(UserCache.query.count(), 0)
     # The following adds an entry to the cache
     user = User(login="******", realm=self.sql_realm)
     self.assertEquals(UserCache.query.count(), 1)
     uinfo = user.info
     user.delete()
     # This should have removed the entry from the cache
     self.assertEqual(UserCache.query.count(), 0)
     # We add the user again for the other tests
     create_user(self.sql_resolver, uinfo)
     self.assertEqual(UserCache.query.count(), 0)
     self._delete_sql_realm()
Exemple #5
0
def delete_user(resolvername=None, username=None):
    """
    Delete a User in the user store.
    The resolver must have the flag editable, so that the user can be deleted.
    Only administrators are allowed to delete users.

    Delete a user object in a user store by calling

    **Example request**:

    .. sourcecode:: http

       DELETE /user/<resolvername>/<username>
       Host: example.com
       Accept: application/json

    """
    user_obj = User(login=username, resolver=resolvername)
    res = user_obj.delete()
    g.audit_object.log({"success": res, "info": "{0!s}".format(user_obj)})
    return send_result(res)
Exemple #6
0
def delete_user(resolvername=None, username=None):
    """
    Delete a User in the user store.
    The resolver must have the flag editable, so that the user can be deleted.
    Only administrators are allowed to delete users.

    Delete a user object in a user store by calling

    **Example request**:

    .. sourcecode:: http

       DELETE /user/<resolvername>/<username>
       Host: example.com
       Accept: application/json

    """
    user_obj = User(login=username, resolver=resolvername)
    res = user_obj.delete()
    g.audit_object.log({"success": res,
                        "info": u"{0!s}".format(user_obj)})
    return send_result(res)
Exemple #7
0
def register_post():
    """
    Register a new user in the realm/userresolver. To do so, the user
    resolver must be writeable like an SQLResolver.

    Registering a user in fact creates a new user and also creates the first
    token for the user. The following values are needed to register the user:

    * username (mandatory)
    * givenname (mandatory)
    * surname (mandatory)
    * email address (mandatory)
    * password (mandatory)
    * mobile phone (optional)
    * telephone (optional)

    The user receives a registration token via email to be able to login with
    his self chosen password and the registration token.

    :jsonparam username: The login name of the new user. Check if it already
        exists
    :jsonparam givenname: The givenname of the new user
    :jsonparam surname: The surname of the new user
    :jsonparam email: The email address of the new user
    :jsonparam password: The password of the new user. This is the resolver
        password of the new user.
    :jsonparam mobile: The mobile phone number
    :jsonparam phone: The phone number (land line) of the new user

    :return: a json result with a boolean "result": true
    """
    username = getParam(request.all_data, "username", required)
    surname = getParam(request.all_data, "surname", required)
    givenname = getParam(request.all_data, "givenname", required)
    email = getParam(request.all_data, "email", required)
    password = getParam(request.all_data, "password", required)
    mobile = getParam(request.all_data, "mobile")
    phone = getParam(request.all_data, "phone")
    options = {"g": g, "clientip": g.client_ip}
    g.audit_object.log({"info": username})
    # Add all params to the options
    for key, value in request.all_data.items():
        if value and key not in ["g", "clientip"]:
            options[key] = value

    # 0. check, if we can do the registration at all!
    smtpconfig = g.policy_object.get_action_values(ACTION.EMAILCONFIG,
                                                   scope=SCOPE.REGISTER,
                                                   unique=True)
    if not smtpconfig:
        raise RegistrationError("No SMTP server configuration specified!")

    # 1. determine, in which resolver/realm the user should be created
    realm = g.policy_object.get_action_values(ACTION.REALM,
                                              scope=SCOPE.REGISTER,
                                              unique=True)
    if not realm:
        # No policy for realm, so we use the default realm
        realm = get_default_realm
    else:
        # we use the first realm in the list
        realm = realm[0]
    resolvername = g.policy_object.get_action_values(ACTION.RESOLVER,
                                                     scope=SCOPE.REGISTER,
                                                     unique=True)
    if not resolvername:
        raise RegistrationError("No resolver specified to register in!")
    resolvername = resolvername[0]
    # Check if the user exists
    user = User(username, realm=realm, resolver=resolvername)
    if user.exist():
        raise RegistrationError("The username is already registered!")
    # Create user
    uid = create_user(
        resolvername, {
            "username": username,
            "email": email,
            "phone": phone,
            "mobile": mobile,
            "surname": surname,
            "givenname": givenname,
            "password": password
        })

    # 3. create a registration token for this user
    user = User(username, realm=realm, resolver=resolvername)
    token = init_token({"type": "registration"}, user=user)
    # 4. send the registration token to the users email
    registration_key = token.init_details.get("otpkey")

    smtpconfig = smtpconfig[0]
    # Send the registration key via email
    body = g.policy_object.get_action_values(ACTION.REGISTERBODY,
                                             scope=SCOPE.REGISTER,
                                             unique=True)
    body = body or DEFAULT_BODY
    email_sent = send_email_identifier(smtpconfig, email,
                                       "Your privacyIDEA registration",
                                       body.format(regkey=registration_key))
    if not email_sent:
        log.warning("Failed to send registration email to {0!r}".format(email))
        # delete registration token
        token.delete()
        # delete user
        user.delete()
        raise RegistrationError("Failed to send email!")

    log.debug("Registration email sent to {0!r}".format(email))

    g.audit_object.log({"success": email_sent})
    return send_result(email_sent)
Exemple #8
0
def register_post():
    """
    Register a new user in the realm/userresolver. To do so, the user
    resolver must be writeable like an SQLResolver.

    Registering a user in fact creates a new user and also creates the first
    token for the user. The following values are needed to register the user:

    * username (mandatory)
    * givenname (mandatory)
    * surname (mandatory)
    * email address (mandatory)
    * password (mandatory)
    * mobile phone (optional)
    * telephone (optional)

    The user receives a registration token via email to be able to login with
    his self chosen password and the registration token.

    :jsonparam username: The login name of the new user. Check if it already
        exists
    :jsonparam givenname: The givenname of the new user
    :jsonparam surname: The surname of the new user
    :jsonparam email: The email address of the new user
    :jsonparam password: The password of the new user. This is the resolver
        password of the new user.
    :jsonparam mobile: The mobile phone number
    :jsonparam phone: The phone number (land line) of the new user

    :return: a json result with a boolean "result": true
    """
    username = getParam(request.all_data, "username", required)
    surname = getParam(request.all_data, "surname", required)
    givenname = getParam(request.all_data, "givenname", required)
    email = getParam(request.all_data, "email", required)
    password = getParam(request.all_data, "password", required)
    mobile = getParam(request.all_data, "mobile")
    phone = getParam(request.all_data, "phone")
    options = {"g": g,
               "clientip": g.client_ip}
    g.audit_object.log({"info": username})
    # Add all params to the options
    for key, value in request.all_data.items():
            if value and key not in ["g", "clientip"]:
                options[key] = value

    # 0. check, if we can do the registration at all!
    smtpconfig = g.policy_object.get_action_values(ACTION.EMAILCONFIG,
                                                   scope=SCOPE.REGISTER,
                                                   unique=True,
                                                   audit_data=g.audit_object.audit_data)
    if not smtpconfig:
        raise RegistrationError("No SMTP server configuration specified!")

    # 1. determine, in which resolver/realm the user should be created
    realm = g.policy_object.get_action_values(ACTION.REALM,
                                              scope=SCOPE.REGISTER,
                                              unique=True,
                                              audit_data=g.audit_object.audit_data)
    if not realm:
        # No policy for realm, so we use the default realm
        realm = get_default_realm
    else:
        # we use the first realm in the list
        realm = list(realm)[0]
    resolvername = g.policy_object.get_action_values(ACTION.RESOLVER,
                                                     scope=SCOPE.REGISTER,
                                                     unique=True,
                                                     audit_data=g.audit_object.audit_data)
    if not resolvername:
        raise RegistrationError("No resolver specified to register in!")
    resolvername = list(resolvername)[0]
    # Check if the user exists
    user = User(username, realm=realm, resolver=resolvername)
    if user.exist():
        raise RegistrationError("The username is already registered!")
    # Create user
    uid = create_user(resolvername, {"username": username,
                                     "email": email,
                                     "phone": phone,
                                     "mobile": mobile,
                                     "surname": surname,
                                     "givenname": givenname,
                                     "password": password})

    # 3. create a registration token for this user
    user = User(username, realm=realm, resolver=resolvername)
    token = init_token({"type": "registration"}, user=user)
    # 4. send the registration token to the users email
    registration_key = token.init_details.get("otpkey")

    smtpconfig = list(smtpconfig)[0]
    # Send the registration key via email
    body = g.policy_object.get_action_values(ACTION.REGISTERBODY,
                                             scope=SCOPE.REGISTER,
                                             unique=True,
                                             audit_data=g.audit_object.audit_data)
    body = body or DEFAULT_BODY
    email_sent = send_email_identifier(
        smtpconfig, email,
        "Your privacyIDEA registration",
        body.format(regkey=registration_key))
    if not email_sent:
        log.warning("Failed to send registration email to {0!r}".format(email))
        # delete registration token
        token.delete()
        # delete user
        user.delete()
        raise RegistrationError("Failed to send email!")

    log.debug("Registration email sent to {0!r}".format(email))

    g.audit_object.log({"success": email_sent})
    return send_result(email_sent)
Exemple #9
0
    def test_15_unassign_missing_user(self):
        """
        Unassign a token from a user that does not exist anymore.

        There is a token which is owned by a user, who was deleted fromt he
        userstore.
        An Event Handler, to notifiy the user via email on unassign is defined.
        This testcase must NOT throw an exception. Well, the user can not be
        notified anymore, since the email also does not exist in the
        userstore anymore.
        """
        # Create our realm and resolver
        parameters = {
            'resolver':
            "notify_resolver",
            "type":
            "sqlresolver",
            'Driver':
            'sqlite',
            'Server':
            '/tests/testdata/',
            'Database':
            "testuser.sqlite",
            'Table':
            'users',
            'Encoding':
            'utf8',
            'Editable':
            True,
            'Map':
            '{ "username": "******", \
                        "userid" : "id", \
                        "email" : "email", \
                        "surname" : "name", \
                        "givenname" : "givenname", \
                        "password" : "password", \
                        "phone": "phone", \
                        "mobile": "mobile"}'
        }
        r = save_resolver(parameters)
        self.assertTrue(r)

        success, fail = set_realm("notify_realm", ["notify_resolver"])
        self.assertEqual(len(success), 1)
        self.assertEqual(len(fail), 0)

        # Create a user
        ## First delete it, in case the user exist
        User("notify_user", "notify_realm").delete()
        uid = create_user("notify_resolver", {"username": "******"})
        self.assertTrue(uid)
        user = User("notify_user", "notify_realm")
        self.assertEqual(user.login, "notify_user")
        self.assertEqual(user.realm, "notify_realm")

        # Create a token for this user
        r = init_token({"type": "spass", "serial": "SPNOTIFY"}, user=user)
        self.assertTrue(r)

        # create notification handler
        eid = set_event("token_unassign", "UserNotification", "sendmail")
        self.assertTrue(eid)

        # delete the user
        r = user.delete()
        self.assertTrue(r)

        # unassign the token from the non-existing user
        # call the notification handler implicitly
        with self.app.test_request_context('/token/unassign',
                                           method='POST',
                                           data={"serial": "SPNOTIFY"},
                                           headers={'Authorization': self.at}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200, res)
            result = json.loads(res.data).get("result")
            self.assertTrue(result.get("value") is True, result)

        # Cleanup
        delete_event(eid)
        delete_realm("notify_realm")
        delete_resolver("notify_resolver")
        remove_token("SPNOTIFY")