Ejemplo n.º 1
0
def login_view(request):
    
    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            defaultdb = form.cleaned_data['defaultdb']
            if defaultdb:
                # log in as default
                username = "******"
                user = authenticate(username=username,password='******')


                # create default user if it doesn't exist
                if not user:
                    user = User.objects.create_user(username, username, "default")
                    user = authenticate(username=username,password='******')

                    userdb = Userdbs(username=username)
                    userdb.save() # creates userdb.id
                    dbname = 'mail.db'
                    userdb.dbname = dbname
                    userdb.save()
                    
                login(request,user)
                return HttpResponseRedirect("/emailanalysis/results/")

            else:
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']

                # check if gmail password is valid
                try:
                    getdata.authenticate_login('imap.googlemail.com',username,password)
                except:
                    # not valid --> need to find a better template to navigate to
                    return HttpResponse('user/password combo invalid')

                # check if user in db
                user = authenticate(username=username,password=password)
                if user is not None:
                    if user.is_active:
                        login(request,user)
                        # should redirect user to the results page
                        return HttpResponseRedirect("/emailanalysis/results/")
                    else:
                        return HttpResponse('user not recognized') # Return fail
                # user doesn't exist: create user
                # download data, return results page
                else:
                    user = User.objects.create_user(username,username,password)
                    user = authenticate(username=username,password=password)
                    login(request,user)
                    # create account for user
                    account = Account(user=user, host="imap.googlemail.com", username="******")
                    account.save()

                    #IMPORTANT: create the connection string and connect to the database
                    conn_string = "host=localhost dbname=liamg user=liamg password=liamg"
                    conn = psycopg2.connect(conn_string)
                    getdata.download_headers(account, password, conn, gettext=False)
                    
                    #make a connection and run the latencies script
                    c = conn.cursor()
                    
                    #get the account id for the specific user
                    actidSQL = "select id from accounts where user_id = (select id from auth_user where username = '******');" % user
                    c.execute(actidSQL)
                    actid = c.fetchone()[0]
                    
                    #call refresh the latencies table
                    getdata.execute_latencies(actid, conn)

                    #redirect to results page
                    return HttpResponseRedirect("/emailanalysis/results")

        else:
            return HttpResponse('form invalid')
    else:
#        form = LoginForm(initial={'username':'******','password':'******','defaultdb':True})
        form = LoginForm(initial={'username':'','password':'','defaultdb':False})
        c = {}
        c.update(csrf(request))

        return render_to_response('emailanalysis/home.html', {
            'form': form,
            },context_instance=RequestContext(request))
Ejemplo n.º 2
0
def login_view(request):

    if request.method == 'POST':
        form = LoginForm(request.POST)


        if form.is_valid():
            defaultdb = form.cleaned_data['defaultdb']
            if defaultdb:
                # log in as default
                username = "******"
                user = authenticate(username=username,password='******')


                # create default user if it doesn't exist
                if not user:
                    user = User.objects.create_user(username, username, "default")
                    user = authenticate(username=username,password='******')

                    userdb = Userdbs(username=username)
                    userdb.save() # creates userdb.id
                    dbname = 'mail.db'
                    userdb.dbname = dbname
                    userdb.save()
                    
                login(request,user)
                return HttpResponseRedirect("/emailanalysis/results/")

            else:
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']

                # check if gmail password is valid
                try:
                    getdata.authenticate_login('imap.googlemail.com',username,password)
                except:
                    # not valid
                    return HttpResponse('user/password combo invalid')

                # check if user in db
                user = authenticate(username=username,password='')
                if user is not None:
                    if user.is_active:
                        login(request,user)
                        # should redirect user to the results page
                        return HttpResponseRedirect("/emailanalysis/results/")
                    else:
                        return HttpResponse('user not recognized') # Return fail
                # user doesn't exist: create user
                # download data, return results page
                else:
                    user = User.objects.create_user(username,'','')
                    user = authenticate(username=username,password='')
                    login(request,user)
                    # create database name for user
                    userdb = Userdbs(username=username)
                    userdb.save() # creates userdb.id
                    dbname = 'user{0}.db'.format(userdb.id)
                    userdb.dbname = dbname
                    userdb.save()
                    print dbname
                    conn = sqlite3.connect(dbname, detect_types=sqlite3.PARSE_DECLTYPES)
                    print conn
                    getdata.setup_db(conn)
                    getdata.download_headers('imap.googlemail.com',username,password,conn)
                    os.system('./analyzedb.sh {0}'.format(dbname))
                    conn.close()

                    # redirect to results page?
                    return HttpResponse('data downloaded')
        else:
            return HttpResponse('form invalid')
    else:
        form = LoginForm(initial={'username':'******','password':'******','defaultdb':True})
        c = {}
        c.update(csrf(request))

        return render_to_response('emailanalysis/home.html', {
            'form': form,
            },context_instance=RequestContext(request))
