Пример #1
0
    def get(self):
        if self.user:
            # Prompt user to logout
            self.session.add_flash('message_reset_password_1', 
                                   key='homepage_flashes')
            self.redirect("/")
        else:
            # Get token from URL
            input_token = self.request.get('token')

            # Check if format of token is valid 
            TOKEN_RE = re.compile(r"^([0-9]{1,30})\-.{3,20}$")
            if not TOKEN_RE.match(input_token):
                # Set invalid reset_id so that a normal error message is sent
                reset_id = 1
            else:
                # Split token to obtain reset_id and temp_pw.
                reset_id = int(input_token.split('-')[0])
                temp_pw = input_token.split('-')[1]

            # Use reset_id to find entry in ResetPasswordRequest DB.
            self.r = ResetPasswordRequest.by_id(reset_id)
            # Check if entry exists 
            if not self.r:
                # Show message that link is not valid.
                self.session.add_flash('message_reset_password_2', 
                                       key='homepage_flashes')
                self.redirect("/")

            # Check if entry is not older than one hour.
            elif datetime.datetime.now() - datetime.timedelta(hours = 1) > self.r.created:
                # Show message that too much time has passed.
                self.session.add_flash('message_reset_password_3', 
                                       key='homepage_flashes')
                self.redirect("/")

            # Check if temp_pw is valid
            elif not ResetPasswordRequest.check_for_valid_request(self.r.email, temp_pw):
                # Show message that the link is not valid.
                self.session.add_flash('message_reset_password_4', 
                                       key='homepage_flashes')
                self.redirect("/")

            # If no error, get user by_email, 
            # log in and render reset_password.html 
            else:
                email = self.r.email
                self.user = User.by_email(email)
                self.login(self.user)
                state = self.make_state()
                self.render('reset_password.html', 
                            user = self.user, 
                            token = input_token,
                            state = state) 
Пример #2
0
    def post(self):
        if self.user:
            # Prompt user to log out.
            self.render('message.html', 
                        user = self.user, 
                        message_forgot_password_1 = True)
        else:
            if not self.check_state():
                logging.warning("Possible CSRF attack detected!")
                self.redirect("/")
                return
            # Receive input from web-page: eamil
            input_email = self.request.get('email').lower()

            error = ''
            self.user = User.by_email(input_email)
            if not self.user:
                state = self.make_state()
                # Render page with error-message.
                self.render('forgot_password.html', 
                            form_email = input_email, 
                            error = True,
                            state = state)
            else:
                # Generate new temporary random password
                length = 10
                temp_pw = ''.join(random.choice(ascii_letters)for x in xrange(length))

                # Create entry in ResetPasswordRequest DB
                u = ResetPasswordRequest.create_request(input_email, temp_pw)
                u.put()

                # Send email with a link to the ResetPassword page. 
                # The link includes email and temporary password to 
                # authenticate the user.
                # ADAPT LINK TO GAE URL
                resetToken = str(u.key().id())+"-"+temp_pw
                link = "http://PROJECT_ID.appspot.com/reset_pw/?token=%s" %(resetToken)

                self.send_email(self.user.email, 
                                'email_subject.html', 
                                'email_forgot_password.html', 
                                subject_type = 'forgot_password', 
                                username = self.user.name, 
                                link = link)

                # Render message-page with message that email was sent
                self.render('message.html', 
                            input_email = input_email, 
                            message_forgot_password_2 = True)
