示例#1
0
文件: user.py 项目: AnneGilles/c3sar
def user_view(request):
    user_id = request.matchdict['user_id']
    user = User.get_by_user_id(user_id)

    if isinstance(user, NoneType):
        return HTTPFound(location=route_url('not_found', request))

    # calculate for next/previous navigation
    max_id = User.get_max_id()
    # previous
    if user.id == 1:            # if looking at first id
        prev_id = max_id        # --> choose highest db row, 'wrap around'
    else:                       # if looking at any other id
        prev_id = user.id - 1   # --> choose previous
    # next
    if user.id != max_id:       # if not on highest id
        next_id = user.id + 1   # --> choose next
    elif user.id == max_id:     # if highest id
        next_id = 1             # --> choose first id ('wrap around'))

    # show who is watching. maybe we should log this ;-)
    viewer_username = authenticated_userid(request)

    return {
        'blank': 'blank',
        'user': user,
        'viewer_username': viewer_username,
        'prev_id': prev_id,
        'next_id': next_id,
        }
示例#2
0
 def user(self):
     userid = unauthenticated_userid(self)
     #print "--- in RequestWithUserAttribute: userid = " + str(userid)
     if userid is not None:
         # this should return None if the user doesn't exist
         # in the database
         #return dbsession.query('users').filter(user.user_id == userid)
         return User.check_user_or_None(userid)
     # else: userid == None
     return userid
示例#3
0
 def test_get_by_user_id(self):
     if DEBUG:  # pragma: no cover
         print "----- this is UserModelTests.test_get_by_user_id"
     instance = self._makeOne()
     self.session.add(instance)
     self.session.flush()  # to get the id from the db
     from c3sar.models import User
     result = User.get_by_user_id(1)
     self.assertEqual(instance.username, 'SomeUsername')
     self.assertEqual(result.username, 'SomeUsername')
示例#4
0
 def test_check_username_exists(self):
     if DEBUG:  # pragma: no cover
         print "----- this is UserModelTests.test_check_username_exists"
     instance = self._makeOne()
     self.session.add(instance)
     self.session.flush()  # to get the id from the db
     from c3sar.models import User
     # this one does not extst
     result = User.check_username_exists(u'SomeUsernameNot')
     #print "UserModelTests.test_check_username_exists: result:"
     #      + str(result)
     #print "UserModelTests.test_check_username_exists: type(result):"
     #      + str(type(result))
     self.assertFalse(result, "result was not False")
     # this one must exist, return True
     result = User.check_username_exists(u'SomeUsername')
     #print "UserModelTests.test_check_username_exists: result:"
     #      + str(result)
     #print "UserModelTests.test_check_username_exists: type(result):"
     #      + str(type(result))
     self.assertTrue(result, "result was not True")
示例#5
0
文件: user.py 项目: AnneGilles/c3sar
def user_confirm_email(request):
    """
    this view takes three arguments from the URL aka request.matchdict
    - code
    - user name
    - user email
    and tries to match them to database entries.
    if matching is possible,
    - the email address in question is confirmed as validated
    - the database entry is changed to reflect this
    """
    # values from URL/matchdict
    conf_code = request.matchdict['code']
    user_name = request.matchdict['user_name']
    user_email = request.matchdict['user_email']

    #get matching user from db
    user = User.get_by_username(user_name)

    # check if the information in the matchdict makes sense
    #  - user
    if isinstance(user, NoneType):
        #print "user is of type NoneType"
        return {
            'result_msg':
            "Something didn't work. "
            "Please check whether you tried the right URL."
            }
    # - email
    if (user.email == user_email):
        #print "this one matched! " + str(user_email)

        if (user.email_is_confirmed):
            #print "confirmed already"
            return {'result_msg': "Your email address was confirmed already."}
        # - confirm code
        #print "checking confirmation code..."
        if (user.email_confirm_code == conf_code):
            #print "conf code " + str(conf_code)
            #print "user.conf code " + str(user.email_confirm_code)

            #print " -- found the right confirmation code in db"
            #print " -- set this email address as confirmed."
            user.email_is_confirmed = True
            return {'result_msg':
                    "Thanks! Your email address has been confirmed."}
    # else
    return {'result_msg': "Verification has failed. Bummer!"}
示例#6
0
文件: user.py 项目: AnneGilles/c3sar
def user_contract_de_username(request):
    """
    get a PDF for the user to print out, sign and mail back

    special feature: username in filename
    """

    try:
        username = request.matchdict['username']
        user = User.get_by_username(username)
        assert(isinstance(user, User))
        if DEBUG:  # pragma: no cover
            print "about to generate pdf for user " + str(user.username)
        return generate_contract_de_fdf_pdf(user)
    except Exception, e:
        if DEBUG:  # pragma: no cover
            print "something failed:"
            print e
        return HTTPFound(location=route_url('home', request))
