Ejemplo n.º 1
0
 def get(self, key):
     if not len(key):
         return util.error(self, 404, 'No level specified')
     lvl = db.get(db.Key(key))
     if not lvl:
         return util.error(self, 404, 'Level not found')
     util.render(self, 'level/read.html', {'level': lvl.getDict(), 'title': lvl.title})
Ejemplo n.º 2
0
    def post(self):
        name = self.request.get('name')
        #uid = TODO get User ID

        #create levelSet

        util.render(self, 'set/read.html', {'name': name})
Ejemplo n.º 3
0
Archivo: read.py Proyecto: naoyat/latin
 def pp(info):
     pos = info['pos']
     if pos == 'n':
         cases_ja = [latin1.cases_ja[case[0:3]] + case[3:6] for case in info['case'].split('/')]
         return util.render([pos, info['base'], info['case'], info['gender'], info['ja'], cases_ja])
     else:
         return util.render(info)
Ejemplo n.º 4
0
    def create_board_post(self, board_name, board_id, current_uid = -1):
        board_info = board.get_board_info(board_id)
        if not acl.is_allowed('board', board_id, current_uid, 'create'):
            return util.render().error(error_message = _('NO_PERMISSION'), help_context='error')
        user_data = web.input()
        comment = 1 if user_data.has_key('commentable') else 0
        write_by_other = 1 if user_data.has_key('writable') else 0
        indexable = 1 if user_data.has_key('indexable') else 0
        show_avatar = 1 if user_data.has_key('show_avatar') else 0

        owner_uid = user._get_uid_from_username(user_data.owner)
        if owner_uid < 0:
            return util.render().error(error_message=_('NO_SUCH_USER_FOR_BOARD_ADMIN'), help_context='error')
        if user_data.name.strip() == '':
            return util.render().error(error_message = _('NO_NAME_SPECIFIED'), help_context='error')
        if board_name == '^root':
            new_path = posixpath.join('/', user_data.name)
        else:
            new_path = posixpath.join('/', board_name, user_data.name)
        if board._get_board_id_from_path(new_path) > 0:
            return util.render().error(error_message = _('BOARD_EXISTS'), help_context='error')

        settings = dict(path=new_path, board_owner = owner_uid,
                cover = user_data.information,
                description = user_data.description,
                type = int(user_data.type),
                guest_write = write_by_other,
                can_comment = comment,
                indexable = indexable, show_avatar = show_avatar,
                current_uid = current_uid)
        ret = board.create_board(board_id, settings)
        if ret[0] == False:
            return util.render().error(error_message = ret[1] ,help_context = 'error')
        raise web.seeother(util.link('%s') % (new_path))
Ejemplo n.º 5
0
    def modify_post(self, current_uid = -1):
        user_id = current_uid
        usr = user.get_user(user_id)[1]

        data = web.input(profile_image = {})
        if data.newpass1 and not user.verify_password(user_id, data.oldpass):
            return util.render().error(error_message=_('INVALID_PASSWORD'), help_context='error')
        if data.newpass1 != data.newpass2:
            return util.render().error(error_message = _('PASSWORD_DO_NOT_MATCH'), help_context='error')
        if len(data.newpass1) > 0 and len(data.newpass1) < 6:
            return util.render().error(error_message = _('PASSWORD_TOO_SHORT'), help_context='error')
        if len(data.newpass1) == 0:
            password = data.oldpass
        else:
            password = data.newpass1
        nick = data.nick
        email = data.email
        homepage = data.homepage
        sig = data.sig
        introduction = data.introduction
        language = data.language
        theme = data.theme
        user_info = user.get_user(user_id)
        change_lang = False
        if language != user_info[1].language:
            change_lang = True
        profile_image = data.profile_image.value
        delete_profile_image = data.has_key('delete_profile_image')

        ret = user.modify_user(user_id, locals())
        if change_lang:
            web.ctx.session.lang = language
        raise web.seeother(util.link('/+u'))
Ejemplo n.º 6
0
    def modify_post(self, board_name, board_id, current_uid = -1):
        board_info = board.get_board_info(board_id)
        if not acl.is_allowed('board', board_id, current_uid, 'modify'):
            return util.render().error(error_message=_('NO_PERMISSION'), help_context='error')
        data = web.input()
        comment = 1 if data.has_key('commentable') else 0
        write_by_other = 1 if data.has_key('writable') else 0
        indexable = 1 if data.has_key('indexable') else 0
        show_avatar = 1 if data.has_key('show_avatar') else 0

        owner_uid = user._get_uid_from_username(web.input().owner)
        if owner_uid < 0:
            return util.render().error(error_message=_('NO_SUCH_USER_FOR_BOARD_ADMIN'), help_context='error')

        board_info = dict(path = data.path, name = data.name,
                owner = owner_uid, board_type = int(data.type),
                can_comment = comment, can_write_by_other = write_by_other,
                indexable = indexable, show_avatar = show_avatar,
                stylesheet = data.stylesheet,
                description = data.description,
                cover = data.information)
        result = board.board_edit(current_uid, board_id, board_info)
        if result[0] == False:
            return util.render().error(error_message = result[1], help_context='error')
        else:
            raise web.seeother(util.link('%s') % result[1])
Ejemplo n.º 7
0
    def lost_login_post(self):
        data = web.input()
        recaptcha_url = 'http://www.google.com/recaptcha/api/verify'
        recaptcha_data = dict(challenge = data.recaptcha_challenge_field,
                response = data.recaptcha_response_field,
                remoteip = web.ctx.ip,
                privatekey = config.recaptcha_private_key)
        req = urllib2.Request(recaptcha_url, urllib.urlencode(recaptcha_data))
        response = urllib2.urlopen(req)
        page = response.read().split('\n')
        if page[0] == 'false':
            if page[1].strip() == 'incorrect-captcha-sol':
                return util.render().error(error_message = _('INCORRECT_CAPTCHA'), help_context='error')
            else:
                return util.render().error(error_message = _('CAPTCHA_ERROR'), help_context='error')
        found_users = user.get_user_from_email(data.email)
        if not found_users:
            return util.render().error(error_message = _('NO_SUCH_MAIL_ADDRESS'), help_context='error')
        salt_string = ''
        for u in found_users:
            salt = user.get_password_salt(u.uSerial)
            salt_string = salt_string + '* User %s: http://noah.kaist.ac.kr/+recover_password?id=%s&key=%s\n' % (u.uId, u.uId, salt)
        message_title = _('NOAH password recovery')
        message_body = _('''Dear NOAH user,

Some user on IP %s requested new password of your account(s). Following list contains your account(s). Click on the corresponding link for recovering password of account.

%s

If you did not requested password recovery, then please log in into your account. This link will not be vaild after logging into the account.''') % (web.ctx.ip, salt_string)
        mail.mail(data.email, message_title, message_body)
        return util.render().error(error_message = _('Message Sent. Please follow instructions on the message.'),
                error_class = _('Information'))