Пример #3
0
    def post(self):
        if self.user:
            if not self.check_state():
                self.redirect("/")
                return

            # Get user input
            input_email = self.request.get('email').lower()
            input_verify_email = self.request.get('verify_email').lower()

            # Check input and set error messages. 
            error_email=""
            error_verify_email=""
            error_user_exists=""

            have_error = False

            if not valid_email(input_email):
                # Set the error-message: not a valid email.
                error_email = True
                have_error = True
            if not valid_verify(input_email, input_verify_email):
                # Set the error-message: emails do not match.
                error_verify_email = True
                have_error = True

            if have_error == False:
                u = User.by_email(input_email)
                if u:
                    # Set the error-message: email already assigned.
                    error_user_exists = True
                    have_error = True
 
            if have_error:
                state = self.make_state()
                # Render page with error-messages.
                self.render('change_email.html',
                            user = self.user,
                            email = input_email,
                            error_email = error_email,
                            error_verify_email = error_verify_email,
                            error_user_exists = error_user_exists,
                            state = state)
            else:
                # Update user object in DB and memcache
                User.update(self.user, email=input_email)

                # Send email notification to new address
                self.send_email(self.user.email, 
                                'email_subject.html', 
                                'email_email_changed.html', 
                                subject_type = 'email_changed', 
                                username = self.user.name, 
                                user_email = self.user.email)
                
                # Render page with message that email was sent
                state = self.make_state()
                self.render('change_email.html', 
                            user = self.user, 
                            success_message = True,
                            state = state)
        else:
            # Prompt user to login.
            self.session.add_flash('message_user_settings_1', 
                                   key='homepage_flashes')
            self.redirect("/")
Пример #4
0
    def post(self):
        if self.user:
            # Prompt user to log out.
            self.session.add_flash('message_forgot_password_1', 
                                   key='homepage_flashes')
            self.redirect("/")
        else:
            if not self.check_state():
                self.redirect("/")
                return
            # Receive input from web-page: eamil
            input_email = self.request.get('email').lower()

            have_error = False
            if not valid_email(input_email):
                # Show the error-message: not a valid email.
                have_error = True

            if have_error:
                state = self.make_state()
                # Render page with error-message.
                self.render('forgot_password.html', 
                            form_email = input_email, 
                            error = True,
                            state = state)
                return

            self.user = User.by_email(input_email)
            if not self.user:
                logging.warning('Unknown email from forgot password page received!')
                # Redirect to "/". Flash message that email was sent.
                self.session.add_flash('message_forgot_password_2', 
                                       key='homepage_flashes')
                self.session.add_flash(input_email, key='input_email')
                self.redirect("/")

            else:
                # Generate new temporary random password
                length = 10
                temp_pw = ''.join(random.choice(ascii_letters)for x in xrange(length))

                # Create entry in ResetPasswordRequest DB
                r = ResetPasswordRequest.create(input_email, temp_pw)

                # Send email with a link to the ResetPassword page. 
                # The link includes email and temporary password to 
                # authenticate the user.
                # ADAPT LINK TO GAE URL
                resetToken = str(r.key().id())+"-"+temp_pw
                link = "http://YOUR_APP_ID.appspot.com/reset_pw/?token=%s" %(resetToken)

                self.send_email(self.user.email, 
                                'email_subject.html', 
                                'email_forgot_password.html', 
                                subject_type = 'forgot_password', 
                                username = self.user.name, 
                                link = link)

                # Redirect to "/". Flash message that email was sent.
                self.session.add_flash('message_forgot_password_2', 
                                       key='homepage_flashes')
                self.session.add_flash(input_email, key='input_email')
                self.redirect("/")
