Esempio n. 1
0
def _update_admin_user(Session, settings):
    """
    Reads the init settings at application start up and sets or add the
    admin user with the set password.
    The necessary setting keys are "lmkp.admin_password" and
    "lmkp.admin_email".
    """

    try:
        pw = settings["lmkp.admin_password"]
        email = settings["lmkp.admin_email"]
    except KeyError:
        raise Exception('"lmkp.admin_password" or "lmkp.admin_email" setting are missing ' "in configuration file.")

    # Try to get the admin user from the database
    admin_user = Session.query(User).filter(User.username == "admin").first()

    if admin_user == None:

        admin_group = Session.query(Group).filter(Group.name == "administrators").first()
        admin_user = User(username="******", password=pw, email=email)
        admin_user.groups.append(admin_group)
        Session.add(admin_user)

    else:
        admin_user.password = pw
        admin_user.email = email

    transaction.commit()
Esempio n. 2
0
        def succeed():
            """
            """

            # Request all submitted values
            profile_field = self.request.POST.get("profile")
            username_field = self.request.POST.get("username")
            firstname_field = self.request.POST.get("firstname")
            lastname_field = self.request.POST.get("lastname")
            password_field = self.request.POST.get("password")
            email_field = self.request.POST.get("email")

            # Get the selected profile
            selected_profile = Session.query(Profile).filter(
                Profile.code == profile_field).first()

            # Get the initial user group
            user_group = Session.query(Group).filter(
                Group.name == "editors").first()

            # Create an activation uuid
            activation_uuid = uuid.uuid4()

            # Create a new user
            new_user = User(username_field, password_field, email_field,
                            firstname=firstname_field,
                            lastname=lastname_field,
                            activation_uuid=activation_uuid,
                            registration_timestamp=datetime.now())

            # Set the user profile
            new_user.profiles = [selected_profile]
            new_user.groups = [user_group]
            # Commit the new user
            Session.add(new_user)

            activation_dict = {
                "firstname": new_user.firstname,
                "lastname": new_user.lastname,
                "activation_link": "http://%s/users/activate?uuid=%s&username="******"%s" % (
                    self.request.environ['HTTP_HOST'], activation_uuid,
                    new_user.username)
            }
            email_text = render(
                get_customized_template_path(
                    self.request, 'emails/account_activation.mak'),
                activation_dict, self.request)

            self._send_email(
                [email_field], _(u"Activate your Account"), email_text)

            return render_to_response(
                get_customized_template_path(
                    self.request, 'users/registration_success.mak'),
                {}, self.request)
Esempio n. 3
0
def add_user(request):
    if 'groups' in request.params:
        requested_groups = request.POST.getall('groups')
    else:
        raise HTTPBadRequest("Missing group parameter")

    if 'username' in request.params:
        username = request.params['username']
    else:
        raise HTTPBadRequest("Missing username parameter")

    if 'email' in request.params:
        email = request.params['email']
    else:
        raise HTTPBadRequest("Missing email parameter")

    if 'password' in request.params:
        password = request.params['password']
    else:
        raise HTTPBadRequest("Missing password parameter")

    # Check email
    email_query = Session.query(User).filter(User.email == email)
    try:
        email_query.one()
        raise HTTPBadRequest(
            'There already exists a user with this email address')
    except NoResultFound:
        pass

    # Check groups
    groups = Session.query(Group).filter(
        Group.name.in_(requested_groups)).all()
    if len(groups) == 0:
        raise HTTPBadRequest("Invalid group parameter")

    if not _user_exists(User.username, username):
        # Create an activation uuid
        activation_uuid = uuid.uuid4()
        # Create a new user
        new_user = User(username=username,
                        password=password,
                        email=email,
                        activation_uuid=activation_uuid,
                        registration_timestamp=datetime.now())
        new_user.groups = groups
        return {"success": True, "msg": "New user created successfully."}
    else:
        request.response.status = 400
        return {"success": False, "msg": "User exists."}