Ejemplo n.º 8
0
def saved(request, start=None):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        return util.render('error.pat', error='you need to login first')

    if not start:
        start = 0
    else:
        try:
            #/200
            start = int(start[1:])
        except ValueError:
            start = 0
        if start < 0:
            start = 0

    news, total = get_saved_news(g.user['id'], start, config.SavedNewsPerPage)
    hack_news(news)

    next = None
    if total > start + config.SavedNewsPerPage:
        next = start + config.SavedNewsPerPage
    return util.render('saved.pat',
                       news=news,
                       user=g.user,
                       start=start,
                       next=next)
Ejemplo n.º 9
0
    def recover_password_get(self):
        if web.ctx.query == '':
            qs = dict()
        else:
            # XXX: http://bugs.python.org/issue8136
            qs = parse_qs(urllib.unquote(web.ctx.query[1:]).encode('latin-1').decode('utf-8'))

        if not (qs.has_key('id') and qs.has_key('key')):
            return util.render().error(error_message = _('INVALID_LINK'),
                    help_context = 'error')
        user_id = qs['id'][0]
        key = qs['key'][0]
        uid = user._get_uid_from_username(user_id)
        if uid < 0:
            return util.render().error(error_message = _('INVALID_USERNAME'),
                    help_context = 'error')
        if user.get_password_salt(uid) != key:
            return util.render().error(error_message = _('INVALID_PASSWORD_KEY'),
                    help_context = 'error')

        self.session_set(user_id)
        web.ctx.session.persistent = False
        user.update_last_login(uid, web.ctx.ip)
        new_pw = user.generate_random_password()
        user.update_password(uid, new_pw)
        return util.render().error(error_message = _('Your temporary password is "%s"(case-sensitive). Change password now.') % new_pw,
                error_class = _('Information'))
Ejemplo n.º 10
0
def callback(request):
    auth_user(request.cookies.get('auth'))
    if g.user:
        return util.redirect('/')

    oauth_client = oauth2.Client2(oauth_settings['client_id'],
                                  oauth_settings['client_secret'],
                                  oauth_settings['base_url'])

    code = request.GET.get('code')
    if not code:
        return util.render('error.pat', user=None, error="no code")

    try:
        data = oauth_client.access_token(code, oauth_settings['redirect_url'])
    except Exception as e:
        return util.render('error.pat',
                           user=None,
                           error="failed to get access token, try again")
    access_token = data.get('access_token')

    (headers, body) = oauth_client.request('https://api.github.com/user',
                                           access_token=access_token,
                                           token_param='access_token')

    error = 0
    try:
        if headers['status'] == '200':
            user = json.loads(body)
            username = user['login']
            email = user.get('email', '')
        else:
            error = 1
    except Exception as e:
        error = 1

    if error:
        return util.render('error.pat',
                           user=None,
                           error='bad login, try again')

    user = get_user_by_name(username)
    if not user:
        #create new user
        auth, msg = create_user_github(username, email)
        if not auth:
            return util.render('error.pat', user=None, error=msg)
    else:
        if 'g' in user['flags']:
            auth = user['auth']
        else:
            return util.render('error.pat',
                               user=None,
                               error='account exists :(')

    res = webob.exc.HTTPTemporaryRedirect(location='/')
    res.headers['Set-Cookie'] = 'auth=' + auth + \
        '; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/'
    return res
Ejemplo n.º 11
0
def callback(request):
    auth_user(request.cookies.get('auth'))
    if g.user:
        return util.redirect('/')

    oauth_client = oauth2.Client2(
        oauth_settings['client_id'],
        oauth_settings['client_secret'],
        oauth_settings['base_url']
        )

    code = request.GET.get('code')
    if not code:
        return util.render('error.pat', user=None,
                           error="no code")

    try:
        data = oauth_client.access_token(code, oauth_settings['redirect_url'])
    except Exception as e:
        return util.render('error.pat', user=None,
                           error="failed to get access token, try again")
    access_token = data.get('access_token')

    (headers, body) = oauth_client.request(
        'https://api.github.com/user',
        access_token=access_token,
        token_param='access_token'
        )

    error = 0
    try:
        if headers['status'] == '200':
            user = json.loads(body)
            username = user['login']
            email = user.get('email', '')
        else:
            error = 1
    except Exception as e:
        error = 1

    if error:
        return util.render('error.pat', user=None, error='bad login, try again')

    user = get_user_by_name(username)
    if not user:
        #create new user
        auth, msg = create_user_github(username, email)
        if not auth:
            return util.render('error.pat', user=None, error=msg)
    else:
        if 'g' in user['flags']:
            auth = user['auth']
        else:
            return util.render('error.pat', user=None, error='account exists :(')

    res = webob.exc.HTTPTemporaryRedirect(location='/')
    res.headers['Set-Cookie'] = 'auth=' + auth + \
        '; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/';
    return res
Ejemplo n.º 12
0
 def get(self):
     #get key
     ls = models.getUserLevelSet()
     self.redirect("/levelSet/" + str(ls.key()))
     return
     #old stuff
     levelSets = models.getUserLevelSets()
     util.render(self, 'user/read.html', {'levelSets': levelSets, 'user': models.getCurrentUser()})
Ejemplo n.º 13
0
 def caller(self, board_name, action, article_id, method):
     board_id = board._get_board_id_from_path(board_name)
     if board_id < 0:
         raise web.notfound(util.render().error(error_message = _('INVALID_BOARD'), help_context='error'))
     try:
         return eval('self.%s_%s' % (action, method))(board_name, board_id, int(article_id))
     except AttributeError:
         raise web.notfound(util.render().error(error_message = _('INVALID_ACTION'), help_context='error'))
Ejemplo n.º 14
0
 def GET(self, username, current_uid = -1):
     user_id = user._get_uid_from_username(username)
     if user_id < 0:
         raise web.notfound(util.render().error(error_message = _('NO_SUCH_USER'), help_context='error'))
     return util.render().myinfo(user = user.get_user(user_id)[1],
             user_id = user_id,
             title = _('User Information'), board_desc = _('User Information'),
             help_context='myinfo')
Ejemplo n.º 15
0
 def delete_post(self, board_name, board_id, article_id, current_uid = -1):
     if not acl.is_allowed('article', article_id, current_uid, 'delete'):
         return util.render().error(error_message = _('NO_PERMISSION'), help_context='error')
     ret = article.delete_article(current_uid, article_id)
     attachment.remove_all_attachment(article_id)
     if ret[0] == True:
         raise web.seeother(util.link('/%s') % (board_name))
     else:
         return util.render().error(error_message = ret[1], help_context='error')
