Skip to content

Commit

Permalink
Revert "tests code"
Browse files Browse the repository at this point in the history
This reverts commit ca0da1d.
  • Loading branch information
Kauannery committed Jun 3, 2024
1 parent 3918279 commit 862ae19
Show file tree
Hide file tree
Showing 10 changed files with 130 additions and 235 deletions.
7 changes: 0 additions & 7 deletions api/view_cors.py

This file was deleted.

59 changes: 0 additions & 59 deletions api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,12 @@
from google_auth_oauthlib.flow import Flow
from google.auth.transport import Request

#new-imports
from google_auth_oauthlib.flow import Flow
from google.auth.transport import Request

os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
SCOPES = [
"https://www.googleapis.com/auth/calendar.app.created",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
<<<<<<< HEAD
"openid",
=======
"openid",
>>>>>>> da576de (tests code)
]

REDIRECT_URL = f"{settings.BASE_URL}/calendar/redirect/"
Expand Down Expand Up @@ -56,7 +48,6 @@ def calendar_init_view(request):
@api_view(['POST'])
def calendar_token(request):
config = get_secret(f"{settings.ENVIRONMENT}/google/calendar")
<<<<<<< HEAD
flow = Flow.from_client_config(config,scopes=SCOPES,redirect_uri="http://localhost:3000")
code = request.data['code']

Expand All @@ -72,55 +63,5 @@ def calendar_token(request):
except Exception as e:
print(f"Error: {e}")
return JsonResponse({"error": str(e)})
=======
flow = Flow.from_client_config(config,scopes=SCOPES,redirect_uri="http://127.0.0.1:3000")
code = request.data['code']
print('code', code)
# flow.fetch_token(code)
# 4/0AdLIrYdjDBOqa7mxm9bGUUdXo_lyOu1YgKIiDh6_UhBCmfZNI_JMkRDLvg33YTHPSaWe2A
try:
credentials = flow.fetch_token(code=code)
print('crendentials:', flow.credentials)
except Exception as e:
print(f"Error: {e}")
return JsonResponse({"error": str(e)})

userinfo_service = googleapiclient.discovery.build("oauth2", "v2", credentials=flow.credentials)
user_info = userinfo_service.userinfo().get().execute()

email = user_info.get("email")
User = get_user_model()
user, created = User.objects.get_or_create(username=email, email=email)
if created:
user.set_unusable_password()
user.save()

if not CredentialsService.get_for(user):
saved_credentials = CredentialsService.create_for(user, credentials)
else:
saved_credentials = CredentialsService.update_for(user, credentials)
if not saved_credentials:
return redirect("api/v1/calendar/init")

saved_credentials.user = user
saved_credentials.save(update_fields=["user"])

authenticated_user = authenticate(request, username=email)
if authenticated_user:
login(request, authenticated_user)

try:
service = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=flow.credentials)

if not user.calendar_id:
calendar = {"summary": "BaheaCal", "timeZone": "America/Bahia"}
created_calendar = service.calendars().insert(body=calendar).execute()
user.calendar_id = created_calendar["id"]
user.save(update_fields=["calendar_id"])

service.events().list(calendarId=user.calendar_id).execute()
except Exception as e:
return JsonResponse({"error": str(e)})
>>>>>>> da576de (tests code)
else:
return JsonResponse({"sucess": True})
15 changes: 0 additions & 15 deletions core/middleware.py

This file was deleted.

3 changes: 1 addition & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
"dependencies": {
"@react-oauth/google": "^0.12.1",
"@types/react": "^18.2.79",
"axios": "^1.7.2",
"cors": "^2.8.5",
"axios": "^1.6.8",
"eslint-plugin-react-refresh": "^0.4.6",
"jwt-decode": "^4.0.0",
"react": "^18.2.0",
Expand Down
55 changes: 55 additions & 0 deletions frontend/src/Buttonapi.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import axios from 'axios'

export default function Login1() {
const Login1 = async () => {
try {
const response = await axios.post('http://localhost:8000/api/v1/calendar/token/', {'bla':'bla'}, {
headers: {
'Content-Type': 'application/json'
}
});
console.log('response-data: ', response.data);
} catch (error) {
console.error('error: ', error);
}
}

return (<button onClick={Login1}> Fazer login</button>)
}





// import {} from 'react-router-dom'
// import axios from 'axios'


// export default function Login1() {
// const Login1 = async () => {




// var options = {
// method: 'POST',
// url: 'http://localhost:8000/api/v1/calendar/token/',
// headers: {
// 'Content-Type': 'application/json',
// 'Allow-Control-Allow-Origin': '*'
// },
// body: {'bla':'bla'}

// };


// axios.request(options).then(function (response) {
// console.log(response.data);
// }).catch(function (error) {
// console.error(error);
// });


// }
// return (<button onClick={() => Login1()}> Fazer login</button>)
// }
51 changes: 18 additions & 33 deletions frontend/src/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,43 +26,28 @@ export default function Login() {
// </div>);

const handleLogin = async (credentialResponse) => {
console.log('credential Response', credentialResponse);
var obj = jwtDecode(credentialResponse.credential);
var data = JSON.stringify(obj);
console.log(data);

try {
const response = await axios.post('http://localhost:8000/api/v1/calendar/token/', credentialResponse, {
headers: {
// 'Access-Control-Allow-Headers': '*',
'Content-Type': 'application/json',
// 'Allow-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': '*'
}
});

console.log('response-data: ', response.data);
} catch (error) {
console.error('error: ', error);
}
}

const login = useGoogleLogin({
scope: "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.app.created https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid",
flow: 'auth-code',
access_type: 'offline',
prompt: 'consent',
onSuccess: handleLogin,
});
// // const data = {your data to send to server};

// return (<button onClick={() => teste()}> oiasodiaosio</button>)
return (<button onClick={() => login()}> Fazer login</button>)
const config = {
method: 'POST',
url: 'http://127.0.0.1:8000/api/v1/calendar/token/',
headers: {},
data: data
}

// return(<GoogleLogin onSuccess={credentialResponse => {
// console.log(credentialResponse);
// }}
// onError={() => {
// console.log('Login Failed');
// }}
// />)
await axios(config)
}

return(
<GoogleOAuthProvider clientId="470653035644-rkr19rof1eclp7f7gmd4044jt110hf9g.apps.googleusercontent.com">
<GoogleLogin
onSuccess={handleLogin}
/>
</GoogleOAuthProvider>)
}


Expand Down
8 changes: 1 addition & 7 deletions frontend/src/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import ReactDOM from 'react-dom/client'
import Login from './Login.jsx'
import Login1 from './Buttonapi.jsx'

import Login1 from './Buttonapi.jsx'

import {
createBrowserRouter,
RouterProvider,
Expand All @@ -29,11 +27,7 @@ const router = createBrowserRouter([
element: <Time />,
},

{
path: "/buttonapi",
element: <Login1/>,

},
]);

ReactDOM.createRoot(document.getElementById('root')).render(
Expand All @@ -42,4 +36,4 @@ ReactDOM.createRoot(document.getElementById('root')).render(
<RouterProvider router={router} />
</GoogleOAuthProvider>
</React.StrictMode>
)
)
Loading

0 comments on commit 862ae19

Please sign in to comment.