示例#7
0
文件: user.py 项目: AnneGilles/c3sar
def user_set_default_license(request):
    """
    let users change some of their details
    """
    dbsession = DBSession()

    user_id = request.matchdict['user_id']
    user = User.get_by_user_id(user_id)

    form = Form(request, schema=UserDefaultLicenseSchema, obj=user)

    if 'form.submitted' in request.POST and form.validate():
        request.session.flash('form validated!')

    return {
        'the_user_id': user_id,
        'the_username': user.username,
        'form': FormRenderer(form),
        }
示例#8
0
文件: user.py 项目: AnneGilles/c3sar
def user_profile(request):
    user_id = request.matchdict['user_id']
    user = User.get_by_user_id(user_id)

    # calculate for next/previous navigation
    prev_id = int(user_id) - 1
    next_id = int(user_id) + 1
    # ToDo: what if foo_id == 0 or nonexistant?
    # maybe use template logic to not show prev-next-link?
    # maybe try to figure out max_id? what is cheaper? just fail/404?
    # we need the 404 anyway, if user picks random url/user_id

    # show who is watching. maybe we should log this ;-)
    viewer_username = authenticated_userid(request)

    return {
        'user': user,
        'viewer_username': viewer_username,
        'prev_id': prev_id,
        'next_id': next_id,
        }
示例#9
0
文件: basic.py 项目: AnneGilles/c3sar
    try:
        num_users = dbsession.query(User).count()
        num_tracks = dbsession.query(Track).count()
        # num_tracks = 0
        num_bands = dbsession.query(Band).count()
        # num_bands = 0
    except ProgrammingError, pe:
        # ProgrammingError: (ProgrammingError)
        # SQLite objects created in a thread can only be used in that same
        # thread.The object was created in thread id -1333776384
        # and this is thread id -1329573888
        print "not a bug, a feature: logout first, please!"
        return HTTPFound(route_url('logout', request))

    logged_in = authenticated_userid(request)
    user_id = User.get_by_username(logged_in)

    return dict(
        logged_in=logged_in,
        num_users=num_users,
        num_tracks=num_tracks,
        num_bands=num_bands,
        user_id=user_id
        )


# ######################################################### listen

@view_config(route_name='listen',
             renderer='../templates/listen.pt',
             permission='view')
示例#10
0
 def _to_python(self, username, state):
     if not User.get_by_username(username):
         raise formencode.Invalid("That username does not exist", username, state)
     return username
示例#11
0
 def _to_python(self, username, state):
     if User.get_by_username(username):
         raise formencode.Invalid("That username already exists", username, state)
     return username
示例#12
0
 def __getitem__(self, key):
     user = User.get_by_user_id(key)
     user.__parent__ = self
     user.__name__ = key
     return user
示例#13
0
文件: user.py 项目: AnneGilles/c3sar
def user_register(request):
    """
    a user registers with the system
    """
    DEBUG = False
    form = Form(request, RegistrationSchema)
    #mailer = get_mailer(request)

    # create a random string for email verification procedure
    # http://stackoverflow.com/questions/2257441/
    #   python-random-string-generation-with-upper-case-letters-and-digits
    N = 6
    randomstring = ''.join(random.choice(string.ascii_uppercase
                                         + string.digits) for x in range(N))
    #print " -- the random string: " + randomstring

    URL = "localhost:6543"
    # ToDo XXX change this to be more generic

    if 'form.submitted' in request.POST and not form.validate():
        # form didn't validate
        request.session.flash('form does not validate!')
        if DEBUG:  # pragma: no cover
            print "submitted, but not validated"
    else:  # pragma: NO COVER # just for debugging, RLY
        if DEBUG:
            print "form.submitted was not seen"
        pass

    if 'form.submitted' in request.POST and form.validate():
        # ready for registration!
        #request.session.flash('form validated!')
        username = unicode(form.data['username'])

        message = Message(
            subject="C3S: confirm your email address",
            sender="*****@*****.**",
            recipients=[form.data['email']],
            body="Hello, " + form.data['surname'] + ", \n"
            "Please confirm your email address by clicking this link: \n"
            "http://" + URL + "/user/confirm/" + randomstring + "/"
            + form.data['username'] + " \n"
            "Thanks!")
        msg_accountants = Message(
            subject="[C3S] new member registration",
            sender="*****@*****.**",
            recipients=['*****@*****.**'],
            body="Hello \n"
            "A new member has registered with your site: \n"
            "Username: "******" \n"
            "First name: " + form.data['surname'] + " \n"
            "Last name: " + form.data['lastname'] + " \n"
            "Email: " + form.data['email'] + " \n"
            "Thanks!")

        user = User(
            username=username,
            password=unicode(form.data['password']),
            surname=unicode(form.data['surname']),
            lastname=unicode(form.data['lastname']),
            email=unicode(form.data['email']),
            email_is_confirmed=False,
            email_confirm_code=unicode(randomstring),
            phone=unicode(form.data['phone']),
            fax=unicode(form.data['fax']),
            )
        user.set_address(street=unicode(form.data['street']),
                         number=unicode(form.data['number']),
                         postcode=unicode(form.data['postcode']),
                         city=unicode(form.data['city']),
                         country=unicode(form.data['country']),
                         )

        user_group = Group.get_Users_group()
        user.groups = [user_group]

        # dbsession.add(user)
        dbsession.flush(user)

        #
        # boto stuff: creating a bucket for that user
        # don't do that -- we better have one bucket for all tracks...
        #
        # from boto.exception import S3CreateError, BotoServerError
        # try:
        #     c3sI2Conn.create_named_bucket(username)
        #     request.session.flash(u'created bucket for ' + username)
        # except BotoServerError, e:
        #     print("There was an error: " + str(e) )
        # except S3CreateError, e:
        #     print("There was an error: " + str(e) )
        #
        # send email
        try:
            if DEBUG:  # pragma: no cover
                print("sending email........")
            else:
                pass
            #mailer.send(message)
            #mailer.send(msg_accountants)

            # instead of sending mails, we inform in-browser
            request.session.flash(
                'DEBUG: not sending email. to test email confirmation view, '
                'append this to URL to confirm email: /user/confirm/'
                + randomstring + '/'
                + str(user.username) + '/' + str(form.data['email']))
        except:  # pragma: no cover
            print "could not send email. no mail configured?"

        # remember who this was == sign in user == log her in
        headers = remember(request, username)

        redirect_url = route_url('home', request)

        return HTTPFound(location=redirect_url, headers=headers)

    return {'form': FormRenderer(form), }