Ejemplo n.º 16
0
def search_byname_view(request):

    error_message = None

    bank = request.user.get_profile().bank

    if request.POST:
        #name_terms = request.POST['namecontains']
        # TODO: I am a terrible person. 
        name_terms = request.POST['term1']
        if request.POST['term2'] != "":
            name_terms += " " + request.POST['search_type'].upper() + " " + \
                    request.POST['term2']
        if request.POST['term3'] != "":
            name_terms += " " + request.POST['search_type'].upper() + " " + \
                    request.POST['term3']
        if request.POST['term4'] != "":
            name_terms += " " + request.POST['search_type'].upper() + " " + \
                    request.POST['term4']

        logger.info(name_terms)

        if len(name_terms.strip()) < 1:
            error_message = "No search terms entered!"
        else:
            if " AND " in name_terms:
                # split on any AND's and strip any remaining whitespace
                name_contains = [a.strip() for a in name_terms.split(' AND ')]

                risks = BankRisk.objects.filter(bank=bank)
                for i in name_contains:
                    risks = risks.filter(
                            name__contains=i,
                    )
            else:

                # split on any OR's and strip any remaining whitespace
                name_contains = [a.strip() for a in name_terms.split(' OR ')]

                risks = []
                for i in name_contains:
                    risks.extend(BankRisk.objects.filter(
                            bank=bank,
                            name__contains=i,
                    ))

            # set the search results session var
            # request.session['search_results'] = risks
            return render('search_results.html',
                          { 'risks': risks,
                            'method': "by Name",
                            'search_again': "name", },
                          request)

    return render('search_byname.html',
                  { 'error_message': error_message }, 
                  request)
Ejemplo n.º 17
0
def newspage(request, news_id):
    auth_user(request.cookies.get('auth'))
    news = get_news_by_id(news_id)
    if not news:
        return util.render('error.pat', user=g.user,
                           error="the news does not exist")

    hack_news(news)
    return util.render('news.pat', user=g.user, news=news)
Ejemplo n.º 18
0
    def search_get(self, board_name, board_id):
        board_info = board.get_board_info(board_id)
        if web.ctx.query == '':
            qs = dict()
        else:
            # XXX: http://bugs.python.org/issue8136
            qs = parse_qs(urllib.unquote(web.ctx.query[1:]).encode('latin-1').decode('utf-8'))

        if not qs.has_key('q'):
            return util.render().error(error_message = _('NO_KEYWORD_SPECIFIED'),
                    help_context = 'error')
        keyword = qs['q'][0]
        if qs.has_key('size'):
            page_size = int(qs['size'][0])
        else:
            page_size = config.page_size
        if qs.has_key('page'):
            page_no = int(qs['page'][0])
        else:
            page_no = 1
        author = False
        title = True
        body = True
        if qs.has_key('author'):
            author = True
            title = False
            body = False
        if qs.has_key('title'):
            title = True
            body = False
        if qs.has_key('body'):
            body = True
        ret = article.search_article(board_id, keyword, page_size, page_no,
                author, title, body)
        search_qs = "/+search?"
        if author:
            search_qs += "author=1&"
        if title:
            search_qs += "title=1&"
        if body:
            search_qs += "body=1&"
        if keyword:
            search_qs += "q=%s" % urllib.quote(keyword.encode('utf-8'))
        if ret[0]:
            return util.render().board(lang="ko",
                title = board_info.bName,
                board_path = board_info.bName[1:],
                board_desc = _('Search Results'),
                stylesheet = board_info.stylesheet,
                articles=ret[2], marked_articles = [],
                total_page = ret[1], page = page_no, feed = False,
                help_context = 'view_board', indent = False,
                author_checked = author, title_checked = title,
                body_checked = body, search_keyword = keyword,
                search_qs = search_qs)
        else:
            return util.render().error(error_message = ret[1], help_context='error')
Ejemplo n.º 19
0
def documentation(request, path='documentation'):
    if '.' in path[-5:]:
        template = 'documentation/%s' % path
    else:
        template = 'documentation/%s.html' % path
    try:
        return render(template, request, context_dict={'navigation_pos': 'documentation'})
    except TemplateDoesNotExist:
        return render('coming-soon.html', request, context_dict={'navigation_pos': 'documentation'})
Ejemplo n.º 20
0
def score_functions(request):
    #TODO: make it part of index/package configuration
    account = request.user.get_profile().account
    if request.method == 'GET':
        index_code = request.GET['index_code']
        index = Index.objects.get(code=index_code)

        functions = get_functions(index)

        form = ScoreFunctionForm()

        context = {
            'form': form,
            'account': request.user.get_profile().account,
            'navigation_pos': 'dashboard',
            'functions': functions,
            'index_code': index_code,
            'functions_available': len(functions) < functions_number,
        }

        return render('score_functions.html', request, context_dict=context)
    else:
        form = ScoreFunctionForm(data=request.POST)

        if form.is_valid():
            index_code = request.POST['index_code']
            index = Index.objects.get(code=index_code)
            name = form.cleaned_data['name']
            definition = form.cleaned_data['definition']

            client = ApiClient(account.get_private_apiurl()).get_index(
                index.name)
            try:
                client.add_function(int(name), definition)
            except InvalidDefinition, e:
                index = Index.objects.get(code=index_code)
                functions = get_functions(index)
                form = ScoreFunctionForm(initial={
                    'name': name,
                    'definition': definition
                })
                messages.error(request, 'Problem processing your formula: %s',
                               str(e))

                context = {
                    'form': form,
                    'account': request.user.get_profile().account,
                    'navigation_pos': 'dashboard',
                    'functions': functions,
                    'index_code': index_code,
                    'functions_available': len(functions) < functions_number,
                }

                return render('score_functions.html',
                              request,
                              context_dict=context)
Ejemplo n.º 21
0
def newspage(request, news_id):
    auth_user(request.cookies.get('auth'))
    news = get_news_by_id(news_id)
    if not news:
        return util.render('error.pat',
                           user=g.user,
                           error="the news does not exist")

    hack_news(news)
    return util.render('news.pat', user=g.user, news=news)
Ejemplo n.º 22
0
 def delete_get(self, board_name, board_id, article_id, current_uid = -1):
     if not acl.is_allowed('article', article_id, current_uid, 'delete'):
         return util.render().error(error_message = _('NO_PERMISSION'), help_context='error')
     default_referer = os.path.join(util.link('/'), board_name, '+read', str(article_id))
     action=os.path.join(util.link('/'), board_name, '+delete', str(article_id))
     return util.render().question(
             question=_('Do you want to delete the article?'),
             board_path = board_name, 
             board_desc = _('Confirmation'), title=_('Confirmation'),
             action = action,
             referer=web.ctx.env.get('HTTP_REFERER', default_referer))