Ejemplo n.º 3
0
def login_view(request):
	
    if request.method == 'POST':
        #store the data as an object Form. This allows you to call the username and password directly from the object 
        form = LoginForm(request.POST)

	#login error message	
	def errorHandle(error):
		form = LoginForm(initial={'username':'','password':'','defaultdb':False})
		c = {}
		c.update(csrf(request))
		return render_to_response('emailanalysis/home.html', {'error': error, 'form': form,},context_instance=RequestContext(request))

        #check if the form is valid. See if all the validation rules pass on the form object from the forms.Form class
        if form.is_valid():
            ##Check to make sure that the form has been filled out
            if (form.cleaned_data['username'] and form.cleaned_data['password']):
                #cleaned_data converts the value to a specific value type in this case it's a string
                username = form.cleaned_data['username'] 
                password = form.cleaned_data['password']

              
                # check if gmail password is valid
                try:
                    #pass in the host name for the imap server, username and password --> authenticate_login makes the connection 
                    #to the imap server via IMAP4_SSL and logs the user into their specific account via IMAP4_SSL.login(user, pass)
                    if username.endswith('@gmail.com'):
                        getdata.authenticate_login('imap.googlemail.com', username, password)
                    elif username.endswith("@yandex.ru"):
                        getdata.authenticate_login('imap.yandex.ru', username, password)

                    else:
                        #if there is not a @yandex or @gmail, then the response will be sent back to the front end as bad
                        return HttpResponse('Username is not recognized.')
                except:
                    #if the try doesn't work, then use errorHandle function in this method (above)
                    return errorHandle(u'Login failed for ' + username + '.<br/>Please try logging in again.')

                # check if user in db. 
                #authenticate(username, password) method returns a user object from the django.auth library
                #if the user exists in the database. returns None if there is no user in the database
                user = authenticate(username=username,password=password)
                if user is not None:
                    #check if the user is active (boolean). This will be false if you want to deactivate an account.
                    if user.is_active:
                        #use django.contrib.auth.views.login
                        login(request,user)
                        # should redirect user to the results page
                        return HttpResponseRedirect("/emailanalysis/results/")
                    else:
                        return HttpResponse('user not recognized') # Return fail


                #############################
                #Need to add a method so that you can update the database with new 
                #messages. 
                #############################

                #if you don't have a user, then download data, return results page. Using the django.auth library you first
                #create_user => creates, saves then returns a user. User that is returned has is_active set to True
                else:
                    #creates and saves a user. user is returned and is_active is set to True
                    user = User.objects.create_user(username,username,password)
                    user = authenticate(username=username,password=password)
                    login(request,user)
                    # create account for user using the models.py. Account class exists in models.py
                    #save the account that was created to the database
                    if username.endswith('@gmail.com'):
                        account = Account(user=user, host="imap.googlemail.com", username=username)
                        account.save()
                    elif username.endswith('@yandex.ru'):
                        account= Account(user=user, host='imap.yandex.ru', username=username)
                        account.save()


                    #IMPORTANT: create the connection string and connect to the database
                    conn = connection
                    #conn_string = "host=localhost dbname=liamg user=liamg password=liamg"
                    #conn = psycopg2.connect(conn_string)
                    getdata.download_headers(account, password, conn, gettext=False)
                    
                    #make a connection and run the latencies script
                    c = conn.cursor()
                    
                    #get the account id for the specific user
                    actidSQL = """select id 
                                     from accounts where user_id = 
                                     (select id from auth_user where username = '******');""" % user
                    c.execute(actidSQL)
                    actid = c.fetchone()[0]
                    
                    #call refresh the latencies table
                    getdata.execute_latencies(actid, conn)

                    #redirect to results page
                    return HttpResponseRedirect("/emailanalysis/results")
		
		#invalid entry messages
        else: 
            username=request.POST.get('username')
            password=request.POST.get('password')
            if not username or not password:
                return errorHandle(u'Please fill in both fields to log in.')
            else:
                return errorHandle(u'Improper email format. Please type out your entire<br />email address (e.g. [email protected])')
				
    else:
        form = LoginForm(initial={'username':'','password':'','defaultdb':False})
        c = {}
        c.update(csrf(request))

        return render_to_response('emailanalysis/home.html', {
            'form': form,
            },context_instance=RequestContext(request))