Пример #5
0
    def get(self):

        # Step 3: Once the consumer has redirected the user back to the oauth_callback
        # URL you can request the access token the user has approved. You use the 
        # request token to sign this request. After this is done you throw away the
        # request token and use the access token returned. You should store this 
        # access token somewhere safe, like a database, for future use.

        access_token_url = 'https://api.twitter.com/oauth/access_token'

        consumer_key = json.loads(open('twitter_client_secrets.json', 'r').read())['web']['consumer_key']
        consumer_secret = json.loads(open('twitter_client_secrets.json', 'r').read())['web']['consumer_secret']

        consumer = oauth.Consumer(consumer_key, consumer_secret)
 
        input_oauth_token = self.request.get('oauth_token')
        input_oauth_verifier = self.request.get('oauth_verifier')
        if not input_oauth_verifier:
            raise Exception("No oauth_verifier received.")

        request_token = self.session.get('request_token')
        logging.error(request_token['oauth_token'])
        if not input_oauth_token == request_token['oauth_token']:
            raise Exception("Invalid request_token.")

        token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
        token.set_verifier(input_oauth_verifier)
        client = oauth.Client(consumer, token)

        resp, content = client.request(access_token_url, "POST")
        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])

        access_token = dict(urlparse.parse_qsl(content))

        logging.error('TWITTER ACCESS TOKEN:')
        logging.error(access_token)

        # Set the API endpoint 
        url = "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true&skip_status=true&include_entities=false"

        token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret'])

        client = oauth.Client(consumer, token)

        resp, content = client.request(url, "GET")
        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])

        user_credentials = json.loads(content)
        self.session['twitter_id'] = user_credentials["id"]
        self.session['provider'] = 'twitter'

        # The access_token must be stored in the login_session in order to properly logout
        self.session['access_token'] = access_token


        logging.error('TWITTER CREDENTIALS:')
        logging.error(content)
        logging.error(user_credentials['email'])

        # see if user exists, if it doesn't make a new one
        u = User.by_email(user_credentials['email'])
        if not u:
            # turn name from Twitter into a unique username
            # replace spaces with underscores
            u_name = str(user_credentials['name'].replace(" ","_"))
            # check if username exists
            # add a random number
            while User.by_name(u_name):
                u_name = u_name + str(randint(0,9))
            
            u = User.register(u_name,
                              None,
                              user_credentials['email'])

            #Send confirmation email
            self.send_email(u.email, 
                            'email_subject.html', 
                            'email_welcome_fb.html', 
                            subject_type = 'welcome', 
                            username = u.name, 
                            user_email = u.email)
            
            #Set session and add a flash welcome message
            self.login(u)
            self.session.add_flash('message_signup_2', 
                               key='homepage_flashes')
   
        else:
            self.login(u)
            self.session.add_flash('message_login_2', 
                               key='homepage_flashes')

        self.redirect('/')
Пример #6
0
    def post(self):
        if self.user:
            # Prompt user to log out.
            self.session.add_flash('message_signup_1', key='homepage_flashes')
            self.redirect("/")
        else:
            if not self.check_state():
                self.redirect("/")
                return

            input_username = self.request.get('username')
            input_password = self.request.get('password')
            input_verify_password = self.request.get('verify_password')
            input_email = self.request.get('email').lower()
            input_verify_email = self.request.get('verify_email').lower()
            input_captcha = self.request.get('g-recaptcha-response')

            error_username=""
            error_password=""
            error_verify_password=""
            error_email=""
            error_verify_email=""
            error_username_exists=""
            error_user_exists=""
            error_captcha=""

            have_error = False

            if not valid_captcha(input_captcha):
                # Show the error-message: captcha not resolved.
                error_captcha = True
                have_error = True

            if not valid_username(input_username):
                # Show the error-message: not a valid username.
                error_username = True
                have_error = True
            if not valid_password(input_password):
                # Show the error-message: not a valid password.
                error_password = True
                have_error = True
            if not valid_verify(input_password, input_verify_password):
                # Show the error-message: passwords do not match.
                error_verify_password = True
                have_error = True
            if not valid_email(input_email):
                # Show the error-message: not a valid email.
                error_email = True
                have_error = True
            if not valid_verify(input_email, input_verify_email):
                # Show the error-message: emails do not match.
                error_verify_email = True
                have_error = True
            if have_error == False:
                u = User.by_name(input_username)
                if u:
                    # Show the error-message: username is already taken.
                    error_username_exists = True
                    have_error = True
                    
                u = User.by_email(input_email)
                if u:
                    # Show the error-message: email already used.
                    error_user_exists = True
                    have_error = True

            if have_error:
                state = self.make_state()
                # Render page with error-messages.
                self.render('signup.html',
                            error_username = error_username,
                            error_username_exists = error_username_exists,
                            error_password = error_password,
                            error_verify_password = error_verify_password,
                            error_email = error_email,
                            error_verify_email = error_verify_email,
                            error_user_exists = error_user_exists,
                            error_captcha = error_captcha,
                            username_form = input_username,
                            email_form = input_email,
                            verify_email_form = input_verify_email,
                            state = state)
            else:
                #Create new entry in the User-DB.
                u = User.register(input_username, input_password, input_email)

                #Send confirmation email
                self.send_email(u.email, 
                                'email_subject.html', 
                                'email_welcome.html', 
                                subject_type = 'welcome', 
                                username = u.name, 
                                user_email = u.email)
                
                # Start session and add welcome flash for homepage
                self.session['provider'] = 'blog'
                self.login(u)
                self.session.add_flash('message_signup_2', 
                                       key='homepage_flashes')
                self.redirect("/")