Ejemplo n.º 23
0
    def GET(self, board_name):
        if board_name == '*' or board_name == '^root':
            v = board_actions()
            return v.subboard_list_get()

        board_id = board._get_board_id_from_path(board_name)
        if board_id < 0:
            #try to find regex match
            board_id = board._get_board_id_from_regex_path(board_name)
            if board_id < 0:
                raise web.notfound(util.render().error(lang='ko', error_message=_('INVALID_BOARD'), help_context='error'))
            else:
                path = board._get_path_from_board_id(board_id)
                raise web.seeother(util.link(path))

        board_info = board.get_board_info(board_id)
        if board_info.bType == 0: # 디렉터리
            v = board_actions()
            return v.subboard_list_get(board_name, board_id)
        elif board_info.bType == 2: # 넘겨주기
            board_id = board._get_board_id_from_path(board_info.bDescription)
            if board_id < 0 or board_info.bDescription.strip() == '':
                raise web.notfound(util.render().error(lang='ko', error_message=_('INVALID_ALIAS'), help_context='error'))
            else:
                raise web.seeother(util.link(board_info.bDescription))

        #processing new_article
        if web.ctx.session.has_key('uid'):
            uid = web.ctx.session.uid
            user.update_unreaded_articles_board(uid, board_id)

        qs = web.ctx.query
        if len(qs) > 0:
            qs = qs[1:]
            qs = parse_qs(qs)


        t = article._get_total_page_count(board_id, config.page_size)
        if qs:
            page = int(qs['page'][0])
        else:
            page = t

        a = article.get_article_list(board_id, config.page_size, page)
        m = article.get_marked_article(board_id)

        return util.render().board(lang="ko",
            title = board_info.bName,
            board_path = board_info.bName[1:],
            board_desc = board_info.bDescription,
            stylesheet = board_info.stylesheet,
            articles=a, marked_articles = m,
            total_page = t, page = page, feed = True,
            help_context = 'board')
Ejemplo n.º 24
0
 def write_get(self, board_name, board_id, current_uid = -1):
     board_info = board.get_board_info(board_id)
     if board_info.bType != 1:
         raise web.notfound(util.render().error(error_message = _('CANNOT_WRITE_ON_THIS_BOARD'), help_context='error'))
     board_desc = board_info.bDescription
     user_info = user.get_user(current_uid)[1]
     return util.render().article_edit(
             title = _('Write article - %s') % (board_name),
             action='write', action_name = _('Write article'),
             board_path = board_name, board_desc = board_desc, lang="ko",
             stylesheet = board_info.stylesheet,
             body = '\n\n\n%s' % user_info['uSig'], help_context='article_edit')
Ejemplo n.º 25
0
    def manage_subscription_post(self, current_uid = -1):
        data = web.input()
        favorite_add = False
        favorite_delete = False
        favorite_delete_list = []
        favorite_name = ''

        subscription_add = False
        subscription_delete = False
        subscription_delete_list = []
        subscription_name = ''

        for k in data.keys():
            if k.startswith('favorite_delete_'):
                favorite_delete_list.append(int(k[16:]))
            elif k.startswith('subscription_delete_'):
                subscription_delete_list.append(int(k[20:]))
            elif k == 'favorite_add':
                favorite_add = True
            elif k == 'favorite_delete':
                favorite_delete = True
            elif k == 'favorite_name':
                favorite_name = data[k]
            elif k == 'subscription_add':
                subscription_add = True
            elif k == 'subscription_delete':
                subscription_delete = True
            elif k == 'subscription_name':
                subscription_name = data[k]

        if favorite_add == True:
            if favorite_name.strip() == '':
                raise web.seeother(util.link('/+u/+manage_subscription'))
            board_id = board._get_board_id_from_path(favorite_name)
            if board_id < 0:
                raise web.notfound(util.render().error(lang='ko', error_message=_('INVALID_BOARD'), help_context='error'))
            user.add_favorite_board(current_uid, board_id)
        elif favorite_delete == True:
            for b in favorite_delete_list:
                user.remove_favorite_board(current_uid, b)
        elif subscription_add == True:
            if favorite_name.strip() == '':
                raise web.seeother(util.link('/+u/+manage_subscription'))
            board_id = board._get_board_id_from_path(subscription_name)
            if board_id < 0:
                raise web.notfound(util.render().error(lang='ko', error_message=_('INVALID_BOARD'), help_context='error'))
            user.add_subscription_board(current_uid, board_id)
        elif subscription_delete == True:
            for b in subscription_delete_list:
                user.remove_subscription_board(current_uid, b)

        raise web.seeother(util.link('/+u/+manage_subscription'))
Ejemplo n.º 26
0
def documentation(request, path='documentation'):
    if '.' in path[-5:]:
        template = 'documentation/%s' % path
    else:
        template = 'documentation/%s.html' % path
    try:
        return render(template,
                      request,
                      context_dict={'navigation_pos': 'documentation'})
    except TemplateDoesNotExist:
        return render('coming-soon.html',
                      request,
                      context_dict={'navigation_pos': 'documentation'})
Ejemplo n.º 27
0
    def comment_post(self, board_name, board_id, article_id, current_uid = -1):
        if not acl.is_allowed('board', board_id, current_uid, 'comment'):
            return util.render().error(error_message=_('NO_PERMISSION'), help_context='error')
        comment = web.input().comment
        board_info = board.get_board_info(board_id)
        ret = article.write_comment(current_uid, board_id, article_id, comment)
        if ret[0] == True:
            user.update_unreaded_articles_board(current_uid, board_id)
            user.read_article(current_uid, ret[1])

            raise web.seeother(util.link('/%s/+read/%s') % (board_name, article_id))
        else:
            return util.render().error(error_message = ret[1], help_context='error')
Ejemplo n.º 28
0
 def get(self, key):
     if not len(key):
         lvl = models.getDefaultGame()
         levelSetName = self.request.get('levelSetName')
         if levelSetName:
             lvl['levelSetName'] = levelSetName
     else:
         lvl = db.get(db.Key(key))
         lvl.levelSetName = lvl.levelSet.name
         if not lvl:
             return util.error(self, 404, 'Level not found')
         lvl = lvl.getDict()
     util.render(self, 'level/edit.html', {'level': lvl})
Ejemplo n.º 29
0
    def leave_post(self, current_uid = -1):
        user_id = current_uid
        usr = user.get_user(user_id)[1]

        password = web.input().password
        if not user.verify_password(user_id, password):
            return util.render().error(error_message= _('INVALID_PASSWORD'), help_context='error')

        result = user.delete_user(user_id)
        if not result[0]:
            return util.render().error(error_message = result[1], help_context='error')
        web.ctx.session.uid = 0
        web.ctx.session.kill()
        raise web.seeother(util.link('/'))
