def search(request, page_index=0, sort_by_new=False): """ Display snippets by user, language or search term """ q = request.REQUEST.get('q', '').strip() if q: users_q = User.objects.filter(username__iexact=q)[:1] if users_q: return HttpResponseRedirect(reverse('app_user', args=[users_q[0].username])) lang_q = Language.objects.filter(name__iexact=q)[:1] print lang_q if lang_q: print lang_q return HttpResponseRedirect(reverse('app_lang', args=[lang_q[0].slug])) page_index = int(page_index) params = { 'q': q.encode('utf-8')} query = '?' + urllib.urlencode(params) active = 'new' if sort_by_new else 'top' snippets = Snippet.search_snippets(q, request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [page_index], params) no_snippets = 'There are no snippets found for this search query' return render_response(request, 'app/search_snippets.html', locals()) return HttpResponseRedirect(reverse('app_home'))
def search(request, page_index=0, sort_by_new=False): """ Display snippets by user, language or search term """ q = request.REQUEST.get('q', '').strip() if q: users_q = User.objects.filter(username__iexact=q)[:1] if users_q: return HttpResponseRedirect( reverse('app_user', args=[users_q[0].username])) lang_q = Language.objects.filter(name__iexact=q)[:1] print lang_q if lang_q: print lang_q return HttpResponseRedirect( reverse('app_lang', args=[lang_q[0].slug])) page_index = int(page_index) params = {'q': q.encode('utf-8')} query = '?' + urllib.urlencode(params) active = 'new' if sort_by_new else 'top' snippets = Snippet.search_snippets(q, request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [page_index], params) no_snippets = 'There are no snippets found for this search query' return render_response(request, 'app/search_snippets.html', locals()) return HttpResponseRedirect(reverse('app_home'))
def comment_read(request, snippet_id, comment_id): """ Display Snippet with particular comment thread """ snippet_id = int(snippet_id) comment_id = int(comment_id) snippet = Snippet.read(snippet_id, request.user, comment_id) return render_response(request, 'app/snippet.html', locals())
def tag_snippets(request, tag_name, page_index=0, sort_by_new=False): """ Display list of snippets by tag """ page_index = int(page_index) active = 'new' if sort_by_new else 'top' snippets = Snippet.tag_snippets(tag_name, request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [tag_name, page_index]) return render_response(request, 'app/tag_snippets.html', locals())
def snippet_read(request, snippet_id, slug=None): """ Display Snippet """ if slug is None: snippet = get_object_or_404(Snippet, id=snippet_id) return HttpResponsePermanentRedirect(snippet.get_absolute_url()) snippet_id = int(snippet_id) snippet = Snippet.read(snippet_id, request.user) return render_response(request, 'app/snippet.html', locals())
def index(request, page_index=0, sort_by_new=False): """ Display all snippets """ page_index = int(page_index) active = 'new' if sort_by_new else 'top' snippets = Snippet.get_snippets(request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [page_index]) recent_sign_ups = User.get_recent_users() return render_response(request, 'app/home_snippets.html', locals())
def lang_snippets(request, slug, page_index=0, sort_by_new=False): """ Displays list of snippets of the particular language """ page_index = int(page_index) active = 'new' if sort_by_new else 'top' lang = get_object_or_404(Language, slug=slug) is_subscribed = request.user.is_authenticated() and Subscription.is_subscribed(lang, request.user) snippets = Snippet.lang_snippets(lang, request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [slug, page_index]) return render_response(request, 'app/lang_snippets.html', locals())
def send_verification(request, user_id): """ Send verification code if user hasn't been verified yet """ if request.method == 'POST': user = get_object_or_404(User, id=user_id) if user.is_verified: error = 'Your account is already verified.' else: _send_verification_email(get_current_site(request).domain, user) message = 'An account verification code has been sent to your email address' return render_response(request, 'app/public/send_verification.html', locals())
def lang_snippets(request, slug, page_index=0, sort_by_new=False): """ Displays list of snippets of the particular language """ page_index = int(page_index) active = 'new' if sort_by_new else 'top' lang = get_object_or_404(Language, slug=slug) is_subscribed = request.user.is_authenticated( ) and Subscription.is_subscribed(lang, request.user) snippets = Snippet.lang_snippets(lang, request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [slug, page_index]) return render_response(request, 'app/lang_snippets.html', locals())
def user_snippets(request, username, page_index=0, sort_by_new=False): """ Display snippets of particular user """ page_index = int(page_index) active = 'new' if sort_by_new else 'top' try: user = User.get_by_username(username) except User.DoesNotExist: raise Http404() is_follower = request.user.is_authenticated() and Follow.is_follower(user, request.user) snippets = Snippet.user_snippets(user, request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [username, page_index]) return render_response(request, 'app/user_snippets.html', locals())
def comment_create(request, snippet_id): """ Creates a new comment for snippet """ if request.method == 'POST': snippet_id = int(snippet_id) comment_text = request.POST.get('comment_text', None) if comment_text: snippet = Snippet.objects.get(id=snippet_id) comment = Comment.save_comment(request.user, snippet_id, comment_text[:settings.MAX_COMMENT_LENGTH]) if request.is_ajax(): return render_response(request, 'app/parts/comment.html', { 'snippet': snippet, 'comment': comment }) return HttpResponseRedirect(reverse('app_snippet_read', args=[snippet_id]) + '#comment-id-' + str(comment.id)) raise Http404()
def user_snippets(request, username, page_index=0, sort_by_new=False): """ Display snippets of particular user """ page_index = int(page_index) active = 'new' if sort_by_new else 'top' try: user = User.get_by_username(username) except User.DoesNotExist: raise Http404() is_follower = request.user.is_authenticated() and Follow.is_follower( user, request.user) snippets = Snippet.user_snippets(user, request.user, page_index, settings.PAGE_SIZE, sort_by_new) prev_url, next_url = paginated_url(request.resolver_match.url_name, snippets, [username, page_index]) return render_response(request, 'app/user_snippets.html', locals())
def change_password(request): """ Updates user's password in database """ error = None if request.method == 'POST': form = ChangePassword(request.POST) if form.is_valid(): data = form.cleaned_data try: request.user.change_password(data['current_password'], data['password']) successfully_changed = True except HunkitError as e: error = e.message else: form = ChangePassword() return render_response(request, 'app/change_password.html', locals())
def snippet_create(request): """ Creates a new code snippet """ tags = [tag.name for tag in Tag.get_tags()] if request.method == 'POST': form = SnippetForm(request.user.is_anonymous(), request.POST) if form.is_valid(): data = form.cleaned_data try: user = request.user if request.user.is_authenticated() else User.get_or_create(data['email']) snippet = Snippet.create(data['gist'], data['code'], data['language'], data['tags'], user) return HttpResponseRedirect(snippet.get_absolute_url()) except HunkitError as e: error = e.message else: form = SnippetForm(request.user.is_anonymous()) return render_response(request, 'app/create_snippet.html', locals())
def verification(request, user_id, code): """ Activates the new user """ if request.method == 'POST': raise Http404() try: user = User.objects.get(id=user_id) if not user.is_verified: if user.verification_code == code: user.verify() else: invalid_code = True else: error = 'Your account is already verified.' except User.DoesNotExist: raise Http404() return render_response(request, 'app/public/verification.html', locals())
def snippet_create(request): """ Creates a new code snippet """ tags = [tag.name for tag in Tag.get_tags()] if request.method == 'POST': form = SnippetForm(request.user.is_anonymous(), request.POST) if form.is_valid(): data = form.cleaned_data try: user = request.user if request.user.is_authenticated( ) else User.get_or_create(data['email']) snippet = Snippet.create(data['gist'], data['code'], data['language'], data['tags'], user) return HttpResponseRedirect(snippet.get_absolute_url()) except HunkitError as e: error = e.message else: form = SnippetForm(request.user.is_anonymous()) return render_response(request, 'app/create_snippet.html', locals())
def login(request): """ Login user using django builten authentication """ next_url = request.GET.get('next', None) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if not user.is_verified: is_verified = True elif user.is_active: login_user(request, user) return HttpResponseRedirect(request.GET.get('next', reverse('app_home'))) else: error = '''Your account has been disabled. We apologize for any inconvenience! If this is a mistake please contact our <a href="mailto:[email protected]">support</a>.''' else: error = '''Username and password didn't matched, if you forgot your password? <a href="%s">Request new one</a>''' % reverse('app_forgot_password') return render_response(request, 'app/public/login.html', locals())
def sign_up(request): """ Create a new user account """ if request.method == 'POST': form = SignUp(request.POST) if form.is_valid(): data = form.cleaned_data try: user = User.sign_up(data['username'], data['email'], data['password'], data['gender']) domain = get_current_site(request).domain _send_verification_email(domain, user) _send_welcome_email(domain, user) successful_signup = True except HunkitError as e: error = e.message else: form = SignUp() return render_response(request, 'app/public/signup.html', locals())
def comment_create(request, snippet_id): """ Creates a new comment for snippet """ if request.method == 'POST': snippet_id = int(snippet_id) comment_text = request.POST.get('comment_text', None) if comment_text: snippet = Snippet.objects.get(id=snippet_id) comment = Comment.save_comment( request.user, snippet_id, comment_text[:settings.MAX_COMMENT_LENGTH]) if request.is_ajax(): return render_response(request, 'app/parts/comment.html', { 'snippet': snippet, 'comment': comment }) return HttpResponseRedirect( reverse('app_snippet_read', args=[snippet_id]) + '#comment-id-' + str(comment.id)) raise Http404()
def login(request): """ Login user using django builten authentication """ next_url = request.GET.get('next', None) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if not user.is_verified: is_verified = True elif user.is_active: login_user(request, user) return HttpResponseRedirect( request.GET.get('next', reverse('app_home'))) else: error = '''Your account has been disabled. We apologize for any inconvenience! If this is a mistake please contact our <a href="mailto:[email protected]">support</a>.''' else: error = '''Username and password didn't matched, if you forgot your password? <a href="%s">Request new one</a>''' % reverse( 'app_forgot_password') return render_response(request, 'app/public/login.html', locals())
def fb_login(request): """ Login or sign up user via facebook """ if request.method == 'POST': params = urllib.urlencode({ 'client_id': settings.FB_APP_ID, 'response_type': 'code', 'redirect_uri': request.build_absolute_uri(request.path), 'state': request.POST.get('next', reverse('app_home')), # redirect uri for user 'scope': 'email' }) return HttpResponseRedirect(settings.FB_AUTH_URL + '?' + params) code = request.GET.get('code', None) next_url = request.GET.get('state', None) if not next_url: next_url = reverse('app_home') if not code: error = request.GET.get('error', None) error_reason = request.GET.get('error_reason', None) if error == 'access_denied' and error_reason == 'user_denied': return render_response( request, 'app/public/facebook_login.html', { 'error': 'You must allow Codehunkit to access your basic information from Facebook.', 'next_url': next_url }) logger.error('Error occurred while signing user through Facebook.\n' + str(request)) return render_response( request, 'app/public/facebook_login.html', { 'error': 'We encounter some error while logging you in through Facebook.', 'next_url': next_url }) params = urllib.urlencode({ 'client_id': settings.FB_APP_ID, 'client_secret': settings.FB_APP_SECRET, 'redirect_uri': request.build_absolute_uri(request.path), 'code': code }) try: access_content = scraper.get_content(settings.FB_ACCESS_TOKEN + '?' + params) access_content = dict(urlparse.parse_qsl(access_content)) access_token = access_content['access_token'] access_expiry = datetime.datetime.now() + datetime.timedelta( seconds=int(access_content['expires'])) request.session['facebook_access_token'] = access_token params = urllib.urlencode({'access_token': access_token}) fb_user = scraper.get_content(settings.FB_GRAPH_ME + '?' + params) fb_user = json.loads(fb_user) try: if request.user.is_authenticated(): user = request.user created = FacebookUser.connect_user(user, fb_user, access_token, access_expiry) if created: FlashMessage.add_success( 'Your Facebook account is successfully connected.', user) else: if not 'email' in fb_user: raise HunkitError( 'You need to allow Codehunkit for access of your email address on Facebook' ) created, user = FacebookUser.get_user_or_create( fb_user, access_token, access_expiry) if not user.is_active: raise HunkitError( 'Your account has been disabled. We apologize for any inconvenience! If this is a mistake please contact our <a href="mailto:[email protected]">support</a>.' ) if created: domain = get_current_site(request).domain if user.is_verified: user.backend = 'django.contrib.auth.backends.ModelBackend' # can't call authenticate since don't know password login_user(request, user) FlashMessage.add_success( 'You have successfully signed up with Facebook account.', user) else: _send_verification_email(domain, user) FlashMessage.add_success( 'You have successfully signed up with Facebook account, but you need to verify your account via email address.', user) _send_welcome_email(domain, user) else: if user.is_verified: user.backend = 'django.contrib.auth.backends.ModelBackend' # can't call authenticate since don't know password login_user(request, user) FlashMessage.add_info( 'Welcome back, ' + user.username + '!', user) else: return HttpResponseRedirect( reverse('app_send_verification')) #if created: #return HttpResponseRedirect(reverse('app_user_friends', args=[user.username]) + '?' + urllib.urlencode({ 'next': return_url})) return HttpResponseRedirect(next_url) except HunkitError as e: transaction.rollback() return render_response(request, 'app/public/facebook_login.html', { 'error': e.message, 'next_url': next_url }) except Exception as e: logger.exception(e) transaction.rollback() return render_response( request, 'app/public/facebook_login.html', { 'error': 'We encounter some error while logging you in through Facebook.', 'next_url': next_url }) return HttpResponseRedirect(reverse('app_home'))
def fb_login(request): """ Login or sign up user via facebook """ if request.method == 'POST': params = urllib.urlencode({'client_id': settings.FB_APP_ID, 'response_type': 'code', 'redirect_uri': request.build_absolute_uri(request.path), 'state': request.POST.get('next', reverse('app_home')), # redirect uri for user 'scope': 'email' }) return HttpResponseRedirect(settings.FB_AUTH_URL + '?' + params) code = request.GET.get('code', None) next_url = request.GET.get('state', None) if not next_url: next_url = reverse('app_home') if not code: error = request.GET.get('error', None) error_reason = request.GET.get('error_reason', None) if error == 'access_denied' and error_reason == 'user_denied': return render_response(request, 'app/public/facebook_login.html', {'error': 'You must allow Codehunkit to access your basic information from Facebook.', 'next_url': next_url }) logger.error('Error occurred while signing user through Facebook.\n' + str(request)) return render_response(request, 'app/public/facebook_login.html', {'error': 'We encounter some error while logging you in through Facebook.', 'next_url': next_url }) params = urllib.urlencode({'client_id': settings.FB_APP_ID, 'client_secret': settings.FB_APP_SECRET, 'redirect_uri': request.build_absolute_uri(request.path), 'code': code }) try: access_content = scraper.get_content(settings.FB_ACCESS_TOKEN + '?' + params) access_content = dict(urlparse.parse_qsl(access_content)) access_token = access_content['access_token'] access_expiry = datetime.datetime.now() + datetime.timedelta(seconds=int(access_content['expires'])) request.session['facebook_access_token'] = access_token params = urllib.urlencode({'access_token': access_token}) fb_user = scraper.get_content(settings.FB_GRAPH_ME + '?' + params) fb_user = json.loads(fb_user) try: if request.user.is_authenticated(): user = request.user created = FacebookUser.connect_user(user, fb_user, access_token, access_expiry) if created: FlashMessage.add_success('Your Facebook account is successfully connected.', user) else: if not 'email' in fb_user: raise HunkitError('You need to allow Codehunkit for access of your email address on Facebook') created, user = FacebookUser.get_user_or_create(fb_user, access_token, access_expiry) if not user.is_active: raise HunkitError('Your account has been disabled. We apologize for any inconvenience! If this is a mistake please contact our <a href="mailto:[email protected]">support</a>.') if created: domain = get_current_site(request).domain if user.is_verified: user.backend='django.contrib.auth.backends.ModelBackend' # can't call authenticate since don't know password login_user(request, user) FlashMessage.add_success('You have successfully signed up with Facebook account.', user) else: _send_verification_email(domain, user) FlashMessage.add_success('You have successfully signed up with Facebook account, but you need to verify your account via email address.', user) _send_welcome_email(domain, user) else: if user.is_verified: user.backend='django.contrib.auth.backends.ModelBackend' # can't call authenticate since don't know password login_user(request, user) FlashMessage.add_info('Welcome back, ' + user.username + '!', user) else: return HttpResponseRedirect(reverse('app_send_verification')) #if created: #return HttpResponseRedirect(reverse('app_user_friends', args=[user.username]) + '?' + urllib.urlencode({ 'next': return_url})) return HttpResponseRedirect(next_url) except HunkitError as e: transaction.rollback() return render_response(request, 'app/public/facebook_login.html', {'error': e.message, 'next_url': next_url }) except Exception as e: logger.exception(e) transaction.rollback() return render_response(request, 'app/public/facebook_login.html', {'error': 'We encounter some error while logging you in through Facebook.', 'next_url': next_url }) return HttpResponseRedirect(reverse('app_home'))