def post(self): email = self.get_argument('email', '').lower() password = self.get_argument('password', '') error = False if not email or not password: error = True user = yield models.get_user_by_email(self.redis, email) if not user: error = True t = time.time() if user and not util.check_pwd(password, user.password): error = True t2 = time.time() logging.debug('check_pwd took {}'.format(t2 - t)) if error: error_text = "Yo! You gave an invalid username or incorrect password!" self.render('login.html', page_title='Log In', user=None, error=error_text) self.tf.send({'users.logins.failure': 1}, lambda x: x) return cookie_args = {'httponly': True} logging.debug('request.protocol is {}'.format(self.request.protocol)) if self.request.protocol == 'https': cookie_args['secure'] = True self.set_secure_cookie('user', str(user.id), **cookie_args) self.tf.send({'users.logins.success': 1}, lambda x: x) self.redirect('/')
def gconnect(): if request.args.get('state') != session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response code = request.data sucesso_code, retorno_code = google_connect.\ exchange_code_for_credentials(code) if not sucesso_code: return retorno_code credentials = retorno_code access_token = credentials.access_token sucesso_token, retorno_token = google_connect.\ verify_access_token(access_token) if not sucesso_token: return retorno_token # Verifica se o token enviado é do usuario sucesso_gplus_id, response_gplus_id = google_connect.\ verify_user_token(credentials, retorno_token, CLIENT_ID) if not sucesso_gplus_id: return response_gplus_id stored_access_token = session.get('access_token') stored_gplus_id = session.get('gplus_id') # Guarda o access_token session['access_token'] = credentials.access_token session['gplus_id'] = response_gplus_id # Busca dados do usuario userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() if not models.get_user_by_email(data['email']): user = models.User() user.id = data['id'] user.email = data['email'] user.name = data['name'] models.create_user(user) logged_user = models.User() logged_user.id = data['id'] logged_user.email = data['email'] logged_user.name = data['name'] login_user(logged_user) return redirect(url_for('home'))
def post(self): email = self.get_argument('email', '').lower() display_name = self.get_argument('display_name', '') password = self.get_argument('password', '') password_confirm = self.get_argument('password_confirm', '') url = self.get_argument('url', '').lower() public = True if self.get_argument('public', '') == 'yes' else False # check for general errors error = False if not email or not password or not password_confirm or not url: error = True if password != password_confirm: error = True if error: error_text = 'Missing a field or passwords do not match, all fields are required.' self.render('register.html', page_title='Register', user=None, error=error_text) return # check that email hasn't already been used check_user = yield models.get_user_by_email(self.redis, email) if check_user: error_text = 'The email you tried already has an account. Please log in or register with a different email address.' self.render('register.html', page_title='Register', user=None, error=error_text) return # make sure url is unique if url and not models.url_unique(url): error_text = 'A unique profile URL is required for public accounts!' self.render("register.html", page_title="Register", user=None, error=error_text) new_user = models.User(email=email) new_user.password = util.hash_pwd(password) new_user.display_name = display_name new_user.url = url new_user.public = public new_user.save(self.redis) self.set_secure_cookie('user', str(new_user.id)) self.tf.send({'users.registrations': 1}, lambda x: x) self.redirect('/')
def login(): if request.method == 'POST': email = request.form['username'] password_candidate = request.form['password'] user = models.get_user_by_email(email) if (user != None): if sha256_crypt.verify(password_candidate, user.password): update_session(user) flash('You are now logged in', 'success') return render_template('index.html', session_user_name=session['username']) else: error = 'Invalid credentials' return render_template('login.html', error=error) else: error = 'Username %s not found' % (email) return render_template('login.html', error=error) return render_template('login.html')
def verify_password(_login, password): """ Verification of password :param _login: :param password: :return bool: """ # Try to see if it's a token first user_id = User.verify_auth_token(_login) if user_id: user = get_user_by_id(user_id) else: user = get_user_by_email(_login) if not user: user = get_user_by_username(_login) if not user or not user.verify_password(password): return False else: if not user.verify_password(password): return False g.user = user return True
def login(provider): # STEP 1 - Parse the auth code code = request.data if provider == 'google': # STEP 2 - Exchange for a token 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) except FlowExchangeError: response = make_response( dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ( 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = Http() result = loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' # Get user info h = Http() userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = r_get(userinfo_url, params=params) data = answer.json() # see if user exists, if it doesn't make a new one user = get_user_by_email(email=data['email']) if not user: user = create_user(username=data.get('name'), picture=data.get('picture'), email=data.get('email'), first_name=data.get('given_name'), last_name=data.get('family_name'), password=get_unique_str(8)) g.user = user # Make token token = g.user.generate_auth_token() # Send back token to the client return jsonify({ 'token': token.decode('ascii'), 'uid': g.user.id, 'first_name': g.user.first_name, 'last_name': g.user.last_name, 'email': g.user.email, 'picture': g.user.picture, 'status': g.user.status, 'full_name': g.user.get_full_name }), 200 elif provider == 'facebook': data = request.json.get('data') access_token = data['access_token'] fb_file = ''.join([BASE_DIR, '/facebook.json']) fb_data = loads(open(fb_file, 'r').read())['facebook'] app_id = fb_data['app_id'] app_secret = fb_data['app_secret'] url = fb_data['access_token_url'] % (app_id, app_secret, access_token) h = Http() result = h.request(url, 'GET')[1] # Use token to get user info from API token = result.split(',')[0].split(':')[1].replace('"', '') url = fb_data['user_info_url'] % token h = Http() result = h.request(url, 'GET')[1] data = loads(result) name = data['name'].split(' ') user_data = dict() user_data['provider'] = 'facebook' user_data['username'] = data.get('name') user_data['first_name'] = name[0] user_data['last_name'] = name[1] user_data['email'] = data.get('email') user_data['facebook_id'] = data.get('id') user_data['access_token'] = token url = fb_data['picture_url'] % token h = Http() result = h.request(url, 'GET')[1] data = loads(result) user_data['picture'] = data['data']['url'] # login_session['picture'] = data["data"]["url"] # see if user exists user_info = get_user_by_email(user_data['email']) if user_info is None: user_info = create_user(username=user_data['username'], password=get_unique_str(8), first_name=user_data['first_name'], last_name=user_data['last_name'], email=user_data['email'], picture=user_data['picture']) g.user = user_info token = g.user.generate_auth_token() return jsonify({ 'token': token.decode('ascii'), 'uid': g.user.id, 'first_name': g.user.first_name, 'last_name': g.user.last_name, 'email': g.user.email, 'picture': g.user.picture, 'status': g.user.status, 'full_name': g.user.get_full_name }), 200 else: return jsonify({'error': 'Unknown provider'}), 200
def oauth(provider): """ Authentication with providers :param provider: :return: """ # STEP 1 - Parse the auth code code = request.data if provider == 'google': # STEP 2 - Exchange for a token 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) except FlowExchangeError: response = make_response( dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token # prepare url turl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' url = (turl % access_token) # get result h = Http() result = loads(h.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' # Get user info h = Http() userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} google_response = r_get(userinfo_url, params=params) data = google_response.json() # see if user exists, if it doesn't make a new one user = get_user_by_email(email=data['email']) if not user: user = create_user(username=data.get('name'), picture=data.get('picture'), email=data.get('email'), first_name=data.get('given_name'), last_name=data.get('family_name'), password=get_unique_str(8)) g.user = user # create session session['uid'] = user.id session['provider'] = 'google' return jsonify({'message': 'Success'}), 200 elif provider == 'facebook': # get data data = request.json.get('data') # get access token access_token = data['access_token'] # prepare path to app facebook data fb_file = ''.join([BASE_DIR, '/facebook.json']) # load data fb_data = loads(open(fb_file, 'r').read())['facebook'] # gat app data app_id = fb_data['app_id'] app_secret = fb_data['app_secret'] # prepare query url for access token url = fb_data['access_token_url'] % (app_id, app_secret, access_token) # get result h = Http() result = h.request(url, 'GET')[1] # Use token to get user info from API token = result.split(',')[0].split(':')[1].replace('"', '') # prepare url for get user info url = fb_data['user_info_url'] % token # get result h = Http() result = h.request(url, 'GET')[1] # load data data = loads(result) # get first name and last name name = findall(r'[a-zA-Z]+', data['name']) # prepare dictionary for save user_data = dict() user_data['provider'] = 'facebook' user_data['username'] = ''.join(name) user_data['first_name'] = name[0] user_data['last_name'] = name[1] user_data['email'] = data.get('email') user_data['facebook_id'] = data.get('id') user_data['access_token'] = token # prepare url for get picture url = fb_data['picture_url'] % token # get result h = Http() result = h.request(url, 'GET')[1] # load data data = loads(result) # add picture link to dictionary user_data['picture'] = data['data']['url'] # get user info user_info = get_user_by_email(user_data['email']) # check the user exist, if not create a new one if user_info is None: user_info = create_user(username=user_data['username'], password=get_unique_str(8), first_name=user_data['first_name'], last_name=user_data['last_name'], email=user_data['email'], picture=user_data['picture']) g.user = user_info # create session session['uid'] = user_info.id session['provider'] = 'facebook' return jsonify({'message': 'Success'}), 200 else: return jsonify({'error': 'Unknown provider'})