Ejemplo n.º 30
0
def score_functions(request):
    #TODO: make it part of index/package configuration
    account = request.user.get_profile().account
    if request.method == 'GET':
        index_code = request.GET['index_code']
        index = Index.objects.get(code=index_code)
    
        functions = get_functions(index)
    
        form = ScoreFunctionForm()
     
        context = {
          'form': form,
          'account': request.user.get_profile().account,
          'navigation_pos': 'dashboard',
          'functions': functions,
          'index_code': index_code,
          'functions_available': len(functions) < functions_number,
        }
        
        return render('score_functions.html', request, context_dict=context)
    else:
        form = ScoreFunctionForm(data=request.POST)
    
        if form.is_valid():
            index_code = request.POST['index_code']
            index = Index.objects.get(code=index_code)
            name = form.cleaned_data['name']
            definition = form.cleaned_data['definition']       
    
            client = ApiClient(account.get_private_apiurl()).get_index(index.name)
            try:
                client.add_function(int(name), definition)
            except InvalidDefinition, e: 
                index = Index.objects.get(code=index_code)
                functions = get_functions(index)
                form = ScoreFunctionForm(initial={'name': name, 'definition': definition})
                messages.error(request, 'Problem processing your formula: %s', str(e))
              
                context = {
                    'form': form,
                    'account': request.user.get_profile().account,
                    'navigation_pos': 'dashboard',
                    'functions': functions,
                    'index_code': index_code,
                    'functions_available': len(functions) < functions_number,
                }
    
                return render('score_functions.html', request, context_dict=context)
Ejemplo n.º 31
0
 def modify_get(self, board_name, board_id, article_id, current_uid = -1):
     if not acl.is_allowed('article', article_id, current_uid, 'modify'):
         return util.render().error(error_message = _('NO_PERMISSION'), help_context='error')
     board_info = board.get_board_info(board_id)
     board_desc = board_info.bDescription
     article_ = article.get_article(board_id, article_id)
     uploads = attachment.get_attachment(article_id)
     return util.render().article_edit(
             title = _('Modify - /%s')% board_name,
             stylesheet = board_info.stylesheet,
             action='modify/%s' % article_id, 
             action_name = _('Modify article'),
             board_path = board_name, board_desc = board_desc,
             article_title = article_.aTitle, body = article_.aContent,
             attachment = uploads, help_context = 'article_edit')
Ejemplo n.º 32
0
    def modify_get(self, board_name, board_id, current_uid = -1):
        board_info = board.get_board_info(board_id)
        if not acl.is_allowed('board', board_id, current_uid, 'modify'):
            return util.render().error(error_message=_('NO_PERMISSION'), help_context='error')
        if board_id == 1:
            board_name = '^root'
        default_referer = posixpath.join(util.link('/'), board_name, '+summary')

        return util.render().board_edit(
                action='modify', board_info = board_info,
                board_path = board_name, 
                board_desc = board_info.bDescription, 
                stylesheet = board_info.stylesheet,
                title = _('Modify information - %s') % (board_info.bName),
                referer = web.ctx.env.get('HTTP_REFERER', default_referer))
Ejemplo n.º 33
0
def create_index(request):
    account = request.user.get_profile().account
    if request.method == 'GET':
        index_qty = len(account.indexes.all())
        default_name = ''  #'Index_' + str(index_qty + 1)

        form = IndexForm(initial={'name': default_name})
        context = {
            'form': form,
            'account': request.user.get_profile().account,
            'navigation_pos': 'dashboard',
        }
        return render('new-index.html', request, context_dict=context)
    else:
        form = IndexForm(data=request.POST)
        if form.is_valid():
            try:
                client = ApiClient(account.get_private_apiurl())
                client.create_index(form.cleaned_data['name'])
                messages.success(request, 'New index created successfully.')
            except IndexAlreadyExists:
                context = {
                    'form': form,
                    'account': request.user.get_profile().account,
                    'navigation_pos': 'dashboard',
                }
                messages.error(request,
                               'You already have an Index with that name.')
                return render('new-index.html', request, context_dict=context)
            except TooManyIndexes:
                context = {
                    'form': form,
                    'account': request.user.get_profile().account,
                    'navigation_pos': 'dashboard',
                }
                messages.error(
                    request,
                    'You already have the maximum number of indexes allowed for your account. If you need more, please contact support.'
                )
                return render('new-index.html', request, context_dict=context)
            except Exception, e:
                print e
                messages.error(
                    request,
                    'Unexpected error creating the index. Try again in a few minutes'
                )
            return HttpResponseRedirect(reverse('dashboard'))
        else:
Ejemplo n.º 34
0
    def login_post(self):
        user_input = web.input()
        username, password = user_input.username.strip(), user_input.password.strip()
        referer = user_input.url.strip()
        if referer == '' or referer == 'None':
            referer = web.ctx.env.get('HTTP_REFERER', 'http://noah.kaist.ac.kr' + util.link('/'))
        if referer.endswith('/+login'):
            referer = referer[:-6]
        err = ''
        valid = True
        login = (False, _('UNDEFINED'))
        autologin = user_input.has_key('autologin')
        username, password = username.strip(), password.strip()
        if username == '' or password == '':
            err = _('No user ID or password specified.')
            valid = False

        if not valid:
            return util.render().login(title = _('Login'), board_desc=_('Login'),
                    lang="ko", error = err, referer = referer)

        login = user.login(username, password)
        if login[0]:
            # 로그인 성공. +login_xdomain에서는 세션 설정 후 referer로 돌아감.
            ts = user.add_login_info(username, 
                    user._generate_noah3k_password(password),
                    referer, autologin)
            xdomain_qs = urllib.urlencode({'t':ts, 'username':username})
            if referer.startswith('https'):
                pos = referer.find('/', len('https')+3)
                if pos > 0:
                    host = referer[:pos]
                else:
                    host = util.https()
            elif referer.startswith('http'):
                pos = referer.find('/', len('http')+3)
                if pos > 0:
                    host = referer[:pos]
                else:
                    host = 'http://noah.kaist.ac.kr'
            else:
                host = 'http://noah.kaist.ac.kr'
            raise web.seeother('%s/+login_xdomain?%s' % (host, xdomain_qs))
        else:
            # 로그인 실패
            err = login[1]
            return util.render().login(title = _('Login'), board_desc=_('Login'),
                lang="ko", error = err, referer = referer)