Esempio n. 4
0
    def login(self):
        """
        Login controller
        """
        login_url = self.request.route_url('login')
        referrer = self.request.path
        if referrer == login_url:
            # never use the login form itself as came_from
            referrer = '/'
        came_from = self.request.params.get('came_from', referrer)
        login = ''
        password = ''
        # Prevent an empty header if /login is directly requested (should actually
        # never happen)
        headers = []
        if 'form.submitted' in self.request.params:
            login = self.request.params['login']
            password = self.request.params['password']

            if User.check_password(login, password):
                log.debug('Login succeed')
                headers = remember(self.request, login, max_age=timedelta(days=30).total_seconds())
            else:
                log.debug('Login failed')
                headers = forget(self.request)
                msg = _(u"Login failed! Please try again.")
                return render_to_response(getTemplatePath(self.request, 'login_form.mak'), {
                                          'came_from': came_from,
                                          'warning': msg
                                          }, self.request)

        return HTTPFound(location=came_from, headers=headers)
Esempio n. 5
0
def user_update(request):
    """
    This function updates user information and sends back a JSON with 'success'
    (true/false) and 'msg'
    User must be logged in, information can only be changed by the user himself
    and if application is not running in demo mode and username is in ignored.
    """
    ret = {'success': False}

    # List of usernames which cannot be changed when in demo mode
    ignored_demo_usernames = ['editor', 'moderator']
    mode = None
    if 'lmkp.mode' in request.registry.settings:
        if str(request.registry.settings['lmkp.mode']).lower() == 'demo':
            mode = 'demo'

    username = request.POST['username'] if 'username' in request.POST else None
    email = request.POST['email']  if 'email' in request.POST else None
    new_password = request.POST['new_password1'] if 'new_password1' in request.POST else None
    old_password = request.POST['old_password'] if 'old_password' in request.POST else None
    
    if username and (email or (new_password and old_password)):

        # Return error message if in demo mode and username one of the ignored
        if (mode is not None and mode == 'demo'
            and username in ignored_demo_usernames):
            ret['msg'] = 'You are not allowed to change this user in demo mode.'
            return ret

        # try to find requested user
        try:
            user = Session.query(User).filter(User.username == username).one()
            # check privileges (only current user can update his own information)
            if authenticated_userid(request) == user.username:
                # do the update (so far only email)
                if email:
                    user.email = email
                    import transaction
                    transaction.commit()
                    ret['success'] = True
                    ret['msg'] = 'Information successfully updated.'
                # do password update
                elif new_password and old_password:
                    # check old password first
                    if User.check_password(username, old_password):
                        user.password = new_password
                        import transaction
                        transaction.commit()
                        ret['success'] = True
                        ret['msg'] = 'Password successfully updated.'
                    else:
                        ret['msg'] = 'Wrong password.'
            else:
                ret['msg'] = 'You do not have the right to update this information.'
                return ret
        except NoResultFound:
            ret['msg'] = 'There is no user with this username.'
            return ret
    return ret
Esempio n. 6
0
    def authenticated_userid(self, request):
        # First handle request made with HTTP Basic Authentication.
        # Such request can e.g. come from external clients like a QGIS plugin
        credentials = self._get_basicauth_credentials(request)
        if credentials is not None:
            if User.check_password(credentials["login"], credentials["password"]):
                # Return the user id if the login and password are correct
                return credentials["login"]
            else:
                raise HTTPUnauthorized()

        return AuthTktAuthenticationPolicy.authenticated_userid(self, request)
Esempio n. 7
0
    def login_json(self):
        """
        Login controller
        """
        # Prevent an empty header if /login is directly requested (should
        # actually never happen)
        headers = []
        body = self.request.json_body
        login = body.get('login')
        password = body.get('password')

        if User.check_password(login, password):
            log.debug('Login succeed')
            headers = remember(
                self.request, login,
                max_age=timedelta(days=30).total_seconds())
            self.request.response.headerlist.extend(headers)
            return {'login': '******'}
        else:
            log.debug('Login failed')
            headers = forget(self.request)
            return {'login': '******'}