def add_new_user(): email = request.json.get('email') password = request.json.get('password') name = request.json.get('name') picture = request.json.get('picture') if email is None or password is None: abort(400) user = session.query(User).filter_by(email=email).first() if user is None: user = User(email = email) user.hash_password(password) user.name = name user.picture = picture session.add(user) session.commit() else: return jsonify({'message': 'user already exists'}), 200 return jsonify({'email': user.email}), 201
def login(provider): # STEP 1 - Parse the auth code auth_code = request.json.get('auth_code') 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(auth_code) except FlowExchangeError: response = make_response(json.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 = httplib2.Http() result = json.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(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' # STEP 3 - Find User or make a new one # Get user info h = httplib2.Http() 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() name = data['name'] picture = data['picture'] email = data['email'] # Si el usuario no existe, en ese momento lo registra user = session.query(User).filter_by(email=email).first() if not user: user = User() user.email = email user.name = name user.picture = picture session.add(user) session.commit() # STEP 4 - Make token token = user.generate_auth_token() # STEP 5 - Send back token to the client return jsonify({'token': token.decode('ascii')}) elif 'local': email = request.json.get('email') password = request.json.get('password') user = session.query(User).filter_by(email=email).first() if not user or not user.verify_password(password): return jsonify( error = {'code': 'InvalidUserPassword', 'message': 'Usuario y/o contraseña incorrecto'}), 401 token = user.generate_auth_token() return jsonify({'token': token.decode('ascii')}) else: return jsonify(json = {'code': 'InvalidProvider', 'message': 'Proveedor de autenticaicón incorrecto'}), 400