Ejemplo n.º 35
0
    def read_get(self, board_name, board_id, article_id):
        board_info = board.get_board_info(board_id)
        board_desc = board_info.bDescription
        a = article.get_article(board_id, article_id)
        comment = article.get_comment(article_id)

        #새글읽기 처리
        if web.ctx.session.has_key('uid'):
            uSerial = web.ctx.session.uid
            user.read_article(uSerial, article_id) 

        read_articles = web.cookies().get('read_articles')
        if read_articles:
            try:
                read_articles = [int(i) for i in read_articles.split(';')]
                if article_id not in read_articles:
                    article.increase_read_count(article_id)
                    read_articles.append(article_id)
            except ValueError:
                read_articles = []
        else:
            article.increase_read_count(article_id)
            read_articles = [article_id]
        read_articles.sort()
        read_articles = ';'.join(['%s' % i for i in read_articles])
        web.setcookie('read_articles', read_articles, 3600)

        prev_id = -1
        next_id = -1

        if not a:
            raise web.notfound(util.render().error(error_message = _('NO_SUCH_ARTICLE'), help_context='error'))
        if a.aIndex > 1:
            prev_id = article.get_article_id_by_index(board_id, a.aIndex - 1)
        if a.aIndex < article._get_article_count(board_id):
            next_id = article.get_article_id_by_index(board_id, a.aIndex + 1)
        page_no = article.get_page_by_article_id(board_id, article_id, config.page_size)
        uploads = attachment.get_attachment(article_id)
        thumbs = attachment.get_thumbnail(article_id, web.config.theme)

        return util.render().article(article = a,
            title = u"%s - %s" % (a.aIndex, a.aTitle),
            stylesheet = board_info.stylesheet,
            board_path = board_name, board_desc = board_desc,
            comments = comment, page_no = page_no,
            prev_id = prev_id, next_id = next_id, feed = True,
            attachment = uploads, thumbnail = thumbs,
            help_context = 'read_article')
Ejemplo n.º 36
0
    def write_post(self, board_name, board_id, current_uid = -1):
        a = dict(title = web.input().title, body = web.input().content)
        board_info = board.get_board_info(board_id)
        ret = article.write_article(current_uid, board_id, a)
        if ret[0] == True:
            user.update_unreaded_articles_board(current_uid, board_id)
            user.read_article(current_uid, ret[1])

            fs = web.ctx.get('_fieldstorage')
            try:
                if fs.has_key('new_attachment'):
                    new_attachment = fs['new_attachment']
                    if type(new_attachment) == list:
                        for f in new_attachment:
                            attachment.add_attachment(ret[1], f.filename, f.value)
                    else:
                        try:
                            attachment.add_attachment(ret[1], new_attachment.filename, new_attachment.value)
                        except:
                            pass
            except:
                pass
            url = util.link('/%s/+read/%s' % (board_name, ret[1]))
            raise web.seeother(url)
        else:
            return util.render().error(error_message = ret[1], help_context='error')
Ejemplo n.º 37
0
def main(data_file, output_folder):
    # first, load the data
    # camera: a PinholeCamera object
    # viewport: used for rendering; this defines a crop of the pixel space in
    #   the form (top, left, height, width)
    # points3D: Nx3 array of (x, y, z) point coordinates
    # rgb: Nx3 array (r, g, b) color values for the 3D points
    camera, viewport, points3D, rgb = util.load_data(data_file)

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # TODO: this code demonstrates how to call the render function; you should
    # change it to modify the camera's intrinsic and extrinsic parameters, in
    # order to recreate the dolly zoom effect

    image = util.render(camera, viewport, points3D, rgb)

    out_file = os.path.join(output_folder, "example.png")
    plt.imsave(out_file, image)

    first_image = image
    last_image = image

    #
    # for quick verification, also show the first image of the sequence, but
    # with the red channel replaced by the red channel of the last image of the
    # sequence
    #

    image = first_image.copy()
    image[:, :, 0] = last_image[:, :, 0]
    out_file = os.path.join(output_folder, "dolly_zoom_change.png")
    plt.imsave(out_file, image)
Ejemplo n.º 38
0
    def submit(self, login, newpass, verpass, email):
        session=cherrypy.request.db

        if data.User.get_by_login(session, login) != None:
            cherrypy.session['message']="User with this login already exists."
            raise cherrypy.InternalRedirect("/login/newuser/")

        old_user=data.User.get_by_email(session, email)

        if old_user != None and old_user.status != '' and old_user.status is not None:
            cherrypy.session['message']="User with this e-mail already exists."
            raise cherrypy.InternalRedirect("/login/newuser/")

        if newpass!=verpass:
            cherrypy.session['message']="Passwords do not match."
            raise cherrypy.InternalRedirect("/login/newuser/")

        date=time.strftime("%Y-%m-%d %H:%M:%S")
        uid=uuid.uuid1().hex

        if old_user!=None:
            user=old_user
            user.login=login
            user.status='NEW'
            user.uuid=uid
            user.date=date
            user.update_passwd(newpass)
        else:
            user=data.User(email,login,newpass,'NEW',uid,date)
            session.add(user)

        util.email(email,'system/email/newuser.genshi',newlogin=login, uuid=uid)
        return util.render('system/msg/newuser.genshi',newlogin=login)
Ejemplo n.º 39
0
def latest(request, start=None):
    auth_user(request.cookies.get('auth'))

    if not start:
        start = 0
    else:
        try:
            #/200
            start = int(start[1:])
        except ValueError:
            start = 0
        if start < 0:
            start = 0

    news, total = get_latest_news(start)
    hack_news(news)

    next = None
    if total > start + config.LatestNewsPerPage:
        next = start + config.LatestNewsPerPage
    return util.render('latest.pat',
                       news=news,
                       user=g.user,
                       start=start,
                       next=next)
Ejemplo n.º 40
0
def demo_index(request):
    '''
        Renders the demo frontend for INSTRUMENTS index.
        if we want to do it for every index, sometime in the future,
        just add an 'index=' parameter to this view.
    '''
    account = request.user.get_profile().account
    for index in account.indexes.all():

        if index.is_demo():
            context = {'index': index}
            return render('instruments.html', request, context_dict=context)
        # else continue

    # no index -> 404
    return render("404.html", request)
Ejemplo n.º 41
0
def change_password(request):
    user = request.user
    message = None
    if request.method == 'GET':
        form = forms.ChangePassForm()
    else:
        form = forms.ChangePassForm(data=request.POST)

        if form.is_valid():
            form_data = form.cleaned_data

            old_pass = form_data.get('old_password')
            new_pass = form_data.get('new_password')
            new_pass_again = form_data.get('new_password_again')

            if user.check_password(old_pass):
                user.set_password(new_pass)
                user.save()
                user.get_profile().change_password = False
                user.get_profile().save()
                messages.success(request,
                                 'Your password was changed successfully.')
                return HttpResponseRedirect(reverse('dashboard'))
            else:
                message = 'Current password is wrong'

    context = {
        'form': form,
        'message': message,
        'navigation_pos': 'dashboard',
    }

    return render('change_password.html', request, context_dict=context)