示例#14
0
文件: user.py 项目: AnneGilles/c3sar
def user_list(request):
    users = User.user_listing(User.id.desc())
    return {'users': users}
示例#15
0
文件: user.py 项目: AnneGilles/c3sar
def login_view(request):
    DEBUG = False
    msg = u''
    if DEBUG:  # pragma: no cover
        print "this is login_view"

    # see https://github.com/Pylons/pyramid/blob/master/docs/tutorials/
    #                         wiki2/src/authorization/tutorial/views.py
    login_url = request.route_url('login')
    referrer = request.url
    if referrer == login_url:  # pragma: no cover
        referrer = '/'
    came_from = request.params.get('came_from', referrer)

    headers = None
    logged_in = authenticated_userid(request)
    if logged_in is not None:  # need to find testcase to cover...
        request.session.flash('you are logged in already!')
        #print('you are logged in already!')
        return HTTPFound(location=came_from,
                         headers=headers)

    if logged_in is None:
        request.session.pop_flash()

    form = Form(request, LoginSchema)

    logged_in = authenticated_userid(request)
    request.session.flash(logged_in)

    login = ''
    password = ''

    post_data = request.POST

    if not 'submit' in post_data:
        if DEBUG:  # pragma: no cover
            request.session.flash('not submitted!')
            print "not submitted"

    if 'submit' in post_data and not form.validate():
        if DEBUG:  # pragma: no cover
            request.session.flash(u'form didnt validate')
            print 'form didnt validate'

    if 'submit' in post_data and form.validate():

        login = post_data['username']
        if DEBUG:  # pragma: no cover
            request.session.flash(u'username: '******'username: '******'password']
        if DEBUG:  # pragma: no cover
            request.session.flash(password)
            print "password: "******"home_view: " + str(home_view)
                #print "came_from: " + str(came_from)
                print "will login the user and redirect her"
            return HTTPFound(
                location=route_url(u'home', request=request), headers=headers)

        else:
            request.session.flash(
                u"username and password didn't match!",  # message
                'passwordcheck')                        # to queue
            msg = u"username and password didn't match!"
            if DEBUG:  # pragma: no cover
                request.session.flash(u'User.check_password was NOT True!')
                print 'User.check_password was NOT True!'
                request.session.flash(
                    u'account not found or passwords didnt match')

    if DEBUG:  # pragma: no cover
        request.session.flash(u'Failed to login. Musta been errors!')
        print "returning the form"
    return {
        'form': FormRenderer(form),
        'msg': msg,
        }
示例#16
0
文件: user.py 项目: AnneGilles/c3sar
    DEBUG = False

    if not has_permission('editUser', request.context, request):
        #print "NOT has_permission !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        request.message = "You do not have permissions to edit this user!"
        raise HTTPForbidden

   # if no user_id in URL and not logged in, tell user to login

    try:
        user_id = request.matchdict['user_id']
    except KeyError, ke:
        #print ke
        return HTTPFound(location=request.route_url('not_found'))

    user = User.get_by_user_id(user_id)

    if user is None:
        msg = "User was not founf in database."
        return HTTPFound(location=request.route_url('not_found'))

    form = Form(request, schema=UserSettingsSchema, obj=user)

    if 'form.submitted' in request.POST and not form.validate():
        # form didn't validate
        request.session.flash('Please check the form below for errors!')
        if DEBUG:  # pragma: no cover
            print "submitted but not validated!"

    if 'form.submitted' in request.POST and form.validate():
        # ready for changing database entries!