Пример #7
0
    def post(self):
        # Validate state token
        if not self.check_state():
            self.response.set_status(401)
            self.response.headers["Content-Type"] = 'text/html'
            self.response.out.write('Invalid state parameter.')
            return

        # Obtain fb_exchange_token
        fb_exchange_token = self.request.body
        logging.error('Request data from Facebook (fb_exchange_token):')
        logging.error(fb_exchange_token)

        # Upgrade the fb_exchange_token into an access_token to get user info from API
        app_id = json.loads(open('fb_client_secrets.json', 'r').read())[
            'web']['app_id']
        app_secret = json.loads(
            open('fb_client_secrets.json', 'r').read())['web']['app_secret']
        url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % (
            app_id, app_secret, fb_exchange_token)
        h = httplib2.Http()
        result = h.request(url, 'GET')[1]

        # Use access_token to get user info from API
        # strip expire tag from access_token
        access_token = result.split("&")[0]

        url = 'https://graph.facebook.com/v2.4/me?%s&fields=name,id,email' % access_token
        h = httplib2.Http()
        result = h.request(url, 'GET')[1]
        data_profile = json.loads(result)
        self.session['facebook_id'] = data_profile["id"]
        self.session['provider'] = 'facebook'

        # The access_token must be stored in the login_session in order to properly logout, let's strip out the information before the equals sign in our access_token
        stored_access_token = access_token.split("=")[1]
        self.session['access_token'] = stored_access_token

        # Get user picture
        url = 'https://graph.facebook.com/v2.4/me/picture?%s&redirect=0&height=200&width=200' % access_token
        h = httplib2.Http()
        result = h.request(url, 'GET')[1]
        data_picture = json.loads(result)

        # see if user exists, if it doesn't make a new one
        u = User.by_email(data_profile['email'])
        if not u:
            # turn name from FB into a unique username
            # replace spaces with underscores
            u_name = str(data_profile['name'].replace(" ","_"))
            # check if username exists
            # add a random number
            while User.by_name(u_name):
                u_name = u_name + str(randint(0,9))
            
            u = User.register(u_name,
                              None,
                              data_profile['email'])

            #Send confirmation email
            self.send_email(u.email, 
                            'email_subject.html', 
                            'email_welcome_fb.html', 
                            subject_type = 'welcome', 
                            username = u.name, 
                            user_email = u.email)
            
            #Set session and add a flash welcome message
            self.login(u)
            self.session.add_flash('message_signup_2', 
                               key='homepage_flashes')
   
        else:
            self.login(u)
            self.session.add_flash('message_login_2', 
                               key='homepage_flashes')

        output = ''
        output += '<h1>Welcome, '
        output += data_profile["name"]

        output += '!</h1>'
        output += '<img src="'
        output += data_picture["data"]["url"]
        output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
        self.response.set_status(200)
        self.response.headers["Content-Type"] = 'text/html'
        self.response.out.write(output)