Ejemplo n.º 42
0
def close_account(request):
    user = request.user
    message = None
    if request.method == 'GET':
        form = forms.CloseAccountForm()
    else:
        form = forms.CloseAccountForm(data=request.POST)

        if form.is_valid():
            form_data = form.cleaned_data

            password = form_data.get('password')

            if user.check_password(password):
                user.get_profile().account.close()
                return HttpResponseRedirect(reverse('logout'))
            else:
                message = 'Wrong password'

    context = {
        'form': form,
        'message': message,
        'navigation_pos': 'dashboard',
    }

    return render('close_account.html', request, context_dict=context)
Ejemplo n.º 43
0
def get_started(request):
    if request.user.is_authenticated():
        package = request.user.get_profile().account.package
        plan = package.code
    else:
        plan = request.GET.get('plan', 'FREE')
        package = Package.objects.get(code=plan)
    if request.is_ajax() and request.method == 'POST':
        email = request.POST['email']
        try:
            is_valid_email(email)
        except:
            return HttpResponse('Invalid email address', status=400)

        try:
            account = create_account(request, email, package)
        except IntegrityError:
            return HttpResponse('Email address already used', status=400)

        return JsonResponse({
            'private_api_url': account.get_private_apiurl(),
            'public_api_url': account.get_public_apiurl(),
            'email': email
        })

    context = {
        'navigation_pos': 'get_started',
        'package': package,
        'plan': plan
    }
    return render('get_started.html', request, context_dict=context)
Ejemplo n.º 44
0
def invite_sign_up(request, password=None):
    try:
        invitation = BetaInvitation.objects.get(password=password)
        if invitation.account:
            return render('used_invite.html', request)
    except BetaInvitation.DoesNotExist:
        return HttpResponseNotFound()

    form = None
    message = None
    if request.method == 'GET':
        if invitation.beta_requester:
            form = forms.SignUpForm(
                initial={'email': invitation.beta_requester.email})
        else:
            form = forms.SignUpForm()
    else:
        form = forms.SignUpForm(data=request.POST)
        if form.is_valid():
            form_data = form.cleaned_data
            try:
                do_sign_up(request, form_data, invitation)
                return HttpResponseRedirect(request.GET.get('next') or '/')
            except IntegrityError, e:
                message = 'Email already exists.'
Ejemplo n.º 45
0
def login(request):
    login_form = forms.LoginForm()
    login_message = ''
    if request.method == 'POST':
        login_form = forms.LoginForm(data=request.POST)
        if login_form.is_valid():
            try:
                email = login_form.cleaned_data['email']
                if email == '*****@*****.**':
                    username = email
                else:
                    username = PFUser.objects.get(email=email).user.username
                user = auth.authenticate(
                    username=username,
                    password=login_form.cleaned_data['password'])
                if user is not None:
                    if user.is_active:
                        auth.login(request, user)
                        return HttpResponseRedirect(
                            request.GET.get('next') or '/dashboard')
                    else:
                        login_message = 'Account disabled'
                else:
                    login_message = 'Wrong email or password'
            except PFUser.DoesNotExist:  #@UndefinedVariable
                login_message = 'Wrong email or password'

    context = {
        'login_form': login_form,
        'login_message': login_message,
        'navigation_pos': 'home',
        'next': request.GET.get('next') or '/dashboard',
    }

    return render('login.html', request, context_dict=context)
Ejemplo n.º 46
0
def _get_started_step1(request):
    context = {
        'navigation_pos': 'get_started',
        'step': '1',
        'step_one': True,
        'next': request.GET.get('next') or '/',
    }
    return render('get_started.html', request, context_dict=context)
Ejemplo n.º 47
0
def heroku_dashboard(request):
    # Possible statuses:
    #    - No index
    #    - Index but no docs
    #    - Index with docs

    account_status = None

    if request.user.get_profile().change_password:
        messages.info(request,
                      'Your password was reset and you need to change it.')
        return HttpResponseRedirect(reverse('change_password'))

    account = request.user.get_profile().account

    indexes = account.indexes.all()

    has_indexes_left = (len(indexes) < account.package.max_indexes)

    totals = dict(size=0, docs=0, qpd=0)
    for index in indexes:
        totals['docs'] += index.current_docs_number
        totals['size'] += index.current_size
        totals['qpd'] += index.queries_per_day

    if len(indexes) == 0:
        account_status = 'NOINDEX'
    elif totals['docs'] == 0:
        account_status = 'INDEXNODOCS'
    else:
        account_status = 'INDEXWITHDOCS'

    percentages = {}

    def add_percentage(k, max, t, p):
        p[k] = 100.0 * t[k] / max

    KB = 1024
    MB = KB * KB
    max_docs = account.package.index_max_size
    max_size = account.package.max_size_mb()
    max_qpd = account.package.searches_per_day

    add_percentage('docs', max_docs, totals, percentages)
    add_percentage('size', max_size, totals, percentages)
    add_percentage('qpd', max_qpd, totals, percentages)

    context = {
        'account': account,
        'indexes': indexes,
        'has_indexes_left': has_indexes_left,
        'account_status': account_status,
        'totals': totals,
        'percentages': percentages,
        'navigation_pos': 'dashboard',
    }

    return render('heroku-dashboard.html', request, context_dict=context)
Ejemplo n.º 48
0
def question_options(question_id):
    stmt = "select * from question where id = %(question_id)s"
    question = db.query(stmt, {'question_id': question_id})[0]
    stmt = "select * from option where question_id = %(question_id)s order by ordernumber"
    options = db.query(stmt, {'question_id': question_id})
    return render("/admin",
                  "question_options.html",
                  question=question,
                  options=options)
Ejemplo n.º 49
0
def submit(request):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        return util.redirect('/login')
    else:
        return util.render('submit.pat',
                           user=g.user,
                           title=request.GET.get('t', ''),
                           url=request.GET.get('u', ''))
Ejemplo n.º 50
0
 def _render(self):
     self.html_content = util.render(self.raw_content,
                                     self.config['format'].lower(),
                                     self.config['linenos'].lower())
     with open(os.path.join('posts', self.header['output_filename']),
               'w') as page:
         page.write(
             self.template.render(select_theme=self.config['theme'],
                                  html_content=self.html_content))