Ejemplo n.º 4
0
def login_view(request):

    if request.method == 'POST':
        #store the data as an object Form. This allows you to call the username and password directly from the object
        form = LoginForm(request.POST)

        #login error message
        def errorHandle(error):
            form = LoginForm(initial={
                'username': '',
                'password': '',
                'defaultdb': False
            })
            c = {}
            c.update(csrf(request))
            return render_to_response('emailanalysis/home.html', {
                'error': error,
                'form': form,
            },
                                      context_instance=RequestContext(request))

        #check if the form is valid. See if all the validation rules pass on the form object from the forms.Form class
        if form.is_valid():
            ##Check to make sure that the form has been filled out
            if (form.cleaned_data['username']
                    and form.cleaned_data['password']):
                #cleaned_data converts the value to a specific value type in this case it's a string
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']

                # check if gmail password is valid
                try:
                    #pass in the host name for the imap server, username and password --> authenticate_login makes the connection
                    #to the imap server via IMAP4_SSL and logs the user into their specific account via IMAP4_SSL.login(user, pass)
                    if username.endswith('@gmail.com'):
                        getdata.authenticate_login('imap.googlemail.com',
                                                   username, password)
                    elif username.endswith("@yandex.ru"):
                        getdata.authenticate_login('imap.yandex.ru', username,
                                                   password)

                    else:
                        #if there is not a @yandex or @gmail, then the response will be sent back to the front end as bad
                        return HttpResponse('Username is not recognized.')
                except:
                    #if the try doesn't work, then use errorHandle function in this method (above)
                    return errorHandle(u'Login failed for ' + username +
                                       '.<br/>Please try logging in again.')

                # check if user in db.
                #authenticate(username, password) method returns a user object from the django.auth library
                #if the user exists in the database. returns None if there is no user in the database
                user = authenticate(username=username, password=password)
                if user is not None:
                    #check if the user is active (boolean). This will be false if you want to deactivate an account.
                    if user.is_active:
                        #use django.contrib.auth.views.login
                        login(request, user)
                        # should redirect user to the results page
                        return HttpResponseRedirect("/emailanalysis/results/")
                    else:
                        return HttpResponse(
                            'user not recognized')  # Return fail

                #############################
                #Need to add a method so that you can update the database with new
                #messages.
                #############################

                #if you don't have a user, then download data, return results page. Using the django.auth library you first
                #create_user => creates, saves then returns a user. User that is returned has is_active set to True
                else:
                    #creates and saves a user. user is returned and is_active is set to True
                    user = User.objects.create_user(username, username,
                                                    password)
                    user = authenticate(username=username, password=password)
                    login(request, user)
                    # create account for user using the models.py. Account class exists in models.py
                    #save the account that was created to the database
                    if username.endswith('@gmail.com'):
                        account = Account(user=user,
                                          host="imap.googlemail.com",
                                          username=username)
                        account.save()
                    elif username.endswith('@yandex.ru'):
                        account = Account(user=user,
                                          host='imap.yandex.ru',
                                          username=username)
                        account.save()

                    #IMPORTANT: create the connection string and connect to the database
                    conn = connection
                    #conn_string = "host=localhost dbname=liamg user=liamg password=liamg"
                    #conn = psycopg2.connect(conn_string)
                    getdata.download_headers(account,
                                             password,
                                             conn,
                                             gettext=False)

                    #make a connection and run the latencies script
                    c = conn.cursor()

                    #get the account id for the specific user
                    actidSQL = """select id 
                                     from accounts where user_id = 
                                     (select id from auth_user where username = '******');""" % user
                    c.execute(actidSQL)
                    actid = c.fetchone()[0]

                    #call refresh the latencies table
                    getdata.execute_latencies(actid, conn)

                    #redirect to results page
                    return HttpResponseRedirect("/emailanalysis/results")

#invalid entry messages
        else:
            username = request.POST.get('username')
            password = request.POST.get('password')
            if not username or not password:
                return errorHandle(u'Please fill in both fields to log in.')
            else:
                return errorHandle(
                    u'Improper email format. Please type out your entire<br />email address (e.g. [email protected])'
                )

    else:
        form = LoginForm(initial={
            'username': '',
            'password': '',
            'defaultdb': False
        })
        c = {}
        c.update(csrf(request))

        return render_to_response('emailanalysis/home.html', {
            'form': form,
        },
                                  context_instance=RequestContext(request))