Пример #8
0
    def post(self):
        # Validate state token
        if not self.check_state():
            self.response.set_status(401)
            self.response.headers["Content-Type"] = 'text/html'
            self.response.out.write('Invalid state parameter.')
            return
        # Obtain authorization code
        code = self.request.body
        logging.error('Request data from Google (Authorization code):')
        logging.error(code)

        try:
            # Upgrade the authorization code into a credentials object
            oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
            oauth_flow.redirect_uri = 'postmessage'
            credentials = oauth_flow.step2_exchange(code)
            logging.error('User credentials recieved from Google (Access token, ...):')
            for attr in dir(credentials):
                logging.error("obj.%s = %s" % (attr, getattr(credentials, attr)))
           
        except FlowExchangeError:
            self.response.set_status(401)
            self.response.headers["Content-Type"] = 'text/html'
            self.response.out.write('Failed to upgrade the authorization code.')
            return

        # Check that the access token is valid.
        access_token = credentials.access_token
        logging.error('In gconnect access token is %s', access_token)
        url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
               % access_token)
        h = httplib2.Http()
        result = json.loads(h.request(url, 'GET')[1])
        logging.error('Check Access token. Result: ')
        logging.error(result)
        # If there was an error in the access token info, abort.
        if result.get('error') is not None:
            self.response.set_status(500)
            self.response.headers["Content-Type"] = 'text/html'
            self.response.out.write(result.get('error'))
            return

        # Verify that the access token is used for the intended user.
        gplus_id = credentials.id_token['sub']
        if result['user_id'] != gplus_id:
            self.response.set_status(401)
            self.response.headers["Content-Type"] = 'text/html'
            self.response.out.write("Token's user ID doesn't match given user ID.")
            return

        # Verify that the access token is valid for this app.
        if result['issued_to'] != self.CLIENT_ID:
            logging.error("Token's client ID does not match app's.")
            self.response.set_status(401)
            self.response.headers["Content-Type"] = 'text/html'
            self.response.out.write("Token's client ID does not match app's.")
            return

        # Store the access token in the session for later use.
        self.session['access_token'] = credentials.access_token
        self.session['gplus_id'] = gplus_id

        # Get user info
        url_userinfo = ('https://www.googleapis.com/oauth2/v1/userinfo?access_token=%s&alt=json'
               % access_token)
        h = httplib2.Http()
        data = json.loads(h.request(url_userinfo, 'GET')[1])
       

        # ADD PROVIDER TO LOGIN SESSION
        self.session['provider'] = 'google'

        # see if user exists, if it doesn't make a new one
        u = User.by_email(data['email'])
        if not u:
            # turn name from Google+ into a unique username
            # replace spaces with underscores
            u_name = str(data['name'].replace(" ","_"))
            # check if username exists
            # add a random number
            while User.by_name(u_name):
                u_name = u_name + str(randint(0,9))
                # SET FLASH MESSAGE THAT USERNAME CAN BE EDITED.
            
            u = User.register(u_name,
                              None,
                              data['email'])

            #Send confirmation email
            self.send_email(u.email, 
                            'email_subject.html', 
                            'email_welcome_gplus.html', 
                            subject_type = 'welcome', 
                            username = u.name, 
                            user_email = u.email)
            
            #Set session and add a flash welcome message
            self.login(u)
            self.session.add_flash('message_signup_2', 
                               key='homepage_flashes')
   
        else:
            self.login(u)
            self.session.add_flash('message_login_2', 
                               key='homepage_flashes')

        output = ''
        output += '<h1>Welcome, '
        output += data['name']
        output += '!</h1>'
        output += '<img src="'
        output += data['picture']
        output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
        self.response.set_status(200)
        self.response.headers["Content-Type"] = 'text/html'
        self.response.out.write(output)
