File size: 4,918 Bytes
a7abf85
d3245ed
36d2eb6
7aa2f67
f4feb03
b12f5e4
9a31124
b6af746
8466b62
 
b6af746
 
 
 
 
 
 
 
 
 
9a31124
7aa2f67
9a31124
 
 
7aa2f67
 
 
 
 
 
 
12665ca
9a31124
 
12665ca
 
 
 
 
 
ec42e3b
87cc2f3
f107fa0
9a31124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc500fd
 
9a31124
 
 
 
 
12665ca
 
9a31124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4e2d12
dc500fd
 
 
 
 
 
12665ca
dc500fd
 
 
9a31124
7aa2f67
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask_session import Session  # Import the Session class
from flask.sessions import SecureCookieSessionInterface  # Import the class
from simple_salesforce import Salesforce
from flask_cors import CORS
import os
import requests
import os
from dotenv import load_dotenv
load_dotenv()  # Load environment variables from .env file

load_dotenv()  # Load environment variables

# Retrieve Salesforce credentials from environment variables
SALESFORCE_USERNAME = os.getenv('SALESFORCE_USERNAME')
SALESFORCE_PASSWORD = os.getenv('SALESFORCE_PASSWORD')
SALESFORCE_SECURITY_TOKEN = os.getenv('SALESFORCE_SECURITY_TOKEN')
CLIENT_ID = os.getenv('SALESFORCE_CLIENT_ID')
CLIENT_SECRET = os.getenv('SALESFORCE_CLIENT_SECRET')
REDIRECT_URI = os.getenv('SALESFORCE_REDIRECT_URI')

# Initialize Flask app
app = Flask(__name__)
app.secret_key = os.urandom(24)  # Random secret key for session management

# Configure session management
app.config["SESSION_COOKIE_SECURE"] = False  # Temporarily disable secure cookie
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"  # Use "Lax" instead of "None"
app.config["SESSION_TYPE"] = "filesystem"  # Use filesystem for session storage
Session(app)  # Initialize the session interface
CORS(app)  # Enable Cross-Origin Resource Sharing (CORS)

# Salesforce OAuth URLs and credentials (hardcoded as per your request)
SALESFORCE_OAUTH_URL = "https://login.salesforce.com/services/oauth2/authorize"
SALESFORCE_TOKEN_URL = "https://login.salesforce.com/services/oauth2/token"

# Hardcoded Salesforce credentials
CLIENT_ID = '3MVG9WVXk15qiz1JbtW1tT9a7WojFUbAfMVyVXfvI4PISHAKAxmZ8RLS1lBHqpnaDPQPZOOInuVdcQpi7smWc'
CLIENT_SECRET = '36C463CD713C420BA2ED78F853359EACCE1ECCE2954C9810FFD7F946564CB0E8'
SECURITY_TOKEN = 'sSSjyhInIsUohKpG8sHzty2q'

# Corrected Redirect URI (make sure it's set correctly in Salesforce's Connected App)
REDIRECT_URI = 'https://huggingface.co/spaces/Yaswanth56/python_test/oauth/callback'  # Your redirect URI

# OAuth flow to redirect to Salesforce login
@app.route('/login')
def login():
    oauth_url = f"{SALESFORCE_OAUTH_URL}?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}"
    return redirect(oauth_url)

# Handle the OAuth callback from Salesforce and exchange the authorization code for an access token
@app.route('/oauth/callback')
def oauth_callback():
    auth_code = request.args.get('code')  # The code returned from Salesforce

    if not auth_code:
        return jsonify({"error": "No authorization code provided"}), 400

    # Exchange the authorization code for an access token
    token_data = {
        'grant_type': 'authorization_code',
        'code': auth_code,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'redirect_uri': REDIRECT_URI
    }

    token_response = requests.post(SALESFORCE_TOKEN_URL, data=token_data)

    if token_response.status_code == 200:
        token_info = token_response.json()
        access_token = token_info['access_token']  # Correct key to fetch the access token
        instance_url = token_info['instance_url']  # Correct key to fetch the instance URL

        # Store access token in session for future API requests
        session['access_token'] = access_token
        session['instance_url'] = instance_url

        # Redirect user to the dashboard or home page after successful login
        return redirect('/dashboard')
    else:
        return jsonify({"error": "Failed to authenticate with Salesforce"}), 400

# Example protected route that uses the Salesforce access token
@app.route('/dashboard')
def dashboard():
    if 'access_token' not in session:
        return redirect('/login')  # If the user is not logged in, redirect to login
    
    access_token = session['access_token']
    instance_url = session['instance_url']
    
    # Use the access token to make API calls to Salesforce (example: fetch user info)
    headers = {'Authorization': f'Bearer {access_token}'}
    user_info_url = f"{instance_url}/services/oauth2/userinfo"
    user_info_response = requests.get(user_info_url, headers=headers)
    
    if user_info_response.status_code == 200:
        user_info = user_info_response.json()
        return jsonify(user_info)  # Display user info from Salesforce
    else:
        return jsonify({"error": "Failed to fetch user info from Salesforce"}), 400

# Salesforce connection setup
def get_salesforce_connection():
    # Fetch Salesforce credentials from environment variables
    sf = Salesforce(
        username=os.getenv('SALESFORCE_USERNAME', 'your_username'),
        password=os.getenv('SALESFORCE_PASSWORD', 'your_password'),
        security_token=SECURITY_TOKEN  # Hardcoded Security Token
    )
    return sf

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=7860)  # Make sure it listens on the correct port