Ejemplo n.º 51
0
def survey_participants(id):
    survey = db.query("SELECT * FROM survey WHERE id = %(id)s", {'id': id})[0]
    participants = db.query("SELECT * FROM participant p "\
        "left join survey_participant sp on (p.id = sp.participant_id and sp.survey_id = %(survey_id)s) order by sp.survey_id",
        {'survey_id':id})
    return render("/admin",
                  "survey_participants.html",
                  survey=survey,
                  participants=participants)
Ejemplo n.º 52
0
def survey_questions(id):
    stmt = "SELECT * FROM survey WHERE id = {id}".format(id=id)
    survey = db.query(stmt)[0]
    stmt = "select * from question where survey_id = %(survey_id)s order by ordernumber"
    questions = db.query(stmt, {'survey_id': id})
    return render("/admin",
                  "survey_questions.html",
                  survey=survey,
                  questions=questions)
Ejemplo n.º 53
0
def manage_index(request, index_code=None):
    account = request.user.get_profile().account

    index = Index.objects.get(code=index_code)

    if index:
        if index.account == account:
            if request.method == 'GET':
                index = Index.objects.get(code=index_code)

                largest_func = max(
                    [int(f.name) + 1
                     for f in index.scorefunctions.all()] + [5])
                functions = get_functions(index, upto=largest_func)

                context = {
                    'account': request.user.get_profile().account,
                    'navigation_pos': 'dashboard',
                    'functions': functions,
                    'index': index,
                    'index_code': index_code,
                    'largest_func': largest_func
                }

                if 'query' in request.GET:
                    maxim = int(request.GET.get('max', '25'))
                    index_client = ApiClient(
                        account.get_private_apiurl()).get_index(index.name)
                    context['results'] = index_client.search(
                        request.GET['query'], length=max)
                    context['query'] = request.GET['query']
                    context['more'] = maxim + 25

                return render('manage_index.html',
                              request,
                              context_dict=context)
            else:
                if 'definition' in request.POST:
                    name = request.POST['name']
                    definition = request.POST['definition']

                    client = ApiClient(account.get_private_apiurl()).get_index(
                        index.name)
                    try:
                        if definition:
                            client.add_function(int(name), definition)
                        else:
                            client.delete_function(int(name))
                    except InvalidDefinition, e:
                        return HttpResponse('Invalid function', status=400)

                    return JsonResponse({'largest': 5})
                elif 'public_api' in request.POST:
                    index.public_api = request.POST['public_api'] == 'true'
                    index.save()
                    return JsonResponse({'public_api': index.public_api})
Ejemplo n.º 54
0
def render_survey(id, survey_id=0):
    # check if the id is a valid id if invite only
    # if there's no session with this id create it
    try:
        if survey_id != 0:
            db.create_session(id, survey_id)
    except:
        pass

    # get the session
    try:
        session = db.get_session(id)
    except:
        return render("/templates",
                      "error.html",
                      errormessage="Ongeldige toegangscode")

    # load the current question
    question = db.get_question(session["survey_id"],
                               session["question_ordernumber"])

    # get options if needed
    options = {}
    if question["type"] in {"1", "M"}:
        options = db.get_options(question["id"])

    # get the template for the question type
    template = get_template(question["type"])
    # load response of question if any
    response = db.get_response(id, question["id"])
    if question["type"] == "M":
        if response != None and len(response) > 0:
            response = map(int, response.split(","))
        else:
            response = []
    # render question
    return render("/templates",
                  template,
                  session_id=id,
                  question=question,
                  options=options,
                  response=response)
Ejemplo n.º 55
0
def editnews(request, news_id):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        return util.render('error.pat',
                           user=g.user,
                           error='you have to login first')

    news = get_news_by_id(news_id)
    if not news:
        return util.render('error.pat',
                           user=g.user,
                           error='the news does not exist')

    if news.get('del'):
        return util.render('error.pat', user=g.user, error='news deleted')

    if news['user_id'] != g.user['id']:
        return util.render('error.pat', user=g.user, error='permission denied')

    hack_news(news)
    return util.render('editnews.pat', user=g.user, news=news)
Ejemplo n.º 56
0
def userpage(request, username):
    auth_user(request.cookies.get('auth'))

    user = get_user_by_name(username)
    if not user:
        return util.render('error.pat',
                           user=g.user,
                           error='the user does not exist')

    user['created'] = "%s days ago" % int(
        (time.time() - int(user['ctime'])) / (3600 * 24))

    #http://en.gravatar.com/site/implement/images/
    user['gravatar'] = "http://www.gravatar.com/avatar/" + \
        hashlib.md5(user['email'].lower()).hexdigest() + "?" + \
        "d=mm&"

    r = g.redis
    user['posted'] = r.zcard("user.posted:" + user['id'])
    user['saved'] = r.zcard("user.saved:" + user['id'])
    user['posted_comments'] = r.zcard("user.comments:" + user['id'])
    return util.render('user.pat', user=g.user, userinfo=user)
Ejemplo n.º 57
0
def login_form(tmpl):
    fl=cherrypy.session.get('force_login')

    if fl != None:
        message=fl.message
        fl.keep=True
    else:
        message=cherrypy.session.get('message')
        try:
            cherrypy.session.pop('message')
        except KeyError:
            pass

    return util.render(tmpl, message=message)
Ejemplo n.º 58
0
    def submit(self, login, email):
        session=cherrypy.request.db

        user=data.User.get_by_login(session, login)

        if not( user != None and user.e_mail==email and (user.status=='OK' or user.status=='FORGOTTEN')):
            cherrypy.session['message']="User with these credentials does not exist."
            raise cherrypy.InternalRedirect("/login/forgotten/")

        user.status='FORGOTTEN'
        user.uuid=uuid.uuid1().hex
#        user.password=''

        util.email(email,'system/email/forgotten.genshi',newlogin=login, uuid=user.uuid)
        return util.render('system/msg/forgotten.genshi',newlogin=login)
Ejemplo n.º 59
0
    def confirm(self, login, uuid):
        session=cherrypy.request.db

        user=data.User.get_by_login(session, login)

        if user != None:
            if user.uuid==uuid:
                if user.status=='NEW':
                    user.status='OK'
                    session.commit()
                    return util.render('system/msg/userconfirm.genshi',login=login)

                if user.status=='OK':
                    raise cherrypy.HTTPError(400, "Account %s already activated."%login)

        raise cherrypy.HTTPError(400)
Ejemplo n.º 60
0
def invite(survey_id, invitees):
    if not isinstance(invitees, list):
        invitees = [invitees]

    for participant_id in invitees:
        session_id = invite_participant(survey_id, participant_id)
        participant = db.query(
            "select * from participant where id = %(participant_id)s",
            {'participant_id': participant_id})[0]
        body = render("/admin",
                      "invitation.html",
                      session_id=session_id,
                      participant=participant)
        email("Uitnodiging", body, participant["email"])

    return survey_participants(survey_id)