Пример #9
0
    def post(self):
        if self.user:
            if not self.check_state():
                logging.warning("Possible CSRF attack detected!")
                self.redirect("/")
                return

            # Get user input
            input_current_password = self.request.get('current_password')
            input_email = self.request.get('email').lower()
            input_verify_email = self.request.get('verify_email').lower()

            # Check input and set error messages. 
            error_current_password=""
            error_email=""
            error_verify_email=""
            error_user_exists=""

            have_error = False

            if not valid_pw(self.user.email, input_current_password, self.user.pw_hash):
                # Set the error-message: incorrect password.
                error_current_password = True
                have_error = True
            if not valid_email(input_email):
                # Set the error-message: not a valid email.
                error_email = True
                have_error = True
            if not valid_verify(input_email, input_verify_email):
                # Set the error-message: emails do not match.
                error_verify_email = True
                have_error = True

            if have_error == False:
                u = User.by_email(input_email)
                if u:
                    # Set the error-message: email already assigned.
                    error_user_exists = True
                    have_error = True
 
            if have_error:
                state = self.make_state()
                # Render page with error-messages.
                self.render('change_email.html',
                            user = self.user,
                            email = input_email,
                            error_current_password = error_current_password,
                            error_email = error_email,
                            error_verify_email = error_verify_email,
                            error_user_exists = error_user_exists,
                            state = state)
            else:
                # Generate password-hash
                # Store new email and password-hash in DB
                pw_hash = make_pw_hash(input_email, input_current_password)
                self.user.pw_hash = pw_hash
                self.user.email = input_email
                self.user.put()
                # Update memcache
                User.update_user_cache(self.user)

                # Send email notification to new address
                self.send_email(self.user.email, 
                                'email_subject.html', 
                                'email_email_changed.html', 
                                subject_type = 'email_changed', 
                                username = self.user.name, 
                                user_email = self.user.email)
                
                # Render page with message that email was sent
                state = self.make_state()
                self.render('change_email.html', 
                            user = self.user, 
                            success_message = True,
                            state = state)
        else:
            # Prompt user to login.
            self.render('message.html', message_user_settings_1 = True)
Пример #10
0
    def post(self):
        if self.user:
            # Prompt user to log out.
            self.render('message.html', 
                        user = self.user, 
                        message_signup_1 = True)
        else:
            if not self.check_state():
                logging.warning("Possible CSRF attack detected!")
                self.redirect("/")
                return

            input_username = self.request.get('username')
            input_password = self.request.get('password')
            input_verify_password = self.request.get('verify_password')
            input_email = self.request.get('email').lower()
            input_verify_email = self.request.get('verify_email').lower()

            error_username=""
            error_password=""
            error_verify_password=""
            error_email=""
            error_verify_email=""
            error_username_exists=""
            error_user_exists=""

            have_error = False

            if not valid_username(input_username):
                # Show the error-message: not a valid username.
                error_username = True
                have_error = True
            if not valid_password(input_password):
                # Show the error-message: not a valid password.
                error_password = True
                have_error = True
            if not valid_verify(input_password, input_verify_password):
                # Show the error-message: passwords do not match.
                error_verify_password = True
                have_error = True
            if not valid_email(input_email):
                # Show the error-message: not a valid email.
                error_email = True
                have_error = True
            if not valid_verify(input_email, input_verify_email):
                # Show the error-message: emails do not match.
                error_verify_email = True
                have_error = True
            if have_error == False:
                u = User.by_name(input_username)
                if u:
                    # Show the error-message: username is already taken.
                    error_username_exists = True
                    have_error = True
                    
                u = User.by_email(input_email)
                if u:
                    # Show the error-message: email already used.
                    error_user_exists = True
                    have_error = True

            if have_error:
                state = self.make_state()
                # Render page with error-messages.
                self.render('signup.html',
                            error_username = error_username,
                            error_username_exists = error_username_exists,
                            error_password = error_password,
                            error_verify_password = error_verify_password,
                            error_email = error_email,
                            error_verify_email = error_verify_email,
                            error_user_exists = error_user_exists,
                            username_form = input_username,
                            email_form = input_email,
                            verify_email_form = input_verify_email,
                            state = state)
            else:
                #Create new entry in the User-DB.
                u = User.register(input_username, input_password, input_email)
                u.put()
                #update memcache
                User.update_user_cache(u)

                #Send confirmation email
                self.send_email(u.email, 
                                'email_subject.html', 
                                'email_welcome.html', 
                                subject_type = 'welcome', 
                                username = u.name, 
                                user_email = u.email)
                
                #Set cookie and render message page with welcome
                self.login(u)
                self.render('message.html', user = u, message_signup_2 = True)